I'm trying to put my head around the mod function. All seemed well until I tried mod (-4) 3 in GHCi. Could someone explain to me why mod (-4) 3 is equal to 2 and not 1? It's really bothering me!
integer x ... -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 ...
mod x 3 ... 0 1 2 0 1 2 0 1 2 0 1 2 ...
The sequence above satisfies the equation mod (x+3) 3 = mod x 3 for any x. Note how 0 1 2 is continuously repeated.
Note that in Haskell we have both
mod (-4) 3 == 2
rem (-4) 3 == -1
where
integer x ... -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 ...
rem x 3 ... 0 -2 -1 0 -2 -1 0 1 2 0 1 2 ...
mod x y is the "remainder" of div x y where the division is rounded down (towards -infinity). Instead rem x y is the remainder of quot x y where the division is rounded towards zero (so the "remainder" can be negative).
It's the same as the mod of a positive number. In arithmetic modulo c, we seek to express any x as qc+r, where r must be a non-negative integer.
Why don't we test it out with an example?
Take −100 mod 8=4. This is because 8⋅−13=−104. The remainder is 4.
I'll try to explain...my way: the qc + r for a positive means that 100 mod 8 = 4 because you can express it as 8*12 + 4 meaning you can pull 12 8's out of it but you'll end of needing 4 in order to reach 100. In the negative case you can "pull out" -13 8's, then you'll need to ADD 4 (positive number) to reach 100.
So in your case you can pull out TWO 3's (ending at -6) then you'll need positive 2 left over to reach -4
might need a mathematician to explain: https://math.stackexchange.com/questions/519845/modulo-of-a-negative-number
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With