Pages

Tuesday, March 31, 2009

Modulo a negative number

I'm quite surprised to found that MOD with -ve dividend number is NOT THE SAME as MOD with +ve dividend number.

What is modulo (MOD)?
It's a operation/function which returns the remainder of a division by two integers. It's like division, except it returns the remainder. E.g. 9/4=2.25, 9 MOD 4 = 1 (since 2x4+1=9).

For +ve dividend number, x MOD n means = x - (floor(x/n) * n)
But for -ve dividend number, x MOD n means =
  1. x + ( floor(-x/n)+1 ) * n, or
  2. -(-x MOD n) + n
Literally, the solution is like this : do as normal MOD, but add the remainder (negative number) with the divisor. E.g. -8 MOD 3, frankly return -2, but then add -2 with 3 = 1. Also in the above formulae, floor() is a function which return the answer rounded up towards bottom integer value e.g. 8.4 = 8, 11.9 = 11 etc. (always take the low integer).

Example:
x = 11, n = 3

11 MOD 3, use x - (floor(x/n) * n);
= 11 - ( floor(11/3) * 3)
= 11 - (3 * 3)
= 2

but if x = -11, n = 3

-11 MOD 3, use x + ( floor(-x/n)+1 ) * n;
= -11 + ( floor(11/3) + 1) * 3
= -11 + (3 + 1) * 3
= -11 + 12
= 1


or

-11 MOD 3, use -(-x MOD n) + n
= -(-(-11) MOD 3) + 3
= -(11 MOD 3) + 3
= -2 + 3
= 1

but, what if -11 MOD -3?
Hmmm...

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


p/s
: if u still wondering what is 'dividend' : if a/b = c, a is dividend, b is divisor and c is quotient.

No comments:

Post a Comment