import java.util.Scanner; import java.util.StringTokenizer; /** Formula4.java -- (this version has diagnostic output) */ public class Formula4 { private static int invocations = 0; public static void main(String [] args) { System.out.print("Enter two positive integers: "); Scanner kbd = new Scanner(System.in); String line = kbd.nextLine(); StringTokenizer tok = new StringTokenizer(line, ", "); int a = Integer.parseInt(tok.nextToken()); int b = Integer.parseInt(tok.nextToken()); System.out.printf("You entered %d and %d\n", a, b); int expValue = exp(a, b); System.out.printf("%d to the %d is %d\n", a, b, expValue); int pascalValue = pascal(a, b); System.out.printf("pascal() invoked %d times.\n", invocations); System.out.printf("Number in row %d col %d of Pascal's triangle = %d\n", a, b, pascalValue); } public static int exp(int a, int b) { System.out.printf("exp(%d, %d): start\n", a, b); if (b == 0) { System.out.printf("exp(%d, %d): base case, returning 1\n", a, b); return 1; } else if (b % 2 == 0) { System.out.printf("exp(%d, %d): Even case, making recursive call" + " to exp(%d, %d)\n", a, b, a, b/2); int returnValue = exp(a, b/2); System.out.printf("exp(%d, %d): After recursive call, squaring %d " + "to return %d\n", a, b, returnValue, returnValue * returnValue); return returnValue * returnValue; } else { System.out.printf("exp(%d, %d): Odd case, making recursive call to " + "exp(%d, %d)\n", a, b, a, b-1); int returnValue = exp(a, b-1); System.out.printf("exp(%d, %d): After recursive call, multiplying " + "base %d by %d to return %d\n", a, b, a, returnValue, a*returnValue); return a * returnValue; } } public static int pascal(int a, int b) { ++invocations; System.out.printf("pascal(%d, %d): start\n", a, b); if (a == b || b == 0) { System.out.printf("pascal(%d, %d): base case, returning 1\n", a, b); return 1; } else if (b > a) { System.out.printf("pascal(%d, %d): base case, returning 0 - " + "we are outside triangle\n", a, b); return 0; } else { System.out.printf("pascal(%d, %d): Making left recursive call to " + "pascal(%d, %d)\n", a, b, a, b-1); int leftValue = pascal(a-1, b-1); System.out.printf("pascal(%d, %d): Left recursive call came back " + "with %d\n", a, b, leftValue); System.out.printf("pascal(%d, %d): Making right recursive call to " + "pascal(%d, %d)\n", a, b, a-1, b); int rightValue = pascal(a-1,b); System.out.printf("pascal(%d, %d): Right recursive call came back " + "with %d\n", a, b, rightValue); System.out.printf("pascal(%d, %d): After recursive calls, returning " + "%d\n", a, b, leftValue + rightValue); return leftValue + rightValue; } } }