## Project Euler in F# – Problem 6

The exercises proposed by **Project Euler** are ordered by difficulty, and the one I'll discuss today is ranked **sixth**.

However, I think it is one of the easiest to solve, since it doesn't require any trick and the solution is already written in its text:

The sum of the squares of the first ten natural numbers is,

1² + 2² + ... + 10² = 385The square of the sum of the first ten natural numbers is,

(1 + 2 + ... + 10)² = 55² = 3025Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 ? 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

We just have to evaluate two formulas and then perform a subtraction, so let's go directly to the **F# code**:

#light let numbers = [1 .. 100] let diff = (numbers |> Seq.fold (+) 0 |> (fun x -> x*x)) - (numbers |> Seq.sumByInt (fun x -> x*x))

You should already know the pipeline operator, which is massively used in F#.

*Seq.fold* is used to apply a function (in our case the sum operator) to all the elements of a collection (i.e. the list of numbers) starting from a base value that we set equal to zero.

Then we pass the result to a function that takes a number and returns its square, actually giving us **the square of the sum** of the first 100 numbers.

In the next line of the *diff* function we evaluate **the sum of the squares** of the first 100 numbers.

It is done thanks to the *Seq.sumByInt* function that returns the sum of the results generated by applying the given function (i.e. the square function) to each element of the collection.

That's it, no tricks and no special mathematical knowledge required, I told you!

### Twitter Updates

- @avalaxy Unfortunately I don't have an ETA. Feel free to submit patches or add suggestions to reach the goal sooner 2012-09-28
- @avalaxy it is planned for the new APIs and the library work is tracked at http://t.co/tAOfAYTA 2012-09-28
- @Sabrina_Miso Prova con uno zaino, non sara' trendy come una borsa, ma almeno le spalle non moriranno :) 2012-09-24
- @duplikey come hai fatto a resistere due giorni? 2012-09-24
- @avalaxy sorry, never tried that on a Metro app. Have you tried building the source instead? 2012-09-09
- More updates...

Michiel BorkentMarch 3rd, 2008 - 15:19

With some cleverness the expression (x_1^2 .. x_100^2) – (x_1 .. x_2)^2 can be simplified to the sum of x_i*x_j, where i ranges from [1 .. 100] and j > i.

Example: (a + b)^2 – (a^2 + b^2) = 2ab.

Exameple: (a + b + c)^2 – (a^2 + b^2 + c^2) = 2(ab+ac+bc)

The following uses this simplification:

#light

let rec diff2 l =

match l with

| [] -> 0

| _ -> 2 * List.sumByInt (fun x -> List.hd l * x) (List.tl l) + diff2 (List.tl l)

diff2 [1 .. 100]

Michiel BorkentMarch 3rd, 2008 - 15:21

Of course I meant the expression (x_1 + .. + x_2)^2 – (x_1^2 + .. + x_100^2) , not (x_1^2 .. x_100^2) – (x_1 + .. + x_2)^2