Sunday, February 22, 2009

[2009.02.22] Project Euler: Problem 2

Now that my previous WPF project is done, I can get back to some F#! Again, I am using Project Euler as my demo platform.

Project Euler: Problem 2

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.

Example

Given the first 10 terms, the sum of the even valued terms will be:
2 + 8 + 34 = 44

Solution

This problem is divided into two parts: creating the Fibonacci sequence and then summing up the even valued terms. The listing illustrates the solution.

    1 #light

    2 #r "FSharp.PowerPack.dll"

    3 

    4 // create recursive function to

    5 //  generate Fibonacci sequence

    6 let rec fibo = function

    7     | 0 | 1 -> 1

    8     | x -> fibo(x - 1) + fibo(x - 2)

    9 

   10 // generate the first 33 Fibonacci numbers

   11 // using lazy evaluation

   12 let fibs = seq{ for i in 1 .. 33 -> fibo i }

   13 

   14 // filter out even terms

   15 // filter out terms less then 4 million

   16 // add each term together

   17 fibs  |> Seq.filter (fun x -> x % 2 = 0)

   18       |> Seq.filter (fun x -> x < 4000000)

   19       |> Seq.fold   (+) 0

   20 

   21 // the result is: 4613732

Notes:

This was not the best approach to use, in that I sort of cheated to know how many terms I need to iterate to fall in the 4 million range. That is, I got these numbers by trial and error since fibo 32 = 3524578 and fibo 33 = 5702887, I knew that by using 33, I will be in the range needed. However, I will try to address this in a revised version. Since it's been a while since I did F#, I wanted to just knock this one out as quickly as possible. My apologies for the little trick.

No comments: