Let a, b and c be non-large positive integers. Does a/b/c always equal a/(b * c) with C# integer arithmetic? For me, in C# it looks like:
int a = 5126, b = 76,
I'll offer my own proof for fun. This also ignores overflow and only handles positives unfortunately, but I think the proof is clean and clear.
The goal is to show that
floor(floor(x/y)/z) = floor(x/y/z)
where /
is normal division (throughout this proof).
We represent the quotient and remainder of a/b
uniquely as a = kb + r
(by that we mean that k,r
are unique and also note |r| < |b|
). Then we have:
(1) floor(x/y) = k => x = ky + r
(2) floor(floor(x/y)/r) = k1 => floor(x/y) = k1*z + r1
(3) floor(x/y/z) = k2 => x/y = k2*z + r2
So our goal is just to show that k1 == k2
. Well we have:
k1*z + r1 = floor(x/y) = k = (x-r)/y (from lines 1 and 2)
=> x/y - r/y = k1*z + r1 => x/y = k1*z + r1 + r/y
and thus:
(4) x/y = k1*z + r1 + r/y (from above)
x/y = k2*z + r2 (from line 3)
Now observe from (2) that r1
is an integer (for k1*z
is an integer by definition) and r1 < z
(also by definition). Furthermore from (1) we know that r < y => r/y < 1
. Now consider the sum r1 + r/y
from (4). The claim is that r1 + r/y < z
and this is clear from the previous claims (because 0 <= r1 < z
and r1
is an integer so we have 0 <= r1 <= z-1
. Therefore 0 <= r1 + r/y < z
). Thus r1 + r/y = r2
by definition of r2
(otherwise there would be two remainders from x/y
which contradicts the definition of remainder). Hence we have:
x/y = k1*z + r2
x/y = k2*z + r2
and we have our desired conclusion that k1 = k2
.
The above proof should work with negatives except for a couple steps that you'd need to check an extra case(s)... but I didn't check.