Java Program Fibonacci Sequence

前端 未结 15 1871
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 03:17

I am writing a \"simple\" program to determine the Nth number in the Fibonacci sequence. Ex: the 7th number in the sequence is: 13. I have finished writing the program, it

15条回答
  •  别那么骄傲
    2020-12-17 03:36

    You can use the caching technic. Since f(n)= f(n-1)+f(n-2) , you'll calculate f(n-2) one more time when you calculate f(n-1). So simply treat them as two incremental numbers like below:

    public int fib(int ithNumber) {
        int prev = 0;
        int current = 1;
        int newValue;
        for (int i=1; i

提交回复
热议问题