Modular arithmetic with negative operands differs in different languages ββand corresponds to the definition of the language for driving. In Java, a Module is more like a Remainder .
Generally, if you want to get a negative number for negative inputs, you can use this:
int r = x % n; if (r > 0 && x < 0) { r -= n; }
Or, if you used a language that returns a negative number on a negative input, and you prefer positive:
int r = x % n; if (r < 0) { r += n; }
So, based on what you need as the desired result, I recommend that you use the appropriate implementation, rather than relying on the language to calculate for you.
Also note that the result should be described in the case of Java in JLS: in section 15.17.3 - Stop operator%. They give motivation there (that% b should be such that (a / b) * b + (a% b) is equal to a), but this is the inclusion of this section in JLS, which makes the result this way.
Saket
source share