C++ programming Write a function to calculate the power of a number x n for a do
ID: 3910984 • Letter: C
Question
C++ programming
Write a function to calculate the power of a number x n for a double x and integer n, using the “divide and conquer” algorithm. double power(double x, int n); • The “divide and conquer” algorithm is explained below. 1. Safeguard: if x == 0 then return 0. Don’t waste time on technicalities with zero. 2. If n < 0 then return power(1.0/x, -n). 3. Next, if n == 0 then return 1.0. 4. Otherwise note the following (this is the “divide and conquer”). 5. The power function (e.g. math library function “pow(x,n)”) has the following property. pow(x, n) = pow(x, n/2) * pow(x, n/2) // n is even pow(x, n) = x * pow(x, n/2) * pow(x, n/2) // n is odd 6. Therefore the calculation of the powers of x can be implemented recursively. • Write the function power(double x, int n) and implement the “divide and conquer” algorithm. • Submit your function code as your answer.
Explanation / Answer
double power(double x, int n) { if(x == 0) { return 0; } else if(n < 0) { return power(1.0/x, -n); } else if(n == 0) { return 1.0; } else if(n % 2 == 0) { double p = power(x, n/2); return p*p; } else { double p = power(x, n/2); return x*p*p; } }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.