forked from nayuki/Project-Euler-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
p002.java
43 lines (35 loc) · 756 Bytes
/
p002.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
/*
* Solution to Project Euler problem 2
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
public final class p002 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p002().run());
}
public String run() {
int sum = 0;
for (int i = 0; ; i++) {
int fib = fibonacci(i);
if (fib > 4000000)
break;
if (fib % 2 == 0)
sum += fib;
}
return Integer.toString(sum);
}
private static int fibonacci(int x) {
if (x < 0 || x > 46)
throw new IllegalArgumentException();
int a = 0;
int b = 1;
for (int i = 0; i < x; i++) {
int c = a + b;
a = b;
b = c;
}
return a;
}
}