題目:git
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.
思路:函數
牛頓迭代法, 導數方程 f'(x)*x'=y', 任何函數f(x)=y,求解某個y=n,都可以轉化爲 f(x)-n=0, 此後就能夠用牛頓迭代法,不斷逼近實際待求x值。 牛頓迭代共識:f'(x_pre)x_pre+x_pre=x_cur 應用: 迭代思想,相似於 動態規劃思想,pre==>cur,進行動態推斷處理
class Solution: def mySqrt(self, x): """ :type x: int :rtype: int """ r=x/2+1 while r*r-x>1e-10: r=(r+x/r)/2 # print(r*r-x)