5 Ways of Generating Fibonacci Numbers
This is just a quick note about 5 ways of generating Fibonacci numbers. Here, I want to create a function whose argument is an int number “n” (representing which number to return in the Fibonacci sequence). This function will return the Fibonacci number I want. In my definition for this question, I want the Fibonacci sequence to start from 0.
1. Recursion without Cache
|
|
The time complexity of this function is $O(1.618^{n})$ by solving the characteristic equation of F(n) = F(n-1) + F(n-2).
2. Recursion with Cache
|
|
By cacheing to avoid repeated calculation, we could significantly reduce the time complexity of the recursion method. The time complexity of this approach is $O(n)$.
3. Induction without Cache
|
|
The time complexity of the third approach is $O(n^{2})$.
4. Induction with Cache
|
|
Here, maybe you don’t see the point of cacheing the Fibonacci sequence in the induction case since we still let the computer do the calculation which doesn’t use the value in our list. However, cache will be useful in our next step.
The time complexity of this method is O($n^{2}$).
5. Math Formula
|
|
The time complexity of the mathematical method is $O(1)$ since it only computes once using the formula. It’s the most efficient way.
What if we want to print the first n numbers (Fibonacci sequence) instead of No. n Fibonacci number?
1. Recursion without Cache
|
|
Since there’s no cache here, as you could imagine, the time complexity of this method would still be $O(1.618^{n})$ since for each number, we only add one step to let the function print itself. It will be really time-consuming when it becomes large such as 100, not to mention even larger numbers.
2. Recursion with Cache
|
|
Same, after computing and cacheing, for every number in our cache, we only need to print it, so the time complexity doesn’t change and still remains $O(n)$.
3. Induction without Cache
|
|
Time complexity of this method is $O(n^2)$
4. Induction with Cache
|
|
Using cache, we could easily return the whole Fibonacci sequence with the time complexity $O(n^2)$
5. Math Formula
|
|
The time complexity of this algorithm is $O(n)$.