Why is the rest (remainder) of both operations 5%3 and 5%-3 different? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 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 Respostas
+ 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