For example we have an int array:
var array = new int[]{ 2147483647, 2147483647, 2147483647, 2147483647};
What is the easiest way to calculate the sum of the array entries, BUT in respect to the example provided above?
array.Sum()
results in:
Arithmetic operation resulted in an overflow
Because the result is not an int anymore..
Because the sum of the values in your array overflows the Int32.MaxValue
you are forced to cast your elements to a long
var array = new int[]{ 2147483647, 2147483647, 2147483647, 2147483647};
var total = array.Sum(x => (long)x);
Console.WriteLine(total);
And you can see that the total variable is of type Int64
Console.WriteLine(total.GetType());
Steve's answer fits your question perfectly. However, if you need to store the sum of values that are longer than the typical datatypes you could use BigInteger
.
var array = new [] { long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue };
var result = new BigInteger();
result = array.Aggregate(result, (current, i) => current + i);
This solution would also work for your provided array.
To expand on Steve's solution to "How to sum a long[] array which exceeds Int64.MaxValue?", decimal type can be used to sum arrays of long[], as:
var array = new [] { long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue };
var result = array.Sum(x => (decimal)x);
decimal has a 96-bit mantissa, which is sufficient for a perfectly accurate result of an array with 2 Giga longs in it, which is the maximum size of an array in C# due to array index being limited to an Int32. Using the above decimal implementation is 5X faster than using BigInteger.
To go even faster:
result = array.AsParallel().Sum(x => (decimal)x);
this solution takes advantage of multi-core CPU for additional performance.
To go even faster, HPCsharp nuget package implements Sum() for int[], uint[], long[], ulong[] and all of the other signed and unsigned integers types, using data parallel SSE instructions, for faster performance on a single core, as well as parallel multi-core, while dealing with the sum exceeding MaxValue for each data type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With