C++ MyProgrammingLab problem Define a recursive function double root( double x,
ID: 3562584 • Letter: C
Question
C++ MyProgrammingLab problem
Define a recursive function
double root(double x, int n, double lower, double upper);
that finds the nth root of x to at least 5 digits of precision.
As a precondition, the parameters lower and upper are such that lower^n <= x and upper^n >=x.
You may want to define a recursive a helper function to compute nth powers.
Hint: try a divide and conquer approach similar to the code for square root.
Use only basic operations +, -, * in your code; no <cmath> or other library functions.
By <cmath>, that means you cannot use built-in functions including pow and abs.
Do not write the entire program.
Here is my solution for this problem:
double power(double x, int n)
{
if(n < 0)
{
return 1.0 / power(x,-n);
}
if(n == 0)
{
return 1.0;
}
return x * power(x,n-1);
}
double root(double x, int n, double lower, double upper)
{
const double epsilon = 0.00001;
double low = power(lower,n);
double high = power(upper,n);
double total = low+high;
double average = (total)/2;
double temp = power(average,n);
if(x-temp > epsilon && x-temp < epsilon)
{
if(temp > x)
{
high = average;
return root(x,n,low,high);
}
else
{
low = average;
return root(x,n,low,high);
}
}
else
{
return x;
}
return average;
}
MyProgrammingLab is not accepting this solution. Can someone please post the correct answer to this problem?