2
\$\begingroup\$

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
\$\endgroup\$
2
  • 1
    \$\begingroup\$ acker(3, 1) should return 13. Doesn't this return 11? \$\endgroup\$ Commented Jan 24, 2019 at 22:59
  • \$\begingroup\$ It is not working. e.g. Ackerman(3,0) = 5. Yours does give back 4. \$\endgroup\$ Commented Dec 9, 2019 at 12:07

1 Answer 1

2
\$\begingroup\$

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
\$\endgroup\$
1
  • 1
    \$\begingroup\$ "can grow quite large". You sir, have mastered the art of understatement! :-) \$\endgroup\$ Commented Feb 28, 2017 at 23:29

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.