Stack Overflow error occurs when using recursive fibonacci function

删除回忆录丶 提交于 2019-11-29 16:14:54

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

Stephan

You can increase the stack size of Java programs. Example:

java -Xss4m YourProgram

Reference

Nevertheless I would also recommend an iterative method.

As Jon Skeet above mentioned, your code would require a huge amount of time to run - 2 to the 4 million, which is not practical in any way. Frankly i'm surprised the stack ran dry at all, I'd think the code would just run for a ridiculous amount of time.

You should use an iterative approach. Here's a nicer implementation of the fibonacci sequence:

static long fib(long i){
    if ( i == 0 || i == 1 ) return 1;
    long a = 1; //This is the 0th element 
    long b = 1; //This is the 1st element
    while( i-- > 1 ){ //Each iteration, sets a and b to the next element in the fibonacci sequence
        long temp = b;
        a += b;
        b = a;
        a = temp;
    }
    return b;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!