'.NET core 6 throws arithmetic overflow exception when using lambda
Why only lambda version of miniMaxSum function throws an Arithmetic overflow exception?
Code with Lambda:
void miniMaxSum(List<int> arr)
{
Int64 maxNum = 0;
Int64 minNum = 0;
Int64 min = 0;
Int64 max = 0;
maxNum = arr.Max();
minNum = arr.Min();
min = arr.Where(n => n != maxNum).Sum();
max = arr.Where(n => n != minNum).Sum();
Console.WriteLine($"{min} {max}");
}
List<int> nums = new List<int>{
256741038,
623958417,
467905213,
714532089,
938071625
};
miniMaxSum(nums);
Output:
Unhandled exception. System.OverflowException: Arithmetic operation resulted in an overflow.
at System.Linq.Enumerable.Sum(IEnumerable1 source) at Program.<<Main>$>g__miniMaxSum|0_0(List1 arr) in /home/gabriel/source/HackerRank/MinMaxSum/Program.cs:line 10
code without Lambda:
void miniMaxSum(List<int> arr)
{
Int64 maxNum = 0;
Int64 minNum = 0;
Int64 min = 0;
Int64 max = 0;
maxNum = arr.Max();
minNum = arr.Min();
Int64 aux = 0;
for (int i =0;i <arr.Count;i++)
{
if (arr[i] != maxNum)
{
aux = checked((Int64)(min=min+arr[i]));
min = aux;
}
if (arr[i] != minNum)
{
aux = checked((Int64)(max=max+arr[i]));
max = aux;
}
}
Console.WriteLine($"{min} {max}");
}
List<int> nums = new List<int>{
256741038,
623958417,
467905213,
714532089,
938071625
};
miniMaxSum(nums);
Output:
2063136757 2744467344
Anyone can explain this behavior?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
