Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation on Fibonacci Recursion

I must understand something about this. It seems like there is no good guide to explain explicitly. What does the function tree look like?

static long Fib(int n)
{  
    if (n <= 2)  
    {   
        return 1;  
    }  
    return Fib(n - 1) + Fib(n - 2); 
}

Assuming I do Fib(7), I actually understand that it should look like this:

The thing is that it seems like the tree is presented as if fib(7) actually means fib(6) + fib(5) which should be true.... However, if I understand recursion than fib(7) is actually fib(6) + fib(5) but fib(5) isn't operated yet since fib(6) will now call itself to fib(4) + fib(3) and once again fib(3) won't be executed since fib(4) will call itself until it stops at the "stop" condition... and than what?

If fib(7) calls fib(6) and so on..... until fib(1), what about all of the other fib(n-2) functions?

How does it actually returns each time the result and tell me what is the value of fib(7)?

like image 500
N3wbie Avatar asked Mar 12 '16 14:03

N3wbie


People also ask

How does Fibonacci work in recursion?

Fibonacci Series Using Recursion in C refers to a number series. The Fibonacci series is created by adding the preceding two numbers ahead in the series. Zero and one are the first two numbers in a Fibonacci series. We generate the rest of the numbers by adding both the previous numbers in the series.

What kind of recursion is Fibonacci?

Write a tail recursive function for calculating the n-th Fibonacci number. A recursive function is tail recursive when the recursive call is the last thing executed by the function.

How does Fibonacci function work?

The Fibonacci sequence is a set of integers (the Fibonacci numbers) that starts with a zero, followed by a one, then by another one, and then by a series of steadily increasing numbers. The sequence follows the rule that each number is equal to the sum of the preceding two numbers.


1 Answers

It doesn't return a value each time, at least not immediately.

Every time the method calls itself, it places the new call on a stack. There's limited space on this stack, so a big number with enough recursive calls will throw a stackoverflow exception. That's also why you have this terminating condition, that tells it when to stop calling itself.

if (n <= 2)  
{   
    return 1;  
}

After your method calls itself for the very last time on each branch of the tree (when n <= 2 and the method returns 1 instead of calling itself), it will unwind the stack, finally evaluating all of those calls and summing up the return values, returning 13 in the case of Fib(7).

like image 153
Grant Winney Avatar answered Oct 04 '22 10:10

Grant Winney