The 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.
F# Solution
I used to hate writing sequence-based algorithms in C#. Everything always just seemed so clunky. Then LINQ came along and make it much nicer.
Since sequences are first-class citizens in F#, it makes working with them very easy.
To solve this problem, we first need a function to produce the sum of the squares of the elements in a sequence.
let sumOfSquares nums =
nums
|> Seq.map (fun n -> n * n)
|> Seq.sum
We use Seq.map
to transform each element into its square, and then Seq.sum
to get the sum.
Contrast that with this:
public static int SumOfSquares(IEnumerable<int> nums)
{
var sum = 0;
foreach (var n in nums)
{
sum += (n*n);
}
return sum;
}
or this:
public static int SumOfSquares(IEnumerable<int> nums)
{
return nums.Sum(n => (n*n));
}
Both C# functions get the job done, but the F# code reads much better to me.
Next, we need a function to produce the square of the sum of a sequence of numbers.
let squareOfSum nums =
nums
|> Seq.sum
|> fun n -> n * n
And finally, put those functions together to get the answer:
(seq { 1..100 } |> squareOfSum) - (seq { 1..100 } |> sumOfSquares)