In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
By definition, the first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two.
A simple version
|
|
The simplest version takes many unnecessary caculations during the process. There are many redundancy in the fibonacci(n-1)
and fibonacci(n-2)
.
This kind of recursion is called tree recursion. How about doing the recursion linearly?
Linear Recursion
|
|
By this way, the recursion becames linear with O(n) time complexity. It’s much faster than the tree recursion version. The reason behind it is that it always cache the latest two result which the tree recursion does not.
How about we create a Map that cache the result of n once we caculate it?
Memoization
|
|
In this implementation, it caches every caculated fibonacci(n) in memo
, which provides better performance than the simplest version. But it takes more spaces than the linear recursion because of the memo
.
All of the above implementation will throw RangeError: Maximum call stack size exceeded
when n is quite big. So why don’t we try to make use of iteration?
Iteration
|
|
By this way, there won’t be RangeError
any more!
Benchmark
There is my different implementations: fibonacci.js.
The picture below shows the performance of different implementations.
Have Fun
ES6 introduced generators. Try fibonacci with generator: :laughing:
|
|
Formula, Lookup Array…
You can read the 3rd reference for more! :yum: