How to find integer nth roots?

后端 未结 11 1499
醉酒成梦
醉酒成梦 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 17:00

    I wonder if starting off with a method based on logarithms can help pin down the sources of rounding error. For example:

    import math
    def power_floor(n, k):
        return int(math.exp(1.0 / k * math.log(n)))
    
    def nth_root(val, n):
        ret = int(val**(1./n))
        return ret + 1 if (ret + 1) ** n == val else ret
    
    cases = [
        (124, 3),
        (125, 3),
        (126, 3),
        (1, 100),
        ]
    
    
    for n, k in cases:
        print "{0:d} vs {1:d}".format(nth_root(n, k), power_floor(n, k))
    

    prints out

    4 vs 4
    5 vs 5
    5 vs 5
    1 vs 1
    

提交回复
热议问题