Why is the rest (remainder) of both operations 5%3 and 5%-3 different? | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 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

17th Feb 2018, 10:40 PM
Javier I. Rivera R.
Javier I. Rivera R. - avatar
2 Respuestas
+ 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! 😉
18th Feb 2018, 9:08 AM
Zephyr Koo
Zephyr Koo - avatar
+ 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)
17th Feb 2018, 11:17 PM
Andrew
Andrew - avatar