69. Sqrt(x)

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;
    }
};

 

posted @ 2017-10-02 20:14  Tsunami_lj  阅读(121)  评论(0编辑  收藏  举报