Java Program to Find the Cube Root Without Using math.cbrt()
Finding the cube root of a number is a common mathematical operation. While Java provides the
Math.cbrt() function, sometimes we need to calculate the cube root manually.
In this blog, we will calculate the cube root of any number — integer or decimal — without using
the built-in function.
We will use the binary search method, which is efficient and accurate for computing cube roots. This method repeatedly narrows down the range until we get a precise value.
Approach (Binary Search Method)
- Take the number as input.
- Set a low and high range based on whether the number is positive or negative.
- Use binary search to find a value
midsuch thatmid³ ≈ number. - Stop when the precision is within a small threshold (e.g., 0.00001).
Java Program:
import java.util.Scanner;
public class CubeRootWithoutCbrt {
public static double cubeRoot(double num) {
double low, high;
// Determine search range
if (num >= 0) {
low = 0;
high = Math.max(1, num);
} else {
low = Math.min(-1, num);
high = 0;
}
double mid;
// Binary search with precision
while (high - low > 0.00001) {
mid = (low + high) / 2;
if (mid * mid * mid > num)
high = mid;
else
low = mid;
}
return low;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
double num = sc.nextDouble();
double result = cubeRoot(num);
System.out.printf("Cube root of %.5f is: %.5f", num, result);
}
}
Example Output:
Enter a number: 64
Cube root of 64.00000 is: 3.99997
Enter a number: 27
Cube root of 27.00000 is: 2.99999
The output may be slightly less or more than the exact cube root due to floating-point precision, but the accuracy is more than sufficient for practical purposes.
Practice Challenges
- Modify the program to return the result rounded to exactly 3 decimal places.
- Rewrite the cube root logic using the Newton–Raphson method instead of binary search.
- Allow the user to input the precision (for example, 0.01 or 0.0001) dynamically.
This manual cube root approach is helpful for learning algorithms, handling restricted environments, and preparing for interviews.