JavaScript Implementation of Problem 6

View source code here on GitHub!

p0006()

Project Euler Problem 6

This turned out to be really easy

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.

Returns:

number --

 1/**
 2 * Project Euler Problem 6
 3 *
 4 * This turned out to be really easy
 5 *
 6 * Problem:
 7 *
 8 * The sum of the squares of the first ten natural numbers is,
 9 * 1**2 + 2**2 + ... + 10**2 = 385
10 *
11 * The square of the sum of the first ten natural numbers is,
12 * (1 + 2 + ... + 10)**2 = 55**2 = 3025
13 *
14 * Hence the difference between the sum of the squares of the first ten natural
15 * numbers and the square of the sum is 3025 − 385 = 2640.
16 *
17 * Find the difference between the sum of the squares of the first one hundred
18 * natural numbers and the square of the sum.
19 *
20 * @return {number}
21 */
22
23exports.p0006 = function() {
24    let sum = 1;
25    let sumOfSquares = 1;
26    for (let i = 2; i < 101; i++) {
27        sumOfSquares += i * i;
28        sum += i;
29    }
30    const squareOfSum = sum * sum;
31    return squareOfSum - sumOfSquares;
32};

Tags: arithmetic-progression, sequence-summation