In this blog post we will be looking at problem 2 of Project Euler and we will be doing it in Java.
This problem of project Euler found here, below is the problem for quick lookup.
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.
-Project Euler problem 2
Let’s break the problem down into some smaller sections.
- We need to create some way to hold the sequence.
- We need a way to get the first 2 terms or hard code them into the program.
- We need to loop till the term is over 4.000.000
- We need to sum all even terms.
- And done!
We start with initializing an ArrayList to hold the sequence. Then we add the first 2 to get a start on the sequence. We initialize the counter of the for loop at 1 because in the loop block we add the last item and the one before it. The loop condition checks whether the last is over 4 million. If it is it exits the loop. After exiting the loop the last entry is deleted since it was above 4 million.
After that we loop through all instances in the sequence array list and add them to sum if they are even. At the end we print the sum.
ArrayList<Integer> sequence = new ArrayList<Integer>();
sequence.add(1);
sequence.add(2);
for (int i = 1; sequence.get(i) < 4_000_000; i += 1) {
sequence.add(sequence.get(i) + sequence.get(i - 1));
}
sequence.remove(sequence.size() -1);
int sum = 0;
for (int number : sequence) {
if (number % 2 == 0) {
sum += number;
}
}
System.out.println(sum);
The output/result is: 4613732.
Some pitfalls concerning this code are:
Off by one errors, like stopping the loop too late. I use the < (smaller than operator) with a check against 4.000.000. This does end up leading you to adding one over 4.000.000 to the arraylist which is why it is important to delete the last entry after exiting the loop.
Or another off by one errors you could make is starting the loop at 0 instead of 1 which will cause problems at compilation time. Since the for loop uses the loop counter to get two entries out of the sequence, the current loop counter position and the one below it(list index 1and 0 at the start of the loop). Which is also why you have to add the first 2 of the fibonacci sequence to the arraylist.
Some improvements:
Not using an arraylist and containing the program to one loop.
Or you could check in the first for loop whether the current term is even and only add it to the list if it is.
You could also include an if in a while loop(instead of the first for loop) block to break out of the loop if the current term is over 4 million making it so that you do not need to remove the last entry.
Check out the ‘Project Euler in Java’ page for more solutions!
That was Project Euler problem 2 in Java!