I tried implementing a function using binary search to solve the following :
Implement a function root that calculates the n’th root of a number. The function takes a non negative number x and a positive integer n, and returns the positive n’th root of x within an error of 0.001 (i.e. suppose the real root is y, then the error is: |y-root(x,n)| and must satisfy |y-root(x,n)| < 0.001). The key is to find the root without using the STL function.
My code:
double binarysearch(double left,double right, double x, int n){
while(left<right){
double mid = left + (right-left)/2;
double answer = pow(mid,n);
if(fabs(answer - x ) <= DELTA)
return mid;
else if(answer > x )
right = mid - DELTA;
else
left = mid + DELTA;
}
return -1;
}
This reaches a condition where left>right and it returns -1.
Is there a way to implement this using binary search?