Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This implies the if a is negative, (a%b) should also be negative.

No, python is giving you the Modulus after division (i.e. a "distance" which should be positive). If you interpret it that way everything is fine:

  >>> a = -1
  >>> b = 3
  >>> (a/b)*b
  -3
  >>> (a%b)
  2
  >>> (a/b)*b + (a%b)
  -1
Perhaps you're thinking of the Remainder?

Edit: it seems there isn't much consensus about what to do when a or b are negative. Wikipedia gives a helpful chart here how different languages choose to implement this: http://en.wikipedia.org/wiki/Modulo_operation



True. I checked the python reference again and it re-adjusts the modulo to have the same sign as the 2nd operand.

>>> 1 % -3 -2 >>> -1 % -3 -1




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: