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))

### Like this:

Like Loading...

*Related*