S1Q1 · Three-Digit Number with Digit-Sum Divisible by k¶
⚡ Quick Reference
Function: is_three_digit_and_digit_sum_divisible_by_k(n: int, k: int) -> bool
Core idea: check the range, sum the digits, check divisibility.
def is_three_digit_and_digit_sum_divisible_by_k(n: int, k: int) -> bool:
if not (100 <= n <= 999):
return False
digit_sum = sum(int(d) for d in str(n))
return digit_sum % k == 0
Key rules:
- Three-digit: 100 <= n <= 999
- Digit sum: sum all digits of n
- Divisible by k: digit_sum % k == 0
- Both conditions must hold
Problem Statement¶
Problem
Write a function is_three_digit_and_digit_sum_divisible_by_k(n, k) that returns True only if n is a three-digit number AND the sum of its digits is divisible by k.
Examples:
n=145, k=5
True
n=123, k=5
False
n=1040, k=5
False
Tracing all examples¶
n |
Three-digit? | Digit sum | % k |
Result |
|---|---|---|---|---|
| 145, k=5 | ✅ 100–999 | 1+4+5=10 | 10%5=0 ✅ | True |
| 123, k=5 | ✅ | 1+2+3=6 | 6%5=1 ❌ | False |
| 450, k=10 | ✅ | 4+5+0=9 | 9%10=9 ❌ | False |
| 999, k=9 | ✅ | 9+9+9=27 | 27%9=0 ✅ | True |
| 1040, k=5 | ❌ (4 digits) | - | - | False |
Solution approaches¶
def is_three_digit_and_digit_sum_divisible_by_k(n: int, k: int) -> bool:
if not (100 <= n <= 999):
return False
hundreds = n // 100
tens = (n // 10) % 10
units = n % 10
digit_sum = hundreds + tens + units
return digit_sum % k == 0
Extracts each digit using integer arithmetic - no string conversion needed.
Key takeaways¶
Check range before digit sum
100 <= n <= 999 is a cheap O(1) check. Return False early so the digit-sum computation only runs for valid three-digit numbers - short-circuit logic at its simplest.
sum(int(d) for d in str(n)) - clean digit sum
Converting to a string gives access to each digit character; int(d) converts back to an integer for summing. Works for any number of digits without manual division.
Arithmetic extraction for three digits: // and %
For exactly three digits: n//100 = hundreds, (n//10)%10 = tens, n%10 = units. Direct and fast - no string conversion needed when you know the exact digit count.