So I wrote a program to find floor of square of a number. It seems to work fine for smaller numbers but for long numbers it gives weird results. Here is my code.
int SquareRoot(long x)
{
long start=1;
long end=x;
long mid;
while(start<end)
{
mid=start+(end-start+1)/2;
if(mid*mid<x)
{
if((mid+1)*(mid+1)>x)
{
return mid;
}
start=mid;
}
else if(mid*mid>x)
{
if((mid-1)*(mid-1<x)
return mid-1;
end=mid;
}
else
return mid;
}
return start;
}
Probably the "weird results" you observe happen when one or both of the computations mid * mid
and (mid + 1) * (mid + 1)
overflows, which will happen when end
is bigger than 2*sqrt(LONG_MAX)
(approximately 6,074,000,998 if long
is 64 bits, or 92680 if long
is 32 bits).
The overflow will cause the comparison with x
to produce an erroneous result (technically, the overflow produces Undefined Behaviour although with gcc the result is predictable but incorrect).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.