# Order of operations involving mod (%)

I was taking a programming test last night that had a math equation that simplified to 11 % 2 * 3, no () or likewise. When I compute it, being taught modulous occurs at the same level of multiplication or division. As a result I get

11 % 2 * 3
1 * 3
3

Final result I get is 3. When I checked my math in spotlight calculator on my mac I get 5. And then we jump into the rabbit hole.

I go to my preferred math calculator and visit WolframAlpha. Answer is 5. Google the formula and get 3.

So we have two possible ways to handle this equation,

(11%2)*3 = 3
11%(2*3) = 5

Which way is correct and definitive? I need sources as if Wolfram alpha is doing incorrectly, I would like to have them change it.

• There might be differences in the correct order of operations for mathematics and for various programming languages. Apr 24, 2014 at 16:57
• For cases like this, where there is no ubiquitous convention, the denotation is ambiguous, so you should always use parentheses to disambiguate. Apr 24, 2014 at 17:08
• I would but with a test question they don't alway do stuff like that. Apr 24, 2014 at 17:42
• @naslundx: examples show the order for Google is not the same as for the other softwares tested. Which is order "for mathematics"? $a\mod b\cdot c=a\mod (b\cdot c)$ or $a\mod b\cdot c=(a\mod b)\cdot c$? Shouldn't this be the answer? Apr 24, 2014 at 19:25

There is no well established convention for the order of precedence between "the modulus operator" and multiplication (or addition, for that matter, because the same problem arises if you replace multiplication with addition in your question.) You have in your hands an example demonstrating that they can't be used with equal precedence.

The acceptability of the final answer hinges entirely upon the choice made for precedence.

While % can certainly be treated as a binary operation of natural numbers, it is not really the main way mathematicians use modulus. Rather than looking at it as an operation, we think of it as indicating the 'environment' where arithmetic is taking place. So $\pmod n$ indicates that we are not working in the natural numbers but with a quotient ring of the integers.

In that context, you can establish an identity between modulus and $+/*$ operations. You could state it this way:

$$(a+b)\%n = ((a \%n)+(b\%n)) \%n$$

and

$$(a*b)\%n = ((a \%n)*(b\%n)) \%n$$

I'm writing it on my own experience, by observing the differences. And my conclusion is that,

In modular arithmetic (general maths), modulo when used without braces usually separates everything to the left of it and everything to the right of it as separate solvable equation and then it is applied as left mod right.

However with programming languages in general, the modulo are used way too often to squash the value to not overflow, hence its usually given higher priority than most of the other arithmetic operations like +, -, *, /.