Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively compute the value of base to the n power

Tags:

java

recursion

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.

like image 378
kachilous Avatar asked Dec 27 '22 21:12

kachilous


1 Answers

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 b2‌n = (b2)n.

like image 122
Josh Lee Avatar answered Jan 12 '23 08:01

Josh Lee