注意32位乘法的问题,和寄存器相关!
int sqrt(int x)
{
if (x <= 0)
return 0;
uint64_t high = x, low = 1, mid;
uint64_t square, square2; //!!! initialize high & low
while (low < high)
{
mid = (high - low) / 2 + low;
square = mid * mid;
square2 = (mid + 1) * (mid + 1);
if (square > x && square2 > x)
high = mid; //!!! pay attention that high = mid, not mid = high
else if (square < x && square2 < x)
low = mid;
else
{
if (square <= x && square2 > x)
return mid; //!!! pay attention to the return value, not square, but mid!
else
//x == square2
return mid + 1;
}
}
}