繁体   English   中英

为什么我的Eratosthenes筛网给出一些复合数字?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM