Java Program to Check Whether a Number Is a Perfect Cube Without Using math.cbrt()
A number is called a perfect cube if it can be expressed as the cube of an integer. For example, 1, 8, 27, 64, 125, 216, etc., are perfect cubes.
In this blog, we will write a Java program to check whether a number is a perfect cube
without using the Math.cbrt() function. Instead, we will use a simple loop to find the integer whose cube matches the given number.
Steps to Check Perfect Cube:
- Take the number as input.
- Iterate from 1 up to the absolute value of the number.
- Check if
i * i * iequals the number. - If yes, it is a perfect cube; otherwise, it is not.
Java Program:
import java.util.Scanner;
public class PerfectCubeWithoutCbrt {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
boolean isCube = false;
for (int i = 1; i <= Math.abs(num); i++) {
if (i * i * i == num || -i * i * i == num) {
isCube = true;
break;
}
}
if (isCube) {
System.out.println(num + " is a perfect cube.");
} else {
System.out.println(num + " is NOT a perfect cube.");
}
}
}
Example Output:
Enter a number: 64
64 is a perfect cube.
Enter a number: 50
50 is NOT a perfect cube.
This approach is simple, effective, and works for both positive and negative numbers without relying on Java's built-in cube root functions.