Java Program Fibonacci Sequence

前端 未结 15 1891
被撕碎了的回忆
被撕碎了的回忆 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:30

    The problem is that because you are using simple recursion, you re-evaluate F(n) multiple times, so your execution time is exponential.

    There are two simple ways to fix this:

    1) Cache values of F(n) when they are evaluated the first time. Check the cache first before evaluating F(n) to see if you have already calculated it for this n.

    2) Use an iterative approach: Calculate F(1), F(2), F(3), etc... until you reach the number you need.

提交回复
热议问题