Simple loop Ackermann function

后端 未结 2 881
清歌不尽
清歌不尽 2021-01-13 09:06

How to write the Ackermann function with a simple non-recursive loop?

2条回答
  •  抹茶落季
    2021-01-13 09:54

    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.

提交回复
热议问题