The sum of squares and the square of sums
Published on Thursday, July 21, 2011Project Euler #6 has been answered more times than problems 3-5, which is generally interpreted as meaning that it's easier than they. It reads:
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.
100 is definitely low enough to allow a brute-force solution, so that's how I approached the problem. Two variables churned through a single, 100-iteration for loop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Problem6
{
class Program
{
static void Main(string[] args)
{
int sumOfSquares = 0;
long squareOfSums = 0;
for (int i = 1; i <= 100; i++)
{
sumOfSquares += (i * i);
squareOfSums += i;
}
squareOfSums *= squareOfSums;
Console.WriteLine("Difference: {0}",(squareOfSums - sumOfSquares));
}
}
}