S1Q2 · Check Divisibility by Last Two Digits¶
⚡ Quick Reference
Function: is_divisible_by_last_two_digits(num: int) -> bool
Core idea: extract the last two digits, guard against zero, check divisibility.
def is_divisible_by_last_two_digits(num: int):
units = num % 10
tens = (num // 10) % 10
if units == 0 or tens == 0:
return False
return num % units == 0 and num % tens == 0
Key rules:
- Last digit (units): num % 10
- Second-to-last digit (tens): (num // 10) % 10
- Return False if either digit is 0 (avoid division by zero)
- Both num % units == 0 and num % tens == 0 must hold
Problem Statement¶
Problem
Write a function is_divisible_by_last_two_digits(num) that returns True if num is divisible by both of its last two digits. Return False if either digit is zero.
Examples:
1236
True
345
False
748
False
740
False
Tracing all examples¶
num |
units (%10) |
tens (//10%10) |
Zero? | num%units |
num%tens |
Result |
|---|---|---|---|---|---|---|
| 1236 | 6 | 3 | ❌ | 1236%6=0 ✅ | 1236%3=0 ✅ | True |
| 345 | 5 | 4 | ❌ | 345%5=0 ✅ | 345%4=1 ❌ | False |
| 748 | 8 | 4 | ❌ | 748%8=4 ❌ | 748%4=0 ✅ | False |
| 740 | 0 | 4 | ✅ (units=0) | - | - | False |
Solution approaches¶
def is_divisible_by_last_two_digits(num: int):
last_digit = num % 10
second_last_digit = (num // 10) % 10
# Guard: return False if either digit is zero
if last_digit == 0 or second_last_digit == 0:
return False
divisible_by_last = num % last_digit == 0
divisible_by_second_last = num % second_last_digit == 0
return divisible_by_last and divisible_by_second_last
Key takeaways¶
(num // 10) % 10 extracts the tens digit
Dividing by 10 shifts the number right by one digit; taking the remainder mod 10 then isolates the new last digit. This pattern generalises - (num // 100) % 10 gives the hundreds digit, and so on.
Check for zero before dividing
Dividing by zero raises a ZeroDivisionError. The zero guard must come before any num % digit call. Short-circuit and won't save you here - check zero explicitly first.
Divisibility by the digit vs divisibility of the digit
The question asks if num is divisible by its digits - i.e. num % digit == 0. A common mistake is checking if the digit divides into the last two digits instead of into num itself.