LeetCode69
实现int sqrt(int x) 函数
主要使用牛顿迭代法求平方根
递推公式如下:
递推到一定精度err返回
代码:
class Solution {
public int mySqrt(int x) {
if (x < 0) {
return -1;
}else {
double err = 1e-15;
double t = x;
while (Math.abs(t - x/t) > err * t){
t = (t + x / t)/2.0;
}
return (int)t;
}
}
}
牛顿迭代法:https://www.zhihu.com/question/20690553
附:
使用牛顿迭代法求k次方根,递推式如下: