Help understanding Mod Math?
So I had 1 class session so far in a computer course that I'm taking and during that class, the teacher was going over a powerpoint that had some things about modular math. I understand some of what he was talking about but not all. I'm asking this because I have a quiz tomorrow on it.
So here's my confusion. So I understand how to solve problems like 11%3. You divide the 2 and find your remainder which is 2. But what of it's the other way around?
An example he gave was -2%5=3. When you divide -2/5, you get less than 1, so where does the 3 come from?
Another example was: 3%9=3.
Along the same lines, how does a negative sign affect how it's solved?
- SamwiseLv 78 years agoFavorite Answer
Modular math is like clocks: instead of whole numbers getting larger or smaller forever, we confine them to a small cycle which repeats over and over. On a clock, for instance, 4 hours before 1:00 is 9:00. (There's an example with a negative value.)
[There is a minor difference; clocks normally go from 1 to the modulus, whereas the computer-programming modulus function goes from 0 to (one less than the modulus). Don't let that bother you; it's just more convenient for programming.]
Actually, what's happening mathematically is that we're dividing the whole infinite set of integers into a number (determined by the modulus) of equivalence classes. Any two numbers whose difference is a multiple of the modulus are in the same equivalence class. That means that for purposes of modular arithmetic, they're equivalent.
There's a slight difference between this concept and the programmers' modulus function: the function is designed always to return the member of the class which is in the characteristic range (from zero to one less than the modulus value). Mathematically, modulus 5 arithmetic doesn't see any difference between 3 and 48; the programming function, on the other hand, always returns 3, for any value in that equivalence class. For program control, this is the best value in that class to return.
If n<m, then n%m returns n, as you've noticed. That's because
0 = m0
is the multiple of m closest to n but less than n, so it's the remainder we want.
Older computer languages sometimes had arguments about taking the modulus of a negative number. But the positive remainder is by far the most useful answer, for the sake of consistency. So when we take
-2 % 5
we note that the nearest multiple of 5 less than or equal to -2 is -5, and so we obtain the remainder
(-2) - (-5) = 3
Before counting on a modulus for a negative number, though, I would check the specifications for the language, and the particular compiler or interpreter, AND the computer that you're using. Or run a test, just to make sure that if you write
-2 % 5
you DON'T get -2.