Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this naive recursive fibonacci implementation not stackoverflow?

As a joke a few months ago, a coworker of mine sought out to "speed up the heat death of the universe" by calculating fibonacci numbers using this exponential algorithm:

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

How does this not cause a stackoverflow in C#? We managed to get to Fib(52) before giving up (and Fib(51) took many hours). I would think this would hammer the stack hard enough to cause a stack overflow, since the CLR by default only allocates 1M to the stack. Also, I'm pretty sure this isn't eligible for tail recursion either.

like image 837
Earlz Avatar asked Mar 07 '13 20:03

Earlz


1 Answers

The recursive calls are not computed at the same time, but sequentially, meaning that Fib(n - 2) will only compute after Fib(n - 1) (or the other way around). This means that even though you create 2^n recursive calls, only n will be active at the same time. Therefore Fib(52) will only need space for 52 stackframes of Fib, which doesn't take any noticable stack space.

like image 188
Grizzly Avatar answered Sep 18 '22 10:09

Grizzly