How to find the sum of all the multiples of 3 or 5 below 1000 in JavaScript

2 Answers

0 votes
function sumOfMultiples(limit) {
    // Calculate the upper bounds
    const upperForThree = Math.floor(limit / 3);
    const upperForFive = Math.floor(limit / 5);
    const upperForFifteen = Math.floor(limit / 15);

    // Calculate the sums using arithmetic series formula
    const sumThree = 3 * upperForThree * (1 + upperForThree) / 2;
    const sumFive = 5 * upperForFive * (1 + upperForFive) / 2;
    const sumFifteen = 15 * upperForFifteen * (1 + upperForFifteen) / 2;

    // Calculate the total sum
    return sumThree + sumFive - sumFifteen;
}

// Define the limit
const limit = 999;

// Calculate and print the result
console.log(sumOfMultiples(limit));


  
  
/*
run:
 
233168

*/

 



answered Apr 15 by avibootz
0 votes
function sumOfMultiples(limit) {
    let sum = 0;

    // Iterate through numbers from 0 to limit-1
    for (let x = 0; x < limit; x++) {
        if (x % 3 === 0 || x % 5 === 0) {
            sum += x;
        }
    }

    return sum;
}

// Define the limit
const limit = 1000;

// Calculate and print the result
console.log(sumOfMultiples(limit));

  
  
/*
run:
 
233168

*/

 



answered Apr 15 by avibootz
...