This is the end of the preview. Sign up
to
access the rest of the document.

Unformatted text preview: Recursion Recursion means to define something in terms of itself. It is a powerful problem-solving 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 &gt;= 0, 2 &lt;= base &lt;= MAX_BASE private static void printIntRec(long n, int base) { if (n &gt;= 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 &lt; b , printIntRec prints one digit correctly. • Inductive step k &gt; 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