Project Euler in F#: Problem 6

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

This is solvable using two simple identities.

let ans n = (n*(n-1)*(n+1)*(3*n+2))/12

But, since I’m trying to learn F#, rather than do high school math, lets try a brute force solution.

 let square n = n * n
 let ans2 = ({1 .. 100} |> Seq.sum |> square) - ({1..100} |> Seq.map square |> Seq.sum)

And yet again, I can learn something from Dustin’s solution. This time, it’s the function composition operator (<<), which lets us write this more simply, avoiding duplicating the sequence.

let diff f1 f2 seq = f1 seq - f2 seq
let ans3 = {1 .. 100} |> diff (square << Seq.sum) (Seq.sum << (Seq.map square))
Advertisements
Project Euler in F#: Problem 6

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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