Does order of operations and computing modulo matter?

354 Views Asked by At

So I read that it does not matter.

Eg: Let $x=14$, $y=25$, $m=12$.

Operations first,computing modulo second: $(x+y)\bmod m=39\bmod12 =3$.

Computing modulo first, operations second: $x\bmod m= 14\bmod 12=2$, $y\bmod m=25\bmod12=1$. Then $1+2=3$.

Yup, seems that order doesn't matter.


But when I try with $x =8$, $y =5$, $m=12$. The results are different.

Operations first,computing modulo second: $(x+y)\bmod m=13\bmod12=1$.

Computing modulo first, operations second: $x\bmod m=8\bmod 12=8$, $y\bmod m=5\bmod 12=5$. Then $8+5=13$.

Does order then matter? It's kind of obvious I made some glaring silly mistake somewhere


Edit: I get that modular arithmetic "wraps around". Both the comments and answer states that $13\bmod 12=1$.

Here's what's confusing me: Doesn't doing $13\bmod 12$ mean that you are including an additional modulo operation?

2

There are 2 best solutions below

0
On

The thing is, if you're working mod 12, then $13\equiv1$! Thus you didn't make any silly mistakes.

Another way to think about it is "clock arithmetic". If you move forwards from 8 o'clock by 5 hours, it's "13 o'clock" (13 hundred hours) -- which is just 1 o'clock.

3
On

If you are thinking in terms of computing effort, then, yes, you would need to compare the steps in (a) calculating modulos, performing you arithmetic and then calculating the modulo of the answer with (b) do all the arithmetic first and only calculate the modulo of the answer.

Mathematically both procedures give the same result, but obviously (a) has potentially many more calculations. On the other hand, if there are a lot of calculation in between, (b) might lead to very large intermediate numbers that either overflow your computer arithmetic or, if size itself is not an issue, take much longer to compute; reducing numbers at each stage to their canonical modulo representation may make sense.

Hope that covers any points missed by other commentators.