Count Numbers Divisible by 3

Count numbers from 1 to n that are divisible by 3.

Logic BuildingBeginner
Logic Building
# Take n as input
n = int(input("Enter n: "))

# Count divisible by 3
count = 0
for i in range(1, n + 1):
    if i % 3 == 0:
        count += 1

print(f"Numbers divisible by 3: {count}")

Output

Enter n: 20
Numbers divisible by 3: 6

Check each number for divisibility by 3.

Key Concepts:

  • Loop from 1 to n
  • Check if divisible by 3 using modulo
  • Count matches