Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 621
FuzzyCat444 Avatar asked Sep 21 '18 16:09

FuzzyCat444


People also ask

How do you find the quotient and remainder in Java?

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.

Can quotient and remainder be same?

Explanation: When 8 is divided by 3 and 7, it returns the same Quotient and Remainder. 8 / 3 = 8 % 3, 8 / 7 = 8 % 7.

Can you floor division in Java?

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.


2 Answers

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.

like image 56
Mike B Avatar answered Sep 30 '22 05:09

Mike B


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.

like image 39
Yug Singh Avatar answered Sep 30 '22 05:09

Yug Singh