+ 6
Why is the rest (remainder) of both operations 5%3 and 5%-3 different?
I understand that being the negative divisor, the rest will be negative, but should it be -2 and not -1 a = 5%3 b = 5%-3 print (a, b) #output a=2 and b=-1
2 RĂ©ponses
+ 15
Andrew nailed it! đ
I find it helpful to remember that modulo operation always return the LARGEST possible remainder between 0 and the divisor. Otherwise, the number we get can go on infinitely to both ends.
For example,
...
â 5 = -1 Ă 3 + 8
â 5 = 0 Ă 3 + 5
â
5 = 1 Ă 3 + 2
â 5 = 2 Ă 3 + (-1)
â 5 = 3 Ă 3 + (-4)
...
and for negative divisor,
...
â 5 = -4 Ă (-3) + (-7)
â 5 = -3 Ă (-3) + (-4)
â
5 = -2 Ă (-3) + (-1)
â 5 = -1 Ă (-3) + 2
â 5 = 0 Ă (-3) + 5
...
Hopefully it helps! đ
+ 9
dividend = divisor * quotient + remainder
For a, quotient is 1, and: 5 = 3 * 1 + 2
For b, quotient is -2, and: 5 = -3 * (-2) + (-1)