Generating digits of square root of 2

后端 未结 9 1175
后悔当初
后悔当初 2020-12-29 08:36

I want to generate the digits of the square root of two to 3 million digits.

I am aware of Newton-Raphson but I don\'t have much clue how to impleme

9条回答
  •  囚心锁ツ
    2020-12-29 09:13

    Here's a more efficient integer square root function (in Python 3.x) that should terminate in all cases. It starts with a number much closer to the square root, so it takes fewer steps. Note that int.bit_length requires Python 3.1+. Error checking left out for brevity.

    def isqrt(n):
        x = (n >> n.bit_length() // 2) + 1
        result = (x + n // x) // 2
        while abs(result - x) > 1:
            x = result
            result = (x + n // x) // 2
        while result * result > n:
            result -= 1
        return result
    

提交回复
热议问题