Find cubic root of a number in C++

C++Server Side ProgrammingProgramming

Here we will see how to get the cubic root of a number. Suppose a number is say 27, then the cubic root of this number is 3. To solve this problem, we will define our own logic without using some library functions. We will use the binary search approach. We have to follow these steps to solve this problem.

Suppose we have threshold value like threshold = 0.000001

  • Start the left value as 0, and right value as number

  • calculate mid := (left + right)/2

  • if the absolute value of (number – mid3) is less than threshold, then return mid as answer

  • if mid3 is greater than number, then set right := mid

  • if mid3 is less than number, then set left := mid

Example

#include<iostream>
#include<cmath>
using namespace std;
   double cubeRoot(int num) {
   double threshold = 0.000001;
   double left = 0, right = num;
   double mid;
   while(left <= right){
      mid = (left + right)/2;
      if(abs(num - (mid*mid*mid)) < threshold)
         return mid;
      if((mid*mid*mid) > num)
         right = mid;
      if((mid*mid*mid) < num)
         left = mid;
   }
}
int main() {
   int n = 3;
   cout << "cube root of 3 is: " << cubeRoot(n);
}

Output

cube root of 3 is: 1.44225
raja
Published on 01-Nov-2019 07:07:38
Advertisements