[java] How does java do modulus calculations with negative numbers?

Am I doing modulus wrong? Because in Java -13 % 64 is supposed to evaluate to -13 but I get 51.

This question is related to java math modulo negative-number

The answer is


The mod function is defined as the amount by which a number exceeds the largest integer multiple of the divisor that is not greater than that number. So in your case of

-13 % 64

the largest integer multiple of 64 that does not exceed -13 is -64. Now, when you subtract -13 from -64 it equals 51 -13 - (-64) = -13 + 64 = 51


I don't think Java returns 51 in this case. I am running Java 8 on a Mac and I get:

-13 % 64 = -13

Program:

public class Test {
    public static void main(String[] args) {
        int i = -13;
        int j = 64;
        System.out.println(i % j);
    }
}

x = x + m = x - m in modulus m.
so -13 = -13 + 64 in modulus 64 and -13 = 51 in modulus 64.
assume Z = X * d + r, if 0 < r < X then in division Z/X we call r the remainder.
Z % X returns the remainder of Z/X.


According to section 15.17.3 of the JLS, "The remainder operation for operands that are integers after binary numeric promotion produces a result value such that (a/b)*b+(a%b) is equal to a. 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)."

Hope that helps.


In Java latest versions you get -13%64 = -13. The answer will always have sign of numerator.


you can use

(x % n) - (x < 0 ? n : 0);

Are you sure you are working in Java? 'cause Java gives -13 % 64 = -13 as expected. The sign of dividend!


In my version of Java JDK 1.8.0_05 -13%64=-13

you could try -13-(int(-13/64)) in other words do division cast to an integer to get rid of the fraction part then subtract from numerator So numerator-(int(numerator/denominator)) should give the correct remainder & sign


Modulo arithmetic with negative operands is defined by the language designer, who might leave it to the language implementation, who might defer the definition to the CPU architecture.

I wasn't able to find a Java language definition.
Thanks Ishtar, Java Language Specification for the Remainder Operator % says that the sign of the result is the same as the sign of the numerator.


To overcome this, you could add 64 (or whatever your modulus base is) to the negative value until it is positive

int k = -13;
int modbase = 64;

while (k < 0) {
    k += modbase;
}

int result = k % modbase;

The result will still be in the same equivalence class.


Your answer is in wikipedia: modulo operation

It says, that in Java the sign on modulo operation is the same as that of dividend. and since we're talking about the rest of the division operation is just fine, that it returns -13 in your case, since -13/64 = 0. -13-0 = -13.

EDIT: Sorry, misunderstood your question...You're right, java should give -13. Can you provide more surrounding code?


Your result is wrong for Java. Please provide some context how you arrived at it (your program, implementation and version of Java).

From the Java Language Specification

15.17.3 Remainder Operator %
[...]
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.
15.17.2 Division Operator /
[...]
Integer division rounds toward 0.

Since / is rounded towards zero (resulting in zero), the result of % should be negative in this case.


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


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to math

How to do perspective fixing? How to pad a string with leading zeros in Python 3 How can I use "e" (Euler's number) and power operation in python 2.7 numpy max vs amax vs maximum Efficiently getting all divisors of a given number Using atan2 to find angle between two vectors How to calculate percentage when old value is ZERO Finding square root without using sqrt function? Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt? How do I get the total number of unique pairs of a set in the database?

Examples related to modulo

'MOD' is not a recognized built-in function name Modulo operation with negative numbers Can't use modulus on doubles? Assembly Language - How to do Modulo? How to use mod operator in bash? How can I calculate divide and modulo for integers in C#? What is the result of % in Python? How does java do modulus calculations with negative numbers? Integer division with remainder in JavaScript? How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers

Examples related to negative-number

How to replace negative numbers in Pandas Data Frame by zero How does java do modulus calculations with negative numbers? Javascript negative number working with negative numbers in python Make a negative number positive