puzzle contents
Contents
raw puzzle

Problem 6

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.

Solution

The sum of the square is:

\[f(n) = \sum\limits_{i=1}^n i^2 = \frac{1}{6} n (n+1) (2 n+1)\]

The square of the sum is:

\[g(n) = \left(\sum\limits_{i=1}^n i\right)^2 = \frac{1}{4} n^2 (n+1)^2\]

The difference:

\[\begin{array}{rl} f(n) - g(n) &= \frac{1}{6} n (n+1) (2 n+1) - \frac{1}{4} n^2 (n+1)^2\\ &= \frac{1}{12} n (n + 1) (3 n^2 - n - 2)\end{array}\]

And the final JS solution:

function solution(n) {

    return n * (n + 1) * (3 * n * n - n - 2) / 12;
}