Find cubic root of a number

Given a number n, find the cube root of n.


Input:  n = 3
Output: Cubic Root is 1.442250

Input: n = 8
Output: Cubic Root is 2.000000

We can use binary search. First we define error e. Let us say 0.0000001 in our case. The main steps of our algorithm for calculating the cubic root of a number n are:

  1. Initialize start = 0 and end = n
  2. Calculate mid = (start + end)/2
  3. Check if the absolute value of (n – mid*mid*mid) < e. If this condition holds true then mid is our answer so return mid.
  4. If (mid*mid*mid)>n then set end=mid
  5. If (mid*mid*mid)

Below is C++ implementation of above idea.

// C++ program to find cubic root of a number
// using Binary Search
#include <bits/stdc++.h>
using namespace std;

// Returns the absolute value of n-mid*mid*mid
double diff(double n,double mid)
    if (n > (mid*mid*mid))
        return (n-(mid*mid*mid));
        return ((mid*mid*mid) - n);

// Returns cube root of a no n
double cubicRoot(double n)
    // Set start and end for binary search
    double start = 0, end = n;

    // Set precision
    double e = 0.0000001;

    while (true)
        double mid = (start + end)/2;
        double error = diff(n, mid);

        // If error is less than e then mid is
        // our answer so return mid
        if (error <= e)
            return mid;

        // If mid*mid*mid is greater than n set
        // end = mid
        if ((mid*mid*mid) > n)
            end = mid;

        // If mid*mid*mid is less than n set
        // start = mid
            start = mid;

// Driver code
int main()
    double n = 3;
    printf("Cubic root of %lf is %lf\n",
           n, cubicRoot(n));
    return 0;


Cubic root of 3.000000 is 1.442250

Time Complexity : O(Log n)

This article is contributed by Madhur Modi .If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:

Writing code in comment? Please use, generate link and share the link here.