我试图解决Project Euler问题10,其中要求用户计算少于200万的所有素数的总和.我通过研究维基百科上的伪代码写了以下内容,但它产生的答案似乎是不正确的,至少根据网站每当我尝试输入它时:
int main()
{
int limit = 2000000;
int answer = 5;
std::vector<bool> isPrime;
for( int i = 0; i < limit; ++i ){
isPrime.push_back( false );
}
int n = 0;
for( int x = 1; x <= ceil( sqrt( limit ) ); ++x ){
for( int y = 1; y <= ceil( sqrt( limit ) ); ++y ){
n = 4*x*x + y*y;
if( (n <= limit) && ( n%12 == 1 || n%12 == 5 ) ){
isPrime.at(n) = ! isPrime.at(n);
}
n = 3*x*x + y*y;
if( (n <= limit) && ( n%12 == 7 ) ){
isPrime.at(n) = ! isPrime.at(n);
}
n = 3*x*x - y*y;
if( (x > y) && (n <= limit) && (n%12 == 11) ){
isPrime.at(n) = ! isPrime.at(n);
}
}
}
for( n = 6; n <= ceil( sqrt( limit ) ); n += 2 ){
if( isPrime.at(n) ){
for( int m = n*n; m < limit; m += n*n ){
isPrime.at(m) = false;
}
}
}
for( int i = 5; i < limit; i += 2 ){
if( isPrime.at(i) ){
answer += i;
}
}
std::cout << "The sum of the primes below " << limit << " is " << answer << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
生成以下输出:
The sum of all the primes below 2000000 is 1179908154
Run Code Online (Sandbox Code Playgroud)
我已经用较小的限制测试了它,我可以手动验证,代码确实对这些数字正确运行.我发现其他人的实现表明答案应该是142913828922,但我无法弄清楚他们的代码与我的不同之处.
任何人都可以看到它在这里做错了吗?
您只有一个带符号的32位整数作为答案.实际答案远高于32位,因此你必须使用64位整数.请尝试使用unsigned long long.
| 归档时间: |
|
| 查看次数: |
196 次 |
| 最近记录: |