Skip to content

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:

Input
1236
Output
True
Input
345
Output
False
Input
748
Output
False
Input
740
Output
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):
    units = num % 10
    tens  = (num // 10) % 10
    if units == 0 or tens == 0:
        return False
    return num % units == 0 and num % tens == 0
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
def is_divisible_by_last_two_digits(num: int):
    digits = [int(d) for d in str(num)[-2:]]   # last two digits
    if 0 in digits:
        return False
    return all(num % d == 0 for d in digits)

str(num)[-2:] slices the last two characters of the string representation. Works cleanly for any number of digits.

def is_divisible_by_last_two_digits(num: int):
    u, t = num % 10, (num // 10) % 10
    return False if u == 0 or t == 0 else num % u == 0 and num % t == 0

Key takeaways

01

(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.

02

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.

03

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.