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

描述

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

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)的做法;

最简单的求解方式是从1进行遍历,直到找到一个数n,满足$n^2>x$,则此时$n-1$就是要找的值,但是该方法需要遍历$int(\sqrt x)$次,当$x$的数值很大时,需要遍历的次数太多;

所以这里采用牛顿迭代法来进行开方,牛顿迭代法能开任意数的平方,并能找到一个逼近解,当然该题只需要找到对应的整数解就可以。牛顿迭代法的原理很简单,其实是根据$f(x)=x^2 – a$在$x_0$附近的值和斜率,估计$f(x)$和$x$轴的交点,因此牛顿迭代法的公式为:

$$x_{n+1}=x_n – \frac{f(x_n)}{f^{‘}(x_n)}$$

其实就是求切线与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)

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

    原文作者:lingjiu
    原文地址: https://segmentfault.com/a/1190000015402083
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞