I need to write a recursive method using Java called power that takes a double x and an integer n and that returns x^n. Here is what I have so far.
public static double power(double x, int n) { if (n == 0) return 1; if (n == 1) return x; else return x * (power(x, n-1)); }
This code works as expected. However, I am trying to go the extra mile and perform the following optional exercise:
"Optional challenge: you can make this method more efficient, when n is even, using x^n = (x^(n/2))^2."
I am not sure how to implement that last formula when n is even. I do not think I can use recursion for that. I have tried to implement the following, but it also does not work because I cannot take a double to the power of an int.
if (n%2 == 0) return (x^(n/2))^2;
Can somebody point me in the right direction? I feel like I am missing something obvious. All help appreciated.
Bottom-up. Sometimes the best way to improve the efficiency of a recursive algorithm is to not use recursion at all. In the case of generating Fibonacci numbers, an iterative technique called the bottom-up approach can save us both time and space.
A proper recursive function must always have a base case: The base case is a way to return without making a recursive call. In other words, it is the mechanism that stops this process of ever more recursive calls and an ever growing stack of function calls waiting on the return of other function calls.
A recursive algorithm must have a base case. A recursive algorithm must change its state and move toward the base case. A recursive algorithm must call itself, recursively.
It's exactly the same principle as for x^n == x*(x^(n-1)): Insert your recursive function for x^(n/2) and (...)^2, but make sure you don't enter an infinite recursion for n == 2 (as 2 is even, too):
if (n % 2 == 0 && n > 2) return power(power(x, n / 2), 2); }
Alternatively, you could just use an intermediate variable:
if (n % 2 == 0) { double s = power(x, n / 2); return s * s; }
I'd probably just handle 2 as a special case, too -- and avoid the "and"-condition and extra variable:
public static double power(double x, int n) { if (n == 0) return 1; if (n == 1) return x; if (n == 2) return x * x; if (n % 2 == 0) return power(power(x, n / 2), 2); return x * (power(x, n - 1)); }
P.S. I think this should work, too :)
public static double power(double x, int n) { if (n == 0) return 1; if (n == 1) return x; if (n == 2) return x * x; return power(x, n % 2) * power(power(x, n / 2), 2); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With