Project Euler – Problem 6


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

Problem:
The sum of the squares of the first ten natural numbers is,
1^(2) + 2^(2) + … + 10^(2) = 385

The square of the sum of the first ten natural numbers is,
(1 + 2 + … + 10)^(2) = 55^(2) = 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:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Euler
{
    class Problem6 : IProblemBase
    {

        //The sum of the squares of the first ten natural numbers is,
        //1^(2) + 2^(2) + ... + 10^(2) = 385

        //The square of the sum of the first ten natural numbers is,
        //(1 + 2 + ... + 10)^(2) = 55^(2) = 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.

        public Problem6()
        {
        }

        public string GetAnswer()
        {
            int limit = 100;
            return (SquareOfTheSum(limit) - SumOfSquares(limit)).ToString();
        }

        private int SquareOfTheSum(int p)
        {
            int result = 0;
            for (int i = 0; i <= p; i++)
            {
                result += i;
            }
            return (result * result);
        }

        private int SumOfSquares(int p)
        {
            int result = 0;
            for (int i = 0; i <= p; i++)
            {
                result += (i * i);
            }
            return result;
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: