Sum of all multiples in JavaScript


We are required to write a JavaScript function that takes in a number, say n, as the first argument, and then any number of arguments following that.

The idea is to sum all numbers upto n which are divided by any of the numbers specified by second argument and after.

For example −

If the function is called like this −

sumMultiples(15, 2, 3);

Then the output should be −

const output = 83;

Because the numbers are −

2, 3, 4, 6, 8, 9, 10, 12, 14, 15

Example

The code for this will be −

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));

Output

And the output in the console will be −

83

Updated on: 25-Nov-2020

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements