I was trying to find out the sum of all prime up to 2 million.
So I wrote the following code for it:
#include <math.h>
#include <stdlib.h>
#define limit 2000000
int main(void)
{
unsigned int *sieve, i, j;
unsigned long long int sum = 0;
sieve = malloc(sizeof(int)*limit);
for(i=2;i<=limit;i++)
sieve[i] = 1;
for(i=2;i<=limit;i++)
{
if(sieve[i])
{
for(j=i;j*i<=limit;j++)
sieve[j*i] = 0;
}
}
for(i=2;i<=limit;i++)
{
if(sieve[i])
sum += i;
}
printf("The sum is %llu\n",sum);
return 0;
}
The answer should be 142913828922
, but I am getting 142889228620
.
Can you tell me what is going wrong? I can't figure it out.
unsigned int *sieve, i, j;
for(j=i;j*i<=limit;j++)
The calculation j*i
overflows for i > 65535
. In this case, that spuriously produces some pseudo-composites.
Stop sieving when i
reaches the square root of the limit.