Hello, @bit5009167409. Welcome to the forums.
20 goes into -5 how many times? 0 right? What is the remainder? -5 correct?
-5 + 20 = 15, but -5 % 20 = -5
The output is correct.
> -5 + 20 15 > -5 % 20 -5
101/ 11 = 99 remainder 2
101 = 11 * 99 + 2
-11 / 3 =
-11 = -4*3 + 1
So the remainder is 1.
Remainders must always be positive.
Reference: Discrete Math & Its Applications, K. Rosen, 7th Edition page 217.
So -5 / 20 =
-5 = -1 * 20 + 15
So the remainder is 15.
Interesting. Python & Ruby behave as you’ve described the correct answer should be, but the others do not.
Haskell produces different results depending on how the mod method is used:
Prelude> mod (-5) 20 15 Prelude> (-5) `mod` 20 15 Prelude> -5 `mod` 20 -5
Thanks for checking all of those out! In the big picture, I don’t think it matters. I just found it curious! In the very very rare event that the topic comes up, I guess its good to know that one can get different interpretations.
Other than not getting the expected outcome. I, not having much of a background in math, (at least not a lot that I remember anymore) saw the expected outcome. With your background, you saw a math error. Thanks for asking your original question. I learned something.
In modular arithmetic things go around, like a clock. You’ll always end up with a result in the valid range. For a clock, 23 + 4 is 3
There are two similar operations, rem and mod, and two ways to divide to go with them.
Haskell’s prelude exports both of those functions, and both ways to divide (rem mod div quot). (watch out with operator precedence) The documentation there also mentions their differences and relations:
I suppose languages that give special meaning to
% pick one or the other and then match division with it (div mod or quot rem) … and if you care about the difference then you’d probably notice.