Modulo Operations with Negative Numbers
Understand how modulo operations work with negative numbers in different systems
Calculate Modulo with Negative Numbers
The number being divided (can be positive or negative)
The number to divide by (cannot be zero)
Quick Examples:
Modulo Results
Division by zero is undefined
Understanding Different Approaches
Truncated Division
Formula: r = a - n × trunc(a/n)
The remainder has the same sign as the dividend (a).
Examples:
• -9 mod 4 = -1 (negative dividend → negative remainder)
• 9 mod -4 = 1 (positive dividend → positive remainder)
Floored Division
Formula: r = a - n × floor(a/n)
The remainder has the same sign as the divisor (n).
Examples:
• -9 mod 4 = 3 (positive divisor → positive remainder)
• 9 mod -4 = -3 (negative divisor → negative remainder)
Euclidean Division
Property: 0 ≤ r < |n|
The remainder is always non-negative, regardless of signs.
Examples:
• -9 mod 4 = 3 (always positive)
• 9 mod -4 = 1 (always positive)
Programming Languages
Truncated Division
• C, C++
• Java
• C#
• JavaScript
• Perl
Floored Division
• Python
• Ruby
• Scheme
• Common Lisp
Euclidean Division
• Mathematical standard
• Some theorem provers
• Number theory
Sign Rules Summary
Common Pitfalls
Different languages give different results for negative modulo
Always check your language's documentation
Use specific functions when behavior matters
Euclidean modulo is best for mathematical proofs
The Mathematics Behind Modulo with Negative Numbers
Mathematical Definition
The modulo operation a mod n finds the remainder r when a is divided by n, such that:
a = q × n + r
where q is the quotient and r is the remainder
Why Different Results?
The ambiguity arises in how we choose the quotient q when dealing with negative numbers. Different rounding methods (truncation vs. floor) lead to different remainders.
Practical Examples
Example: -9 mod 4
Truncated: -9 = 4 × (-2) + (-1) → result: -1
Floored: -9 = 4 × (-3) + 3 → result: 3
Euclidean: -9 = 4 × (-3) + 3 → result: 3
Example: 9 mod -4
Truncated: 9 = (-4) × (-2) + 1 → result: 1
Floored: 9 = (-4) × (-3) + (-3) → result: -3
Euclidean: 9 = (-4) × (-2) + 1 → result: 1