Java Program to Find the Cube Root of Any Number Without Using math.cbrt()

Learn how to calculate the cube root of any number in Java without using the math.cbrt() function. This guide explains an efficient binary search method that works for both integers and decimals.

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)

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

  1. Modify the program to return the result rounded to exactly 3 decimal places.
  2. Rewrite the cube root logic using the Newton–Raphson method instead of binary search.
  3. 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.