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