Perfect Cube in Java
A Perfect Cube is a number that can be represented as the cube of an integer. In simple terms, a number N is a Perfect Cube if:
N = a³, for some integer a
For example, 8 = 2³ and 27 = 3³, so both are perfect cubes.
Examples
Example 1: 27
- Cube root of 27 = 3
- 3 × 3 × 3 = 27
- So, 27 is a Perfect Cube.
Example 2: 30
- Cube root of 30 ≈ 3.107...
- Not an integer
- So, 30 is NOT a Perfect Cube.
Java Program to Check Perfect Cube
public class PerfectCube {
// Function to check if a number is a perfect cube
static boolean isPerfectCube(int num) {
int cubeRoot = (int) Math.round(Math.cbrt(num));
return cubeRoot * cubeRoot * cubeRoot == num;
}
public static void main(String[] args) {
int num = 27;
if (isPerfectCube(num)) {
System.out.println(num + " is a Perfect Cube");
} else {
System.out.println(num + " is NOT a Perfect Cube");
}
}
}
How the Program Works
We use Math.cbrt() to calculate the cube root of the number.
Then we round it to the nearest integer and check if its cube equals the original number.
Practice Challenges
- Print all perfect cubes between 1 and 1000.
- Write a program to find the cube root of a number without using inbuilt functions.
- Given an array of numbers, print only those which are perfect cubes.