Project Euler #2: Sum of even Fibonacci values less than 4,000,000
Problem #2 in Project Euler requires us to calculate the sum of even Fibonacci values that are less than 4,000,000. For this purpose, it may be helpful to understand what Fibonacci series is.
The first two numbers in Fibonacci series are 0 and 1. Each following number is the sum of the previous two numbers. The formula can be written as below.
Hence, Fibonacci series is of the following sequence: 0, 1, 1, 2, 3, 5, 8, 13, …
Knowing this, solving Project Euler problem #2 is quite straight forward. The following C# code does the job.
using System;
namespace Euler2
{
/* Sum of even Fibonacci values that do not exceed 4,000,000 */
class Program
{
static void Main(string[] args)
{
int fibA = 0;
int fibB = 1;
int fib = 0;
int total = 0;
int remainder;
while (fib < 4000000)
{
Math.DivRem(fib, 2, out remainder);
if (remainder == 0)
{
total += fib;
}
fib = fibA + fibB;
fibA = fibB;
fibB = fib;
}
Console.WriteLine("Finding sum of even Fibonacci values under 4,000,000");
Console.WriteLine("Answer is {0}", total);
}
}
}
I’ve decided to write the above program in C# since I’ve already got Visual Studio C# Express open from solving Project Euler #1. Whatever language you decide to program in, it is important to make sure that the data type chosen can support large enough number to hold the answer to the problem without overflowing.
