C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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