Finding sum of multiples in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a number as a limit (the only argument). The function should calculate the sum of all the natural numbers below the limit that are multiples of 3 or 5.

For example −

If the limit is 10

Then the sum should be 3+5+6+9 = 23

Example

Following is the code −

const sumOfMultiple = (limit = 10) => {
   let i, sum = 0;
   for (i = 3; i < limit; i += 1) {
      if (i % 3 === 0 || i % 5 === 0) {
         sum += i;
      };
   };
   return sum;
}
console.log(sumOfMultiple(1000));
console.log(sumOfMultiple(10));
console.log(sumOfMultiple(100));

Output

Following is the output on console −

233168
23
2318
raja
Published on 10-Dec-2020 07:39:06
Advertisements