S1Q1 · Nearest Multiple¶
⚡ Quick Reference
Function: near_multiple(n: int, k: int) -> int
Core idea: find the lower multiple with //, compute upper multiple, return whichever is closer. Ties → upper.
def near_multiple(n: int, k: int) -> int:
lower = (n // k) * k
upper = lower + k
return upper if (n - lower) >= (upper - n) else lower
Key rules:
- Lower multiple: (n // k) * k
- Upper multiple: lower + k
- Tie (exactly halfway): return the larger (upper) multiple
- >= in the condition handles the tie correctly
Problem Statement¶
Problem
Write a function near_multiple(n, k) that returns the multiple of k closest to n. If n is exactly halfway between two multiples, return the larger one.
Examples:
n=13, k=5
15
n=12, k=5
10
n=7, k=4
8
n=20, k=6
18
Understanding the problem¶
For any n, two multiples of k surround it:
Then compare distances:
dist_lower = n - lower
dist_upper = upper - n
if dist_lower < dist_upper → return lower
if dist_upper < dist_lower → return upper
if equal (tie) → return upper (larger)
The condition (n - lower) >= (upper - n) returns upper for both the tie case and the "closer to upper" case.
Why >= handles the tie?
When n is exactly halfway, n - lower == upper - n. Using >= makes the condition true in the tie case, so upper is returned - matching the "return the larger multiple" rule.
Tracing all examples¶
n |
k |
lower |
upper |
dist↓ | dist↑ | Result |
|---|---|---|---|---|---|---|
| 13 | 5 | 10 | 15 | 3 | 2 | 15 (upper closer) |
| 12 | 5 | 10 | 15 | 2 | 3 | 10 (lower closer) |
| 7 | 4 | 4 | 8 | 3 | 1 | 8 (upper closer) |
| 20 | 6 | 18 | 24 | 2 | 4 | 18 (lower closer) |
| 15 | 3 | 15 | 18 | 0 | 3 | 15 (n is a multiple) |
Solution approaches¶
def near_multiple(n: int, k: int) -> int:
# round(n / k) gives nearest integer with Python's banker's rounding
# Use custom logic to ensure ties go to upper
q = n / k
rounded = int(q) if q - int(q) < 0.5 else int(q) + 1
return rounded * k
Divides by k, rounds to the nearest integer (always up on 0.5), multiplies back. Avoids computing lower/upper explicitly.
Key takeaways¶
(n // k) * k gives the lower multiple
Integer division n // k truncates toward zero, giving the largest integer quotient ≤ n/k. Multiplying back by k gives the nearest multiple below n.
Use >= to handle the tie correctly
The condition (n - lower) >= (upper - n) returns upper when distances are equal. If you used >, ties would incorrectly return lower.
n is already a multiple → lower == n, dist_lower == 0
If n is exactly a multiple of k, then lower == n and dist_lower == 0. Since 0 < dist_upper, lower (= n itself) is correctly returned.