Generating digits of square root of 2

后端 未结 9 1255
后悔当初
后悔当初 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:24

    Here is a short version for calculating the square root of an integer a to digits of precision. It works by finding the integer square root of a after multiplying by 10 raised to the 2 x digits.

    def sqroot(a, digits):
        a = a * (10**(2*digits))
        x_prev = 0
        x_next = 1 * (10**digits)
        while x_prev != x_next:
            x_prev = x_next
            x_next = (x_prev + (a // x_prev)) >> 1
        return x_next
    

    Just a few caveats.

    You'll need to convert the result to a string and add the decimal point at the correct location (if you want the decimal point printed).

    Converting a very large integer to a string isn't very fast.

    Dividing very large integers isn't very fast (in Python) either.

    Depending on the performance of your system, it may take an hour or longer to calculate the square root of 2 to 3 million decimal places.

    I haven't proven the loop will always terminate. It may oscillate between two values differing in the last digit. Or it may not.

提交回复
热议问题