Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 620
Milan Vodák Avatar asked Oct 03 '18 18:10

Milan Vodák


People also ask

How do you throw an overflow exception?

OverflowException -> printfn $"Exception: {value} > {SByte. MaxValue}." // The example displays the following output: // Exception: 241 > 127. Dim value As Byte = 241 Try Dim newValue As SByte = (CSByte(value)) Console. WriteLine("Converted the {0} value {1} to the {2} value {3}.", _ value.

How do you handle arithmetic overflow exception in C#?

If you want to ensure that arithmetic operations will throw overflow exceptions if an overflow happens, you need to use the checked { ... } code block. When using the checked { ... } code block, if any arithmetic operation causes an overflow, an OverflowException will be thrown, and will need to be catched and handled.

What happens when integer overflow in C#?

When integer overflow occurs, what happens depends on the execution context, which can be checked or unchecked. In a checked context, an OverflowException is thrown. In an unchecked context, the most significant bits of the result are discarded and execution continues.

Does Java throw overflow exception?

Java does not throw an exception when an overflow occurs; that is why it can be hard to find errors resulting from an overflow. Nor can we directly access the overflow flag, which is available in most CPUs.


2 Answers

Try converting to Int64 (long) before getting sum:

Console.WriteLine(numbers.Select(x=> (long)x).Sum().ToString());
like image 53
Ashkan Mobayen Khiabani Avatar answered Oct 20 '22 22:10

Ashkan Mobayen Khiabani


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

like image 29
China Syndrome Avatar answered Oct 20 '22 23:10

China Syndrome