Explain Codes LogoExplain Codes Logo

Mod in Java produces negative numbers

java
remainder
modulus
java-8
Alex KataevbyAlex Kataev·Feb 28, 2025
TLDR

To achieve a positive result through the modulus operation in Java, you can apply this formula: ((a % b) + b) % b. This makes sure the outcome is always from 0 to b-1, even with a negative a.

int result = ((-7 % 5) + 5) % 5; // Result is 3 because -2 took an honest feedback of being negative too seriously

Remember in Java, % operator returns the remainder, which can be negative. But, fear not! From Java 8 onwards, we have Math.floorMod(int x, int y) that works like charm for negative numbers.

Unraveling Java Modulus Mysteries

Distinguishing Modulus from Remainder

In Java, % operator leads to a remainder operation rather than a mathematical modulus. The resultant remainder can be negative, but a modulus is a positive chap, always.

How to Secure Positive Results

Use the ternary operator to smoothly convert a negative remainder to a positive modulus:

int result = (a % b) < 0 ? (a % b) + b : a % b; // trio of integers working hard for positive result

Have Java 8 or higher? Utilize the function Math.floorMod(). It aligns with the mathematical definition of modulus blissfully:

int result = Math.floorMod(-7, 5); // Result is 3, as -7 decided to look at life positively

Masking with Power of 2

When you've powers of 2 at hand, employ bitwise operations for a quick win:

int result = -1 & (Integer.highestOneBit(b) - 1); // b = 2^n, and -1 decided to say no to negativity

Always Check Your Divisors

Before performing a modulo operation, make sure the divisor b is a non-zero champ to avoid the infamous ArithmeticException.

Language Matters

Remember, different programming languages have distinct behaviors. Python, for example, happily returns a non-negative result from modulus operations.

Deep-diving into Modulo Intricacies

Mathematics Behind Adjustments

Adjustment of modulo outcomes is explained by the diverse definitions of the operation in various mathematical contexts. In number theory, modulo refers to non-negative residues within [0, b), ensuring consistency.

Consistent Modulus Operations

Java Math.floorMod() conforms to the Floor Division concept, used by mathematicians and various programming languages, and outputs negative values only if the divisor (modulo-value) itself is negative.

Bitwise Modulus for Powers of Two

For divisors that are powers of two, efficient modulo can be achieved:

int result = a & (b - 1); // when life gives you b = 16 (2^4), you get b - 1 = 15 (1111 in binary)

Correcting Division and Modulus for Negative Numbers

Both division and modulus operations for negative numbers can be correctly handled by using Java's precise BigDecimal or BigInteger classes for calculations involving large numbers.