I have been trying to solve a problem which requires me to write a function called mySqrt
of the form int mySqrt(int x)
.
I am supposed to compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
I tried to implement a straightforward algorithm where I start from i=0
and then increment the value of i
until $i*i<=x$
and then return i-1
.
public int mySqrt(int x) {
int i=0;
while(i*i<=x){
i++;
}
return (i-1);
}
I have an idea of what is happening but I really can't understand why.
When i is large enough such that i^2 >2^31-1
the comparison in the while loop (i*i<=x)
for x=2147395600
(which is less that 2^31-1
) gives me a true. Why would that be? And as a consequence I am getting junk results. What is exactly happening when I try to evaluate (i^2<=x
) when i^2
can no longer be stored in an int?