[Leetcode]@python 69. Sqrt(x)

题目链接

https://leetcode.com/problems/sqrtx/

题目原文

Implement int sqrt(int x).
Compute and return the square root of x.

题目大意

实现一个整型的开平方根

解题思路

使用牛顿迭代法进行求解

牛顿迭代公式
设r是f(x) = 0的根,选取x0作为r初始近似值,过点(x0,f(x0))做曲线y = f(x)的切线L,L的方程为y = f(x0)+f'(x0)(x-x0),求出L与x轴交点的横坐标 x1 = x0-f(x0)/f'(x0),称x1为r的一次近似值。过点(x1,f(x1))做曲线y = f(x)的切线,并求该切线与x轴交点的横坐标 x2 = x1-f(x1)/f'(x1),称x2为r的二次近似值。重复以上过程,得r的近似值序列,其中x(n+1)=x(n)-f(x(n))/f'(x(n)),称为r的n+1次近似值,上式称为牛顿迭代公式。

代码

class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x == 0:
            return 0
        ans = float(x)
        while True:
            tmp = ans
            ans = (ans + x / ans) / 2
            if abs(ans - tmp) < 1:
                break
        return int(ans)        
原文地址:https://www.cnblogs.com/slurm/p/5126430.html