0

我最近偶然发现了Ackermann 函数,它使用一种“嵌套递归”来计算一个值。我在 C++ 中实现了我自己的函数,它缓存中间结果以加快计算速度(比较没有缓存的实现)。

问题:

ackermann最终将耗尽堆栈空间。您应该如何实现一个执行“深度递归”(多次调用自身)而不用完堆栈空间的函数?

我的实现:

玩它!

#include <iostream>
#include <map>
#include <tuple>

std::map<std::tuple<int, int>, int> cache;

int ackermann(int n, int m)
{
    if (cache.count(std::tuple<int, int>(n, m)))
    {
        return cache.at(std::tuple<int, int>(n, m));
    }
    if (n == 0)
    {
        cache.insert(std::pair<std::tuple<int, int>, int>(std::tuple<int, int>(n, m), m + 1));
        return m + 1;
    }
    else
    {
        if (m == 0)
        {
            int tmp = ackermann(n - 1, 1);
            cache.insert(std::pair<std::tuple<int, int>, int>(std::tuple<int, int>(n-1, 1), tmp));
            return tmp;
        }
    }
    int tmp = ackermann(n, m - 1);
    cache.insert(std::pair<std::tuple<int, int>, int>(std::tuple<int, int>(n, m - 1), tmp));
    int tmp2 = ackermann(n - 1, tmp);
    cache.insert(std::pair<std::tuple<int, int>, int>(std::tuple<int, int>(n - 1, tmp), tmp2));
    return tmp2;
}

int main()
{
    for (int i = 0; i < 7; ++i)
    {
        for (int j = 0; j < 7; ++j)
        {
            std::cout << "ackermann of i=" << std::to_string(i) << ", j=" << std::to_string(j) << " is " << std::to_string(ackermann(i, j)) << '\n';
        }
    }
}

输出:

ackermann of i=0, j=0 is 1
ackermann of i=0, j=1 is 2
ackermann of i=0, j=2 is 3
ackermann of i=0, j=3 is 4
ackermann of i=0, j=4 is 5
ackermann of i=0, j=5 is 6
ackermann of i=0, j=6 is 7
ackermann of i=1, j=0 is 2
ackermann of i=1, j=1 is 3
ackermann of i=1, j=2 is 4
ackermann of i=1, j=3 is 5
ackermann of i=1, j=4 is 6
ackermann of i=1, j=5 is 7
ackermann of i=1, j=6 is 8
ackermann of i=2, j=0 is 3
ackermann of i=2, j=1 is 5
ackermann of i=2, j=2 is 7
ackermann of i=2, j=3 is 9
ackermann of i=2, j=4 is 11
ackermann of i=2, j=5 is 13
ackermann of i=2, j=6 is 15
ackermann of i=3, j=0 is 5
ackermann of i=3, j=1 is 13
ackermann of i=3, j=2 is 29
ackermann of i=3, j=3 is 61
ackermann of i=3, j=4 is 125
ackermann of i=3, j=5 is 253
ackermann of i=3, j=6 is 509
ackermann of i=4, j=0 is 13
ackermann of i=4, j=1 is 65533
Segmentation fault (core dumped)
4

0 回答 0