-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem002.java
More file actions
89 lines (76 loc) · 2.51 KB
/
Copy pathProblem002.java
File metadata and controls
89 lines (76 loc) · 2.51 KB
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
/* =====================================================================
*
* PROGRAM NAME : Project Euler Problem #2
*
*
*
* Description:
* After running this code, the solution to the program will appear
* in the console output at the last entry.
*
* Problem: Each new term in the Fibonacci sequence is generated by adding
* the previous two terms. By starting with 1 and 2, the first 10 terms will be:
* 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
* By considering the terms in the Fibonacci sequence whose values do not
* exceed four million, find the sum of the even-valued terms.
*
* This program first creates a text file named Problem002_fibonacci.txt
* containing the fibonacci numbers up to 5702887. This is done in the first
* while loop. The text file is done being written to at System.out.println
* command saying it was written successfully.
* The second while loop reads each line and adds it up to the sum accumulator
* if it's even. The System.out.prinln call is used for making sure the correct
* terms were added to the accumulator with the final answer being the very last
* entry
*
*
* Functions Called :
* NONE
*
* Parameters:
* NONE
*
* Created by: MJH,
* 7/22/2015: Initial 1.0 release
* 7/27/2015: Added documentation
*
* =====================================================================
*/
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Problem002 {
public static void main(String[] args) throws IOException
{
int number = 1, previousNumber = 0, previousPreviousNumber = 0; // for the fibonacci algorithm
String filename = "Problem002_fibonacci.txt";
PrintWriter outputfile = new PrintWriter(filename);
File file = new File(filename);
Scanner inputFile = new Scanner(file);
double sum = 0;
int entry = 1;
// First write the methods that put the fibonacci numbers in a text file
// NOTE: this following algorithm prints the first number bigger than 4M. However
// it doesn't matter that it does this because it's odd. anyway
while (number < 4000000)
{
previousPreviousNumber = previousNumber;
previousNumber = number;
number = previousPreviousNumber + previousNumber;
outputfile.println("\n" + number);
}
System.out.println("File written successfully.");
outputfile.close();
// Now read the file and add them up if they're even
while (entry < 4000000)
{
entry = inputFile.nextInt();
if (entry % 2 == 0)
{
sum += entry;
}
System.out.println(entry + " " + sum);
}
}
}