Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does java do modulus calculations with negative numbers?

Am I doing modulus wrong? Because in Java -13 % 64 evaluates to -13 but I want to get 51.

like image 445
Jakir00 Avatar asked Dec 09 '10 21:12

Jakir00


People also ask

How does modulus work with negative numbers Java?

The sign of the first operand decides the sign of the result. x % y always equals x % -y . You can think of the sign of the second operand as being ignored.

How do you do modulus with negative numbers?

The modulus of a negative number is found by ignoring the minus sign. The modulus of a number is denoted by writing vertical lines around the number. Note also that the modulus of a negative number can be found by multiplying it by −1 since, for example, −(−8) = 8.

Can the result of a modulus be negative?

Can a modulus be negative? % can be negative as it is the remainder operator, the remainder after division, not after Euclidean_division. Since C99 the result may be 0, negative or positive.


2 Answers

Both definitions of modulus of negative numbers are in use - some languages use one definition and some the other.

If you want to get a negative number for negative inputs then you can use this:

int r = x % n; if (r > 0 && x < 0) {     r -= n; } 

Likewise if you were using a language that returns a negative number on a negative input and you would prefer positive:

int r = x % n; if (r < 0) {     r += n; } 
like image 104
Mark Byers Avatar answered Oct 05 '22 02:10

Mark Byers


Since "mathematically" both are correct:

-13 % 64 = -13 (on modulus 64)   -13 % 64 = 51 (on modulus 64) 

One of the options had to be chosen by Java language developers and they chose:

the sign of the result equals the sign of the dividend.

Says it in Java specs:

https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3

like image 39
Caner Avatar answered Oct 05 '22 00:10

Caner