Skip to main content

Project Euler Problem2 [c#]


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ProjectEuler
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Problem2());
        }

        /// <summary>
        /// http://projecteuler.net/problem=2
        /// </summary>
        /// <returns></returns>
        public static ulong Problem2()
        {
            var sum = Fibonacci().Where(x => x % 2 == 0)
                                 .TakeWhile(x => x < 4000000)
                                 .Aggregate((add, x) => add + x);
            return sum;
        }

        public static IEnumerable<ulong> Fibonacci()
        {
            var a = 0UL;
            var b = 1UL;
            var c = a + b;

            while (true)
            {
                yield return c;

                c = a + b;
                a = b;
                b = c;
            }


        }
    }
}

Comments

Popular posts from this blog