- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements