4

How come -20 % 3 = 1?

Just confused with the formulae used for negative number % positive number.

(I have seen many question related in quora but still not clear with formula used)

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
havin
  • 203
  • 4
  • 17
  • 1
    Well, seems like `3-(20%3)`. https://math.stackexchange.com/a/2341177 – OneCricketeer Sep 08 '17 at 07:00
  • 1
    python does floor division , you can find a good explanation here http://python-history.blogspot.in/2010/08/why-pythons-integer-division-floors.html – Kallz Sep 08 '17 at 07:13
  • Note, this is very useful, and a bit more natural. Suppose you number your days 0-6, and you know you are on day 4, then what day was it 20 days ago? `(4 - 20) % 7 == -16 % 7 == 5` – juanpa.arrivillaga Sep 08 '17 at 07:14
  • @Kallz Difficult to understand – havin Sep 08 '17 at 07:40
  • @juanpa.arrivillaga How come days are calculated – havin Sep 08 '17 at 07:40
  • Python follows the rules of mathematics, where modulo is either zero or has the same sign as the divisor. Effectively the division is truncated towards negative infinity. Languages like APL which dates back to the 1960's also implements modulo this way. C, C++, and some other languages have the remainder equal to zero or the same sign as the dividend, where effectively the division is rounded towards zero. The math / Python method has the advantage that the relationship (a + b m)%m = a, regardless if b is less than, equal to, or greater than zero. – rcgldr Sep 08 '17 at 07:47

1 Answers1

0

I am not sure about the formula but you can add x to the negative number such that (x+ negative number)>=0 and x is a multiple of mod value . This is right because x % k = (x+ y*k) % k

Arount
  • 9,853
  • 1
  • 30
  • 43
ksohan
  • 1,165
  • 2
  • 9
  • 23
  • Can you please explain with above numbers(-20%3 = 1).Cannot understand. – havin Sep 08 '17 at 07:35
  • @havin - when truncating division towards negative infinity, `-20 / 3 = -7`, so `-20 % 3 = (-20) - (-21) = 1` or `3 x (-7) + 1 = -21 + 1 = -20` . – rcgldr Sep 08 '17 at 07:51
  • add 21 with -20 `-20 % 3 = (-20 + 21) % 3 = 1 % 3 = 1` Here `(-20 + 21) % 3` can be written as `(-20 %3 ) + (21 % 3 )` . Since `(21 % 3) = 0` , so it will not affect the answer nut will help us find the answer – ksohan Sep 08 '17 at 08:17