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
- @Sabrina_Miso Che ne pensi di Community Manager per Google? In caso contattami ;) http://t.co/tBQ2e0N9 #stage #casaeditrice 1 week ago
- @MarcoEscher chi si rivede! In bocca al lupo per il tuo cammino e chissà che magari un giorno tu non mi raggiunga in Google! ;) 2 weeks ago
- @pigatss you should give one to me because I hosted you for lunch at the Googleplex :) #volunia 2012-01-13
- Avete visto quante posizioni per italiani sono aperte in Google a Dublino? http://t.co/ZlUfZ4uA 2012-01-10
- @thetarro congratulations, I gained 4 kg in 4 weeks :( 2012-01-08
- More updates...
Posting tweet...


