recursion-induction

# recursion-induction - Computer Science 211 Data Structures...

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

Computer Science 211 Data Structures Mount Holyoke College Fall 2009 Topic Notes: Recursion and Mathematical Induction Recursion An important tool when trying to solve a problem is the ability to break the problem down into some number of smaller sub-problems, the solutions to which you can use to solve the original problem. Oftentimes, those sub-problems look a lot like the original problem. In fact, they might be the same problem, just on a smaller set of input data. These kinds of problems often have a self-referential or recursive solution. It’s a strange idea at first – calling the method you’re writing before you’re done writing it. Well, if my method needs to call my method to finish up, how am I ever going to get anywhere? Many algorithms may be recursive. Once you are used to them, they can be easier to understand (and prove correct) than iterative algorithms. Even if you’re fairly comfortable with recursion, I expect that few of you have formally proven properties about recursive algorithms before. We will be doing some of that soon. We start with a simple and classically recursive example: computing a factorial. n ! = n · ( n 1) · ... · 1 We could write a simple method to compute this with a for or while loop. But it is just begging to be solved recursively. n ! is nothing more than n · ( n 1)! . So to compute it, all we do is compute ( n 1)! (which is certainly easier than computing n ! ) and then multiply by n and we have the answer. public static int factorial(int n) { return n * factorial(n-1); } That’s great. We were writing a method to compute factorials anyway, so why not call it? Assum- ing we know how to compute ( n 1)! , we now can compute n ! . Problem: what about 2? 2! = 2 (1!) = 2 1 (0!) = 2 1 0 ( 1!) ... That won’t work. We need to stop the recursion somehow. We need a base case . Well, 1!=1, so let’s stop our factorial when it gets to 1:

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

View Full Document
CS 211 Data Structures Fall 2009 public static int factorial(int n) { if (n == 1) return 1; return n * factorial(n-1); } The keys to a successful recursive solution: identify the base case and make sure the recursive step is making progress toward the solution (closer to the base case). Pros and Cons of Recursion
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 5

recursion-induction - Computer Science 211 Data Structures...

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

View Full Document
Ask a homework question - tutors are online