Back to C#
Published on Wednesday, July 20, 2011The second Project Euler problem was a bit more involved. It reads:
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, …
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
I decided to first compile a list of all members of the Fibonacci sequence below four million and then folding all even values in that list into a variable. I had trouble writing a loop that didn't append the first value over 4,000,000 to the list, so I came up with the less than elegant solution of having it evaluate a “nextFib” variable, append said variable to the list, and then recalculate it before beginning the loop again. Putting the calculation after the evaluation and Add() meant that I had to feed it the first value, which I probably wouldn't do if I knew the language better.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSharpProblem2
{
class Program
{
static void Main(string[] args)
{
int result = 0;
List<int> fibonacci = new List<int>();
fibonacci.Add(1);
fibonacci.Add(1);
int nextFib = 2;
while (nextFib < 4000000)
{
fibonacci.Add(nextFib);
nextFib = fibonacci[fibonacci.Count - 1] + fibonacci[fibonacci.Count - 2];
}
foreach (int seq in fibonacci)
{
if (seq % 2 == 0) { result += seq; }
}
Console.WriteLine("The sum of all Fibonacci sequence numbers below 4,000,000 is {0}", result);
}
}
}