Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sum of all multiples in JavaScript
We need to write a JavaScript function that takes a number n as the first argument, followed by any number of divisor arguments. The function should sum all numbers up to n that are divisible by any of the specified divisors.
Problem Statement
Given a number n and multiple divisors, find the sum of all numbers from 1 to n that are multiples of any of the divisors.
For example, if we call:
sumMultiples(15, 2, 3)
We need to find numbers up to 15 that are divisible by either 2 or 3:
2, 3, 4, 6, 8, 9, 10, 12, 14, 15
The sum of these numbers is 83.
Solution
Here's the implementation using a while loop and rest parameters:
const num = 15;
const sumMultiple = (num, ...arr) => {
const dividesAny = num => arr.some(el => num % el === 0);
let sum = 0;
while (num) {
if (dividesAny(num)) {
sum += num;
}
num--;
}
return sum;
};
console.log(sumMultiple(num, 2, 3));
83
How It Works
The function uses several key concepts:
-
Rest Parameters:
...arrcollects all divisor arguments into an array -
Helper Function:
dividesAny()checks if a number is divisible by any divisor usingsome() - While Loop: Iterates from n down to 1, checking each number
-
Modulo Operator:
num % el === 0tests for exact divisibility
Alternative Approach with For Loop
const sumMultiplesFor = (num, ...divisors) => {
let sum = 0;
for (let i = 1; i <= num; i++) {
if (divisors.some(divisor => i % divisor === 0)) {
sum += i;
}
}
return sum;
};
console.log(sumMultiplesFor(15, 2, 3));
console.log(sumMultiplesFor(10, 3, 5));
83 18
Testing with Multiple Examples
// Test various combinations
console.log("Sum of multiples of 2,3 up to 15:", sumMultiple(15, 2, 3));
console.log("Sum of multiples of 3,5 up to 10:", sumMultiple(10, 3, 5));
console.log("Sum of multiples of 7 up to 20:", sumMultiple(20, 7));
console.log("Sum of multiples of 2,5 up to 12:", sumMultiple(12, 2, 5));
Sum of multiples of 2,3 up to 15: 83 Sum of multiples of 3,5 up to 10: 18 Sum of multiples of 7 up to 20: 21 Sum of multiples of 2,5 up to 12: 42
Conclusion
This solution efficiently finds the sum of all multiples using rest parameters and the some() method. The approach works for any number of divisors and handles edge cases gracefully.
