How to write the Ackermann function with a simple non-recursive loop?
Here's a possible implementation:
import java.util.ArrayList;
public class LinearAckermann {
static ArrayList mList = new ArrayList();
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.