简体   繁体   中英

Finding the value of Recursive Ackermann Function

What is wrong in my code? It doesn't return the correct answer,

#include <iostream>
using namespace std;

int ack(int m, int n)
{
    if (m == 0) return n + 1;

    if(n == 0) return ack(m - 1, 1);

    return ack(m - 1, ack(m, n - 1));

}

int main()
{
    cout << ack(4, 1) << endl;
    return 0;
}

Here is the output:

在此处输入图像描述

Thanks.

Compiling it with a C compiler, instead of C++ , your ack() function returned correctly, 65533, for me in about 20 seconds.

Using a recursive algorithm from RosettaCode that isn't doubly recursive like yours, returns the correct value in about 10 seconds:

int ack(int m, int n)
{
    for (; m > 0; m--) {
        n = (n == 0) ? 1 : ack(m, n - 1);
    }

    return n + 1;
}

Since you're not going to reach higher Ackermann values with this code, I don't see the point in going much faster .

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