Two ways to realize "Fibonacci sequence" in Java -- array and recursive optimization

Posted by demophoon88 on Mon, 31 Jan 2022 04:37:21 +0100

This paper uses three ways to realize Fibonacci sequence - array, recursion and optimized recursion.

This paper focuses on the comparison and optimization of the implementation efficiency of Fibonacci sequence.

1, Array implementation of Fibonacci sequence

Test code:

public class ArrayTest {
    public static void main(String[] args) {
        // Start timing
        long start = System.currentTimeMillis();
        // Fibonacci
        long[] array = new long[50];
        array[0] = 1L;
        array[1] = 1L;
        for (int i = 2; i < array.length; i++) {
            array[i] = array[i-1] + array[i-2];
        }
        System.out.println("Number of Fibonacci series in the 50th place:" + array[49]);
        // End timing
        long end = System.currentTimeMillis();
        System.out.println(end - start + " ms");
    }
}

Console output results:

Number of Fibonacci number series in the 50th place: 12586269025
1 ms

Process finished with exit code 0

It only takes 1 millisecond to implement through array.

2, Recursive implementation of Fibonacci sequence

Test code:

public class RecursionTest {

    public static void main(String[] args) {
        // Start timing
        long start = System.currentTimeMillis();
        // Fibonacci
        long fibonacci_50 = fibonacci(50);
        System.out.println("Number of Fibonacci series in the 50th place:" + fibonacci_50);
        // End timing
        long end = System.currentTimeMillis();
        System.out.println(end - start + " ms");
    }

    public static long fibonacci(int index){
        if(index == 1 || index == 2){
            return 1;
        }
        return fibonacci(index - 1) + fibonacci(index - 2);
    }

}
Number of Fibonacci number series in the 50th place: 12586269025
44750 ms

Process finished with exit code 0

The traditional recursive method takes nearly 45 seconds.

3, Analysis and optimization

The efficiency of array is 1 millisecond and that of traditional recursion is 45 seconds.

So, what is the reason for the large efficiency gap between array and traditional recursion?

Through the DEBUG trace code, we find that every time the traditional recursion gets the current index, it needs to get the previous index again. Finding duplicate indexes increases the computational cost and therefore reduces efficiency.

If you find the cause, you can suit the remedy to the case.

terms of settlement:
We set a container in the global variable to record the queried Fibonacci series. Each time the Fibonacci number corresponding to the subscript is calculated, it is obtained from the container first. If it exists in the container, it is obtained directly. On the contrary, the calculated result is stored in the container.

4, Optimized recursive implementation of Fibonacci sequence

Test code:

public class OptimizedRecursionTest {

    private static final Map<Integer, Long> FIBONACCI_MAP = new HashMap<>();

    public static void main(String[] args) {
        // Start timing
        long start = System.currentTimeMillis();
        // Fibonacci
        FIBONACCI_MAP.put(1, 1L);
        FIBONACCI_MAP.put(2, 1L);
        long fibonacci_50 = optimizedFibonacci(50);
        System.out.println("Number of Fibonacci series in the 50th place:" + fibonacci_50);
        // End timing
        long end = System.currentTimeMillis();
        System.out.println(end - start + " ms");
    }

    public static long optimizedFibonacci(int index){
        if (FIBONACCI_MAP.containsKey(index)){
            return FIBONACCI_MAP.get(index);
        }else {
            FIBONACCI_MAP.put(index, optimizedFibonacci(index - 1) + optimizedFibonacci(index - 2));
        }
        return optimizedFibonacci(index - 1) + optimizedFibonacci(index - 2);
    }

}

Console output results:

Number of Fibonacci number series in the 50th place: 12586269025
2 ms

Process finished with exit code 0

5, Summary

Although the recursive efficiency after optimization is still not as good as that of array, 2 milliseconds is amazing compared with 44750 milliseconds.

This idea of optimizing recursion is not limited to Fibonacci. If it can be integrated, there is no need to worry about efficiency when using recursion in developing business processes.

Topics: Java Algorithm