Newsgroups: comp.misc Path: utzoo!utgpu!news-server.csri.toronto.edu!torsqnt!lethe!druid!darcy From: darcy@druid.uucp (D'Arcy J.M. Cain) Subject: Re: Signed integer division - implementation questions Message-ID: <1991Jun30.123047.3944@druid.uucp> Organization: D'Arcy Cain Consulting, West Hill, Ontario References: <1991Jun29.172953.20536@ux1.cso.uiuc.edu> Date: Sun, 30 Jun 91 12:30:47 GMT In article <1991Jun29.172953.20536@ux1.cso.uiuc.edu> Glenn Chappell writes: >In article (The Lab Rat) writes: >>qustions arise. In particular, what does one do in the case of signed >>division. >> -11 / 4 = -2, remainder -3 >> 11 / -4 = -2, remainder 3 >> -11 / -4 = 2, remainder -3 >> >> -11 / 4 = -3, remainder 1 >> 11 / -4 = -2, remainder 3 >> -11 / -4 = 3, remainder 1 >> >> -11 / 4 = -3, remainder 1 >> 11 / -4 = -3, remainder -1 >> -11 / -4 = 2, remainder -3 > >I would prefer it if everyone would use the second system (remainder >always non-negative), since it conforms most closely to the usual way >mathematicians use modular arithmetic. Here is the rationale I used when tackling this problem: |---------------------------------------------------------------------------| | What does div and ldiv do with negative numbers? Working backwards from | | the observation that when positive numbers are involved, the remainder | | added to the product of the quotient and denominator should give the | | numerator, I get the following examples: | | | | num denom quot rem | | === ===== ==== === | | +13 +5 +2 +3 | | -13 +5 -2 -3 | | +13 -5 -2 +3 | | -13 -5 +2 -3 | | | | if denom is 0 then I return quotient as 0 and remainder as the numerator. | | That seems to fit the model: (0 * 0) + rem == num. | |---------------------------------------------------------------------------| Furthermore I have since found the following in K&R2 pp205: "Otherwise, [second operand not 0] it is always true that (a/b)*b + a%b is equal to a." which is another way of saying the above. -- D'Arcy J.M. Cain (darcy@druid) | D'Arcy Cain Consulting | There's no government Toronto, Ontario, Canada | like no government! +1 416 424 2871 |