rpg711 -4 years ago 70
C++ Question

# What, actually, is the modulo of a negative number?

I have seen many answers for questions concerning modulo of negative numbers. Every answer placed the standard

(a/b)*b + a%b is equal to a

explanation. I can calculate any modulo with this method, and I understand it's necessary employ a modulo function that adds b to the value of a%b if it is negative for the modulo to make sense.

I am trying to make sense of this in laymen's terms. Just what is the modulo of a negative number? I read somewhere that you can calculate the proper modulo of negative numbers by hand some laymen's method of just adding numbers together. This would be helpful, because the a/b *b + a%b method is a little tedious.

To clarify, the modulo of a positive number can be interpreted in laymen's terms as the remainder when you divide the numbers. Obviously this isn't true in the case of negative numbers, so how do you properly "make sense" of the result?

1. Division truncates, i.e. `a / b` is the mathematical value with the fractional part discarded. For example, `9 / -5` is the truncation of −1.8, so it's `-1`.
2. The remainder operation `a % b` is defined by the identity you presented. So let's compute: `(a / b) * b` is `-1 * -5` is `5`, so `9 % -5` is `4`.
By contrast,`-9 % 5` is `-4`. So even though `a / -b` is the same as `-a / b`, `a % -b` is in general different from `-a % b`. (Similarly, the mathematical notion of modular equivalence, where two integers are congruent modulo `n` if they differ by an integral multiple of `n`, is invariant under replacing `n` with `-n`.)