Towers of HanoiTopPowers

Powers

Our earlier examples of programs using recursion involved recursive structures - classes that included instance variables with the same interface as the class itself. Another form of recursion is based on integers. The idea is the same as before - more complicated cases are solved by invoking the method on simpler cases.

Let's look at a recursive program to raise numbers to powers:

    /** 
      * @param exponent >= 0 
      * @returns base raised to exponent
    power 
    **/ 
    public int power(int base, int exponent) { 
       if (exponent == 0) {
          return 1; 
       } else {
          return base * power(base,exponent-1);
       }
    }

The key is that we are using the facts that b0 = 1 and be+1 = b*be to calculate powers. Because we are calculating complex powers using simpler powers we eventually get to our base case.

Using a simple modification of the above recursive program we can get a very efficient algorithm for calculating powers. In particular, if we use either of the above programs it will take 1024 multiplications to calculate 31024. Using a slightly cleverer algorithm we can cut this down to only 11 multiplications!

    /*
     * @param exponent >= 0
     * @returns base raised to exponent power
     */ 
    public int fastPower(int base, int exponent) {
        if (exponent == 0) 
      return 1;
        else if (exponent%2 == 1)       // exponent is odd
      return base * fastPower(base, exponent-1);
        else                            // exponent is even 
      return fastPower(base * base, exponent / 2);
    }

The full source code appears in the following:

Demo: Powers

See the text for details as to why this program is so efficient.

We can both write and understand recursive programs as follows:

  1. Write the base case. Convince yourself that this works correctly.
  2. Write the "recursive" case.

Towers of HanoiTopPowers