C# Implementation of Problem 2

View source code here on GitHub!

class p0002
: Euler.IEuler
object Answer ()
 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*/
17using System;
18
19namespace Euler
20{
21    public class p0002 : IEuler
22    {
23        public object Answer()
24        {
25            int answer = 0,
26                i = 2,
27                j = 8,
28                tmp = 0;
29
30            while (i < 4000000)
31            {
32                answer += i;
33                tmp = 4 * j + i;
34                i = j;
35                j = tmp;
36            }
37
38            return answer;
39        }
40    }
41}

Tags: fibonacci-number, divisibility