Is cube root integer?

前端 未结 6 700
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 21:12

This seems to be simple but I cannot find a way to do it. I need to show whether the cube root of an integer is integer or not. I used is_integer() float method

6条回答
  •  星月不相逢
    2020-12-01 21:55

    To elaborate on the answer by @nneonneo, one could write a more general kth-root function to use instead of cube_root,

    def kth_root(n,k):
        lb,ub = 0,n #lower bound, upper bound
        while lb < ub:
            guess = (lb+ub)//2
            if pow(guess,k) < n: lb = guess+1
            else: ub = guess
        return lb
    
    def is_perfect_cube(n):
        return kth_root(n,3) == n
    

提交回复
热议问题