Beruflich Dokumente
Kultur Dokumente
Recursion
A function may be called from another function or it may call itself. Recursion implies a
function calling itself. If a function call occurs inside the function itself, it is called direct
recursion. If a function calls another function, which in turn makes a call to the first one,
it is called indirect recursion.
Each invocation of a function causes a new allocation of the variables declared inside it.
The storage for auto variables is automatically allocated and freed on function entry and
return.
Ackermann function
It takes two natural numbers as arguments and yields another natural number. Its value
grows extremely quickly; even for small inputs. For example for (4,3), the values of the
Ackermann function are so large that they cannot be feasibly computed, and in fact their
decimal expansions require more digits than there are particles in the entire visible
universe.
The evaluation of these functions always terminates. The recursion is bounded because in
each recursion either m decreases, or m remains the same and n decreases. Each time that
n reaches zero, m decreases, so m eventually reaches zero as well. However, when m
decreases there is no upper bound on how much n can increase.
For small values of m like 1, 2, or 3, the Ackermann function grows relatively slowly
with respect to n. For m ≥ 4, however, it grows much more quickly. The expansion of
A(4, 3) cannot be recorded in the known physical universe.
Computing A(1, n) takes linear time in n. Computing A(2, n) takes quadratic time in n.
The time required for higher values of m, is much more.
Explanation
We now illustrate the expansion of the function for m = 1, and n = 2. The
evaluation of A(1, 2) proceeds as follows:
The Ackermann function, due to its definition in terms of extremely deep recursion, can
be used as a benchmark of a compiler's ability to optimize recursion. This function can be
used to compare the amount of time required to evaluate this function for fixed arguments
in many different programming language implementations.
Program
/* Ackermann's function */
#include <stdio.h>
#include <conio.h>
void main()
{
int n; /* number entered by the user */
int res1, res2, res3, res4; /* value of fn ack() */
clrscr();
getch();
}