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.
1# Print numbers2print("Numbers with digit sum multiple of 3:")3for num in range(1, 101):4 # Calculate digit sum5 digit_sum = 06 temp = num7 while temp > 0:8 digit_sum += temp % 109 temp //= 101011 # Check if multiple of 312 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
For each candidate, reset digit_sum.
- 2
Extract and add all digits.
- 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.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum