arrow-left

All pages
gitbookPowered by GitBook
1 of 1

Loading...

10.1. Fibonacci Sequence

This section discusses recursive, iterative, and dynamic programming ways of generating the Fibonacci sequence.

The Fibonacci sequencearrow-up-right is a sequence of numbers generated as follows:

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

  • Fn=Fn−1+Fn−2F_n = F_{n-1} + F_{n-2}Fn​=Fn−1​+Fn−2​ where n≥2n \geq 2n≥2

hashtag
Abstraction

Let us create the interface that contains one abstract method:

  • L2: returns the 'th Fibonacci number.

hashtag
Recursion

The followings demonstrate how to generate the Fibonacci sequence using recursion:

Let us create the class inheriting Fibonacci:

What is the worst-case complexity of this recursive algorithm?

hashtag
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.

What is the worst-case complexity of this dynamic programming algorithm?

hashtag
Iteration

For this particular task, the efficiency can be further enhanced using iteration. Let us create the class inheriting Fibonacci:

hashtag
Benchmark

The followings show performance comparisons:

L17
: fills in the dynamic table using recursion.
kkk
iii
iii
Fibonacciarrow-up-right
FibonacciRecursivearrow-up-right
FibonacciIterativearrow-up-right
public interface Fibonacci {
    int get(int k);
}
public class FibonacciRecursive implements Fibonacci {
    @Override
    public int get(int k) {
        return switch (k) {
            case 0 -> 0;
            case 1 -> 1;
            default -> get(k - 1) + get(k - 2);
        };
    }
}
public class FibonacciDynamic implements Fibonacci {
    @Override
    public int get(int k) {
        return getAux(k, createTable(k));
    }
    
    private int[] createTable(int k) {
        int[] table = new int[k + 1];
        table[0] = 0;
        table[1] = 1;
        Arrays.fill(table, 2, k + 1, -1);
        return table;
    }

    private int getAux(int k, int[] table) {
        if (table[k] >= 0) return table[k];
        return table[k] = getAux(k - 1, table) + getAux(k - 2, table);
    }
}
public class FibonacciIterative implements Fibonacci {
    @Override
    public int get(int k) {
        if (k < 2) return k;
        int f0 = 0, f1 = 1, f2;

        for (int i = 2; i < k; i++) {
            f2 = f0 + f1;
            f0 = f1;
            f1 = f2;
        }

        return f0 + f1;
    }
}