I am implementing a simple binary search to find the square root of a integer. The code runs correctly. But it seems to timeout for large inputs if I change the condition in the if
from mid * mid > x
to mid > (x / mid)
then all is fine.
int sqrt(int x) {
if(x < 0) return -1;
if(x <= 1) return x;
int l,r,mid,ans;
l = 0;
r = x;
while(l <=r ){
mid = (l + r) / 2;
if((mid * mid) == x) return mid;
if((mid * mid) > x ){ //<===== here if I change to mid > (x / mid)
r = mid - 1;
}else{
l = mid + 1;
ans = mid;
}
}
return ans;
}
};
Therefore I conclude that division is faster than multiplication. But the research I've done so far all points to multiplication being faster than division.