C++ 中的递归函数

发布于 2024-10-22 07:39:34 字数 645 浏览 2 评论 0原文

如果我有这个递归函数:

int mystery(int n) {

if ( n == 0 || n == 1 ||  n ==  2) return  n ;
 return (mystery(n-1) + mystery(n-2) + mystery(n-3))  ;
}

我正在寻找神秘(20)。

如何查明计算函数时执行了多少次加法运算以及计算 mymy(20) 时调用了多少次 Mystery() ?

我尝试添加一些 cout 语句,例如:

int mystery(int n) {
    if ( n == 0 || n == 1 ||  n ==  2) {
      cout << n << endl; 
      return  n ;
    }
        cout << n << endl;
    return (mystery(n-1) + mystery(n-2) + mystery(n-3))  ;
}

但我无法真正理解它,因为输出了一千多个数字。而且我不相信这些 cout 语句能告诉我执行了多少次加法运算以及有多少次调用 Mystery() 来计算 Mystery(20)?

感谢您的任何帮助!

If I have this recursive function:

int mystery(int n) {

if ( n == 0 || n == 1 ||  n ==  2) return  n ;
 return (mystery(n-1) + mystery(n-2) + mystery(n-3))  ;
}

I am working with finding mystery(20).

How can I find out how many addition operations are carried out when calculating the function and how many invocations of mystery() there are in order to calculate mystery(20)?

I tried adding some cout statements like:

int mystery(int n) {
    if ( n == 0 || n == 1 ||  n ==  2) {
      cout << n << endl; 
      return  n ;
    }
        cout << n << endl;
    return (mystery(n-1) + mystery(n-2) + mystery(n-3))  ;
}

But I couldn't really make sense of it since there were over a thousand numbers outputted. And I don't believe those cout statements do much in the way of telling me how many addition operations are carried out and how many invocations of mystery() there are in order to calculate mystery(20)?

Thanks for any and all help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

小傻瓜 2024-10-29 07:39:34

最简单的方法是增加全局(或静态全局)变量。

类似于获取神秘呼叫的数量:

int nb_of_invok = 0;
int mystery(int n)
{
  nb_of_invok++;
  ...your code here...
}

这可以获取添加的数量:

int nb_of_invok = 0;
int nb_of_add = 0;
int mystery(int n)
{
  nb_of_invok++;
  if(...)return n;
  nb_of_add++;
  return(...);
}

The easiest way to do is to increment a global (or static global) variable.

Something like to get the number of mystery call:

int nb_of_invok = 0;
int mystery(int n)
{
  nb_of_invok++;
  ...your code here...
}

And this to get the number of additions:

int nb_of_invok = 0;
int nb_of_add = 0;
int mystery(int n)
{
  nb_of_invok++;
  if(...)return n;
  nb_of_add++;
  return(...);
}
昨迟人 2024-10-29 07:39:34

如果我理解正确的话...您可以使用静态计数器变量并在每次调用该方法时递增该变量。或者,您可以传递对计数器的引用并仅递增该引用。

If I'm understanding you correctly... you can use a static counter variable and increment that every time you call the method. Alternatively, you can pass around a reference to the counter and just increment that.

乖乖兔^ω^ 2024-10-29 07:39:34

这可以用数学来算出来。但如果您想凭经验测量它,您可以在函数中使用静态计数器。这个逻辑也很容易扩展到计算加法的数量。

int mystery(int n) {
    static int invocations = 1;

    cout << "mystery has been invoked " << invocations++ << " times.\n";
    if ( n == 0 || n == 1 ||  n ==  2) {
      return  n ;
    }
    return (mystery(n-1) + mystery(n-2) + mystery(n-3))  ;
}

您还可以使用全局变量。但我不喜欢这两种解决方案。它们使多线程变得困难,并且违反了一些重要的设计原则。作为一次性回答这个问题,然后从代码中删除它们很好,但是如果我希望将其作为永久功能,我会做的是:

#include <iostream>

class counted_mystery {
   public:
    counted_mystery() : invocations_(0), additions_(0) { }

    unsigned int getInvocations() const { return invocations_; }
    void resetInvocations(unsigned int newval = 0) { invocations_ = newval; }

    unsigned int getAdditions() const { return additions_; }
    void resetAdditions(unsigned int newval = 0) { additions_ = newval; }

    operator ()(int n) {
        ++invocations_;
        counted_mystery &mystery = *this;

        if ( n == 0 || n == 1 ||  n ==  2) {
          return  n ;
        }
        // The code is about to perform two additions.
        additions_ += 2;
        return (mystery(n-1) + mystery(n-2) + mystery(n-3));
    }

   private:
    unsigned int count_, additions_;
};

int main(int argc, char *argv[])
{
    using ::std::cout;

    counted_mystery mystery;
    mystery(20);
    cout << "mystery was called " << mystery.getCount() << " times for n == 20\n";
    return 0;
};

用数学解决这个问题是一个有趣的问题,但可能也不是太有趣难的。我认为这将会呈指数级增长。

顺便说一句,不要使用 endl 除非那是您想要使用的。它非常慢,因为每当您使用它时它都会强制刷新缓冲区。使用'\n'

This is possible to figure out with math. But if you wanted to measure it empirically, you could use a static counter in the function. This logic is easy to extend to counting the number of additions as well.

int mystery(int n) {
    static int invocations = 1;

    cout << "mystery has been invoked " << invocations++ << " times.\n";
    if ( n == 0 || n == 1 ||  n ==  2) {
      return  n ;
    }
    return (mystery(n-1) + mystery(n-2) + mystery(n-3))  ;
}

You could also use a global variable. I don't like either of those solutions though. They make multi-threading hard, and they violate some important design principles. As a one-off to answer this question and then remove from your code they're fine, but what I would do if I wanted this as a permanent feature is this:

#include <iostream>

class counted_mystery {
   public:
    counted_mystery() : invocations_(0), additions_(0) { }

    unsigned int getInvocations() const { return invocations_; }
    void resetInvocations(unsigned int newval = 0) { invocations_ = newval; }

    unsigned int getAdditions() const { return additions_; }
    void resetAdditions(unsigned int newval = 0) { additions_ = newval; }

    operator ()(int n) {
        ++invocations_;
        counted_mystery &mystery = *this;

        if ( n == 0 || n == 1 ||  n ==  2) {
          return  n ;
        }
        // The code is about to perform two additions.
        additions_ += 2;
        return (mystery(n-1) + mystery(n-2) + mystery(n-3));
    }

   private:
    unsigned int count_, additions_;
};

int main(int argc, char *argv[])
{
    using ::std::cout;

    counted_mystery mystery;
    mystery(20);
    cout << "mystery was called " << mystery.getCount() << " times for n == 20\n";
    return 0;
};

Figuring this out with math is an interesting problem, but likely not too hard. I think it will turn out to be exponential.

BTW, don't use endl unless that's what you mean to use. It's very slow since it forces a buffer flush whenever you use it. Use '\n'.

王权女流氓 2024-10-29 07:39:34

另一种选择是使其成为类的方法,该方法允许使用成员变量而不是全局变量,同时保持 int Mystery(int) 接口干净。

Another option is to make this is method of a class which would allow use of a member variable rather than a global, and at the same time keeps the int mystery(int) interface clean.

堇年纸鸢 2024-10-29 07:39:34

声明两个不同的静态 int 变量来跟踪调用次数和加法运算的次数。

Declare two different static int variables to keep track of number of times invoked and number of addition operations.

樱&纷飞 2024-10-29 07:39:34

使用(并递增)全局变量。 http://www.cplusplus.com/doc/tutorial/variables/

我会请输入一个示例,但我的手受伤了。

Use (and increment) a global variable. http://www.cplusplus.com/doc/tutorial/variables/

I would type an example but I've got a hand injury.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文