Average of 3 long integers

前端 未结 12 1748
我寻月下人不归
我寻月下人不归 2020-12-07 10:05

I have 3 very large signed integers.

long x = long.MaxValue;
long y = long.MaxValue - 1;
long z = long.MaxValue - 2;

I want to calculate th

12条回答
  •  长情又很酷
    2020-12-07 10:48

    Patching Patrick Hofman's solution with supercat's correction, I give you the following:

    static Int64 Avg3 ( Int64 x, Int64 y, Int64 z )
    {
        UInt64 flag = 1ul << 63;
        UInt64 x_ = flag ^ (UInt64) x;
        UInt64 y_ = flag ^ (UInt64) y;
        UInt64 z_ = flag ^ (UInt64) z;
        UInt64 quotient = x_ / 3ul + y_ / 3ul + z_ / 3ul
            + ( x_ % 3ul + y_ % 3ul + z_ % 3ul ) / 3ul;
        return (Int64) (quotient ^ flag);
    }
    

    And the N element case:

    static Int64 AvgN ( params Int64 [ ] args )
    {
        UInt64 length = (UInt64) args.Length;
        UInt64 flag = 1ul << 63;
        UInt64 quotient_sum = 0;
        UInt64 remainder_sum = 0;
        foreach ( Int64 item in args )
        {
            UInt64 uitem = flag ^ (UInt64) item;
            quotient_sum += uitem / length;
            remainder_sum += uitem % length;
        }
    
        return (Int64) ( flag ^ ( quotient_sum + remainder_sum / length ) );
    }
    

    This always gives the floor() of the mean, and eliminates every possible edge case.

提交回复
热议问题