This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: Last Time: * The stack: calling multiple funcitons * Recursion: base case, inductive step * Recursive functions: factorial, numOnes Today: * The recursion "space problem": * what it is, and how to fix it * Tailrecursion: a "small" recursive twist * Testing programs ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ So far, we've introduced the notion of recursive problems and, correspondingly, recursive functions. Something is recursive if it refers to itself. A problem is recursive if it has: * One or more trivial base cases * Other cases defined in terms of smaller problem instances. (these are "inductive steps") A function is recursive if it calls itself. We then gave a few examples of how to map from recursive definitions to recursive functions: identify the base case, and write that down. Then, write the inductive step as a recursive call. Last time, I left you with the following question: Let's consider the resource costs of the recursive version of factorial: int factorial(int x) { if (x == 0) { return 1; } else { return x * factorial(x1); } } Compare this to a version with a loop: int fact_iter(int x) { int result = 1; while (x) { result *= x; x; } return result; } Questions for the class, small groups ~5 minutes: * How many multiplications does each version perform? * How much space does each one require? The recursive version is much less efficient in terms of space! Happily, there is a way to rewrite the recursive version to use (approximately) the same amount of space as is required by the iterative version. Consider the following implementation: int fact_helper(int n, int result) // REQUIRES: n >= 0 // EFFECTS: returns result * n! { if (n == 0) { return result; } else { return fact_helper(n1, result * n); } } int factorial(int num) // REQUIRES: n >= 0 // EFFECTS: returns num! { return fact_helper(num, 1); } This function is equivalent to the original factorialwe'll prove this by induction. There are two steps to any indutive proof. First, prove the base case, and second, the inductive step. First, let's state the hypothesis: fact_helper (n, r) = n! * r Naturally, if this is true, then fact_helper(n, 1) would be n!, and factorial() would be correct. So, it's a pretty useful hypothesis. ;) First, the base case: if n=0, the fact_helper(0,r) = r = 1 * r = (0!) * r so, the hypothesis holds for the base case. next, let's prove that if the hypothesis holds for step n1, it also holds for n: we know that if n > 0: fact_helper(n, result) = fact_helper(n1,result*n) by our hypothesis, this is = (n1)! * (result*n) = ((n1)! * n) * result : = n! * result so, given that our hypothesis holds for n1, it also holds for n....
View
Full Document
 Winter '08
 NOBLE
 Recursion

Click to edit the document details