DSA Factory
Free lessonsProgramming basics · Stage 3 · Loops that count · Step 3

Counting the ones that count

Count only the numbers that pass a test, by putting an if inside a loop. About 9 minutes.

A loop with a question inside

A teacher looks at every child in the class and counts only those wearing a red shirt. She doesn't count everyone, only the ones who pass the test.

In code, that's a loop with an if inside it. Make a counter box that starts at zero. On each pass, ask the question about the current number. If the answer is true, add one to the counter. If not, do nothing and move on to the next number.

Count only when the test is true: put the adding inside the if.
In code
count = 0
for i in range(1, n + 1):
    if i % 3 == 0:
        count = count + 1

Is it a multiple?

How do you ask whether a number is a multiple of 3? Think of the remainder. If you divide by 3 and nothing is left over, then the number fits into whole groups of 3. A remainder of zero means it is a multiple.

You can ask for two things at once with or. Is the number a multiple of 3, or a multiple of 5? Counting from 1 to 10, the answers are 3, 5, 6, 9 and 10.

A remainder of zero: means it divides evenly.
In code
if i % 3 == 0 or i % 5 == 0:
    count = count + 1
Multiples of 3 or 5, from 1 to 10
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
i
i
2
count
0

1 and 2 are not multiples of 3 or 5, so the count stays at 0.

Move 1 of 8
Quick check

How many numbers from 1 to 15 are multiples of 5?

  1. A3
  2. B2
  3. C15
Show the answer

3. They are 5, 10 and 15.

Your problem

Threes and fives

Count how many numbers from 1 up to n (including n) are a multiple of 3 or a multiple of 5. A number that is a multiple of both is still counted once.

Example
n = 10 → 5

0 ≤ n ≤ 1,000,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding