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:

  • F0=0,F1=1F_0 = 0, F_1 = 1

  • Fn=Fn1+Fn2F_n = F_{n-1} + F_{n-2} where n2n \geq 2

Abstraction

Let us create the Fibonacci interface that contains one abstract method:

public interface Fibonacci {
    int get(int k);
}
  • L2: returns the kk'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 ii'th dimension is to be filled with the ii'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?