Bill Blogs in C#

Bill Wagner discusses C#, LINQ, and other items of interest

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.

Published Friday, April 11, 2008 3:24 PM by wwagner
Filed under: , , ,

Comments

# re: Project Euler problem 6@ Saturday, April 12, 2008 1:00 AM

I know it probably isn't as performant since we loop twice (althoug there is less instanciations), but I find the following approach easier to understand:

int sum = Enumerable.Range(1, 100).Sum();

int sumOfSquare = Enumerable.Range(1, 100).Select(i => i * i).Sum();

int diff = (sum * sum) - sumOfSquare;