How about this? (requires y non-negative, so don't use this in the rare case where y is a variable with no non-negativity guarantee)
q = (x > 0)? 1 + (x - 1)/y: (x / y);
I reduced y/y
to one, eliminating the term x + y - 1
and with it any chance of overflow.
I avoid x - 1
wrapping around when x
is an unsigned type and contains zero.
For signed x
, negative and zero still combine into a single case.
Probably not a huge benefit on a modern general-purpose CPU, but this would be far faster in an embedded system than any of the other correct answers.