Playing with Python and the mod operation I encountered that (5 % -3) = -1. This is confirmed by WolframAlpha, and I have not been able to find any simple explanation for this online, mostly because all I can find about modular arithmetic uses a positive n
.
I am surprised by this result. My understanding of the modulo operation is that a mod n
is a number c
computed by taking the integer part q = a / n
, and then substracting n·q
from a
.
Therefore, for 5 mod -3
I would do:
q = int(5 / -3) = int(-1.6667) = -1
5 - (-3)·(-1) = 5 - 3 = 2
Where am I wrong?
I have realised that -1 is congruent with 2 modulo -3, so maybe the answer is that the result must be between 0 and n, so if n is negative we need to add n
to the positive result, but not sure if this is really the reason.
Please consider that I am not a mathematician, so the simpler the explanation the better.