Rounding up without floats: (a + b − 1) // b
7 bananas at 3 per hour takes 3 hours, not 2.33. Integer 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.
Pseudocode
The steps in plain words. ← means “set to”; indentation shows what's inside what.
See it run
The worked example, step by step, beside the Python. The highlighted line is the one running.
Step-by-step
piles = [3, 6, 7, 11], speed = 4
piles
Solution · Pythonline 1
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)Step 1 of 6· line 1
A pile of a bananas at 4 per hour takes ⌈a / 4⌉ hours: a part-hour still counts as a whole one. (a + b − 1) // b rounds up using whole numbers only.
How to spot it
- “how many hours / days / boxes / trucks”, “at most k per…”, 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.
Practise the ideas first
One small exercise per idea, right in the editor, before the problems below.
Where it comes up
Go further
Up next for you · Beginner
“Have I seen this?” is a set →