% operator with negatives
Brad Sherman
bks at alfa.berkeley.edu
Tue Dec 18 04:50:10 AEST 1990
--Quite distinct from the "%" is [not] a modulus operator discussion--.
For those wishing to implement a modulous function that behaves in
a reasonable manner for all integers I offer the following notes
taken from a book by Knuth and others (title forgotten).
To make "m mod n" well defined for any integer value, positive
or negative start from the relation:
m = n * floor(m/n) + m mod n
producing:
m mod n = m - n * floor(m/n)
e.g.:
5 mod 3 = 5 - 3 * floor( 5 / 3 ) = 5 - 3 * 1 = 2
-5 mod 3 = -5 - 3 * floor(-5 / 3 ) = -5 - 3 * (-2) = 1
5 mod -3 = 5 - (-3) * floor( 5 /(-3)) = 5 - (-3) * (-2) = -1
-5 mod -3 = -5 - (-3) * floor(-5 /(-3)) = -5 - (-3) * 1 = -2
Note that the result always matches the modulus in sign. No
no one has ever come up with a good name for "m" and they
suggest (with no smiley in the text!) "modumor."
[Errors in the above are mine, not Knuth's, I'm sure.]
---------------------------------
Brad Sherman (bks at alfa.berkeley.edu)
"Mathematics is the queen of the sciences and number theory
the queen of mathematics." -- C.F. Gauss
More information about the Comp.lang.c
mailing list