-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathFibonacci.java
92 lines (80 loc) · 2.34 KB
/
Fibonacci.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* Copyright 2022 jingedawang
*/
package math;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import utils.ArrayPrinter;
/**
* Fibonacci sequence.
*
* To reuse the generated fibonacci sequence, this class is designed as singleton.
*/
public class Fibonacci {
/**
* Demo code.
*/
public static void main(String[] args) {
List<BigDecimal> fibonacciList = Fibonacci.getInstance().getFibonacciList(10);
System.out.println("The first 10 fibonacci numbers are:");
ArrayPrinter.print(fibonacciList.toArray(new BigDecimal[1]));
System.out.println("The 99-th fibonacci number is " + Fibonacci.getInstance().getFibonacci(99) + ".");
}
/**
* Get the singleton instance of this class.
*
* @return The singleton instance.
*/
public static Fibonacci getInstance() {
if (instance == null) {
instance = new Fibonacci();
}
return instance;
}
/**
* Get the first {@code n} fibonacci numbers.
*
* @param n The length of the sequence wanted.
* @return A list of the first {@code n} fibonacci numbers.
*/
public List<BigDecimal> getFibonacciList(int n) {
if (n <= fibonacciSequence.size()) {
return fibonacciSequence.subList(0, n);
}
generateFibonacciToN(n);
return fibonacciSequence;
}
/**
* Get the {@code i}-th item of the fibonacci sequence.
*
* @param i The index of the item to be fetched.
* @return The {@code i}-th item of the fibonacci sequence.
*/
public BigDecimal getFibonacci(int i) {
if (i < fibonacciSequence.size()) {
return fibonacciSequence.get(i);
}
generateFibonacciToN(i + 1);
return fibonacciSequence.get(i);
}
// Singleton instance.
private static Fibonacci instance;
// Cache list for generated fibonacci sequence.
private final List<BigDecimal> fibonacciSequence = new ArrayList<>();
// Disabled constructor.
private Fibonacci() {
}
// Generate all the fibonacci numbers below n.
private void generateFibonacciToN(int n) {
if (n > fibonacciSequence.size() && fibonacciSequence.size() == 0) {
fibonacciSequence.add(new BigDecimal(0));
}
if (n >= fibonacciSequence.size() && fibonacciSequence.size() == 1) {
fibonacciSequence.add(new BigDecimal(1));
}
while (fibonacciSequence.size() < n) {
fibonacciSequence.add(fibonacciSequence.get(fibonacciSequence.size() - 1).add(fibonacciSequence.get(fibonacciSequence.size() - 2)));
}
}
}