If r = a % n
, then a = n * q + r
for some q
. That means that you have many choices for the value of r
, depending on the value of q
that gets chosen.
I'd recommend reading http://en.wikipedia.org/wiki/Modulo_operation, which says that most programming languages choose r
with -n < r < n
. That means that, unless r
is zero, you have two choices for the value of r
- one positive, one negative. Different programming languages make different decisions about whether to take the positive or negative one. You'll find a table on that page that summarizes what different languages do:
- Python chooses
r
with the same sign as n
(which is what you see above).
- C++ 2011 chooses
r
with the same sign as a
(and before the 2011 standard, it's implementation defined).
If you want to be sure that you get the positive one in Python, use this:
r = a % n
if r < 0:
r += n