-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEuler002.java
More file actions
executable file
·62 lines (48 loc) · 1.52 KB
/
Copy pathEuler002.java
File metadata and controls
executable file
·62 lines (48 loc) · 1.52 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
import java.util.Date;
/*
Project Euler Problem 2
=======================
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, ...
Find the sum of all the even-valued terms in the sequence which do not
exceed four million.
*/
public class Euler002 {
public static void main(String[] args) {
Date start, end;
start = new Date();
long sum = 0, fib = 0;
for (int i = 0; fib <= 4000000; i++)
sum = ((fib = fibonacci(i)) % 2 == 0) ? sum + fib : sum;
end = new Date();
System.out.println("Sum = " + sum); // outputs the sum
System.out.println("Execution Time: "
+ (end.getTime() - start.getTime()));
}
// Generates Fibonacci's sequence iteratively
public static long fibonacci(int term) {
long term1 = 0l;
long term2 = 1l;
if (term == 1)
return term1 + 1;
if (term == 2)
return term1 + term2;
for (int i = 0; i < term; i++) {
long temp = term1;
term1 = term1 + term2;
term2 = temp;
}
return term1;
}
// Generates Fibonacci's sequence recursively
public static long fibonacciR(int term) {
if (term == 0) {
return 0l;
}
if (term == 1) {
return 1l;
}
return fibonacciR(term - 1) + fibonacciR(term - 2);
}
}