recursion

recursion - Introduction My friend and I recently had a...

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

View Full Document Right Arrow Icon
My friend and I recently had a competition to see who could write the shortest method to calculate a factorial. We had a few basic ground rules: the method will take an int, which I may assume is non- negative, and will return the factorial of that number (Recall: n factorial is written n! and is equal to: n * (n-1) * (n-2) * . . . * 1). Here was my solution: static int factorial1(int n) { int fact = 1; for (int i=n; i >= 1; i--) { fact = fact*i; } return fact; } I was pretty confident that I would win: that's a pretty short method. My friend, however, came up with a shorter one: static int factorial2(int n) { return n*factorial1(n - 1); } I said that he couldn't do that: his method doesn't work. He said it does though, as long as the method I wrote worked: This would give the correct answer, because one of the definitions of the factorial function is that n! = n*(n - 1)!, with 0! = 1. So I asked him, "All you need there is any method that works, right? Then your method will work?" He said it would. So I said, "So, if your method works, why can't you use that one, like this:" static int factorial2(int n) { return n*factorial2(n-1); } So we decide to try it out. We called his function with 4 as the parameter. This then called factorial2(3), which called factorial2(2), then factorial2(1), factorial2(0), factorial2(-1), . .. The program never ended. So we decided there was a problem: we needed some way to stop the sequence. Since factorials do not exist for negative numbers, we decided that if somebody passed us a 0, this would be a good time to stop calling the method. So, we ended up with this last method: static int factorial3(int n) { if (n == 0) { return 1;
Background image of page 1

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

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 4

recursion - Introduction My friend and I recently had a...

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

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