Check if a Number is a Perfect Cube

problem-solving
Published

July 18, 2023

Perfect cubes are numbers that can be obtained by raising an integer to the power of 3. For example, 8 is a perfect cube (2³ = 8), 27 is a perfect cube (3³ = 27), and so on. This blog post explores different methods in Python to efficiently determine if a given number is a perfect cube.

Method 1: Using the round() function and cube root

This method leverages the fact that the cube root of a perfect cube will be an integer. We can calculate the cube root using the ** operator (exponentiation) with an exponent of 1/3. However, due to floating-point precision limitations, the result might not be exactly an integer even if the input is a perfect cube. Therefore, we use the round() function to round the result to the nearest integer and check if it’s equal to the original cube root.

import math

def is_perfect_cube_method1(n):
  """
  Checks if a number is a perfect cube using the round() function.

  Args:
    n: The number to check.

  Returns:
    True if n is a perfect cube, False otherwise.
  """
  if n < 0:
    return False # Negative numbers cannot be perfect cubes of positive integers.
  cube_root = round(n**(1/3))
  return cube_root**3 == n

print(is_perfect_cube_method1(8))   # Output: True
print(is_perfect_cube_method1(27))  # Output: True
print(is_perfect_cube_method1(10))  # Output: False
print(is_perfect_cube_method1(-8)) # Output: False

Method 3: Integer Cube Root using round() (Improved)

This method is similar to Method 1 but addresses potential inaccuracies by using int() to ensure we’re dealing with integers throughout the process.

def is_perfect_cube_method3(n):
    """Checks if a number is a perfect cube using int() for improved accuracy."""
    if n < 0:
        return False
    cbrt = int(round(n**(1/3)))
    return cbrt**3 == n

print(is_perfect_cube_method3(8))   # Output: True
print(is_perfect_cube_method3(27))  # Output: True
print(is_perfect_cube_method3(10))  # Output: False
print(is_perfect_cube_method3(-8)) # Output: False

Each method offers a different approach to solving this problem. The choice of method depends on factors such as the expected range of input numbers and the desired balance between code simplicity and computational efficiency. Method 2 (Binary Search) generally provides better performance for very large numbers. Method 3 offers a concise and generally accurate solution.