-7

I am familiar with the usual mod result but not for negative numbers. What is the logic?

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
  • Think about a clock with 5 hours instead of 12. With the hand at 5 (at the top position), move back 11 hours. Where's the hand? Note, you make two full rotations, and then you have a spare hour... – juanpa.arrivillaga Mar 14 '18 at 06:13

3 Answers3

3

Taken from https://docs.python.org/3/reference/expressions.html

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [1].

Looks like modulus operator always yields results with same sign as second operator. Hence for -11 mod 5 will yield positive (4) result.

>>> -11 % 5
4

While 11 mod -5 will yield negative (-4) result.

>>> 11 % -5
-4
Anil_M
  • 10,893
  • 6
  • 47
  • 74
1

To find −b mod N, just keep adding N to −b until the number is between 0 and N

In your case, N = 5, b = −11. Add 5 to -11, you get -6, again you get -1, and again you get 4.

So, −11 mod 5 = 4.

Joseph M
  • 141
  • 1
  • 6
0

Python's modulo operator (%) always return a number having the same sign as the denominator (divisor)

In -11%5 as 5 is a positive number, the output you got is positive

Aditi
  • 820
  • 11
  • 27