使用递归斐波那契函数时发生堆栈溢出错误

使用递归斐波那契函数时发生堆栈溢出错误

本文介绍了使用递归斐波那契函数时发生堆栈溢出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,它运行良好,值为400到4000,但一旦大约4mil,我就会出现堆栈溢出错误。

Here's my code and it runs well with values of 400 to 4000 but once it's about 4mil, I get stack overflow errors.

提前致谢!

public class Fib {
static int c=1,b=2;
static long sum1=0,sum2=0;

static long fib(long a){
if(a==1){
    return 1;
}
if(a==2){
    return 2;
}
else{
    return fib(a-1)+fib(a-2);
}

    }


    public static void main(String[] args){
sum2= fib(4000000);
    System.out.println("Sum %f" +sum2);
}
    }


推荐答案

是 - 你的堆栈空间不足。它远非无限,你在每次递归调用时都会使用它。你试图最终得到一个有400万个堆栈帧的堆栈 - 这不会起作用。

Yes - you're running out of stack space. It's far from infinite, and you're using it up on each recursive call. You're trying to end up with a stack with 4 million stack frames - that's not going to work.

我建议你考虑一种迭代方法。即使你有无限量的堆栈,在宇宙热死之前,这些代码可能无法完成。 (想想这段代码的复杂性......)

I suggest you consider an iterative approach. Even if you had an infinite amount of stack, that code would probably not complete before the heat death of the universe. (Think about the complexity of this code...)

这篇关于使用递归斐波那契函数时发生堆栈溢出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 21:38