Problem Two is defined as

 

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 the even-valued terms in the sequence which do not exceed four million.

 F# Code:

let fib = Seq.unfold (fun (n0,n1) -> Some(n0,(n1, n0 + n1)))(1I,1I)
let fiblessthan n = {
  let e = fib.GetEnumerator()
  while e.MoveNext() && e.Current < n do
  yield e.Current }
let even = fiblessthan 4000000I |> Seq.filter (fun x -> x % 2I = 0I) 
let p2 = even |> Seq.fold1 (fun sum i -> sum + i)
print_any p2

After finishing my version of this problem in F#, I went online and look at some other solutions.  One of the best, I found was by Dustin Campbell on his blog "Did it with .NET"

C# 3.0 (using extension method)

static public class Numbers
{
    public static IEnumerable<Int64> Fibonacci
    {
        get
        {
            int a = 1;
            int b = 2;
            int t = 0;
            yield return a;
            yield return b;
            while (true)
            {
                yield return t = a + b; a = b; b = t;
            }
        }
    }
 
}
 
Numbers.Fibonacci.TakeWhile(x => x <= 4000000).Where(x => x % 2 == 0).Sum()
del.icio.us Tags: ,,