2

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.

Dmitry
  • 13,797
  • 6
  • 32
  • 48

3 Answers3

7

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.

Habib
  • 219,104
  • 29
  • 407
  • 436
0

The sum of the first 21000 primes is 2 368 647 159 (according to Wolfram Alpha). This value will not fit in a 32 bit signed integer. It will be appear as a negative number.

The sum of the first 148933 primes is 142 913 828 922. This can be represented as a 64 bit integer.

Whatever sum you calculated in a 32 bit number will be wrong, and could be either positive or negative depending on magnitude.

david.pfx
  • 10,520
  • 3
  • 30
  • 63
-1
if (primes[i] < 0)
    {
        Console.WriteLine(primes[i]);
    }

This does not ensure that there are only positive numbers in the array, it only lets you know when there is a negative prime number.

If you do not want to include negatives into the sum, try this:

for (int i = 0; i < primes.GetLength(0); i++)
{
    if (sum >= 0)
    {
        sum += primes[i];
    }
}
nyl2000
  • 1
  • 1
  • This is a comment, not an answer. But it's hard to put code in comments, so let it pass. – david.pfx Jul 10 '14 at 14:35
  • He claimed that no numbers were printed. It was there for him to be confident that there were no negative numbers, so there is no *need* to alter which numbers are added to the sum. This change would not alter the execution of his program. – Servy Jul 10 '14 at 14:56
  • As Servy points out, I only used the if-statement for debugging and to make sure I didn't do anything wrong when I put the integers into the list. – Henrik Støren Jul 11 '14 at 06:05