[英]Why doesn't my code generate the prime numbers correctly
The number of prime numbers less than 10,000,000 is 664,579 but my code generates only 664,214. 小于10,000,000的质数数为664,579,但我的代码仅生成664,214。 The source of the numbers is https://primes.utm.edu/howmany.html
数字的来源是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;
}
You have an integer overflow when calculating i*i
. 计算
i*i
时,整数溢出。 The fact that you then assign the result to a long long doesn't make the compiler promote the types before the multiplication. 然后将结果分配给很长很长的事实并不能使编译器在乘法之前提升类型。
If I declare i
as a long long unsigned int
then your program outputs 664579 如果我将
i
声明为long long unsigned int
则您的程序输出664579
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.