Today I had a quick bash at problem 6. To me this has been the easiest of the problems so far. It is the first time though that I got to use the Seq.Fold function which was good to get exposure to. I am not to happy with my code though, I can’t explain it, but it just seems a bit messy…

Anyhow, I look forward to feedback from everyone in the F# community on their approaches.

Problem

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.

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

My Solution

let Square n = n*n
let Problem6 n =
let myseq = seq{1..n}
let SumOfSquares n = myseq |> Seq.fold(fun acc x -> acc+(Square x)) 0
let SquareOfSums n = Square(myseq |> Seq.sum)
SquareOfSums(n) - SumOfSquares(n)

Posted on Saturday, June 26, 2010 7:25 PM
F#
| Back to top

Related Posts on Geeks With Blogs
Matching Categories

Looks like a reasonable solution to me. You can optimise a little though:

let Problem6 n = let myseq = seq{1..n} let SumOfSquares = myseq |> Seq.sumBy Square let SquareOfSums = Square(myseq |> Seq.sum) SquareOfSums - SumOfSquares

No probs Mark, in never ceases to amaze me how many things the F# team thought of when designing the core libraries, I am finding new stuff all the time!

I kind of cheated on this one. Fromt the form of the problem, I realized that there must be a formula so I decided to look for it. I'm not that great with concrete mathematics, but -- with a little experimentation and algebra -- I was able to stumble onto it, lol. I did at least *implement* it in F#:

let Problem6 n =

let myseq = seq{1..n}

let SumOfSquares = myseq |> Seq.sumBy Square

let SquareOfSums = Square(myseq |> Seq.sum)

SquareOfSums - SumOfSquares

Chris.

I never even realized that there was a sumBy function...

I am going to use that one in future!

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

let f n =

let x = seq {1..n} |> Seq.sum

let y = seq {1..n} |> Seq.map (fun i -> i * i) |> Seq.sum

(x * x) - y