If the modulus is a power of 2 then you can use a bitmask:
int i = -1 & ~-2; // -1 MOD 2 is 1
By comparison the Pascal language provides two operators; REM takes the sign of the numerator (x REM y
is x - (x DIV y) * y
where x DIV y
is TRUNC(x / y)
) and MOD requires a positive denominator and returns a positive result.
Since Java 8 you can use the Math.floorMod() method:
Math.floorMod(-1, 2); //== 1
Note: If the modulo-value (here 2
) is negative, all output values will be negative too. :)
if b > 0:
int mod = (mod = a % b) < 0 ? a + b : a;
Doesn't use the %
operator twice.
If you need n % m
then:
int i = (n < 0) ? (m - (abs(n) % m) ) %m : (n % m);
mathematical explanation:
n = -1 * abs(n)
-> n % m = (-1 * abs(n) ) % m
-> (-1 * (abs(n) % m) ) % m
-> m - (abs(n) % m))
Source: Stackoverflow.com