Search code examples
c#.netlinqmathinteger-overflow

List sum too large, throwing overflow exception


I have a list of prime numbers up to 2 000 000. That's a list containing almost 150 000 very large integers. I want a sum of all the numbers in it. Here's a random list of large integers just for demonstration:

List<int> numbers = new List<int>();
for (int i = 0; i < 100; i++)
{
    numbers.Add(1000000000);
}
Console.WriteLine(numbers.Sum().ToString());

I'm getting a "Arithmetic operation resulted in an overflow" exception. I guess the sum is too large, but converting it to Int64 didn't help, it still throws the same exception.

Console.WriteLine(Convert.ToUInt64(numbers.Sum()).ToString());

I even tried saving the sum into Int64 variable and then using it, but this didn't work either.

long sum = numbers.Sum();
Console.WriteLine(sum.ToString());

Is there any data type that can hold this large number, or am I making the mistake somewhere else? Thanks for any help.


Solution

  • Problem is your answer is over 2.65 billions. Change the int to Int64

    List<Int64> numbers = new List<Int64>();
    for (int i = 0; i < 100; i++)
    {
        numbers.Add(1000000000);
    }
    Console.WriteLine(numbers.Sum().ToString());
    

    To Clarify an Int has a max value of 2.65 billion roughly and Int64 is in the trillions