Geeks With Blogs
Mark Pearl

 

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


Comments on this post: F# Euler Problem 6

# re: F# Euler Problem 6
Requesting Gravatar...
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

Chris.
Left by Chris Ballard on Jun 26, 2010 9:25 PM

# re: F# Euler Problem 6
Requesting Gravatar...
Thanks Chris

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

I am going to use that one in future!
Left by MarkPearl on Jun 27, 2010 9:34 AM

# re: F# Euler Problem 6
Requesting Gravatar...
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!
Left by Chris Ballard on Jun 27, 2010 12:22 PM

# re: F# Euler Problem 6
Requesting Gravatar...
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 f n = (3*(n*n*n*n-n*n)+2*(n*n*n-n))/12





Left by TechNeilogy on Jun 27, 2010 5:22 PM

# re: F# Euler Problem 6
Requesting Gravatar...
thought of posting my solution too:

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
Left by Balaji on Jun 27, 2010 8:40 PM

Your comment:
 (will show your gravatar)


Copyright © MarkPearl | Powered by: GeeksWithBlogs.net