LeetCode-69 x的平方根

LeetCode69
实现int sqrt(int x) 函数
主要使用牛顿迭代法求平方根
递推公式如下:
x n + 1 = 1 2 ( x n + c x n ) x_{n+1} = \frac{1}{2}(x_n + \frac{c}{x_n})
递推到一定精度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次方根,递推式如下:
x n + 1 = 1 k ( ( k 1 ) x n + c x n k 1 ) x_{n+1} = \frac{1}{k}((k-1)x_n + \frac{c}{x_n^{k-1}})

原创文章 187 获赞 29 访问量 6万+

猜你喜欢

转载自blog.csdn.net/weixin_43826242/article/details/105890461