Project Euler :: Problem #2
Continuing with the Project Euler problems, I’ll go over my solution to Problem #2.
Problem #2 says:
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 of the even-valued terms in the sequence which do not exceed four million.
First, a little on the Fibonacci Numbers. Fibonacci Numbers are numbers in the Fibonacci Sequence. The down-and-dirty version of the sequence is that the numbers are the sum of the sequence of the last 2 numbers in the sequence. Wikipedia has this great little PNG definition explaining it clearly:
If the number we’re trying to find in the Fibonacci Number of is less than or equal to 1 then the Fibonacci Number is the original number itself. Integers greater than 1 is where things get interesting. You can see that the formula at that point becomes:
Fn = Fn – 2 + Fn – 1
Yay, recursion! So each number greater than 1 we compute the Fibonacci Number for n – 2 and for n – 1 and then add them together. Lets try with a couple numbers:
F4 = F4 – 2 + F4 – 1
F4 = F2 + F3
F4 = (F2 – 2 + F2 – 1) + (F3 – 2 + F3 – 1)
F4 = (F0 + F1) + (F1 + F2)
F4 = (0 + 1) + (1 + (F2 – 2 + F2 – 1))
F4 = (0 + 1) + (1 + (F0 + F1))
F4 = (0 + 1) + (1 + (0 + 1))
F4 = 0 + 1 + 1 + 0 + 1
F4 = 3
Jeeeeeez, that’s a of work. Maybe we’ll skip “doing a couple” and just go right to the code. The problem says that we need to find the sum of all of the even terms in the Sequence below 4,000,000. So what we”ll do is iterate over a set of numbers adding the even terms to our holding variable until we reach our limit.
using System;
class Program
{
public static void Main(string[] Args)
{
int l = (Args.Length > 0 ? Int32.Parse(Args[0]) : 4000000);
int sumOfEvens = 0;
for (int i = 0; ; i++)
{
int f = ComputeFib(i);
if (f >= l)
break;
if (f % 2 == 0)
sumOfEvens += f;
}
Console.WriteLine(sumOfEvens.ToString());
Console.WriteLine("Done, press enter to quit...");
Console.ReadLine();
}
public static int ComputeFib(int n)
{
if (n == 0 || n == 1)
return n;
return ComputeFib(n - 2) + ComputeFib(n - 1);
}
}
