![](/img/trans.png)
[英]Why is my sieve of Eratosthenes code looping infinitely. I have tested with a few numbers
[英]Why is my Sieve of Eratosthenes giving some composite numbers?
因此,在运行我的Eratosthenes筛网的实现后,在某些情况下,它还为我提供了复合数。
例如。
当数字限制为10时,我也得到2、3、5、7和9。
当限制为30时,我与质数一起得到25。
为什么是这样? 我的代码是:
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
long long n;
int main()
{
cout << "Till what number to find primes of?" << endl;
cin >> n;
int m = sqrt(n);
vector<bool> prime(n+1, true);
for(int i = 2; i<m; i++)
{
if(prime[i])
{
for(int k=i*i; k<=n; k=k+i)
{
prime[k] = false;
}
}
}
for(int j=2; j<=n; j++)
{
if(prime[j])
{
cout << j << endl;
}
}
return 0;
}
因为您要检查的是i < m
而不是i <= m
,所以您永远不会检查9的平方根,等等25。
更改
for(int i = 2; i<m; i++)
至
for(int i = 2; i<=m; i++)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.