Is cube root integer?

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

    In SymPy there is also the integer_nthroot function which will quickly find the integer nth root of a number and tell you whether it was exact, too:

    >>> integer_nthroot(primorial(12)+1,3)
    (19505, False)
    

    So your function could be

    def is_perfect_cube(x): return integer_nthroot(x, 3)[1]
    

    (And because SymPy is open source, you can look at the routine to see how integer_nthroot works.)

提交回复
热议问题