直接二分搜索解法:
int mySqrt(int x) {
long long low=0,high=x,mid;
while(low<=high)
{
mid=(low+high)/2;
if(mid*mid<=x&&(mid+1)*(mid+1)>x)
return mid;
else if(mid*mid<=x)
low=mid+1;
else high=mid-1;
}
}
牛顿法(不断作切线逼近)
![](https://i-blog.csdnimg.cn/blog_migrate/ee0d376b008c889b9ed30429e07495b6.png)
int mySqrt(int x) {
long r = x;//避免溢出
while (r*r > x)//同时排除0
r = (r + x/r)>>1;//能用移位运算的尽量用移位运算,除法所耗时间为乘法的几十倍
return r;
}
由于牛顿法的计算过程和初始值的选取有很大的联系,有大牛创造了以下神奇的代码,一个字快
float InvSqrt(float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x; // get bits for floating VALUE
i = 0x5f375a86- (i>>1); // gives initial guess y0
x = *(float*)&i; // convert bits BACK to float
x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy
x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy
x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy
return 1/x;
}