How does java do modulus calculations with negative numbers?

JavaMathModuloNegative Number

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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;
}

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

Note that this answer was for a previous, different version of the question.

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

From the https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.3">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.

Solution 5 - Java

you can use

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

Solution 6 - Java

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?

Solution 7 - Java

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.

Solution 8 - Java

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.

Solution 9 - Java

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.

Solution 10 - Java

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

Solution 11 - Java

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

Solution 12 - Java

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

Solution 13 - Java

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.

Solution 14 - Java

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);
	}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJakir00View Question on Stackoverflow
Solution 1 - JavaMark ByersView Answer on Stackoverflow
Solution 2 - JavaCanerView Answer on Stackoverflow
Solution 3 - JavaKeyxeqView Answer on Stackoverflow
Solution 4 - JavastarblueView Answer on Stackoverflow
Solution 5 - JavaruslikView Answer on Stackoverflow
Solution 6 - JavaNava CarmonView Answer on Stackoverflow
Solution 7 - JavawallykView Answer on Stackoverflow
Solution 8 - Javauser415789View Answer on Stackoverflow
Solution 9 - JavaAndreasView Answer on Stackoverflow
Solution 10 - JavaSalman ParachaView Answer on Stackoverflow
Solution 11 - JavaRobert GreenView Answer on Stackoverflow
Solution 12 - Javavsn harish rayasamView Answer on Stackoverflow
Solution 13 - JavakudesiajiView Answer on Stackoverflow
Solution 14 - JavaceprateekView Answer on Stackoverflow