我正在做欧拉项目,我遇到了这个问题。我在 VS 2013 中运行代码,程序由于溢出而崩溃。
这是我的方法:
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);
*/
}
此方法包括 2 种计算范围内所有素数之和的方法PRIME_LIMIT
。第二种方法需要很长时间才能获得结果,并且可能需要一整天。第一种方法是使用阿特金的筛子,程序崩溃!
我的代码有什么错误吗??请帮忙!