Homework 4 Solutions cs230 Fall 2000 1) power public static double power (double x, int n) { if (n == 0) return 1.0; return x * power (x, n-1); } Number of recursions = n. 2) morePower public static double powerBetter (double x, int n) { if (n == 0) return 1.0; double half = powerBetter (x, n/2); if (n%2 == 0) { return half*half; } else { return half*half*x; } } Number of recursions = log2 (n) Note: make _one_ recursive call and save the result, otherwise the number of recursions is 2 * log2 (n) 3) Ackerman's function public static int ack (int m, int n) { if (m == 0) return n+1; if (n == 0) return ack (m-1, 1); return ack (m-1, ack(m, n-1)); } Yes, I can prove this method terminates. 4) Something useful: here is an iterative version of fibonacci. You need two extra variables (ult and penult) to keep track of the previous two values. Although this is efficient in time (proportional to n) and space (constant), it is difficult to prove correct. public static int fibonacci (int n) { if (n < 2) return 1; int ult = 1; int penult = 1; int next = 0; for (int i=1; i