Sunday, February 22, 2009

[2009.02.22] Project Euler: Problem 6

Project Euler in F#!

Project Euler: Problem 6

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

Example

The sum of the squares of the first ten natural numbers is:
12 + 22 + ... + 102 = 385

The square of the sum of the first ten natural numbers is:
(1 + 2 + ... + 10)2 = 552 = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640.

Solution

This is a pretty simple problem, especially in F#. Yes, I know it can be reduced to one line, but I did it this way to increase readability at least. In addition, I tried to use lazy sequence evaluation instead of lists.

    1 #light

    2 #r "FSharp.PowerPack.dll"

    3 

    4 let sumOfSquare =

    5     seq{ for i in 1 .. 100 -> i * i }

    6     |> Seq.fold (+) 0

    7 let squareOfSum =

    8     seq{ 1 .. 100 }

    9     |> Seq.fold (+) 0 |> (fun x -> x*x)

   10 let result = squareOfSum - sumOfSquare

   11 // result = 25164150

No comments: