How to find integer nth roots?

后端 未结 11 1500
醉酒成梦
醉酒成梦 2020-12-01 16:22

I want to find the greatest integer less than or equal to the kth root of n. I tried

int(n**(1/k))

But for n=125, k=3 this gives the wrong

11条回答
  •  不知归路
    2020-12-01 16:48

    Here it is in Lua using Newton-Raphson method

    > function nthroot (x, n) local r = 1; for i = 1, 16 do r = (((n - 1) * r) + x / (r ^ (n -   1))) / n end return r end
    > return nthroot(125,3)
    5
    > 
    

    Python version

    >>> def nthroot (x, n):
    ...     r = 1
    ...     for i in range(16):
    ...             r = (((n - 1) * r) + x / (r ** (n - 1))) / n
    ...     return r
    ... 
    >>> nthroot(125,3)
    5
    >>> 
    

提交回复
热议问题