从递归到迭代

时间:2014-02-18 17:44:21

标签: java performance

我已经花了很长时间尝试将此函数转换为循环但我无法找到实现它的方法。我已经开始使用while(m != 0)然后是内部条件,但是第三个是不允许我这样做的。

public static int calculatePayment(int n, int m){
    if(m == 0) return n + 1;
    if(n == 0 && m > 0) return calculatePayment(1, m - 1);
    if(n > 0 && m > 0) return calculatePayment(calculatePayment(n - 1, m), m - 1);
    return 0;
}

此外,我不知道是否需要使用BigInteger,aretrograde和inverteds程序将运行StackOverFlow Error并且如果需要它将不会让我知道。

编辑:

第一

输入中的

m不能小于零,这绝不会发生。与n相同的情况,代码不需要处理它。

到目前为止,我有这个:

while(m > 0){
             if(n == 0 && m > 0){n = 1; m--;}
             if(n > 0 && m > 0){m--; n = IDONTKNOWWHAT;}//here n is the value of
                                                        //the payment if n = n - 1
                                                        //and m = m
                                                        //here is the big deal.
            }
if(m == 0) return n + 1;   //or print

此外,代码不能简化为数学公式,我试过了。

1 个答案:

答案 0 :(得分:2)

看起来你正试图找到一种用于计算Ackermann函数的非递归算法。我不介意让我的工资计算得那样:)我想这是为了掩饰一个家庭作业?

无论如何,您只需模拟堆栈并存储中间值,然后就可以轻松完成,请参阅:How to rewrite Ackermann function in non-recursive style?

顺便说一下,阿克曼的功能发展得非常快。你可以使用BigInteger,但无论如何它都将是徒劳的。只有几个最小的参数才知道函数的确切值。此外,涉及大量递归,因此您需要缓存中间值以推迟StackOverflow,谷歌关于memoization。

相关问题