1

Recently i solved a problem where i have to compute (a-b)%n.The results were self explanatory when a-b is an positive number but for negative numbers the results that i got seems confusing..i just wanted to know how can we calculate this result for negative numbers.

Any links dealing with modulo operator properties are most welcome.

Joni
  • 108,737
  • 14
  • 143
  • 193
user122345656
  • 1,523
  • 5
  • 15
  • 20
  • This explains it pretty well : http://stackoverflow.com/questions/4003232/how-to-code-a-modulo-operator-in-c-c-obj-c-that-handles-negative-numbers – gaganbm Mar 25 '13 at 13:48

1 Answers1

2

http://en.m.wikipedia.org/wiki/Modulo_operation

In many programming languages (C, Java) the modulo operator is defined so that the modulus has the same sign as the first operand. This means that the following equation holds:

(-a) % n = -(a % n)

For example, -8%3 would be -2, since 8%3 is 2.

Others, such as Python, compute a % n instead as the positive remainder when diving by n, which means

(-a) % n = n - (a % n)

For example, -8%3 is 1 because 3-(8%3) is 3-2 is 1.

Note that in modular arithmetic adding or subtracting any multiple of n does not change the result because "equality" (or congruence if you prefer that term) is defined with respect to divisibility: X is equal to 0 if it is a multiple of n, and A is equal to B if A-B is a multiple of n. For example -2 is equal to 1 modulo 3 because -2-1 = -3 is divisible by 3.

Joni
  • 108,737
  • 14
  • 143
  • 193
  • Thanks for your answer but i didn't get the last point:adding or subtracting multiple of n doesn't make...,say we find -11%13=-11..but adding 13 to -11 and then finding result gives 2%13=2..the results are different..then why you said that?? – user122345656 Mar 25 '13 at 08:01
  • See update. -11 is equal to 2 modulo 13 because -11-2 = -13 is a multiple of 13. – Joni Mar 25 '13 at 10:16