码迷,mamicode.com
首页 > 其他好文 > 详细

69. Sqrt(x)

时间:2017-10-02 20:55:09      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:solution   int   nbsp   public   log   search   long   color   return   

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)

标签:solution   int   nbsp   public   log   search   long   color   return   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!