This question already has an answer here:
When I calculate int i = -1 % 2
I get -1
in Java. In Python, I get 1
as the result of -1 % 2
.
What do I have to do to get the same behavior in Java with the modulo function?
This question already has an answer here:
When I calculate int i = -1 % 2
I get -1
in Java. In Python, I get 1
as the result of -1 % 2
.
What do I have to do to get the same behavior in Java with the modulo function?
If the modulus is a power of 2 then you can use a bitmask:
By comparison the Pascal language provides two operators; REM takes the sign of the numerator (
x REM y
isx - (x DIV y) * y
wherex DIV y
isTRUNC(x / y)
) and MOD requires a positive denominator and returns a positive result.The problem here is that in Python the % operator returns the modulus and in Java it returns the remainder. These functions give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results. There's some more information about it in this question.
You can find the positive value by doing this:
or this:
(obviously -1 or 2 can be whatever you want the numerator or denominator to be)
Doesn't use the
%
operator twice.If you need
n % m
then:mathematical explanation:
Since Java 8 you can use the Math.floorMod() method:
Note: If the modulo-value (here
2
) is negative, all output values will be negative too. :)Source: https://stackoverflow.com/a/25830153/2311557