Skip to the content of the web site.

Project K.8: Ackermann function

Implement the Ackermann function, which is defined as

$A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0\end{cases}}$.

Your function declaration should be

unsigned long ackermann( unsigned long m, unsigned long n );

The one difficulty is if $n + 1$ overflows, so if this occurs, you should throw a std::range_error exception.

Try the following program:

#include <iostream>
#include <stdexcept>

unsigned long ackermann( unsigned long m, unsigned long n );
int main();

int main() {
    for ( unsigned long m{0}; m <= 4; ++m ) {
        for ( unsigned long n{0}; n <= 4; ++n ) {
            std::cout << "A( " << m << ", " << n << " ) = "
                      << A(m, n) << std::endl;
        }

        std::cout << std::endl;
    }

    return 0;
}