模拟递归思想实现Ackermann函数
#include<iostream>
#include<stack>
using namespace std;
int main()
{
int n, m;
cin >> m >> n;
stack<int>s1, s2;
s1.push(m);
s2.push(n);
//while (!s1.empty() && !s2.empty())一个空另一个一定也空,成双成对的
while (!s1.empty()) {
if (m == 0) {
//要先出栈再判断
while (!s1.empty() && s2.top() != -1) {
s1.pop();
s2.pop();
}
//如果s1空两边都空,如果s2.top==-1,s1,s1不空
if (s2.empty()) {
//说明s1,s2都空
cout << n + 1;
break;
}
else {
//说明s2.top==-1
n++;
m = s1.top();
s2.pop();
s2.push(n);
}
}
else if (n == 0) {
m--;
n = 1;
s1.push(m);
s2.push(n);
}
else {
s1.push(m - 1);
s2.push(-1);
n--;
s1.push(m);
s2.push(n);
}
}
return 0;
}
验证:
ack(0,5) = 6
ack(1,5) = 7
ack(2,4) = 11
ack(3,6) = 509
ack(4,0) = 13