03+-+Tail+Recursion+and+Intro+to+Testing

# 03+-+Tail+Recursion+and+Intro+to+Testing - Recursion...

This preview shows pages 1–2. Sign up to view the full content.

EECS 280 Programming and Introductory Data Structures Recursion Another kind of factorial int fact_helper(int n, int result) // REQUIRES: n >= 0 // EFFECTS: returns result * n! { if (n == 0) { return result; } else { return fact_helper(n-1, result * n); } } int factorial(int num) // REQUIRES: n >= 0 // EFFECTS: returns num! { return fact_helper(num, 1); } Re-write the recursive version to use the same amount of space as is required by the iterative version (approximately). Recursion Group Exercise: Another kind of factorial c This function is equivalent to the original factorial. c Try to come up with a proof for why. c There are two steps. First, prove the base case, and second, the inductive step. int fact_helper(int n, int result) // REQUIRES: n >= 0 // EFFECTS: returns result * n! { if (n == 0) { return result; } else { return fact_helper(n-1, result * n); } } int factorial(int num) // REQUIRES: n >= 0 // EFFECTS: returns num! { return fact_helper(num, 1); } Recursion Another kind of factorial c There is an important thing to notice about fact_helper. c For every call to fact_helper: n! * result == num! c For the first call, this is easy to see, since: n == num result == 1 int fact_helper(int n, int result) // REQUIRES: n >= 0 // EFFECTS: returns result * n! { if (n == 0) { return result; } else { return fact_helper(n-1,result*n); } } int factorial(int num) // REQUIRES: n >= 0 // EFFECTS: returns num! { return fact_helper(num, 1); } Recursion Another kind of factorial c For every call to fact_helper: n! * result == num! c For the second call: n == (num - 1) result == (1*num) == num Substituting, we get: (num-1)! * num == num! c This is true by inspection. You can continue unwinding if you like. int fact_helper(int n, int result) // REQUIRES: n >= 0 // EFFECTS: returns result * n! { if (n == 0) { return result; } else { return fact_helper(n-1,result*n); } } int factorial(int num) // REQUIRES: n >= 0 // EFFECTS: returns num! { return fact_helper(num, 1); } Recursion Another kind of factorial c For every call to fact_helper: n! * result == num! c This is called the “recursive invariant” of fact_helper and is something that is always true. c

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

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

## This note was uploaded on 10/26/2010 for the course EECS 280 taught by Professor Noble during the Fall '08 term at University of Michigan.

### Page1 / 4

03+-+Tail+Recursion+and+Intro+to+Testing - Recursion...

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

View Full Document
Ask a homework question - tutors are online