Grade 10 · RecursionCitește în română

The Ackermann function

Original: Funcția Ackermann

ExponentialC++1739 lines2 examples

The idea

The Ackermann function has two arguments: A(0, n) = n + 1; A(m, 0) = A(m - 1, 1); A(m, n) = A(m - 1, A(m, n - 1)). Its values grow extremely fast (A(4, 2) has almost 20,000 digits), which is why it is used only with small values (m <= 3, n <= 5). Worth remembering: A(1, n) = n + 2, A(2, n) = 2n + 3, A(3, n) = 2^(n+3) - 3.

Original description (Romanian)

Funcția Ackermann are două argumente: A(0, n) = n + 1; A(m, 0) = A(m - 1, 1); A(m, n) = A(m - 1, A(m, n - 1)). Valorile cresc extrem de repede (A(4, 2) are aproape 20 000 de cifre), de aceea se folosește doar cu valori mici (m <= 3, n <= 5). Merită ținut minte: A(1, n) = n + 2, A(2, n) = 2n + 3, A(3, n) = 2^(n+3) - 3.

Complexity
grows faster than any exponential function
Grade
Grade 10 (Clasa a X-a)
Chapter
Recursion

Examples

Example 1

Input

2 3

Expected output

9
Example 2

Input

3 3

Expected output

61

The code

Comments are in Romanian, as in the original collection. Edit freely: you can reset at any time.

functia-ackermann.cpp
/*
 * Titlu: Funcția Ackermann
 * Clasa: 10
 * Capitol: Recursivitate
 * Descriere: Funcția Ackermann are două argumente: A(0, n) = n + 1;
 *            A(m, 0) = A(m - 1, 1); A(m, n) = A(m - 1, A(m, n - 1)). Valorile cresc
 *            extrem de repede (A(4, 2) are aproape 20 000 de cifre), de aceea se
 *            folosește doar cu valori mici (m <= 3, n <= 5). Merită ținut minte:
 *            A(1, n) = n + 2, A(2, n) = 2n + 3, A(3, n) = 2^(n+3) - 3.
 * Complexitate: crește mai repede decât orice funcție exponențială
 *
 * Exemplu
 * Intrare: 2 3
 * Ieșire: 9
 *
 * Exemplu
 * Intrare: 3 3
 * Ieșire: 61
 */
#include <iostream>
using namespace std;

long long ackermann(long long m, long long n)
{
    if (m == 0)
        return n + 1;
    if (n == 0)
        return ackermann(m - 1, 1);
    return ackermann(m - 1, ackermann(m, n - 1));
}

int main()
{
    long long m, n;
    cin >> m >> n;
    cout << ackermann(m, n) << '\n';
    return 0;
}

Runs on a real g++ (C++17, -O2) through Compiler Explorer. Keep runs short; there's a time limit.