用c语言编写一个函数(Ackermann):当m=0时,Ack(m,n)=n+1;当m!=0,n=0时,Ack(m,n)=Ack(m-1,n);当m!=0,n!=0时,Ack(m,n)=Ack(m-1,Ack(m,n-1))。写出此递归算法,并计算Ack(2,1)计算
时间: 2024-05-16 09:12:04 浏览: 56
递归子程序计算ackermann函数ACK(m,n)
5星 · 资源好评率100%
函数Ackermann的递归算法实现如下:
```
int Ackermann(int m, int n) {
if (m == 0) {
return n + 1;
} else if (n == 0) {
return Ackermann(m - 1, 1);
} else {
return Ackermann(m - 1, Ackermann(m, n - 1));
}
}
```
那么,计算Ack(2,1)的结果为:
```
Ackermann(2, 1) = Ackermann(1, Ackermann(2, 0))
= Ackermann(1, Ackermann(1, 1))
= Ackermann(1, Ackermann(0, Ackermann(1, 0)))
= Ackermann(1, Ackermann(0, Ackermann(0, 1)))
= Ackermann(1, Ackermann(0, 2))
= Ackermann(1, 3)
= Ackermann(0, Ackermann(1, 2))
= Ackermann(0, Ackermann(0, Ackermann(1, 1)))
= Ackermann(0, Ackermann(0, Ackermann(0, Ackermann(1, 0))))
= Ackermann(0, Ackermann(0, Ackermann(0, 2)))
= Ackermann(0, Ackermann(0, 3))
= Ackermann(0, 4)
= 5
```
因此,Ack(2,1)的结果为5。
阅读全文