I'm doing project Euler and I got this problem. I run the code in VS 2013 and the program crashes because of overflow.
This is my method:
void problem10()
{
long long int iter = 2, sum = 0;
//Sieve of Atkin
bool isPrime[PRIME_LIMIT+1];
for (long long int i = 5; i <= PRIME_LIMIT; i++)
{
isPrime[i] = false;
}
long long int lim = ceil(sqrt(PRIME_LIMIT));
for (long long int x = 1; x <= lim; x++)
{
for (long long int y = 1; y <= lim; y++)
{
long long int n = 4 * x*x + y*y;
if (n <= PRIME_LIMIT && (n % 12 == 1 || n % 12 == 5))
{
isPrime[n] = true;
}
n = 3 * x*x + y*y;
if (n <= PRIME_LIMIT && (n % 12 == 7))
{
isPrime[n] = true;
}
n = 3 * x*x - y*y;
if (x > y && n < PRIME_LIMIT && n % 12 == 11)
{
isPrime[n] = true;
}
}
}
// eliminate composites by seiving
for (long long int n = 5; n <= lim; n++)
{
if (isPrime[n])
{
for (long long int k = n*n; k <= PRIME_LIMIT; k+= k*k)
{
isPrime[k] = false;
}
}
}
for (long long int n = 5; n <= PRIME_LIMIT; n++)
{
if (isPrime[n])
{
sum += n;
}
}
sum = sum + 2 + 3;
printf("%lld\n", sum);
/* //A basic approach -- too slow
while (iter < PRIME_LIMIT)
{
bool isDivisible = false;
int prime = iter;
for (int a = 2; a < iter; a++)
{
if (prime%a == 0)
{
isDivisible = true;
break;
}
}
if (isDivisible){}
else
{
//printf("prime is: %d\n", prime);
sum += prime;
}
iter++;
}
printf("Sum of prime is: %d\n", sum);
*/
}
This method includes 2 approaches to calculate the sum of all prime numbers in ranges PRIME_LIMIT
. The second approach take too long to get the result, and probably take whole day. The first approach is using sieve of Atkin, the program crashes!
Is there any mistake in my code?? Please help!