// CSE 143, Winter 2010, Marty Stepp // This program demonstrates a recursive pow method that // performs exponentiation recursively. public class Powers { public static void main(String[] args) { System.out.println(pow(3, 4)); System.out.println(pow(2, 8)); System.out.println(pow(2, 24)); System.out.println(pow(10, 3)); } // Returns (base) raised to the (exponent) power, recursively. // Precondition base >= 0 and exponent >= 0 public static int pow(int base, int exponent) { if (exponent < 0) { throw new IllegalArgumentException(); } if (exponent == 0) { // base case return 1; } else if (exponent % 2 == 0) { // recursive case 2 // optimization: 3^12 == (3^2)^6 return pow(base * base, exponent / 2); } else { // recursive case 1 return base * pow(base, exponent - 1); } } // 7^4 == 7 * 7^3 // == 7 * 7^2 // == 7 * 7^1 // == 7 * 7^0 // == 1 }