简体   繁体   English

这个天真的递归fibonacci实现怎么没有stackoverflow?

[英]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#? 这怎么不会导致C#中的stackoverflow? We managed to get to Fib(52) before giving up (and Fib(51) took many hours). 我们设法在放弃之前得到了Fib(52)(而Fib(51)花了很多时间)。 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. 我认为这会严重破坏堆栈以导致堆栈溢出,因为CLR默认只将1M分配给堆栈。 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). 递归调用不是同时计算的,而是顺序计算的,这意味着Fib(n - 2)将仅在Fib(n - 1) (或相反的方式)计算。 This means that even though you create 2^n recursive calls, only n will be active at the same time. 这意味着即使您创建了2^n递归调用,也只有n同时处于活动状态。 Therefore Fib(52) will only need space for 52 stackframes of Fib , which doesn't take any noticable stack space. 因此, Fib(52)将仅需要空间用于52Fib堆栈帧,其不占用任何显着的堆栈空间。

The naive Fibonacci implementation indeed generates a large number of function calls (equal to the result, in fact), but it doesn't recurse very deeply. 天真的Fibonacci实现确实会产生大量的函数调用(实际上等于结果),但它并没有非常深入地进行递归。 The maximum depth of recursion is n . 最大递归深度为n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM