Average of 3 long integers

前端 未结 12 1756
我寻月下人不归
我寻月下人不归 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:53

    I also tried it and come up with a faster solution (although only by a factor about 3/4). It uses a single division

    public static long avg(long a, long b, long c) {
        final long quarterSum = (a>>2) + (b>>2) + (c>>2);
        final long lowSum = (a&3) + (b&3) + (c&3);
        final long twelfth = quarterSum / 3;
        final long quarterRemainder = quarterSum - 3*twelfth;
        final long adjustment = smallDiv3(lowSum + 4*quarterRemainder);
        return 4*twelfth + adjustment;
    }
    

    where smallDiv3 is division by 3 using multipliation and working only for small arguments

    private static long smallDiv3(long n) {
        assert -30 <= n && n <= 30;
        // Constants found rather experimentally.
        return (64/3*n + 10) >> 6;
    }
    

    Here is the whole code including a test and a benchmark, the results are not that impressive.

提交回复
热议问题