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 = 0
for i in range(1, n + 1):
if i % 3 == 0:
count = count + 1Is 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.
if i % 3 == 0 or i % 5 == 0:
count = count + 1- i
- 2
- count
- 0
1 and 2 are not multiples of 3 or 5, so the count stays at 0.
How many numbers from 1 to 15 are multiples of 5?
- A3
- B2
- C15
Show the answer
3. They are 5, 10 and 15.
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.
n = 10 → 5
0 ≤ n ≤ 1,000,000