- Published on
Multiples of 3 and 5
- Authors
- Name
- Nicolas Justin
- @onicolasjustin
This post is part of the Project Euler series.
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 the provided parameter value number.
Solution
function isMultiple(dividend, divisor) {
return dividend % divisor === 0
}
function multiplesOf3and5(number) {
let sum = 0
for (let n = 3; n < number; n++) {
if (isMultiple(n, 3) || isMultiple(n, 5)) {
sum += n
}
}
return sum
}
multiplesOf3and5(10) // Expected output: 23
multiplesOf3and5(21) // Expected output: 98
multiplesOf3and5(148) // Expected output: 5175
multiplesOf3and5(474) // Expected output: 52094
multiplesOf3and5(1072) // Expected output: 268394
multiplesOf3and5(1998) // Expected output: 929670
Explanation
We can find out if a number is divisible by another number using the remainder (%) operator. This operator returns the remainder left over when one operand is divided by a second operand. For the operation n % d
, n
is called the dividend and d
is called the divisor.
NOTE: The remainder always takes the sign of the dividend.
console.log(7 % 5) // Expected output: 2
console.log(-7 % 5) // Expected output: -2
If there is no remainder after the division operation, the return will be 0
. It means that the dividend is a multiple of the divisor. For example:
4 (dividend) is a multiple of 2 (divisor) because the remainder of division is 0.
console.log(4 % 2) // Expected output: 0
console.log(-4 % 2) // Expected output: -0
13 (dividend) is not a multiple of 6 (divisor) because the remainder of the division is 5.
console.log(13 % 8) // Expected output: 5
console.log(-13 % 8) // Expected output: -5
Thus, we can create a function to check if a number is a multiple of another using the remainder operator and comparing with 0.
function isMultiple(dividend, divisor) {
return dividend % divisor === 0
}
After that, we can start a loop from the number 3 (because that's the first number divisible by 3 or 5) to the given number.
Inside the loop, we check if the current number is divisible by 3 or 5, if so, we add it to the sum
variable and at the end we return the result of the sum.
function multiplesOf3and5(number) {
let sum = 0
for (let n = 3; n < number; n++) {
if (isMultiple(n, 3) || isMultiple(n, 5)) {
sum += n
}
}
return sum
}
And that's it! We have solved this problem 🎉
References
Thanks for reading this far and see you in the upcoming posts! 👋
Happy coding! 🚀