Skip to main content

Command Palette

Search for a command to run...

Project Euler: #6 - Sum square difference

Published
2 min read
Project Euler: #6 - Sum square difference
S
I'm a frontend-heavy full stack developer who works with JavaScript, React, Next.js, TypeScript, and Node.js. ==== Currently Reworking my Blog ====

Problem

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

$$1^2 + 2^2 + 3^2 + 4^2 + 5^2 + 6^2 + 7^2 + 8^2 + 9^2 + 10^2 = 385$$

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

$$(1+2+3+4+5+6+7+8+9+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.


Problem Description

Well, the problem itself is self-explanatory.

The example given is for first 10 natural numbers. We need to find the difference between the Sum of Squares & Squares of the Sum of first 100 natural numbers.

i.e. 1 to 100.


Approach

This is a detailed approach.

Two functions are involved. One function is to calculate the square of each number from 1 to 100 and add those squares.

Another function is to add the numbers from 1 to 100 and square their sum.

Finally, find the difference between both.

Very simple, Right?


Solution

const sumOfSqrNums = (start, end) => {
    let sumOfSqrs = 0;

    if (start > end) {
        console.log(`${start} > ${end}! Enter a valid Start & End.`);
    } else {
        for (let i = start; i <= end; i++) {
            sumOfSqrs += Math.pow(i, 2);
        }
    }
    return sumOfSqrs;
}

const sqrOfSumNums = (start, end) => {
    let sumOfNums = 0;

    if (start > end) {
        console.log(`${start} > ${end}! Enter a valid Start & End.`);
    } else {
        for (let i = start; i <= end; i++) {
            sumOfNums += i;
        }
    }
    return Math.pow(sumOfNums, 2);
}

let difference = sqrOfSumNums(1, 100) - sumOfSqrNums(1, 100);
console.log(difference);

You can find my solution on GitHub 06

This particular solution was executed with a better complexity in Hacker rank. But there are still much better solutions to this. If you have another or a better solution, please leave it in the comments below.

For the other Project Euler Solutions, please follow the series Project Euler Solutions in JS.

Thank you!

More from this blog

T

The Introvert Coder | Quietly Building Loud Code!

23 posts

Quietly Building Loud Code!