18

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

but

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

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

I'd appreciate any comment.

6
  • Unfortunately that's not a sane way to do it. Commented May 13, 2014 at 2:23
  • @IgnacioVazquez-Abrams Ok!Is there any sane way then? Commented May 13, 2014 at 2:25
  • Not especially. I'd put/find an upper limit and keep a list. Commented May 13, 2014 at 2:27
  • @IgnacioVazquez-Abrams but it wouldn't be accurate in some extent. Commented May 13, 2014 at 2:29
  • 2
    I suspect you're encountering floating point rounding issues with your cube root. If your value differs from an integer by some tiny fraction, you'll see it as a non-integer. Try using a more float-appropriate test: abs((x-round(x))/x) < epsilon (for some small epsilon).
    – Blckknght
    Commented May 13, 2014 at 2:33

8 Answers 8

30

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
8
  • That seems good, but unfortunately my numbers are a bit bigger that $10^{13}.$ Commented May 13, 2014 at 3:15
  • 3
    Then use the binary search approach.
    – nneonneo
    Commented May 13, 2014 at 3:16
  • 2
    For the binary search you can take the logarithm of the input and use it to compute an initial lo and hi, to restrict the search space. Commented May 13, 2014 at 3:41
  • abs(n) < 2**n.bit_length() -> abs(n)**(1/3) < 2**((n.bit_length() + 2) // 3) -> hi = 2**((n.bit_length() + 2) // 3) e.g., for n=10**13 -> hi = 2**15 = 32768
    – jfs
    Commented Jan 21, 2015 at 14:11
  • You don't need the point in n**(1/3.) in python 3. The division always returns a float there, so you can use n**(1/3).
    – xuiqzy
    Commented Jan 30, 2021 at 16:41
6

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.)

0
1

To elaborate on the answer by @nneonneo, one could write a more general kth-root function to use instead of cube_root,

def kth_root(n,k):
    lb,ub = 0,n #lower bound, upper bound
    while lb < ub:
        guess = (lb+ub)//2
        if pow(guess,k) < n: lb = guess+1
        else: ub = guess
    return lb

def is_perfect_cube(n):
    return kth_root(n,3) == n
1

in Python 3.11 you can use math.cbrt

 x = 64
 math.cbrt(x).is_integer

(or)

or use numpy.cbrt

import numpy as np
x = 64
np.cbrt(x).is_integer
3
  • math.cbrt((2**18)**3+1) will test as being an integer even though the argument is not a perfect cube.
    – smichr
    Commented Jan 4 at 18:11
  • This won't work when x^(1/3) >= 2^54 since a standard float in Python (which is not a standard float but a standard double) has only 53 bits of precision for the mantissa.
    – Max
    Commented Apr 5 at 12:59
  • What advantage does this have over using **(1/3) ?
    – qwr
    Commented May 11 at 21:20
1

Thanks for the feedback smichr and Max. Below is the modified script based on your feedback. It should account for large numbers.

# Import `math` module.
import math

# Define `is_integer`
def is_integer(num: float, root: float) -> bool:
    """Return True if the nth root of an number is an integer.

    Args:
        num (float): number to evaluate if it has an integer for the nth root
        root (float): nth root to evaluate the number against

    Returns:
        bool: `True` if the nth root of an integer is a whole number
    """
    try:
        # Calculate the nth root of an integer
        nth_root = num**(1/root)
        print(f'\nThe {root} root of {num} is ~{nth_root}.')
        # Calculate the nearest whole number
        nearest_whole_number = round(nth_root)
        print(f'The nearest whole number to {nth_root} is {nearest_whole_number}')
        # Check if the nth root is close (default: 1e-09) to the nearest whole number
        is_whole_number = math.isclose(nth_root, nearest_whole_number)
        print(f'Is the {root} root of {num} close to a whole number? {is_whole_number}')
        return is_whole_number
    except Exception as e:
        print(f'Review Error: {e}')
        return False

# Call `is_integer` with (2**17)**3 and 3 as arguments
if __name__ == '__main__':
    num = eval(input('Enter a number: '))  # e.g., (2**17)**3 for number
    root = eval(input('Enter a root: '))  # e.g., 3 for root
    print(is_integer(num, root))

Line 2: Import math module.
Line 17: Shortened function.
Line 20: Removed specifying the precision. floating point approximations
Line 23: Use math.isclose() to check if nth root is close to a nearest whole number value.

2
  • Let num = (2**17)**3 and root=3 -- the decimal portion is not 0.
    – smichr
    Commented Jan 4 at 18:15
  • you should certainly not use round(...,10)! Why deliberately discard "precious" digits? But anyways this won't work for large enough numbers. Also, I don't understand why so many ppl would write pow(x,(1/3)) instead of simply pow(x, 1/3) or, shorter and better, x^(1/3).
    – Max
    Commented Apr 5 at 13:02
0

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
1
  • I think it is very inefficient to compute the exact 3rd root which you don't really need. It would be much more efficient to check whether the prime divisors of "number" occur to a power that is a multiple of 3. You start checking for 2 (then 3, 5...) which is extremely fast and will immediately rule out most of the candidates, so only in very few cases you'll have to go up to larger primes. BTW, sympy does have a function perfect_power which does exactly that.
    – Max
    Commented Apr 5 at 13:12
0

I think you should use the round function to get the answer. If I had to write a function then it will be as follows:

def cube_integer(n):
    if round(n**(1.0/3.0))**3 == n:
        return True
    return False

You can use something similar to int(n**(1.0/3.0)) == n**(1.0/3.0), but in python because of some issues with the computation of the value of cube root, it is not exactly computed. For example int(41063625**(1.0/3.0)) will give you 344, but the value should be 345.

0

The module sympy library has two functions that could be useful here, integer_nthroot and perfect_power. The first computes the integer part of the n-th root of a number, and also whether it is the exact result (so True would mean it's a perfect cube). It will do so using integer arithmetic which should be faster and more precise than computations with floats (viz, x**(1/3) = exp(1/3*log(x))).

The function perfect_power should choose the best way to determine whether a number is a perfect power. It will probably check whether all prime divisors p of "number" occur to a power (called the p-valuation of the number, or in sympy, the multiplicity) that have a common greatest divisor g, i.e., all the exponents are a multiple of g. If (and only if) that g is a multiple of 3 you have a perfect cube. Most candidates will be ruled out checking this for the fist few primes, starting with p=2 where you just have to check the number of trailing zero bits, cf. the sympy function trailing().

Obviously this is unnecessarily general for your case: if it finds that the 2-valuation is 10 (= 2*5), it will go on to compute the 3-valuation, say it's 2, then so far we have a commen divisor of 2, and it will go on with the 5-valuation and so on, until the gcd is 1. But we could already stop when we see that 10 isn't a multiple of 3.

So you could do the same thing and stop as soons as the p-valuation isn't a multiple of 3: (Since we want to avoid unnecessary factorization, we don't use factorint which would make it )

import sympy
def is_cube(n: int) -> bool:
    if t := sympy.trailing(n):   # 2-valuation
        if t % 3: return False
        n >>= t  # remove the powers of 2
    p = 3
    while n >= p**3:
        if m: = sympy.multiplicity(p, n):
            if m % 3: return False
            n //= p**m # make the number smaller
            if n == 1: return True
        p = sympy.nextprime(p)
    return False

You start checking for 2 (then 3, 5...) which is extremely fast (the 2-valuation is just the number of trailing zero bits) and will immediately rule out most of the candidates, so only in very few cases you'll have to go up to larger primes. There are also other checks that could be made before searching for very large prime facors if necessary. For example x % 7 must be one of {0, 1, 6} for any 3rd power.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.