How to compute the nth root of a very big integer

后端 未结 10 578
暖寄归人
暖寄归人 2020-12-01 06:28

I need a way to compute the nth root of a long integer in Python.

I tried pow(m, 1.0/n), but it doesn\'t work:

OverflowError: lo

10条回答
  •  渐次进展
    2020-12-01 07:00

    I came up with my own answer, which takes @Mahmoud Kassem's idea, simplifies the code, and makes it more reusable:

    def cube_root(x):
        return decimal.Decimal(x) ** (decimal.Decimal(1) / decimal.Decimal(3))
    

    I tested it in Python 3.5.1 and Python 2.7.8, and it seemed to work fine.

    The result will have as many digits as specified by the decimal context the function is run in, which by default is 28 decimal places. According to the documentation for the power function in the decimal module, "The result is well-defined but only “almost always correctly-rounded”.". If you need a more accurate result, it can be done as follows:

    with decimal.localcontext() as context:
        context.prec = 50
        print(cube_root(42))
    

提交回复
热议问题