Stack Overflow error occurs when using recursive fibonacci function

后端 未结 3 1418
Happy的楠姐
Happy的楠姐 2020-12-21 11:12

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.

Thanks in advance!

public class F         


        
3条回答
  •  轮回少年
    2020-12-21 11:57

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

提交回复
热议问题