views:

413

answers:

3

Question is: Find the sum of all the primes below 2 million.

I pretty much did the Sieve of Erastothenes thing, and the program below seems to work for small number i.e. define LIMIT as 10L produces 17 as answer.

I submitted 1179908154 as the answer, as produced by the following program, and it was incorrect.

Please help pointing out the problem. Thanks.

#include <stdio.h>

#define LIMIT 2000000L
int i[LIMIT];

int main()
{
    unsigned long int n = 0, k, sum = 0L;
    for(n = 0; n < LIMIT; n++)
        i[n] = 1;
    i[0] = 0;
    i[1] = 0;

    unsigned long int p = 2L;

    while (p*p < LIMIT)
    {
        k = 2L;
        while (p*k < LIMIT)
        {
            i[p*k] = 0;
            k++;
        }
        p++;
    }

    for(n = 0; n < LIMIT; n++)
        if (i[n] == 1)
        {
            sum += n;
        }
    printf("%lu\n",sum);

    return 0;
}
+6  A: 

You calculate the primes correctly, but the sum is too large (over 2^32) and won't fit in an unsigned 32-bit long. You can use a 64-bit number (long long on some compilers) to fix this.

interjay
thanks. ya i simply assumed that long unsigned was already too big for any purpose. silly me
idazuwaika
You will run into this from time to time; there are many Euler problems with big numbers. Sometimes you can do clever trickery to avoid using `long long` or even unlimited types; sometimes you cannot.
Thomas
+4  A: 

Your logic seems to be correct, but you are messing up with the data types and their ranges.Check whether this works or not:

#include <stdio.h>

#define LIMIT 2000000
int i[LIMIT];

int main()
 {
   long long int n = 0, k, sum = 0;
  for(n = 0; n < LIMIT; n++)
    i[n] = 1;
  i[0] = 0;
  i[1] = 0;

  long long int p = 2;

  while (p*p < LIMIT)
  {
    k = 2;
    while (p*k <LIMIT)
    {
        i[p*k] = 0;
        k++;
    }
    p++;
  }

  for(n = 0; n < LIMIT; n++)
    if (i[n] == 1)
    {
        sum += n;
    }
  printf("%lld\n",sum);

  return 0;
}

Output :142913828922

Prasoon Saurav
A: 

You might also find that you need to use the compiler switch -std=c99 as well. I did with gcc (GCC) 3.4.5 (mingw-vista special r3).

i.e.

gcc -Wall -std=c99 -o problem10 problem10.c

Adrian