Implement int sqrt(int x).git
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.session
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.code
Example:ci
Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
該題就是求一個數的開平方,此處忽略這種直接用int(x ** 0.5)
的作法;get
最簡單的求解方式是從1進行遍歷,直到找到一個數n,知足$n^2>x$,則此時$n-1$就是要找的值,可是該方法須要遍歷$int(\sqrt x)$次,當$x$的數值很大時,須要遍歷的次數太多;it
因此這裏採用牛頓迭代法來進行開方,牛頓迭代法能開任意數的平方,並能找到一個逼近解,固然該題只須要找到對應的整數解就能夠。牛頓迭代法的原理很簡單,實際上是根據$f(x)=x^2 - a$在$x_0$附近的值和斜率,估計$f(x)$和$x$軸的交點,所以牛頓迭代法的公式爲:io
$$x_{n+1}=x_n - \frac{f(x_n)}{f^{'}(x_n)}$$class
其實就是求切線與x軸的交點。原理
class Solution: def mySqrt(self, x): """ 利用牛頓法進行x0的更新,比直接從1開始遍歷所做的循環要少 :type x: int :rtype: int """ x0 = 1 while True: x1 = x0 - (x0 ** 2 - x)/(2*x0) if int(x1) == int(x0): break else: x0 = x1 return int(x0)
牛頓迭代法的基本原理,請參考:
牛頓迭代法求開平方循環