Powers |
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:
See the text for details as to why this program is so efficient.
We can both write and understand recursive programs as follows:
Powers |