Problem 6: Sum Square Difference

The sum of the squares of the first ten natural numbers is,

The square of the sum of the first ten natural numbers is,

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is .

Find the difference between the sum of the squares of the first natural numbers and the square of the sum.

How to Solve

We need to compute two values and find their difference. There are well-known mathematical formulas for both:

Sum of Squares

The sum of the squares of the first n natural numbers:

Square of the Sum

The square of the sum of the first n natural numbers:

The Difference

The difference between the square of the sum and the sum of squares:

For smaller values of , we can simply iterate through each number, computing the sum and sum of squares directly. For larger values, the closed-form formulas above provide a more efficient solution.

Code Solution

function sumSquareDifference(n) {
  // Square of the sum: (1 + 2 + ... + n)^2
  let sum = 0;
  for (let i = 1; i <= n; i++) {
    sum += i;
  }
  const squareOfSum = sum * sum;

  // Sum of squares: 1^2 + 2^2 + ... + n^2
  let sumOfSquares = 0;
  for (let i = 1; i <= n; i++) {
    sumOfSquares += i * i;
  }

  return squareOfSum - sumOfSquares;
}

Test the Solution