Here is what I have for my solution:
public int powerN(int base, int n) {
if(n == 0)
return 1;
else if(n % 2 == 0)
return base * base;
else
return base * powerN(base, n-1);
}
However, if n > 3 then this function doesn't work. For instance, powerN(2, 4) yields 4 and powerN(2, 5) yields 8. I know that a much simpler solution exists, but it just bothers me that I can't figure out why this is not working correctly.
else if(n % 2 == 0)
return base * base;
This bit is incorrect — it returns the square for any even power, not just 2. It looks like you’re trying to implement the square and multiply optimization. So if you want to compute powerN(base, n)
, what recursive call can you make that takes advantage of the fact that n
is even? What new values will you pass in for base
and n
? Use the identity that b2n = (b2)n.
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