In the Fibonacci sequence, I have seen conventional implementations which recursively call the same method twice:
public void fibonacci(int i) { fibonacci(1) + fibonacci(2); }
Now this method is not the exact copy of what I have seen or the right way of solving the problem, but I’ve seen the two methods added together like above. So the method isn’t recursively called, but recursively called twice. What exactly happens when writing code like this in C#? Are the two methods run on seperate threads? What is happening under the hood?
This is one of those times when it’s useful to think about the way the computer does it.
Let’s start with the function. I’m going to write it in Python flavored pseudocode because I want you to get away from thinking about the LANGUAGE for a second.
Now let’s walk through this for fib(2)
fib(2)has n>1, so it takes the third branch,so it calls fib() with 0, which is 0
calls fib() with 1
and we see the result 1. Now consider fib(3):
n>1, so
and since 3-2 is 1, we get fib(1) for the first term, which is 1:
and now when we call fib(3-1), which is to say fib(2), we don’t have the direct answer yet; n>1. So it becomes
which becomes
ans we pop back to the earlier call
and get the value 2. So, you see, there’s no separate thread, it just works its way across the expression. I’ll leave it as an exercise to work out an example for fib(4); I bet if you do, though, you’ll have it nailed.
Pop quiz: why is the iterative version so dramatically more efficient?