69.Sqrt(x)(二分搜索,牛顿迭代法)

题目:
Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842…, and since
the decimal part is truncated, 2 is returned.

解析:求数x的开平方。
方法一:二分搜索。参考http://www.cnblogs.com/grandyang/p/6854825.html。思路是求一个候选值的平方,与目标值x比较大小。找最后一个不大于目标值的数。

class Solution {
public:
    int mySqrt(int x) {
        if(x<=1) return x;//这一句不可缺少,对于特殊情况的单独处理。缺少它会报错
        int left=0,right=x;
        while(left < right)
        {
            int mid = left+(right-left)/2;
            if(x/mid >= mid) left=mid+1;
            else right=mid;
        }
        return right-1;
    }
};

方法二:牛顿迭代法。

class Solution {
public:
    int mySqrt(int x) {
        if(x == 0) return 0;
        double last,res;//注意这里的类型
        last=0,res=1;
        while(abs(last-res)>1e-6)//循环条件是前后两个解xi和xi-1是否无限接近
        {
            last = res;
            res = (res+x/res)/2;  
        }
        return (int)res;//类型强制转换为int
    }
};

牛顿迭代法详解:http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html

计算x2 = n的解,令f(x)=x2-n,相当于求解f(x)=0的解,如下图所示。

首先取x0,如果x0不是解,做一个经过(x0,f(x0))这个点的切线,与x轴的交点为x1。

同样的道理,如果x1不是解,做一个经过(x1,f(x1))这个点的切线,与x轴的交点为x2。

以此类推。

以这样的方式得到的xi会无限趋近于f(x)=0的解。

判断xi是否是f(x)=0的解有两种方法:

一是直接计算f(xi)的值判断是否为0,二是判断前后两个解xi和xi-1是否无限接近。

经过(xi, f(xi))这个点的切线方程为f(x) = f(xi) + f’(xi)(x - xi),其中f’(x)为f(x)的导数,本题中为2x。令切线方程等于0,即可求出xi+1=xi - f(xi) / f’(xi)。

继续化简,xi+1=xi - (xi2 - n) / (2xi) = xi - xi / 2 + n / (2xi) = xi / 2 + n / 2xi = (xi + n/xi) / 2。

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/gyhjlauy/article/details/89065768
今日推荐