w3resource

JavaScript: Sum the multiples of 3 and 5 under 1000

JavaScript Conditional Statement and loops: Exercise-12 with Solution

Sum of Multiples of 3 and 5 under 1000

Write a JavaScript program to sum 3 and 5 multiples under 1000.

Sample Solution

JavaScript Code:

// Variable to store the sum of numbers divisible by 3 or 5
var sum = 0;

// Loop through numbers from 0 to 999
for (var x = 0; x < 1000; x++) {
    // Check if the current number is divisible by 3 or 5
    if (x % 3 === 0 || x % 5 === 0) {
        // Add the current number to the sum
        sum += x;
    }
}

// Output the final sum
console.log(sum); 

Output:

233168

Flowchart:

Flowchart: JavaScript:- Sum the multiples of 3 and 5 under 1000

Live Demo:

See the Pen javascript-conditional-statements-and-loops-exercise-12 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that calculates the sum of all multiples of 3 and 5 below 1000 using a loop with conditional checks.
  • Write a JavaScript function that computes the sum of multiples of 3 and 5 under 1000 using the arithmetic series formula.
  • Write a JavaScript function that uses recursion to sum all multiples of 3 and 5 below 1000.
  • Write a JavaScript function that iterates through numbers below 1000 and sums those that are multiples of 3 or 5 while optimizing for performance.

Go to:


PREV : GCD of Two Numbers.
NEXT : javascript Event Handling Exercises Home

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.