Unit05 - Recursion Recursion "To understand recursion, you...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
1 1 Recursion "To understand recursion, you must first understand recursion" 5 2 Recursion A recursive function is a function that is defined in terms of itself. Every recursive definition must have a base case that is not recursive. The non-recursive nature of the base case allows us to then solve previous recursive steps. There can be more than one base case. 3 Factorial n! = n * (n-1) * (n-2) * . .. * 2 * 1 for n > 0 = 1 for n = 0 But, since (n-1)! = (n-1) * (n-2) * 2 * 1, we can use recursion to define the factorial function: n! = n * (n-1)! for n > 0 = 1 for n = 0 (base case) Example: 4! = 4*3! = 4*(3*2!) = 4*(3*(2*1!)) = 4*(3*(2*(1*0!))) = 4*(3*(2*(1*1))) = 4*(3*(2*1)) = 4*(3*2) = 4*6 = 24 4 Factorial in Java public static int factorial(int n) { // Precondition: n >= 0 int result; if (n == 0) result = 1; else result = n * factorial(n-1); return result; ! } 5 Improved Factorial public static int factorial(int n) { if (n < 0) throw new IllegalArgumentException(); int result; if (n == 0) result = 1; else result = n * factorial(n-1); return result; ! } 6 Another Factorial public static int factorial(int n) { if (n < 0) throw new IllegalArgumentException(); return fact(n, 1); } private static int fact(int n, int total) { if (n == 0) return total; return fact(n-1, n*total); ! } tail recursive
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 7 Tail Recursion A tail recursive method can always be converted into an iterative one. Which is more efficient? public static int factorial(int n) { // Precondition: n >= 0 int result = 1; for (int k = 1; k <= n; k++) result *= k; return result; ! } 8 Recursion and the Run-Time Stack rest of run-time stack n 3 result ret addr n 4 result ret addr Activation record ... int x = factorial(4); ... public static int factorial(int n) { // Precondition: n >= 0 int result; if (n == 0) result = 1; else result = n * factorial(n-1); return result; ! } n 2 result ret addr n 1 result ret addr n 0 result ret addr 9 Fibonacci Numbers 1 1 2
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 12/19/2009 for the course CS 121 taught by Professor Reid-miller during the Spring '09 term at Carnegie Mellon.

Page1 / 6

Unit05 - Recursion Recursion "To understand recursion, you...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online