如何计算递归程序的步骤

How would one count the steps of a recursive program

本文关键字:程序 递归 何计算 计算      更新时间:2023-10-16

我知道我需要一个程序计数器,我需要跟踪每个递归调用或步骤,这在for循环中很容易做到,但对于递归程序来说很难。我一直纠结于如何计算所有递归步骤。到目前为止,这就是我所拥有的。我也想过让我的方法void,但有了int,我至少可以根据最后的步骤尝试return counter,但它不起作用。

int fibRec( int x, int counter )
{  
    if (x == 0)
        return  0;
    else if (x == 1)
        return 1;
    else
    {
        counter++;
        return fibRec((x - 1) + (x - 2), counter);
    }
}

这在for循环中很容易做到,但对于递归程序来说很难做到

对不起,你错了——在C++中为递归程序添加计数器之类的东西是很琐碎的。

a) 请注意,不需要全局设置
b) 不需要额外的方法参数。

和往常一样,C++解决方案是创建一个类

作为类的一部分的非静态递归方法将始终具有this指针,从而访问类的任何部分,包括您可能需要的任何数量的添加计数器和报告或方法。

这里有一种可能的方法:

class FibRec
{
public:
   FibRec() : counter(0) {
      std::cout << "FibRec ctor " << counter << std::endl;
   };
   ~FibRec() { // output final value with dtor
      std::cout << "FibRec dtor " << counter << std::endl;
   };
   int exec( int x )
      {
         if (x == 0)       return  0;
         else if (x == 1)  return 1;
         else
         {
            counter++;
            // dbg: std::cout << counter << "  " <<  x << std::endl;
            return (exec(x - 1) + exec(x - 2)); 
            // note -- Fibonacci fix?
         }
      }
private:
   int counter;
};

int t407(void)
{
   FibRec f;   // class instance
   f.exec(5);  // invoke recursive method
   return(0);
}

注意:使用g++,ubuntu 15.10的默认堆栈大小为8M字节。这是大量的递归。

不幸的是,您的代码有一个错误——它"添加"并很快增长到溢出。当计数器为272261时,我的代码显示溢出。您需要修复代码。

我猜这段代码应该是fibonacci,它是两个中间值的和。不是你编码的。

你可能会通过更改你的代码来实现你想要的:

return fibRec((x - 1) + (x - 2), counter);

至:

return (fibRec(x - 1, counter) + fibRec(x - 2, counter));

祝你好运。

您需要将counter作为引用传入:

int fibRec( int x, int &counter )

这样,传入的调用方的本地变量就会更新。此外,您可能需要考虑增加基本情况(0和1)的counter,因为从技术上讲,它们也是步骤。

您可以将变量作为引用传递

void fibRec( int x, int &counter )

或者你可以声明一个全局变量计数器,就像下面的代码一样

int counter = 0;
int fibRec( int x )
{  
    if (x == 0)
        return  0;
    else if (x == 1)
        return 1;
    else
    {
        counter++;
        return fibRec((x - 1) + (x - 2));
    }
}