Friday, 25 February 2011

Modulo and Negative Numbers

Did you know that the modulo of a negative number is negative? In the presumed words of Micheal Caine it seems that “not a lot of people know that”. For example its obvious that:

5 % 2 = 1

but it isn’t so obvious that:

5 % -2 = -1


-5 % 2 = -1

This can have an effect on your code; take the following:

  private static boolean isOdd(int val) {
return (val % 2) == 1;

you may think that this code will determine whether or not a number is odd or not: well it does for at least 75% of the time. It will fail; however, when trying to figure out whether or not a negative odd number is odd as all negative arguments will return false irrepective of value.

The fix is very straight forward: don’t test for a remainder value, test for a non-zero value:

  private static boolean isOddFixed(int val) {
return (val % 2) != 0;

No comments: