立方根是整数吗? [英] Is cube root integer?

查看:57
本文介绍了立方根是整数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 in Python 3.4 but that wasn't successful. As

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

但是

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

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

I tried x%1 == 0,x == int(x) and isinstance(x,int) with no success.

感谢您的评论.

推荐答案

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

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 = 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

这篇关于立方根是整数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆