首页 > 其他 > 详细

69. Sqrt(x)

时间:2017-10-02 20:41:30      阅读:271      评论:0      收藏:0      [点我收藏+]

Implement int sqrt(int x).

Compute and return the square root of x.

 方法一:牛顿迭代

f(x)=f(x0)+f‘(x0)(x-x0)======>x=x0-f(x0)/f‘(x0)

在此处f(x)=x^2-n, f‘(x)=2x,代入并整理得到x=(x0+n/x0)/2;将n初始化为一个较大值。

class Solution {
public:
    int mySqrt(int x) {
        long long int n=x;
        while(n*n>x){
            n=(n+x/n)/2;
        }
        return n;
    }
};

方法二:二分查找,由于fx=x^2-n,在0到正无穷上单调,因而可以用binary search进行查找

class Solution {
public:
    int mySqrt(int x) {
        if(x<2) return x;
        int y=x/2;
        while(y>x/y) {
            y=(y+x/y)/2;
        }
        return y;
    }
};

 

69. Sqrt(x)

原文:http://www.cnblogs.com/tsunami-lj/p/7622217.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!