Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Count Numbers Divisible by 3

Count integers divisible by three between one and n with Python. Students separate a match counter from a total and use modulo inside a bounded for loop.

BeginnerPhase 2 - Level 1: Basic LoopingExample 11 of 14
count-numbers-divisible-by-3.py
1# Take n as input
2n = int(input("Enter n: "))
3
4# Count divisible by 3
5count = 0
6for i in range(1, n + 1):
7 if i % 3 == 0:
8 count += 1
9
10print(f"Numbers divisible by 3: {count}")

Output

Enter n: 20
Numbers divisible by 3: 6

In this one

  • Filter multiples
  • Count rather than sum
  • Start a counter at zero

How it works

  1. 1

    Visit one through n.

  2. 2

    Increment count when i % 3 is zero.

  3. 3

    Print count after all candidates are checked.

Edge cases

Is zero considered?

Is zero considered?

No. The interval begins at one.

What if n is two?

What if n is two?

No value passes, so count remains zero.

What's going on

The loop visits every integer from one through n. count increases only when the current integer has remainder zero after division by three.

For n equal to ten, matches are three, six, and nine, so the answer is three. The program counts matching values; it does not add those values. The counter starts at zero so an empty interval naturally reports no matches.

Is zero considered? No. The interval begins at one.

What if n is two? No value passes, so count remains zero.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is added for each match?

Pick an answer to check it.

Question 2

Is zero considered?

Pick an answer to check it.

Questions people ask

Is zero considered?

No. The interval begins at one.

What if n is two?

No value passes, so count remains zero.

What is added for each match?

One.