为什么我的欧拉计划 #10 失败了?
问题是:求200万以下所有素数的和。
我几乎做了埃拉斯托尼筛法,下面的程序似乎适用于小数,即定义 LIMIT 为 10L 产生 17 作为答案。
我提交了 1179908154 作为答案,由以下程序生成,但它不正确。
请帮忙指出问题所在。谢谢。
#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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正确计算了素数,但总和太大(超过 2^32)并且不适合无符号 32 位长。您可以使用 64 位数字(在某些编译器上为
long long
)来解决此问题。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.您的逻辑似乎是正确的,但您弄乱了数据类型及其范围。检查这是否有效:
Output :142913828922
Your logic seems to be correct, but you are messing up with the data types and their ranges.Check whether this works or not:
Output :142913828922
您可能还会发现还需要使用编译器开关-std=c99。我使用的是gcc (GCC) 3.4.5 (mingw-vistaspecial r3)。
IE
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.