Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.Sum() results in an overflow

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)

like image 482
vdthe Avatar asked Oct 31 '18 02:10

vdthe


2 Answers

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);
like image 157
DiplomacyNotWar Avatar answered Oct 22 '22 00:10

DiplomacyNotWar


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 to 2,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.

like image 37
TheGeneral Avatar answered Oct 22 '22 01:10

TheGeneral