I' using Sieve to calculate the sum of all prime number below 2 million, but the program keeps crashing after trying several times due to overflow. It works fine with PRIME_LIMIT = 200000
So what is the problem in my code? I don't think that's the algorithm problem. When I put static
keyword when declaring the boolean array, it prints out the wrong sum ... without the keyword, it's overflow ...
This is the method I wrote:
void problem10()
{
unsigned long long int iter = 2, sum = 0;
static bool prime[PRIME_LIMIT];
for (unsigned long long int i = 0; i < PRIME_LIMIT; i++)
{
prime[i] = true;
}
unsigned long long int limit = ceil(sqrt(PRIME_LIMIT));
for (unsigned long long int i = 2; i <= limit; i++)
{
if (prime[i])
{
for (unsigned long long int j = i*i; j < PRIME_LIMIT; j += i)
{
prime[j] = false;
}
}
}
for (unsigned long long int i = 2; i < PRIME_LIMIT; i++)
{
if (prime[i])
{
sum += i;
//printf("Primes are: %d\n", i);
}
}
printf("Sum of prime is: %llu\n", sum);
}