Path: utzoo!censor!geac!torsqnt!news-server.csri.toronto.edu!cs.utexas.edu!usc!apple!agate!usenet From: bks@alfa.berkeley.edu (Brad Sherman) Newsgroups: comp.lang.c Subject: Re: % operator with negatives Message-ID: <1990Dec17.175010.12654@agate.berkeley.edu> Date: 17 Dec 90 17:50:10 GMT References: <7461:Dec1310:04:0990@kramden.acf.nyu.edu> <1529@bbxsda.UUCP> <540@taumet.com> Sender: usenet@agate.berkeley.edu (USENET Administrator) Organization: University of California, Berkeley Lines: 27 --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@alfa.berkeley.edu) "Mathematics is the queen of the sciences and number theory the queen of mathematics." -- C.F. Gauss