-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathFibonacciSequence.java
77 lines (65 loc) · 2.33 KB
/
FibonacciSequence.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
// outputs the Fibonacci values at the input's index values (index 0 = index 1 = 1)
// imports for the Fibonacci sequence
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Scanner;
public class FibonacciSequence{
// variables for outputting the Fibonacci sequence
public BigInteger[] sequence;
public int stoppingPoint = 0;
public ArrayList<Integer> input;
public static final String inputFile = "FibonacciSequence.in";
// main method to run test sequence
public static void main(String[] args) throws IOException{
FibonacciSequence fs = new FibonacciSequence(inputFile);
}
// object that outputs a Fibonacci sequence
public FibonacciSequence(String fileInput) throws IOException{
// need to input a file to generate the sequence values at certain indices
Scanner inputStream = null;
PrintWriter outputStream = null;
try{
// input the file to know where to get values in the sequence
inputStream = new Scanner(new BufferedReader(new FileReader(fileInput)));
outputStream = new PrintWriter(new FileWriter("fib.out"));
input = new ArrayList();
while(inputStream.hasNextInt()){
input.add(inputStream.nextInt());
}
// create the sequence only as far as needed
findIndexMaximum();
createSequence();
// output the values of the Fibonacci sequence
for(int i : input){
outputStream.println(sequence[i]);
}
// after processing the sequence values and outputting, close streams
}finally{
if(inputStream != null)
inputStream.close();
if(outputStream != null)
outputStream.close();
}
}
// find the maximum value for the Fibonacci sequence
public void findIndexMaximum(){
for(int i = 0; i < input.size(); i++){
if(stoppingPoint < input.get(i))
stoppingPoint = input.get(i);
}
}
// generate the Fibonacci sequence up to some value
public void createSequence(){
sequence = new BigInteger[stoppingPoint + 1];
sequence[0] = BigInteger.ONE;
sequence[1] = BigInteger.ONE;
for(int i = 2; i <= stoppingPoint; i++){
sequence[i] = sequence[i-1].add(sequence[i-2]);
}
}
}