简体   繁体   中英

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. The initial values are m=1, n=2.

I've thought the function is called for 7 times.

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.

This how 7 is arrived at:

  1. Ack(1,2)
  2. Ack(0,Ack(1,1))
  3. Ack(1,1)
  4. Ack(0,Ack(1,0))
  5. Ack(1,0)
  6. Ack(0,1), a function which returns 2. Ack(0,1)=Ack(1,0)=2 ==>
  7. Ack(0,2) (we came back to number 4) = 3
  8. Ack(0,3) (we came back to number 2)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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