Sunday, May 1, 2011

Project Euler - Problem 6

Welcome to week 6 of Project Euler.

Problem 6:
What is the difference between the sum of the squares and the square of the sums?

Details:
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.


Code:
// What is the difference between the sum of the squares and the square of the sums?
class Problem0006
{
    static void Main(string[] args)
    {
        int sum = 0;
        int sumOfSquares = 0;
        for (int i = 1; i <= 100; i++)
        {
            sum += i;
            sumOfSquares += (i * i);
        }

        int squareOfSums = (sum * sum);

        Console.WriteLine((squareOfSums - sumOfSquares).ToString());
        Console.Read();
    }
}



Solution:
I am not entirely sure how this problem made the cut.  Granted, squaring the first 100 natural numbers would take a bit, but this is not challenging in any programming language at all. In fact most graphing calculators can be programmed to do this with little to no effort.  That being said...

I started off simply with two variables, one for the sum of the integers themselves, and one for the sum of the squares.  For through the numbers needed adding each one to the sum variable and the square (number * number) to the sumOfSquares variable.  At the end I squared the sum that I had running (not the sumOfSquares), subtracted the two, and printed the answer.

Up next week will be problem 7 dealing with Prime Numbers again.  Those really seem to be a running favorite, at least in the early questions. Until then...

Enjoy!

0 comments:

Post a Comment