LeetCode69. Sqrt(x) -- 求一个数的开方

描述

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

Exampleci

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)

牛顿迭代法的基本原理,请参考:
牛顿迭代法求开平方循环

相关文章
相关标签/搜索