Project Euler – Problem 2 Solution

Yan Cui

I help clients go faster for less using serverless technologies.

Problem

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.

Solution

Here’s my solution in F#:

let fibonacciSeq = Seq.unfold (fun (current, next) -> Some(current, (next, current + next))) (0, 1)

let fibTotal =
    fibonacciSeq
    |> Seq.takeWhile (fun n -> n < 4000000)
    |> Seq.filter (fun n -> n % 2 = 0)
    |> Seq.sum

Here I’ve used a sequence, whilst a sequence is similar to a list or array in F# in that it holds a series of elements, there’s a crucial difference, each sequence element is computed only as required so it provides better performance than a list in situations which not all elements are used. If that sounds familiar to you, that’s because a sequence is basically an IEnumerable<T>!

In the first step of this code I’m building up the fibonacci sequence using the Seq.unfold function which given an initial value, generates a sequence by continuously applying some computation to work out each subsequent element in the sequence:

let fibonacciSeq = Seq.unfold (fun (current, next) -> Some(current, (next, current + next))) (0, 1)

This sequence, if iterated through, will contain all the numbers in the fibonacci sequence to infinity, which is why in the next line I’ve specified that we should take values from the sequence until the value exceeds 4 million:

fibonacciSeq
|> Seq.takeWhile (fun n -> n < 4000000)
&#91;/code&#93;

The next two lines then identifies and sums all the even numbers in the sequence:

&#91;code lang="fsharp"&#93;
|> Seq.filter (fun n -> n % 2 = 0) // only interested in even numbers
|> Seq.sum // add them up!

Whenever you’re ready, here are 3 ways I can help you:

  1. Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game.
  2. Consulting: If you want to improve feature velocity, reduce costs, and make your systems more scalable, secure, and resilient, then let’s work together and make it happen.
  3. Join my FREE Community on Skool, where you can ask for help, share your success stories and hang out with me and other like-minded people without all the negativity from social media.

 

3 thoughts on “Project Euler – Problem 2 Solution”

  1. The initial value passed to unfold should be (1, 2) instead of (0, 1), right? (I get that it doesn’t affect the final answer due to filtering for evens, but if someone is building up the solution like i was doing and printing out the intermediate results, the results of starting with (0, 1) could be confusing)

Leave a Comment

Your email address will not be published. Required fields are marked *