Java modulo operator % is based on the truncated division (see Wikipedia: Modulo operation).
5%3produces2(note that5/3produces1)5%(-3)produces2(note that5/(-3)produces-1)(-5)%3produces-2(note that(-5)/3produces-1)(-5)%(-3)produces-2(note that(-5)/(-3)produces1)
In computing science, given two integers a and n, n > 0, sometimes it is useful to get the unique integer r within [a,n[ which is congruent to a modulo n.
Question
Is there an efficient generic operator / method in Java which respects this specification of modulo?
This is to avoid rewriting it in every project where it is needed...
Miscellaneous
I found a lot of questions on stackoverflow about this problem, most of them confusing the different modulo implementations. If you are just troubled about the results of the modulo operation on negative numbers, below are some implementations based on the Java % operator that may be useful.
Common hack
Since we hardly use a negative divisor, this implementation returns the Euclidean or floored modulo when n > 0.
static int mod(int a, int n){
return a<0 ? (a%n + n)%n : a%n;
}
mod( 5, 3)produces2mod(-5, 3)produces1
Euclidean modulo
static int euclideanModulo(int a, int n){
return n<0 ? euclideanModulo(a, -n) : mod(a, n);
}
euclideanModulo( 5, 3)produces2euclideanModulo(-5, 3)produces1euclideanModulo( 5,-3)produces2euclideanModulo(-5,-3)produces1
Floored modulo
static int flooredModulo(int a, int n){
return n<0 ? -flooredModulo(-a, -n) : mod(a, n);
}
flooredModulo( 5, 3)produces2flooredModulo(-5, 3)produces1flooredModulo( 5,-3)produces-1flooredModulo(-5,-3)produces-2
Math.floor()(JavaDocs) - classicjonesynzMath.floor()is worse than any of the solutions above. - UmNyobea - n * (int)Math.floor((double)a/n);is mathematically correct for the floored modulo, but not efficient, and not generic. - boumbh(-5)magicmod(-3)give?-2or2? - UmNyobe