Here is another possible option, valid for positive dividers and arbitrary dividends.
int div_floor(int n, int d) { return n >= 0 ? n / d : -1 - (-1 - n) / d; }
Explanation: for negative n write q for (-1 - n) / d , then -1 - n = qd + r for some r satisfying 0 <= r < d . The permutation gives n = (-1 - q)d + (d - 1 - r) . It is clear that 0 <= d - 1 - r < d , therefore d - 1 - r is the remainder of the sex division operation, and -1 - q is the factor.
Please note that arithmetic operations here are safe from overflow, regardless of the internal representation of signed integers (two additions, their complement, sign-value).
Assuming two additional representations for signed integers, a good compiler should optimize two -1-* operations for bitwise negation operations. On my x86-64 machine, the second branch of the conditional code is compiled into the following sequence:
notl %edi movl %edi, %eax cltd idivl %esi notl %eax
Mark dickinson
source share