Fibonacci Sequence in Java taking too long?

前端 未结 6 994
余生分开走
余生分开走 2021-01-13 18:44

I\'m trying to find the sum of the Fibonacci sequence in Java, but the run time is taking way too long (or is it suppose to?). This slows down anytime I use an integer past

6条回答
  •  南方客
    南方客 (楼主)
    2021-01-13 18:46

    Recursive solutions don't necessarily have to be slow. If you were to use this tail-recursive solution, you'd save up a lot of memory and still achieve great speed (e.g. Fib(10000) runs in 1.1s on my machine).

    Here n is the sequence number for which you're calculating Fibonacci number, while f0 and f1 are two accumulators, for previous and current Fibonacci numbers respectively.

    public class FibonacciRec {
        public static int fib(int n, int f0, int f1) {
            if (n == 0) {
                return f0;
            } else if (n == 1){
                return f1;
            } else {
                return fib(n-1, f1, f0+f1);
            }
        }
    
        public static void main(String[] args) {
            System.out.println(fib(10, 0, 1));
        }
    }
    

提交回复
热议问题