Skip to content

S1Q1 · Check if a Number is Divisible by Exactly One of Two Numbers

⚡ Quick Reference

Function: div_by_exactly_one(num: int, a: int, b: int) -> bool

Core idea: XOR - true when exactly one of two conditions is true.

def div_by_exactly_one(num: int, a: int, b: int) -> bool:
    return (num % a == 0) != (num % b == 0)

Key rules: - Divisible by a but not bTrue - Divisible by b but not aTrue - Divisible by both → False - Divisible by neither → False - != on two booleans is XOR


Problem Statement

Problem

Write a function div_by_exactly_one(num, a, b) that returns True if num is divisible by exactly one of a or b.

Examples:

Input
num=20, a=5, b=6
Output
True
Input
num=20, a=5, b=10
Output
False
Input
num=20, a=6, b=10
Output
True
Input
num=20, a=6, b=7
Output
False

Understanding the problem

"Exactly one" means the XOR of two boolean conditions:

div by a? div by b? Exactly one?
True
True
False (both)
False (neither)

!= as XOR for booleans

For two boolean values, p != q is exactly XOR - True when exactly one is True. So (num % a == 0) != (num % b == 0) is the most compact expression for "exactly one".


Tracing all examples

num a b %a==0 %b==0 != Result
20 5 6 True
20 5 10 False
20 6 10 True
20 6 7 False

Solution approaches

def div_by_exactly_one(num: int, a: int, b: int) -> bool:
    return (num % a == 0) != (num % b == 0)
def div_by_exactly_one(num: int, a: int, b: int) -> bool:
    div_a = num % a == 0
    div_b = num % b == 0
    if div_a and div_b:
        return False
    elif div_a or div_b:
        return True
    else:
        return False
def div_by_exactly_one(num: int, a: int, b: int) -> bool:
    return (num % a == 0) ^ (num % b == 0)

Python's ^ is bitwise XOR. For booleans, it's equivalent to !=.

div_by_exactly_one = lambda num, a, b: (num % a == 0) != (num % b == 0)

Key takeaways

01

!= is XOR for booleans

p != q returns True when exactly one of p or q is True. The cleanest way to express "exactly one of two conditions".

02

^ is explicit XOR

p ^ q works identically to p != q for booleans. More readable to someone familiar with logic/CS notation.

03

"Exactly one" vs "at least one"

"Exactly one" → XOR. "At least one" → OR. "Both" → AND. "Neither" → NOR. Recognise which the problem asks for before writing the condition.