简体   繁体   English

这个函数被调用了多少次?

[英]How many times is this function called?

I have this subalgorithm on recursion and I know that it's called 5 times, but I don't understand why.我有这个关于递归的子算法,我知道它被调用了 5 次,但我不明白为什么。 The initial values are m=1, n=2.初始值为 m=1,n=2。

I've thought the function is called for 7 times.我认为该函数被调用了 7 次。

int Ack(int m, int n)
{
    if (m==0) 
        return n+1;
    else 
         {
            if (m>0 && n==0) 
                return Ack(m-1,1);
            else 
                return Ack(m-1,Ack(m,n-1));
        }
}

I expect that it's called 7 times or even more, but the actual number is 5.我预计它会被调用 7 次甚至更多,但实际数量是 5。

This how 7 is arrived at: 7 是这样得出的:

  1. Ack(1,2)确认(1,2)
  2. Ack(0,Ack(1,1))确认(0,确认(1,1))
  3. Ack(1,1)确认(1,1)
  4. Ack(0,Ack(1,0))确认(0,确认(1,0))
  5. Ack(1,0)确认(1,0)
  6. Ack(0,1), a function which returns 2. Ack(0,1)=Ack(1,0)=2 ==> Ack(0,1),一个返回 2 的函数。 Ack(0,1)=Ack(1,0)=2 ==>
  7. Ack(0,2) (we came back to number 4) = 3 Ack(0,2)(我们回到数字 4)= 3
  8. Ack(0,3) (we came back to number 2) Ack(0,3)(我们回到了数字 2)

您重复计算了 2 个调用:#7 与 #4 相同,#8 与 #2 相同(仅显示Ack返回的值):“回来”与调用不同。

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

相关问题 计算一个函数被调用的次数 - Counting how many times a function is called 计算一次 function 被调用多少次 - Count how many times a function is called in a time 如何执行多次调用的函数,只执行一次! - How to execute a function called many times, only once ! 调用构造函数的次数是多少? - How many times the constructors are called? google mock - 怎么说“必须使用某个参数调用一次函数,但可以使用不同的参数调用多次”? - google mock - how to say “function must be called ONCE with a certain parameter but ok to be called many times with different parameters”? 复制 ctor 在下面被调用了多少次? - How many times the copy ctor is called in the following? 无论我运行同一个应用程序多少次,应用程序(.exe)中的函数都应该只调用一次 - A Function in an application(.exe) should be called only once regardless of how many times I run the same application 跟踪在 C++ 中调用递归函数的次数 - Keep track of how many times a recursive function has been called in C++ 在curl_easy_setopt()中设置的回调函数将被调用多少次? - How many times the callback function would be called which is set in curl_easy_setopt()? 如何最小化调用递归函数的次数 - How to minimize the times a recursive function is called
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM