Is cube root integer?

前端 未结 6 691
爱一瞬间的悲伤
爱一瞬间的悲伤 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 22:19

    For small numbers (<~1013 or so), you can use the following approach:

    def is_perfect_cube(n):
        c = int(n**(1/3.))
        return (c**3 == n) or ((c+1)**3 == n)
    

    This truncates the floating-point cuberoot, then tests the two nearest integers.

    For larger numbers, one way to do it is to do a binary search for the true cube root using integers only to preserve precision:

    def find_cube_root(n):
        lo = 0
        hi = n
        while lo < hi:
            mid = (lo+hi)//2
            if mid**3 < n:
                lo = mid+1
            else:
                hi = mid
        return lo
    
    def is_perfect_cube(n):
        return find_cube_root(n)**3 == n
    

提交回复
热议问题