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.
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.
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.
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.
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.
Try converting to Int64 (long) before getting sum:
Console.WriteLine(numbers.Select(x=> (long)x).Sum().ToString());
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With