Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

思路: 其实就是求解 非线性方程  x^2 = A. (A为开方的数)

一般形式是 求解 f (x) = 0


解法1: 牛顿切线法

这是牛顿在 1736年提出的方法,其实思想非常简单, 如下图。

给定一个初始值 x0, 在点 (x0, f(x0))处画一切线,求切线与 x轴的交点得到 x1, 依次类推。。

得到以下的迭代式                                   



class Solution {
public:
    int sqrt(int x) {
        if(x < 2) return x;
        
        double root(x);
        while(fabs(root*root - x) >= 1) /*直到误差足够小*/
        {
            root = (root*root + x)/(2*root);
        }
        return root;
    }
};


解法2: 二分法

class Solution {
public:
    int sqrt(int x) {
      if(x == 1) return 1;
      int left(0), right(x);
      int mid(0);
      
      while(left+1 < right){
          mid = left + (right-left)/2;
          if(mid > x/mid){ //mid*mid-x 溢出
              right = mid;
          }
          else if(mid < x/mid){
              left = mid;
          }
          else{
              return mid;
          }
      }
      return left;
    }
};


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值