Fibonacci Sequence ExamplesGenerate the Fibonacci sequence using a for-loop and a temporary variable.
Java
Fibonacci sequence. 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.
Fibonacci method. 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.
for
Detail This is the index of the Fibonacci number. So an argument of 14 with return 377, the fifteenth number in the sequence.
Note Each call to 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
An array example. 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.
Array
Detail Often, mathematical methods are slow. Using a table to store (memoize) their results tends to yield speed boosts.
Here We can access Fibonacci numbers with just an array access, an element load, by using the "sequence" array.
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
A review. Fibonacci numbers are easy to compute, but a temporary variable is helpful. With recursion, we can compute Fibonacci numbers, but this has little advantage.
Recursion
And for performance, lookup tables, which memoize values rather than recompute them each time, are a clear win. We implemented an iterative Fibonacci method and a lookup table generator.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.