Check if a number is the cube of 3
Write a Python program to check whether a number is the cube of 3, and in general whether it is a perfect cube.
27, 28
27 cube of 3: True | perfect cube: True 28 cube of 3: False | perfect cube: False
Approach
- Compare with
3 ** 3; for the general test round the cube root and cube it again.
Solution
for n in [27, 28]: root = round(n ** (1 / 3)) print(n, "cube of 3:", n == 3 ** 3, "| perfect cube:", root ** 3 == n)27 cube of 3: True | perfect cube: True 28 cube of 3: False | perfect cube: False
Line by line
n ** (1/3) is a float cube root such as 3.0000000000000004, so it is rounded before checking.
Learn the concept
New to this topic? Read the lesson, then come back.