Crack LeetCode 之 69. Sqrt(x)

https://leetcode.com/problems/sqrtx/

本题可以采用二分法和牛顿法,以下分别为C++和python实现。

struct Solution {
	int sqrt(int x) {
		if (x == 0)
			return 0;

		double lastY = 0;
		double y = 1;
		while (y != lastY) {
			lastY = y;
			y = (y + x / y) / 2;
		}

		return (int)(y);
	}
};
class Solution:
    def mySqrt(self, x):
        if x == 0:
            return 0

        l = 1
        r = int(x/2)
        
        while l <= r:
            m = (int)((l+r) / 2)
            if (x >= m*m) and (x < (m+1)*(m+1)):
                return m
            
            if x > m*m:
                l = m + 1
            else:
                r = m - 1
        
        return 1
struct Solution {
    int mySqrt(int x) {
		if(x == 0)
			return 0;

		int l=1;
		int r=x/2+1;
		while( l <= r ) {
			int m = (l+r)/2;
			if(m<=x/m && x/(m+1)<m+1)
				return m;

			if(x/m<m)
				r = m-1;
			else
				l = m+1;
		}

		return 0;
    }
};

以下是我找到的两篇讲解牛顿法的文章,一篇通俗讲解了牛顿法的思想,另一篇推导了牛顿法求平方根的公式。牛顿法求平方根的本质就是在抛物线上任取一点做切线,再把该切线与x轴的交点代入该抛物线方程又得到一根更逼近根的切线,如此迭代最终获得结果。但是就像第一篇文章所说的,牛顿法求函数根,需要该函数有二阶导数,否则牛顿法会在根附近抖动甚至越来越远。

https://www.zhihu.com/question/20690553

http://www.voidcn.com/article/p-btcbtpcx-gk.html

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值