3长整型平均 [英] Average of 3 long integers

查看:127
本文介绍了3长整型平均的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个非常大的有符号整数。

I have 3 very large signed integers.

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

我想计算他们的平均截断。预计平均值为 long.MaxValue - 1 ,这是 9223372036854775806

这是不可能计算出它:

long avg = (x + y + z) / 3; // 3074457345618258600

注:我看过所有关于平均水平的2号这些问题,但我不明白怎么说技术可以应用的3个数字平均

Note: I read all those questions about average of 2 numbers, but I don't see how that technique can be applied to average of 3 numbers.

这将是很容易与的BigInteger 的用法,但让我们假设我不能使用它。

It would be very easy with the usage of BigInteger, but let's assume I cannot use it.

BigInteger bx = new BigInteger(x);
BigInteger by = new BigInteger(y);
BigInteger bz = new BigInteger(z);
BigInteger bavg = (bx + by + bz) / 3; // 9223372036854775806

如果我转换为,然后,当然,我输了precision:

If I convert to double, then, of course, I lose precision:

double dx = x;
double dy = y;
double dz = z;
double davg = (dx + dy + dz) / 3; // 9223372036854780000

如果我转换为十进制,它的工作原理,同时也让我们假设我不能使用它。

If I convert to decimal, it works, but also let's assume that I cannot use it.

decimal mx = x;
decimal my = y;
decimal mz = z;
decimal mavg = (mx + my + mz) / 3; // 9223372036854775806

问:有没有一种方法来计算3个非常大的整数截断平均只有与的使用很长键入?不考虑这个问题,因为C#特异性,只是更容易为我提供的样品在C#。

Question: Is there a way to calculate the truncated average of 3 very large integers only with the usage of long type? Don't consider that question as C#-specific, just it is easier for me to provide samples in C#.

推荐答案

这code将工作,但不是pretty的。

This code will work, but isn't that pretty.

它首先将所有三个值(这层楼的价值观,所以你输的余数),然后把其余的:

It first divides all three values (it floors the values, so you 'lose' the remainder), and then divides the remainder:

long n = x / 3
         + y / 3
         + z / 3
         + ( x % 3
             + y % 3
             + z % 3
           ) / 3

请注意,上述示例不总是具有一个或多个负值时正常工作。

Note that the above sample does not always work properly when having one or more negative values.

与乌卢格别克讨论,因为评论的数量爆炸下面,这里是正面和负面的价值观当前最好的解决方案。

As discussed with Ulugbek, since the number of comments are exploding below, here is the current BEST solution for both positive and negative values.

由于答案和乌卢格别克Umirov ,的詹姆斯小号 KevinZ ,的Marc货车Leeuwen gnasher729 这是当前的解决方案:

Thanks to answers and comments of Ulugbek Umirov, James S, KevinZ, Marc van Leeuwen, gnasher729 this is the current solution:

static long CalculateAverage(long x, long y, long z)
{
    return (x % 3 + y % 3 + z % 3 + 6) / 3 - 2
            + x / 3 + y / 3 + z / 3;
}

static long CalculateAverage(params long[] arr)
{
    int count = arr.Length;
    return (arr.Sum(n => n % count) + count * (count - 1)) / count - (count - 1)
           + arr.Sum(n => n / count);
}

这篇关于3长整型平均的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆