Java Fibonacci Sequence Examples

These Java examples generate the Fibonacci sequence. They use a for-loop and a temporary variable.
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

Argument: 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.

Java program that gets Fibonacci numbers 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)); } } } Output 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.Int Array

Lookup table: 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.

Java program that gets Fibonacci 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); } } } Output 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.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls