In 1202 Fibonacci introduced a sequence. In it, each number of the sum of the two previous numbers. This sequence has uses in financial applications.
With iteration, we can compute the Fibonacci sequence. And we can store each number in an array for later use. This sequence is easy to generate, but does require a few instructions.
We use several variables within the Fibonacci()
method, which loops up to the Fibonacci sequence index required. It computes the number and then returns it.
Fibonacci()
computes the entire sequence up to the specified point. We can instead store them in an array as we proceed.public class Program { public static int fibonacci(int n) { int a = 0; int b = 1; // Compute Fibonacci sequence. for (int i = 0; i < n; i++) { int temp = a; a = b; b = temp + b; } return a; } public static void main(String[] args) { // Get first 15 Fibonacci numbers. for (int i = 0; i < 15; i++) { System.out.println(fibonacci(i)); } } }0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
This program computes Fibonacci numbers in the same way as before, but stores them in an array as it proceeds to the desired index. We can reuse the array cache.
public class Program { public static int[] fibonacci(int n) { int a = 0; int b = 1; int[] sequence = new int[n]; // Fill array with Fibonacci values. for (int i = 0; i < n; i++) { sequence[i] = a; int temp = a; a = b; b = temp + b; } return sequence; } public static void main(String[] args) { // Get Fibonacci array. int[] sequence = fibonacci(15); for (int value : sequence) { System.out.println(value); } } }0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Fibonacci numbers are easy to compute, but a temporary variable is helpful. With recursion, we can compute Fibonacci numbers, but this has little advantage.
And for performance, lookup tables, which memoize values rather than recompute them each time, are beneficial. We implemented an iterative Fibonacci method and a lookup table generator.