java尾递归,java-如何使用我的斐波那契方法实现尾递归...

实现您想要的系列的简单递归可以是:

public class FibRecursion{

private static BigInteger[] fval;

public static void main(String[] args) {

int index = 10;

fval = new BigInteger[index];

fib(0,1,0,index);

System.out.println(Arrays.toString(fval));

}

public static void fib(long a, long b, int index, int endIndex ) {

if (index >= endIndex) {

return ;

}

fval[index] = BigInteger.valueOf(a).add(BigInteger.valueOf(b));

index++;

fib(b, a+b, index , endIndex);

}

}

为了避免堆栈限制,您可以限制递归深度,并以几个“段”进行复活.这是一系列50个元素的示例,其深度限制为10(RECURRSION_DEPTH = 10):

public class FibRecursion{

private static BigInteger[] fval;

//limit of the recursion depth. valid values are >=2

private final static int RECURRSION_DEPTH = 10;

public static void main(String[] args) {

int index = 50;

fval = new BigInteger[index];

BigInteger aValue = BigInteger.valueOf(0);

BigInteger bValue = BigInteger.valueOf(1);

int startIndex = 0;

int endIndex = RECURRSION_DEPTH;

while (endIndex > startIndex) {

fib(aValue,bValue,startIndex,endIndex);

aValue = fval[endIndex-2];

bValue = fval[endIndex-1];

startIndex = endIndex;

endIndex = Math.min(endIndex + RECURRSION_DEPTH, index);

}

System.out.println(Arrays.toString(fval));

}

//use BigInteger to avoid integer max value limitation

public static void fib(BigInteger a, BigInteger b, int index, int endIndex ) {

if (index >= endIndex) {

return ;

}

fval[index] = a.add(b);

index++;

fib(b, a.add(b), index , endIndex);

}

}

当然,这还有其他限制,与堆栈大小无关.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值