How to write the Ackermann function with a simple non-recursive loop?
The following "iterative" version of Ackermann’s function (using lists of natural numbers) is a simple loop, expressed using tail recursion.
ackloop (n::0::list) = ackloop (n+1::list)
ackloop (0::m::list) = ackloop (1::m-1::list)
ackloop (n::m::list) = ackloop (n-1::m::m-1::list)
ackloop [m] = m
Now ack(m,n) = ackloop [n,m].
Here's a possible implementation:
import java.util.ArrayList;
public class LinearAckermann {
static ArrayList<Long> mList = new ArrayList<Long>();
public static long ackermann(long m, long n) {
while (true) {
if (m == 0) {
n += 1;
if (mList.isEmpty()) {
return n;
} else {
int index = mList.size() - 1;
m = mList.get(index);
mList.remove(index);
}
} else if (n == 0) {
m -= 1;
n = 1;
} else {
mList.add(m - 1);
n -= 1;
}
}
}
public static void main(String[] args) {
System.out.println(ackermann(4, 1));
}
}
It uses mList
instead of a stack to hold pending work; when the stack becomes empty, it can return the accumulated value.