6

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)

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
vdthe
  • 71
  • 1
  • 4
  • 2
    `arr.Select(z => (long)z).Sum()` – mjwills Oct 31 '18 at 02:46
  • Possible duplicate of [How to calculate the sum of an int array whose result exceeds Int32.Max value](https://stackoverflow.com/questions/41515299/how-to-calculate-the-sum-of-an-int-array-whose-result-exceeds-int32-max-value) – mjwills Oct 31 '18 at 02:46
  • @vdthe The key thing to understand here is that `Sum` doesn't choose the return type based on what is needed to store the `Sum` (which, in this case would be a `long`). Instead, it chooses it based on the type of the enumerable being summed. You are summing `int` so, alas, it tries (unsuccessfully) to fit the sum into an `int`. – mjwills Oct 31 '18 at 02:51

5 Answers5

18

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);
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
3

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.

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
1

You can find sum as shown below

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        int[] arr = {999999999, 999999999, 999999999,999999999, 999999999};
         long sum = 0;
         for (int i = 0; i < arr.Length; i += 1)
         {
           sum += arr[i];
         }
        Console.WriteLine(sum);
    }
}

Datatype and Range Reference

Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42
  • Thanks but in my question I said that I don't want to use any kind of loop :) @John's solution is fabulous – vdthe Nov 01 '18 at 07:50
0

When you call sum on array of integer, output type is an integer, and sum of entered numbers are more than integer maxvalue. as @TheGeneral said sum method check overflow and throw exception.

may be you expect the sum method return result as long, but its return type is an integer.

int a = 256741038;
int b = 623958417;
int c = 467905213;
int d = 714532089;
int e = 938071625;

long sumInt = a + b + c + d + e;
//-1293758914 //overflow happened withoud exception
long sumLong = (long)a + b + c + d + e;//clr now the result may be more than int.maxvalue
//3001208382
Mehrdad
  • 1,523
  • 9
  • 23
0

A shorter way is as shown below

using System;
namespace Test
{
    public partial class TestPage : System.Web.UI.Page
    {
        public int[] p = { 999999999, 999999999, 999999999, 999999999, 999999999 };
        protected void Page_Load(object sender, EventArgs e)
        {
            long s = Sum;
        }
        public long Sum
        {
            get { long s = 0; Array.ForEach(p, delegate (int i) { s += i; }); return s; }
        }        
    }
}

Hope this will help you.

Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42
  • 1
    Thanks but in my question I said that I don't want to use any kind of loop :) – vdthe Nov 02 '18 at 08:37
  • No issue I can understand and one another answer has been already given by another way so I can not repeat that but someone can get help from your question and different way...Thanks and welcome – Suraj Kumar Nov 02 '18 at 10:34