-1

i am new in c#. I have a windows form program that can show odd number from 1 to n. This is the source code :

                    List<int> t = Enumerable.Range(1, 123456).ToList();
                    var oddNumbers = t.Where(num => num % 2 != 0);
                    txtHasil.Text += oddNumbers.Sum() + Environment.NewLine;
                    txtHasil.Text += string.Join(",", oddNumbers.Select(n => n.ToString()).ToArray()) + Environment.NewLine;
                    txtHasil.Text += oddNumbers.Count() + Environment.NewLine;

If i use 1234 in the range, the program work well. If i use 12345 in the range, the program still work well. But if i use 123456 in the range, the program error "Arithmetic operation resulted in an overflow" in oddNumbers.Sum() line.

What should i do for 123456 data ?

ckruczek
  • 2,361
  • 2
  • 20
  • 23
Liudi Wijaya
  • 898
  • 2
  • 8
  • 24
  • try to use `decimal` instead of `int`, or `long` – Markiian Benovskyi Oct 04 '17 at 12:10
  • Question title nearly say [BigInteger](https://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx). – Sinatr Oct 04 '17 at 12:11
  • [Most of the time, error messages will tell you exactly what is wrong, if you bother to read them](https://stackoverflow.com/questions/4756542/arithmetic-operation-resulted-in-an-overflow-adding-integers). – waka Oct 04 '17 at 12:15
  • The sum of odd numbers from 1...(2n-1) is n*n, if you have to do that a lot. [Direct Proof that 1+3+5+⋯+(2n−1)=n⋅n](https://math.stackexchange.com/q/136237/189637) – Andrew Morton Oct 04 '17 at 12:30

2 Answers2

3

You can use a larger type like Long or Decimal:

List<long> t = Enumerable.Range(1, 123456).Select(i => (long)i).ToList();
var oddNumbers = t.Where(num => num % 2 != 0);
long sum = oddNumbers.Sum();

If you want to support arbitrary size you can use System.Numerics.BigInteger:

List<BigInteger> t = Enumerable.Range(1, 123456).Select(i => new BigInteger(i)).ToList();
var oddNumbers = t.Where(num => num % 2 != 0);
BigInteger sum = oddNumbers.Aggregate(new BigInteger(0), BigInteger.Add);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
3

This line

oddNumbers.Sum()

will return an integer. Your sum is going over the limit for the maximum size of an integer.

You can use an Int64 instead, giving you a larger capacity.

List<Int64> t = Enumerable.Range(1, 123456).Select(i => (Int64)i).ToList();
var oddNumbers = t.Where(num => num % 2 != 0);
decimal sum = oddNumbers.Sum();
Justin Harvey
  • 14,446
  • 2
  • 27
  • 30