I am writing a program in assembly to calculate the modulus of a number. I do not need help with the the program, but I do need help understanding how modulo works with negative numbers. I have researched stackoverflow but I seem to be finding conflicting results.
Also, I would like to know how it works purely in mathematical terms, not as it relates to programming, just so I understand the basic concept. I did find this page semi-useful: Modulo operation with negative numbers However, the top two answers seem to be conflicting and now I have gotten myself even more confused with the difference between modulo vs remainders (based on the answers given on that page). Not to say that their answers are poor in any way, but at this point I seem to be having difficulty finding the forest through the trees.
Please help me answer these simple problems, and explain to to me in purely mathematical terms how you reached your answer. Also, I don't need to be explained the difference between modulo and remainder since I just seemed to become more confused when I looked at the webpage listed. Please explain it to me just in terms of modulus, and I can connect the dots from there ;)
Here are some examples:
-15 mod 2 = ?
15 mod -2 = ?
-4 mod 9 = ?
4 mod -9 = ?
-5 mod -9 = ?
Thank you in advance for your responses!
There is no clear convention for those cases.
Remember the formula for modulo is: n = am + b
. Usually, it is required that the remainder b
is within the interval [0..(m-1)]
. This makes it very easy for all natural numbers.
For negative numbers, some conventions want the remainder to be in the interval [-(m-1)..0]
, some stick with above definition, and some take the solution where |b|
is minimal.
Thus, you have to try the implementation the compiler or library developer chose.
Some programming languages have two operators to give you some freedom. Ada for example has rem
and mod
.
Behaviour:
In (n rem m)
the remainder always has the sign of n, while in (n mod m)
, it takes on the sign of m.
The third convention, using the smaller remainder of the two, rarely is implemented.