Find cubic root of a number | C ++ program to find cubic root of a number using Binary Search ; Returns the absolute value of n - mid * mid * mid ; Returns cube root of a no n ; Set start and end for binary search ; Set precision ; If error is less than e then mid is our answer so return mid ; If mid * mid * mid is greater than n set end = mid ; If mid * mid * mid is less than n set start = mid ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double diff ( double n , double mid ) { if ( n > ( mid * mid * mid ) ) return ( n - ( mid * mid * mid ) ) ; else return ( ( mid * mid * mid ) - n ) ; } double cubicRoot ( double n ) { double start = 0 , end = n ; double e = 0.0000001 ; while ( true ) { double mid = ( start + end ) / 2 ; double error = diff ( n , mid ) ; if ( error <= e ) return mid ; if ( ( mid * mid * mid ) > n ) end = mid ; else start = mid ; } } int main ( ) { double n = 3 ; printf ( " Cubic ▁ root ▁ of ▁ % lf ▁ is ▁ % lf STRNEWLINE " , n , cubicRoot ( n ) ) ; return 0 ; }