Project Euler problem 6
Euler Problem six asks you to find the difference between the sum of squares and the square of the sum for the natural numbers 1 through 100.
I took the easy route, and made a brute force implementation in C#. There are a couple new bits of LINQ syntax here. This query creates two different anonymous types. One for the number / square pair, the second is the aggregate answer for the sum and the sum of squares.
The important points are that this is done in a single iteration. It's pulling each value in from the initial sequence and doing all the calculations in one iteration of the sequence:
1 var aggregate = (from number in Enumerable.Range(1, 100)
2 select new { number, square = number * number }).
3 Aggregate(new { Sum = 0, SumOfSquares = 0 },
4 (sums, val) => new { Sum = sums.Sum+val.number,
5 SumOfSquares = sums.SumOfSquares + val.square});
6
7 int SquareOfSums = aggregate.Sum * aggregate.Sum;
8
9 Console.WriteLine("{0} - {1} = {2}", SquareOfSums, aggregate.SumOfSquares,
10 SquareOfSums - aggregate.SumOfSquares);
There you go. Another simple bit of code.