\$\begingroup\$
\$\endgroup\$
2
Here's an iterative implementation of the Ackermann function for review:
#include <stack>
#include <iostream>
#include <tuple>
#include <vector>
int Ackermann(int m, int n) {
std::stack<int> s;
s.push(m);
while (!s.empty()) {
m = s.top();
s.pop();
if (m == 0 || n == 0)
n += m + 1;
else {
s.push(m - 1);
s.push(m);
n--;
}
}
return n;
}
int main() {
std::vector<std::tuple<int, int, int>> tests{
{ 0, 0, 1},
{ 1, 0, 2},
{ 1, 1, 3},
{ 2, 1, 5}
};
for (auto const &test : tests) {
using std::get;
auto result = Ackermann(get<0>(test), get<1>(test));
if (result == get<2>(test)) {
std::cout << "Ackermann("
<< get<0>(test) << ", "
<< get<1>(test) << ") == "
<< result << ": passed\n";
}
else {
std::cerr << "Error: Ackermann("
<< get<0>(test) << ", "
<< get<1>(test)
<< ": expected" << get<2>(test)
<< ", but got: " << result << "\n";
}
}
}
Any comments appreciated.
asked Feb 28, 2017 at 16:49
-
1\$\begingroup\$ acker(3, 1) should return 13. Doesn't this return 11? \$\endgroup\$Kache– Kache2019年01月24日 22:59:33 +00:00Commented Jan 24, 2019 at 22:59
-
\$\begingroup\$ It is not working. e.g. Ackerman(3,0) = 5. Yours does give back 4. \$\endgroup\$lumpigerAffe– lumpigerAffe2019年12月09日 12:07:27 +00:00Commented Dec 9, 2019 at 12:07
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
The results of the Ackermann function can grow quite large. An int
is only guaranteed to cover up to 32767.
A two-dimensional memorization table would probably be worthwhile.
answered Feb 28, 2017 at 17:25
-
1\$\begingroup\$ "can grow quite large". You sir, have mastered the art of understatement! :-) \$\endgroup\$Jerry Coffin– Jerry Coffin2017年02月28日 23:29:28 +00:00Commented Feb 28, 2017 at 23:29
lang-cpp