3

From what I understand, in mathematics, the mod operator is the result of the remainder of Euclidean division. Where 0 ≤ r < |b|, meaning that the result will always be positive.

In programming however, there are operators in many languages which can be used to mean either the remainder operator or modulo operator which differ with respect to how they handle negative values.

(I believe that mod operator in math, remainder operator in programming, and mod operator in programming yield the same results for positive numbers)

According to Modulo operation with negative numbers

"With a remainder operator, the sign of the result is the same as the sign of the dividend while with a modulo operator the sign of the result is the same as the divisor."

So the mod operator in programming is not referring to the mod operator in math?

Is the sign of the answer the main distinguishing factor between mod operator vs remainder operator in programming?

1 Answer 1

0

Mathematically, the modulus is part of group theory, and the idea of a set. You can generate all the numbers in a set by addition, with the modulus. So if your set is integers modulus 10, you count 0-9 and then start over at 0. There is no concept of a negative number under modulus.

In programming, the remainder is what portion is left after doing a division. So if you divide 3 by 10, you're left with 0 and a remainder of 3. If you divide -3 by 10, you get 0 with a remainder of -3, rather than -1 remainder 7. But the mathematical modulus is 7.

Those who designed integer division that we now use decided that it's more logical to round towards 0, rather than round towards negative infinity, so by necessity, a negative division will result in a negative remainder.

If you want to convert a remainder to a modulus, you need to add your modulus to any negative remainders in order to map them into the proper range.

Sign up to request clarification or add additional context in comments.

2 Comments

so although remainder and mod in programming are different (remainder being what is left after division, mod being finding "wrap around numbers") they are both calculated in a similar fashion which involves finding the remainder?
Yes, they're identical for positive numbers, so that's probably why sometimes remainder is called "mod" operator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.