Skip to content

Project Euler #2: Sum of even Fibonacci values less than 4,000,000

March 15, 2010

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.

fibformula 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.

Advertisement
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.