Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modulus of negative numbers in Python [duplicate]

Tags:

python

modulus

23 % -5 = -2
23 % 5 = 3

Can someone explain to me how I can understand this because I have an exam tomorrow. I want to say its because -5 * -5 =25 then 25 -2 = 23 which is how they get the 23. Is this correct?

like image 841
anon_nerd Avatar asked Jan 25 '26 12:01

anon_nerd


1 Answers

In Python, the sign of the remainder is the same as the sign of the denominator (which differs from languages like C, where it is the same as the sign of the numerator).

Mathematically, you are always guaranteed that if a, b = divmod(n, d), then a*d + b == n.

Note that 23//5 == 4 and 23//-5 == -5 (Python always does floor division). Thus, we have 4*5 + 3 == 23 and -5*-5 - 2 == 23, as you have said.

like image 99
nneonneo Avatar answered Jan 28 '26 02:01

nneonneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!