javainteger-division

Java - get the quotient and remainder in the same step?


It seems that in order to find both the quotient and remainder of a division in Java, one has to do:

int a = ...
int b = ...

int quotient = a / b;
int remainder = a % b;

Is there a way to write this so that the quotient and remainder are found in a single step (one division operation)? Or does Java already automatically optimize this code so that they are?


Solution

  • The natural behaviour of all architectures is for the divide instructions to supply the quotient and remainder in separate registers (for binary) or storage areas (for packed decimal as found on the IBM zSeries). The only high level language that I know of that does the same is COBOL. It does always seem wasteful having to repeat the divide instruction again to get the remainder.