#### In C# integer arithmetic, does a/b/c always equal a/(b*c)?

Total Post:89

Points:629

1651  View(s)
Ratings:
Rate this:
Hi Expert,

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, c = 14;
int x1 = a / b / c;
int x2 = a / (b * c);

So my question is: does x1 == x2 for all a, b and c?

Thanks in advance.
1. ##### Re: In C# integer arithmetic, does a/b/c always equal a/(b*c)?

Hi Takeshi,

Let \ denote integer division (the C# / operator between two ints) and let / denote usual math division. Then, if x,y,z are positive integers and we are ignoring overflow,

(x \ y) \ z
= floor(floor(x / y) / z)      
= floor((x / y) / z)           
= floor(x / (y * z))
= x \ (y * z)

where

a \ b = floor(a / b)

The jump from line  to line  above is explained as follows. Suppose you have two integers a and b and a fractional number f in the range [0, 1). It is straightforward to see that

floor(a / b) = floor((a + f) / b)  

If in line  you identify a = floor(x / y), f = (x / y) - floor(x / y), and b = z, then  implies that  and  are equal.

You can generalize this proof to negative integers (still ignoring overflow), but I'll leave that to the reader to keep the point simple.

Thanks in advance.

### Answer

Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.