Project Euler in F#, Problems 1 and 2

I recently stumbled across the Project Euler website. From wikipedia: “Project Euler (named after Leonhard Euler) is a website dedicated to a series of computational problems intended to be solved with computer programs”.

I thought this would be a good opportunity to continue working with F# and have some material for writing more blog articles.

Problem 1 is very straight forward.

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

I went with the most logical algorithm I could think of.

  1. Enumerate though each of the numbers 1-999.
  2. Filter the values that are multiples of either 3 or 5.
  3. Add up the resulting values.

The resulting F# code is quite elegant:

let problem1 = 
    [1..999] |> Seq.filter (fun i -> i % 3 = 0 || i % 5 = 0) |> Seq.sum

After looking at other algorithms people had used, there are more efficient methods using summations. But not bad for my first solution. On to 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, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Again, there is a pretty obvious solution here.

  1. Generate the Fibonacci sequence up to 4 million.
  2. Filter the values that are even.
  3. Add up the resulting values.

The resulting F# code:

let Problem2 =
    Seq.unfold (fun state ->
        if (snd state > 4000000) then None
        else Some(fst state + snd state, (snd state, fst state + snd state))) (1,1)
            |> Seq.filter (fun x -> x % 2 = 0) |> Seq.sum

Again, a more efficient solution can be found but this is at least semantically easy to follow.

I’m planning on continuing this series of blog articles with a problem or 2 for each entry, and seeing how many of the problems I can get through.  I’ll also provide the source code.   If you’re interested in more in this series stay tuned!


Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s