简体   繁体   中英

Overflow exception during sum of all the values of integer array in C#

Hi I was solving a very basic problem on Hackerrank about determining Mini-Max Sum of all the values in an integer array. Basically given an array of 5 values like [1, 2, 3, 4, 5], the minimum sum will be 1+2+3+4 = 10 and maximum sum will be 2+3+4+5 = 14. Very simple question, but I am running into an issue with a certain large input values. Below are my solutions and their result.

//Input: 256741038 623958417 467905213 714532089 938071625
//Output: 2063136757 2744467344

Below is using inbuilt Sum() method.

static void Main(string[] args)
{
    int[] arr = new int[5] {256741038,623958417,467905213,714532089,938071625};
    Array.Sort(arr);
    long arrSum = arr.Sum();  //System.OverflowException: 'Arithmetic operation resulted in an overflow.'
    long minSum = arrSum - arr[arr.Length - 1];
    long maxSum = arrSum - arr[0];
    Console.WriteLine(minSum + " " + maxSum);
}

Below is using Aggregate extension method.

static void Main(string[] args)

{
    int[] arr = new int[5] {256741038,623958417,467905213,714532089,938071625};
    Array.Sort(arr);
    long arrSum = arr.Aggregate((total, next) => total + next); // arrSum = -1293758914
    long minSum = arrSum - arr[arr.Length - 1];
    long maxSum = arrSum - arr[0];
    Console.WriteLine(minSum + " " + maxSum);
}

Output: -2231830539 -1550499952

And if I use the regular foreach loop like below:

static void miniMaxSum(int[] arr)
{
    Array.Sort(arr);
    long arrSum = 0;
    foreach (var value in arr)
    {
        arrSum += value;
    }
    long minSum = arrSum - arr[arr.Length - 1];
    long maxSum = arrSum - arr[0];
    Console.WriteLine(minSum + " " + maxSum);
}

The output is correct as expected i.e. 2063136757 2744467344

The OverflowException class description here says "An arithmetic operation produces a result that is outside the range of the data type returned by the operation". But the arrSum value is within long range so I am not able to figure out the issue. So not sure if I am missing anything or using the functions incorrectly but not able to understand this behavior.

Any detail is appreciated.

Reason its failing is because the Sum() method is being executed on the int arrays. If you convert the numbers of the int array to long and then run the Sum operation on them, then you will get your result.

long arrSum = nums.Sum(x => (long)x);

// or, for readability
long arrSum = nums.Select(x => (long)x).Sum();

This will run the Sum operation only on long s. Way you are doing it, it sums up the integers until it is done with all of them and "then" saves it to your long.. while doing the addition, it fails because Int32 cant go too big.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM