[leetcode] 【分治法】 69. Sqrt(x)

来源:互联网 发布:苹果cms定时任务采集 编辑:程序博客网 时间:2024/06/06 09:50

Implement int sqrt(int x).

Compute and return the square root of x.

题意

实现平方根函数,返回x的根。

题解

二分法,取到合适的数为止。

class Solution {public:    int mySqrt(int x) {        if(x<2) return x;        double begin=0,end=x,mid=1,res=0;        while(abs(res-x)>0.000001)        {            mid=(begin+end)/2;            res=mid*mid;            if(res>x) end=mid;            else begin=mid;        }        return (int)mid;    }};
牛顿迭代法(我没有用这个方法,这题主要练练二分法):

牛顿迭代法Newton's method)又称为牛顿-拉夫逊(拉弗森)方法(Newton-Raphson method),它是牛顿在17世纪提出的一种在实数域和复数域上近似求解方程的方法。


以下代码cur = pre/2 + x/(2*pre)是化简计算的结果。。这里的f(x) = x^2-n

class Solution {public:    int mySqrt(int x) {        double pre = 0;          double cur = x;           //  这里从x开始 从x/2开始会导致 1 不能满足  x(n+1)= xn - f'(xn)/f(xn)           while(abs(cur - pre) > 0.000001){              pre = cur;              cur = (pre/2 + x/(2*pre));          }          return int(cur);    }};



 

0 0
原创粉丝点击