1. 程式人生 > >Crack LeetCode 之 69. Sqrt(x)

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