Java Implementation of Problem 2
View source code here on GitHub!
1/*
2Project Euler Problem 2
3
4This is a port of the optimized version found in python. For a proof of why this
5works, see that implementation
6
7Problem:
8
9Each new term in the Fibonacci sequence is generated by adding the previous two
10terms. By starting with 1 and 2, the first 10 terms will be:
11
121, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
13
14By considering the terms in the Fibonacci sequence whose values do not exceed
15four million, find the sum of the even-valued terms.
16*/
17package euler;
18
19public class p0002 implements IEuler {
20 @Override
21 public Object answer() {
22 int answer = 0, i = 2, j = 8, tmp = 0;
23
24 while (i < 4000000) {
25 answer += i;
26 tmp = 4 * j + i;
27 i = j;
28 j = tmp;
29 }
30
31 return answer;
32 }
33}