Is cube root integer?

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

    If your numbers aren't big, I would do:

    def is_perfect_cube(number):
        return number in [x**3 for x in range(15)]
    

    Of course, 15 could be replaced with something more appropriate.

    If you do need to deal with big numbers, I would use the sympy library to get more accurate results.

    from sympy import S, Rational
    
    def is_perfect_cube(number):
        # change the number into a sympy object
        num = S(number)
        return (num**Rational(1,3)).is_Integer
    

提交回复
热议问题