public class Ch20_4_Exercise // page 741 { public static void main(String[] args) { System.out.println("2^5 = " + twoToThePowerOf(5)); System.out.println("2^16 = " + twoToThePowerOf(16)); System.out.println("2^30 = " + twoToThePowerOf(30)); System.out.println("2^0 = " + twoToThePowerOf(0)); System.out.println("2^-5 = " + twoWithNegative(-5)); System.out.println("2^5 = " + twoWithNegative(5)); } public static int twoToThePowerOf(int n) { if(n>0) return 2*twoToThePowerOf(n-1); // recursive case returns 2*powerOf(n-1) else return 1; // base case is 0 } public static double twoWithNegative(int n) // what about computing 2^-n? { // notice the change to a double since we are dividing by 2 instead of multiplying by 2 if(n>0) return 2.0*twoWithNegative(n-1); else if(n<0) return 1.0/2*twoWithNegative(n+1); else return 1.0; } }