如何计算阿克曼函数自称的次数?

时间:2014-05-10 05:01:25

标签: c++

#include <iostream>

using namespace std;

long int A(int, int);

int main()
{
    int m, n;
        cout << "Enter two numbers for Ackerman's Function." << endl;
        cin >> m >> n;

        cout << A(m, n) << endl;
}

long int A(int m, int n)
{
    if(m == 0)
    {
        return n+1;
    }
    else if(m > 0 && n == 0)
    {
        return A(m-1,1);
    }
    else if(m > 0 && n > 0)
    {
        int temp = A(m,n-1);
        return A(m-1, temp);
    }
}

这是Ackerman功能的简单代码。我想知道如果m是一个常数,这个Ackerman的函数有多少次将自身称为n的函数?我的大脑爆炸试图解决它。

2 个答案:

答案 0 :(得分:1)

您可以使用count全局变量来查找

#include <iostream>

using namespace std;

long int A(int, int);
int count=0;

int main()
{
    int m, n;
        cout << "Enter two numbers for Ackerman's Function." << endl;
        cin >> m >> n;

        cout << A(m, n) << endl;
        count << " Ackerman's Function runs " << count << " times.";
}

long int A(int m, int n)
{   
    count++;
    if(m == 0)
    {
        return n+1;
    }
    else if(m > 0 && n == 0)
    {
        return A(m-1,1);
    }
    else if(m > 0 && n > 0)
    {
        int temp = A(m,n-1);
        return A(m-1, temp);
    }
}

答案 1 :(得分:0)

int&函数中添加A类型的额外参数:

long int A(int m, int n, int& count)
{   
    count++;

更新原型,并进行匹配的递归调用。

在你的主要功能中:

int count = 0;
cout << A(m, n, count) << endl;
cout << "A calls: " << count << endl;

这避免了全局变量,这是有问题的。