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

前端 未结 6 1378
半阙折子戏
半阙折子戏 2021-02-01 11:39

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,          


        
6条回答
  •  情书的邮戳
    2021-02-01 12:13

    I liked this question so much I made it the subject of my blog on June 4th, 2013. Thanks for the great question!


    Large cases are easy to come by. For example:

    a = 1073741823; 
    b = 134217727;
    c = 134217727;
    

    because b * c overflows to a negative number.

    I would add to that the fact that in checked arithmetic, the difference between a / (b * c) and (a / b) / c can be the difference between a program that works and a program that crashes. If the product of b and c overflows the bounds of an integer then the former will crash in a checked context.

    For small positive integers, say, small enough to fit into a short, the identity should be maintained.


    Timothy Shields just posted a proof; I present here an alternative proof. Assume all the numbers here are non-negative integers and none of the operations overflow.

    Integer division of x / y finds the value q such that q * y + r == x, where 0 <= r < y.

    So the division a / (b * c) finds the value q1 such that

    q1 * b * c + r1 == a
    

    where 0 <= r1 < b * c

    the division ( a / b ) / c first finds the value qt such that

    qt * b + r3 == a
    

    and then finds the value q2 such that

    q2 * c + r2 == qt
    

    So substitute that in for qt and we get:

    q2 * b * c + b * r2 + r3 == a
    

    where 0 <= r2 < c and 0 <= r3 < b.

    Two things equal to the same are equal to each other, so we have

    q1 * b * c + r1 == q2 * b * c + b * r2 + r3
    

    Suppose q1 == q2 + x for some integer x. Substitute that in and solve for x:

    q2 * b * c + x * b * c + r1 = q2 * b * c + b * r2 + r3
    x  = (b * r2 + r3 - r1) / (b * c)
    

    where

     0 <= r1 < b * c
     0 <= r2 < c
     0 <= r3 < b
    

    Can x be greater than zero? No. We have the inequalities:

     b * r2 + r3 - r1 <= b * r2 + r3 <= b * (c - 1) + r3 < b * (c - 1) + b == b * c
    

    So the numerator of that fraction is always smaller than b * c, so x cannot be greater than zero.

    Can x be less than zero? No, by similar argument, left to the reader.

    Therefore integer x is zero, and therefore q1 == q2.

提交回复
热议问题