10.1. Fibonacci Sequence
This section discusses recursive, iterative, and dynamic programming ways of generating the Fibonacci sequence.
The Fibonacci sequence is a sequence of numbers generated as follows:
where
Abstraction
Let us create the Fibonacci interface that contains one abstract method:
public interface Fibonacci {
int get(int k);
}L2: returns the 'th Fibonacci number.
Recursion
The followings demonstrate how to generate the Fibonacci sequence using recursion:
Let us create the FibonacciRecursive class inheriting Fibonacci:
What is the worst-case complexity of this recursive algorithm?
Dynamic Programming
The followings demonstrate how to generate the Fibonacci sequence using dynamic programming:
Let us create the FibonacciDynamic class inheriting Fibonacci:
L7: creates a dynamic table represented by an array where the 'th dimension is to be filled with the 'th Fibonacci number.L16: returns the value in the dynamic table if exists.L17: fills in the dynamic table using recursion.
What is the worst-case complexity of this dynamic programming algorithm?
Iteration
For this particular task, the efficiency can be further enhanced using iteration. Let us create the class FibonacciIterative inheriting Fibonacci:
Benchmark
The followings show performance comparisons:
Last updated
Was this helpful?