7

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)

3
  • 2
    arr.Select(z => (long)z).Sum() Commented Oct 31, 2018 at 2:46
  • Possible duplicate of How to calculate the sum of an int array whose result exceeds Int32.Max value Commented Oct 31, 2018 at 2: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. Commented Oct 31, 2018 at 2:51

5 Answers 5

20

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);
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

1 Comment

Thanks but in my question I said that I don't want to use any kind of loop :) @John's solution is fabulous
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

Comments

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.

2 Comments

Thanks but in my question I said that I don't want to use any kind of loop :)
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.