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?
Get the remainder using % operator. Expressions used in program to calculate quotient and remainder: quotient = dividend / divisor; remainder = dividend % divisor; Note: The program will throw an ArithmeticException: / by zero when divided by 0.
Explanation: When 8 is divided by 3 and 7, it returns the same Quotient and Remainder. 8 / 3 = 8 % 3, 8 / 7 = 8 % 7.
floorDiv() is used to find the largest integer value that is less than or equal to the algebraic quotient. This method first divide the first argument by the second argument and then performs a floor() operation over the result and returns the integer that is less or equal to the quotient.
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.
There is no way to do this in one step as both are different operations. One is division and other is remainder. So you require two variables to store result for both operations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With