online advertising
Processing math: 100%

Friday, August 16, 2013

Problem 2: Even Fibonacci numbers

Problem:

Please find the problem here.

Solution:

Again, brute force worked great. Observe that Fibonacci numbers are growing exponentially, there are only a handful of terms before the sequence reach four million. Here is the code:


namespace Euler
{
    using System;

    internal static partial class Program
    {
        public static void Problem002()
        {
            int fib, fibLast, fibLastLast;
            fibLast = 1;
            fibLastLast = 1;
            int sum = 0;
            do
            {
                fib = fibLast + fibLastLast;
                if (fib % 2 == 0)
                {
                    sum += fib;
                }

                fibLastLast = fibLast;
                fibLast = fib;
            } while (fib < 4000000);
            Console.WriteLine(sum);
        }
    }
}

Again, we do have better method, which doesn't really worth the time. But for completeness sake, I will describe it here. First, observe that even valued Fibonacci numbers appear as every third element, there is an easy way to show this is exactly the case.

Proposition 1.1: Fn is even if and only if n=2mod3.
Prove: Apparently, the proposition is true for small n, in particular, n3. Assume the proposition is true for all nk, for Fk+1=Fk+Fk1, we can deduce Fk is even if and only if both Fk and Fk1 are both odd or both even. But they cannot be both even (by assumption), so Fk+1 is even if and only if Fk and Fk1 are both odd, that correspond to k=1mod2 and therefore the position also hold true for n=k+1. By the principle of mathematical induction the proposition is true for all natural number n.

With the proposition above, we could avoid the division and just do the sum as follow, and it is guaranteed to give the same result.


namespace Euler
{
    using System;

    internal static partial class Program
    {
        public static void Problem002()
        {
            int fib, fibLast, fibLastLast;
            fibLast = 1;
            fibLastLast = 1;
            int sum = 0;
            int i = 0;
            do
            {
                fib = fibLast + fibLastLast;

                if (i == 0)
                {
                    sum += fib;
                }

                i++;
                if (i == 3)
                {
                    i = 0;
                }

                fibLastLast = fibLast;
                fibLast = fib;
            } while (fib < 4000000);

            Console.WriteLine(sum);
        }
    }
}

Answer: 4613732.

No comments :

Post a Comment