I have an int array like this
int[] arr = {256741038,623958417,467905213,714532089,938071625};
and then I created an int64 var
Int64 sum = arr.Sum();
But this reslted in an overflow
Run-time exception (line 19): Arithmetic operation resulted in an overflow.
How can I solve this problem without using loop to sum it up ? (array type must be int)
The issue is that while the individual values fit within an int
, the sum of these numbers results is larger than an int
can hold.
You therefore need to cast the values to long
(or another datatype that takes numbers that big, but since you're using Int64...):
long sum = arr.Sum(v => (long)v);
You will have to cast it to long so you don't overflow
var result = arr.Select(x => (long)x).Sum();
int (C# Reference)
Range =
-2,147,483,648
to2,147,483,647
Some background, this is the source code for Sum
public static int Sum(this IEnumerable<int> source)
{
if (source == null) throw Error.ArgumentNull("source");
int sum = 0;
checked
{
foreach (int v in source)
sum += v;
}
return sum;
}
Meaning, whether you like it or not, someone is using a for loop, additionaly the usage of checked
is why it throws :)
checked (C# Reference)
The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.
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