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

Viewed 8032

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?

4 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.

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 need to do this,

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

int quotient = a / b;
int remainder = b - (a * b);

uses slightly less CPU, but there's not much in it unless you're doing it lots of times. Doing it a billion times took 5.3 seconds the first way, 3.8 the second. There's a FOR loop in there too in my test.

public int []result (int a , int b){
int quotient = a / b;
int remainder = a % b;
int [] array=new int[2];
array[0]=quotient;
array[1]=remainder;
return array;
}

public void main(){

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

int [] results=result(a,b);
}
Related