Question

Why do I get 2 and not -2 in the following?

System.out.println(11%-3);

Considering that:

System.out.println(-11%3);

returns -2..

Thanks in advance.

Was it helpful?

Solution

Quoting JLS:

The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a.


It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive. Moreover, the magnitude of the result is always less than the magnitude of the divisor.

(Emphasis mine.)

Additionally, refer to Modulo operation for information about modulo operators in various programming languages.

OTHER TIPS

Rules are specified in Jls 15.17.3 Remainder Operator % -

It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive. Moreover, the magnitude of the result is always less than the magnitude of the divisor.

Becaue the sign of the result equals the sign of the dividend. http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.17.3

First, "remainder()" means: if a=b*c+r, a,b,c,r are integers. Then a%b = c

But, how to choose c, different Programming Language has different implementation.

To C and Java, remainder was calculated as truncating:

-11 % 3 = 3*(-3)+(-2) 11 % (-3) = (-3)*(-3)+2

The key point is why choose -3? Because:

truncate(-11/3)=truncate(-3.66)=-3

"truncate()" get the int part close to 0

In other programming language,like Python, use floor division. Which means that in Python: -11 % 3 = 3 * (floor(-11/3))+2

Please refer to: http://python-history.blogspot.sg/2010/08/why-pythons-integer-division-floors.html

This is a math problem.

1st, -11%3 and 11%-3 are the same.

2nd, if you want a positive number, please remove 'minus'. try 11%3 or -11%-3

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top