0

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:

  1. q = int(5 / -3) = int(-1.6667) = -1
  2. 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.

2 Answers2

1

An integer is divisible by 3 if and only if it is divisible by -3. The usual definition of congruence mod 3 is that $a\equiv_3 b$ if and only if $3\mid a-b$ (i.e if and only if $a-b$ is divisible by 3). So you have the same structure mod 3 and mod -3. The reason they didnt give you 2 as your answer is probably because they want to choose representatives from the set $\{0,-1,-2\}$.

  • This was something I encountered in a test in uni, and 2 was given as a possible answer in the test, but it was not the right answer. I assume the reason is the one you mention and that I suspected: they expect answers in the set between 0 and n, despite not making it explicit. – user2891462 Nov 16 '19 at 15:37
0

There is nothing wrong with the two answers $-1$ and $2$. These are the same modulo $-3$.

Note that $-1=2+(-3)$.

  • I see. I was curious about this because they showed up in a single-answer test in university, and the options were 2, -1 and 1, and -1 was marked as the valid answer. I assume the issue is that maybe the result needs to be between 0 and n, so if n is negative one need to add n to the result to bring it to the accepted range, but this was never made explicit anywhere, so I assumed there was a deeper mathematical reason for -1 being the right answer instead of 2. – user2891462 Nov 16 '19 at 15:36
  • 1
    Your suggestion for why -1 was chosen is feasible but it should have been made clear in the question! –  Nov 16 '19 at 15:38
  • 1
    Also % is remainder in some languages not strictly mod. in Mod you can add a multiple of you modulus aftward and get the same amount. remainder if not taken again, will just add that multiple to your result. –  Nov 16 '19 at 15:42