![](/img/trans.png)
[英]Why is my D code for finding prime numbers much faster than my C++ code?
[英]Why doesn't my code generate the prime numbers correctly
小于10,000,000的质数数为664,579,但我的代码仅生成664,214。 数字的来源是https://primes.utm.edu/howmany.html
#include <iostream>
#include <bitset>
#include <vector>
using namespace std;
const int N = 10000001;
bitset<N>num;
vector<int>prime;
inline void sieve()
{
num.flip();
num[0] = num[1] = 0;
for(int i=2;i<N;i++)
if(num[i])
{
prime.push_back(i);
for(long long unsigned j=i*i; j<N;j+=i)
num[j] = 0;
}
}
int main() {
sieve();
cout << prime.size() << endl;
return 0;
}
计算i*i
时,整数溢出。 然后将结果分配给很长很长的事实并不能使编译器在乘法之前提升类型。
如果我将i
声明为long long unsigned int
则您的程序输出664579
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.