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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With