int sqrt(int x) {
if(x == 0) return 0;
if(x == 1) return 1;
int i = 0, j = x;
while(i <= j) {
float m = i + (j-i)/2;
long long q = m*m;
if(q == x)
return m;
else if(q < x)
i = m+1;
else
j = m-1;
}
return j; // return j not i is because j < i. We use the smaller one.
}
// sqrt for double precision
double sqrt(double x) {
const double EPS = 1e-6;
double low = 0, high = x; // should be double not int here
while(low + EPS < high) { // gist, note this predicate!
double mid = (low + high) / 2;
if(mid * mid > x) high = mid;
else low = mid;
}
return low; // it seems that returning'low' or 'high' will have the same results
}