题目:
Implement int sqrt(int x)
.
Compute and return the square root of x.
代码如下:
int sqrt(int x) {
if(x<=0) return 0;
double a=x,b=0,ErrorMargin=0.0000001;
while(abs(a-b)>ErrorMargin)
{
a = (a+b)/2;
b = x/a;
}
int i=static_cast<int>(a);
if(i*i<=x)
return i;
else
return i-1;
}