gpt4 book ai didi

python - 立方根是整数吗

转载 作者:太空狗 更新时间:2023-10-29 17:54:27 26 4
gpt4 key购买 nike

这看起来很简单,但我找不到实现它的方法。我需要显示整数的立方根是否为整数。我在 Python 3.4 中使用了 is_integer() float 方法,但没有成功。作为

x = (3**3)**(1/3.0) 
is_integer(x)
True

但是

x = (4**3)**(1/3.0) 
is_integer(x)
False

我尝试了 x%1 == 0x == int(x)isinstance(x,int) 但没有成功.

如有任何评论,我将不胜感激。

最佳答案

对于小数字(<~1013 左右),您可以使用以下方法:

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

这会截断浮点立方根,然后测试两个最接近的整数。

对于较大的数字,一种方法是仅使用整数对真正的立方根进行二进制搜索以保持精度:

def find_cube_root(n):
lo = 0
hi = 1 << ((n.bit_length() + 2) // 3)
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

关于python - 立方根是整数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23621833/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com