Skip to main content

Command Palette

Search for a command to run...

Project Euler: #1 - Multiples of 3 or 5

Published
2 min read
Project Euler: #1 - Multiples of 3 or 5
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

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.


Problem Description

This is a more straightforward problem.

The natural numbers below 10 would be 1,2,3,4,5,6,7,8 and 9 (Since it is below 10, 10 is exclusive)

And those multiples of 3 are 3, 6 and 9

And multiples of 5 would be 5.

So now, the sum of all those multiples would be,

3 + 6 + 9 + 5 = 23.

So now, we want to find the sum of all the multiples of 3 and 5 below 1000 (1000 is exclusive)


Approach

My approach is to get all the multiples of 3 or 5 in an array - multiples and then use Array.prototype.reduce() function to calculate the sum of all items in that array multiples

For my solution, the time taken is between 0.11ms and 0.14ms.

Another approach can be to add the multiples directly to a variable, instead of pushing to an array. Inside the if, we can use sum += i and print the sum which is our result.

As I said before, there is more than one approach to each problem!


Solution

const multiples = [];

for (let i = 1; i < 1000; i++) {
    if (i % 3 === 0 || i % 5 === 0) {
        multiples.push(i);
    }
}

console.time("p#1");
console.log(multiples.reduce((acc, curVal) => acc + curVal));
console.timeEnd("p#1");

Project Euler: #1 Solution Answer

The GitHub repo for this problem is found at 01

If you have another 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!

Project Euler: JS Solution Explained!

Part 17 of 18

In this series, I will be discussing Project Euler Solutions. 'Project Euler' helps in improving problem-solving and programming skills. Remember, there is always a better solution to the problem. 💯

Up next

Project Euler: About the Solution Series

Solving Project Euler Problems using Javascript!

More from this blog

T

The Introvert Coder | Quietly Building Loud Code!

23 posts

Quietly Building Loud Code!