Mod in Java produces negative numbers [duplicate]

2019-01-03 04:45发布

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?

标签: java math mod
5条回答
祖国的老花朵
2楼-- · 2019-01-03 05:15

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.

查看更多
聊天终结者
3楼-- · 2019-01-03 05:24

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:

int i = (((-1 % 2) + 2) % 2)

or this:

int i = -1 % 2;
if (i<0) i += 2;

(obviously -1 or 2 can be whatever you want the numerator or denominator to be)

查看更多
Explosion°爆炸
4楼-- · 2019-01-03 05:30
if b > 0:
    int mod = (mod = a % b) < 0 ? a + b : a;

Doesn't use the % operator twice.

查看更多
Bombasti
5楼-- · 2019-01-03 05:35

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))
查看更多
成全新的幸福
6楼-- · 2019-01-03 05:39

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. :)

Source: https://stackoverflow.com/a/25830153/2311557

查看更多
登录 后发表回答