Generally more efficient than doing both modulus and division work, it's easy to convert floor division:
x // y
into ceil
division (and unlike using math.ceil
, it runs no risk of getting incorrect results due to floating point imprecision for large values):
(x + y - 1) // y
If x
is exactly divisible by y
, then adding y - 1
changes nothing; the floor division makes the end result unchanged. If it's not evenly divisible, this increases it above the next multiple, getting you ceil division with only a single division operation instead of two (division is expensive; doing it twice is doubly expensive), and no floating point precision issues.
The above doesn't work for negative y
, but there is a solution that does work for it (at the expense of appearing more magical):
-(-x // y)
By flipping the sign on x
first, you change the rounding behavior to work in the opposite direction after flipping the sign again at the end. So for x == 5
and y == -2
, this second solution produces -2
(the ceiling of -2.5
) correctly. It's typically more efficient than the original solution, but it's not as obvious how it works, so I can't strictly recommend it over the clearer solution when the divisor is known to be positive.