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.
Key rules:
- Divisible by a but not b → True
- Divisible by b but not a → True
- 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:
num=20, a=5, b=6
True
num=20, a=5, b=10
False
num=20, a=6, b=10
True
num=20, a=6, b=7
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¶
Python's ^ is bitwise XOR. For booleans, it's equivalent to !=.
Key takeaways¶
!= 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".
^ is explicit XOR
p ^ q works identically to p != q for booleans. More readable to someone familiar with logic/CS notation.
"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.