one time a CS professor took points off an assignment (build interpreting calculator in assembly) and I had to bring in my number theory textbook to demonstrate that it is in fact the C language that does division incorrectly

C either rounds towards 0 on integer division or maybe does something implementation specific if the denominator is negative?

anyway

the "correct" definition of integer / and % is:
a / b = x, a % b = r, where
a = bx + r
0 <= r < |b|

(remainder is always positive, which requires rounding towards negative infinity)

*math is made up and you can define division however you want, unless you want algebra to work, then there's some rules you gotta follow

Follow

integer division // 

real division has these nice properties: if
a / b = q, then
1: (a+b) / b = q + 1
2: (-a) / b = -(a / b) = a / (-b) = -q

how should integer division handle negative numbers? simple approach is to follow property 2 above; convert both to positive numbers, then negate the result if exactly one of the operands was negative:

5 / 3 = 1 rem 2
(-5) / 3 = -(5/3) = -1 rem -2

the problem is this breaks property 1 above:

(5 + 6) / 3 = 3 rem 2
(5 + 3) / 3 = 2 rem 2
(5 + 0) / 3 = 1 rem 2
(5 - 3) / 3 = 0 rem 2 (so far so good!)
(5 - 6) / 3 = (-1) / 3 = -(1 / 3) = -(0 rem 1) = 0 rem -1
(5 - 9) / 3 = -1 rem -1 (b/c -4/3)

(-1) / 3 == (-1 + 3) / 3 !!

to be consistent, the sequence of quotients should have gone 3 2 1 0 -1 -2, but instead we got 0 twice in a row and the remainder changed from +2 to -1!

property 2 (for real numbers) is a special case of:
a / b = q --> (ka / b) = kq
where k = -1

but that can't work with integer division in the first place!
5 / 3 = 1 rem 2
(2*5) / 3 = 10 / 3 = 3 rem 1

Sign in to participate in the conversation
Cybrespace

cybrespace: the social hub of the information superhighway jack in to the mastodon fediverse today and surf the dataflow through our cybrepunk, slightly glitchy web portal support us on patreon or liberapay!