代码之家  ›  专栏  ›  技术社区  ›  Aakash Goel

递归如何使运行时内存的使用变得不可预测?

  •  5
  • Aakash Goel  · 技术社区  · 14 年前

    引用自 Code Complete 2 ,

    int Factorial( int number ) {
       if ( number == 1 ) {
          return 1;
       }
       else {
          return number * Factorial( number - 1 );
       }
    }
    

    除了 缓慢的 [ 1 ] 和制造 运行时内存的使用 不可预知的 〔2〕 ,递归版本 这是很难做到的 比迭代版本更容易理解, 如下:

    int Factorial( int number ) {
       int intermediateResult = 1;
       for ( int factor = 2; factor <= number; factor++ ) {
          intermediateResult = intermediateResult * factor;
       }
       return intermediateResult;
    }
    

    我认为缓慢的部分是因为不必要的函数调用开销。

    但是递归如何使运行时内存的使用变得不可预测?

    我们不能总是预测需要多少内存吗(我们知道什么时候递归应该结束)?我认为它会像迭代一样不可预测,但不会再有了。

    3 回复  |  直到 14 年前
        1
  •  3
  •   codymanix    14 年前

        2
  •  1
  •   Community CDub    8 年前

    halting problem

    void u(int x) {
        if (x != 1) {
            u((x % 2 == 0) ? x/2 : 3*x+1);
        }
    }
    

        3
  •  0
  •   darioo    14 年前

    number

    推荐文章