C++ Best way to get integer division and remainder

On x86 the remainder is a by-product of the division itself so any half-decent compiler should be able to just use it (and not perform a div again). This is probably done on other architectures too.

Instruction: DIV src

Note: Unsigned division. Divides accumulator (AX) by “src”. If divisor
is a byte value, result is put to AL and remainder to AH. If divisor
is a word value, then DX:AX is divided by “src” and result is stored
in AX and remainder is stored in DX.

int c = (int)a / b;
int d = a % b; /* Likely uses the result of the division. */

Leave a Comment