简单循环阿克曼函数 [英] Simple loop Ackermann function

查看:65
本文介绍了简单循环阿克曼函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过简单的非递归循环编写 Ackermann函数?

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

推荐答案

以下是可能的实现:

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));
    }
}

它使用mList而不是堆栈来保存挂起的工作;当堆栈变空时,它可以返回累加值.

It uses mList instead of a stack to hold pending work; when the stack becomes empty, it can return the accumulated value.

这篇关于简单循环阿克曼函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆