BeginnerMath for DSABinary Search
Rounding up without floats: (a + b − 1) // b
7 bananas at 3 per hour takes 3 hours, not 2.33. Integer ceiling division gets it right without floating-point surprises.
The idea
Normal integer division rounds down: 7 // 3 = 2. Many problems need rounding up: hours, trucks, pages, groups. Adding b − 1 first pushes any remainder over the next multiple: (7 + 2) // 3 = 3.
If a is already a multiple of b, adding b − 1 isn't enough to reach the next one, so exact divisions stay exact: (6 + 2) // 3 = 2.
Worked example
Koko eats piles [3, 6, 7, 11] at speed 4
- 3 → (3 + 3) // 4 = 1 hour; 6 → 9 // 4 = 2; 7 → 10 // 4 = 2; 11 → 14 // 4 = 3.
- Total 8 hours.
In code (Python)
def ceil_div(a, b):
return (a + b - 1) // b # for a >= 0, b > 0
# Python alternative that also works for negatives:
def ceil_div_any(a, b):
return -(-a // b)How to spot it
- “how many hours / days / boxes / trucks”, “at most k per…”, binary search on a speed or capacity.
Common mistakes
- math.ceil(a / b) with huge numbers: floats lose precision past 2⁵³.
- Using a // b + 1, which is wrong when a divides evenly.
Where it comes up
Go further
Up next for you · Beginner
“Have I seen this?” is a set →