Project Euler #2

Filed Under (Development) by Robert Green on 28-05-2009

Tagged Under : ,

Problem #2 in the Project Euler series is:

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.

My solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
static void Problem2() {
    int term1 = 0;
    int term2 = 1;
    int term3 = 1;
    int max = 4000000;
    double sum = 0;
 
    while(term1 < max && term2 < max && term3 < max) {
        term1 = term2 + term3;
        term2 = term1 + term3;
        term3 = term2 + term1;
 
        if(term1 % 2 == 0) {
            sum += term1;
        }
        if(term2 % 2 == 0) {
            sum += term2;
         }
         if(term3 % 2 == 0) {
            sum += term3;
         }
 
    }
}

Leave a Reply