Simple loop Ackermann function

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

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

相关标签:
2条回答
  • 2021-01-13 09:44

    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].

    0 讨论(0)
  • 2021-01-13 09:54

    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.

    0 讨论(0)
提交回复
热议问题