Search code examples
c#arraysnegative-numbersum-of-digits

Positive integers in array sum to a negative number


I have this piece of code:

int[] primes = generatePrimes(bound);

int sum = 0;
for (int i = 0; i < primes.GetLength(0); i++)
{
    if (sum < 0)
    {
        Console.WriteLine(sum);
    }
    sum += primes[i];
}

I have checked to make sure that my array "primes" only contains positive integers like so:

if (primes[i] < 0)
{
    Console.WriteLine(primes[i]);
}

But nothing will be printed. However, for some reason the sum will sometimes be negative and will get printed when I run the first piece of code. The length of the array is 148933. I don't know that much C#, but I didn't think that the length should matter here? :S

If someone knows why this is happening, I would greatly appreciate any help.


Solution

  • the length of the array is 148933.

    Most probably your sum is over flowing the possible values for int (-2,147,483,648 to 2,147,483,647), that is why you see negative numbers.

    Use long for your sum calculation. But you might need BigInteger to calculate the sum.