If r = a % n , then a = n * q + r for some q . This means that you have many options for the r value, depending on the q value selected.
I would recommend reading http://en.wikipedia.org/wiki/Modulo_operation , which says that most programming languages ββchoose r with -n < r < n . This means that if r is zero, you have two options for the value of r - one positive, one negative. Different programming languages ββmake different decisions about whether to accept positive or negative. On this page you will find a table in which different languages ββare summarized:
- Python chooses
r with the same sign as n (this is what you see above). - C ++ 2011 chooses
r with the same sign as a (and before the 2011 standard, its implementation is defined).
If you want to be sure you get a positive result in Python, use this:
r = a % n if r < 0: r += n
thomson_matt
source share