Java Program Fibonacci Sequence

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

    The issue is that your algorithm, while mathematically pure (and nice) isn't very good.
    For every number it wants to calculate, it has to calculate two lower ones which in turn have to calculate two lower ones, etc. Your current algorithm has a Big O notation complexity of about O(1.6n), so for very large numbers (100 for example) it takes a long time.

    This book, Structure and Interpretation of Computer programs has a nice diagram: showing what happens when you generate fib 5 with your algorithm

    (source: mit.edu)

    The simplest thing to do is to store F - 1 and F - 2, so that you don't have to calculate them from scratch every time. In other words, rather than using recursion, use a loop. Than means that the complexity of the algorithm goes from O(1.6n) to O(n).

提交回复
热议问题