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

Numbers with Digit Sum Multiple of 3

Select numbers with digit sums divisible by three using Python. Students trace nested loops and compare a digit-based rule with direct number divisibility.

AdvancedPhase 2 - Level 5: Logical Loop CombinationsExample 4 of 12
numbers-with-digit-sum-multiple-of-3.py
1# Print numbers
2print("Numbers with digit sum multiple of 3:")
3for num in range(1, 101):
4 # Calculate digit sum
5 digit_sum = 0
6 temp = num
7 while temp > 0:
8 digit_sum += temp % 10
9 temp //= 10
10
11 # Check if multiple of 3
12 if digit_sum % 3 == 0:
13 print(num, end=" ")
14print()

Output

...

The sample abbreviates a longer result. The program prints the intervening values; it does not print these dots.

In this one

  • Use a digit-sum divisibility rule
  • Reset an accumulator
  • Compare derived and direct tests

How it works

  1. 1

    For each candidate, reset digit_sum.

  2. 2

    Extract and add all digits.

  3. 3

    Print when the sum has remainder zero modulo three.

Edge cases

Does 100 print?

Does 100 print?

No. Its digit sum is one.

Does 99 print?

Does 99 print?

Yes. Its digit sum eighteen is divisible by three.

What's going on

The inner loop adds the decimal digits of each candidate from one through one hundred. The outer filter tests that completed sum modulo three.

For 12, the sum is three and the number prints. In base ten this gives the same matches as divisibility by three, but the lesson deliberately practices extracting digits. Resetting digit_sum is necessary before scanning the next candidate.

Does 100 print? No. Its digit sum is one.

Does 99 print? Yes. Its digit sum eighteen is divisible by three.

Quiz

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

Question 1

What is tested after the inner loop?

Pick an answer to check it.

Question 2

Does 100 print?

Pick an answer to check it.

Questions people ask

Does 100 print?

No. Its digit sum is one.

Does 99 print?

Yes. Its digit sum eighteen is divisible by three.

What is tested after the inner loop?

The completed digit sum.