This preview shows pages 1–2. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: Recursion Recursion means to define something in terms of itself. It is a powerful problemsolving technique. Example: Printing a number in any base What is the number 83790 in base 8. Yes, the answer is 243516 8 . And how did you find it? It’s easy to find the last digit of a number n in base 8: It’s n mod 8 ( n % 8 in Java). The remaining digits are the representation of n/ 8 in base 8. The following method implements this recursive strategy: // Print n in any base, recursively // Precondition: n >= 0, 2 <= base <= MAX_BASE private static void printIntRec(long n, int base) { if (n >= base) printIntRec(n / base, base); System.out.print(DIGIT_TABLE.charAt((int) (n % base))); } To design a recursive function, do not try to mentally simulate how the program is executed. Instead, reason about your method by assuming that the recursive call works correctly, and then argue that the method itself will do the right thing. This is entirely analogous to a proof by mathematical induction, and when we want to prove that a recursive method works correctly, we also use a proof by induction. For example, to prove that the method printIntRec is correct, we use induction on k , where k is the number of digits of n in base b . • Base case k = 1: Since 0 ≤ n < b , printIntRec prints one digit correctly. • Inductive step k > 1: We assume that printIntRec works correctly for numbers with less than k digits. Consider now a number n with k digits in base b . Then n/b has k 1 digits. By the induction1 digits....
View Full
Document
 Fall '09
 Lee
 Recursion

Click to edit the document details