4.15 Exercise: Sum of multiples of 3 and 5

Here is another simple but great exercise to train your programming brain. Write a function sum that takes a limit and returns the sum of every integer between 0 and the limit that is a multiple of 3 or 5. For example, sum(10) should return 33, because the qualifying numbers are 3, 5, 6, 9 and 10 — and 3 + 5 + 6 + 9 + 10 = 33. Pause the video and try it before reading the solution.

Solution

function sum(limit) {
  let total = 0;

  for (let i = 0; i <= limit; i++) {
    if (i % 3 === 0 || i % 5 === 0)
      total += i;
  }

  return total;
}

console.log(sum(10)); // 33
  • The for loop iterates from 0 to limit included.
  • The condition i % 3 === 0 || i % 5 === 0 filters multiples of 3 or 5.
  • The matching values are accumulated in total via the compound assignment +=.

Notice the blank line before the return statement. Separating the loop logic from the value being returned is a good readability habit — it visually marks where the computation ends and the result is handed back. See you in the next demo.

Summary

This lesson demonstrates how to build a function that calculates the sum of all multiples of 3 and 5 up to a given limit. The instructor walks through a worked example where the multiples of 3 and 5 below 10 (3, 6, 9, 5, 10) sum to 33. The solution uses a for loop, applies the modulo operator to check divisibility, accumulates results in a sum variable, and follows best practices for code formatting and readability.

Key points

  • Use the modulo operator (%) to check divisibility: if i % 3 === 0 || i % 5 === 0, the number is a multiple of 3 or 5
  • Initialize a sum variable to 0 before the loop, then incrementally add each qualifying multiple
  • Use a for loop to iterate from 0 up to the given limit, incrementing the counter with each iteration
  • Return the accumulated sum after the loop completes
  • Improve code readability by using line breaks to separate initialization, core logic, and return statements

FAQ

How do you identify if a number is a multiple of 3 or 5?

Use the modulo operator (%) to find the remainder after division. If i % 3 === 0 or i % 5 === 0, then the number is divisible by 3 or 5 respectively.

Why start the sum variable at 0?

Initializing sum to 0 establishes the base case for accumulation, ensuring the first multiple added produces the correct result and the total is calculated correctly throughout the loop.

What multiples would be found between 0 and 10?

The multiples of 3 are 3, 6, and 9; the multiples of 5 are 5 and 10. Adding these together: 3 + 5 + 6 + 9 + 10 = 33.