1

Possible Duplicate:
Mod in Java produces negative numbers

When I try to print -16 mod 57, I should get 41. However, I keep getting -16 as my answer. What gives?

Here is my code:

public class TestMod {

public static void main(String[] args) {
    int number = -16;
    int mod = 57;
    int answer = number%mod;
    System.out.println(answer);

}

}
Community
  • 1
  • 1
user1996035
  • 19
  • 1
  • 1
  • 3

2 Answers2

11

From the 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.

Substitute the numbers from your example, and you'll see that -16 is what the language spec mandates.

This identity holds even in the special case that the dividend is the negative integer of largest possible magnitude for its type and the divisor is -1 (the remainder is 0).

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.

Here is how you can get the result you're expecting:

public static void main(String[] args) {
    int number = -16;
    int mod = 57;
    int answer = ((number % mod) + mod) % mod;
    System.out.println(answer);

}
NPE
  • 486,780
  • 108
  • 951
  • 1,012
3

When the first operand is negative, the remainder operator % returns a negative result. That's common behaviour in many languages.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431