下面是一个使用埃氏筛法的C++程序,它可以筛选出小于等于给定数n的所有素数:

#include <iostream>
#include <vector>

using namespace std;

vector<int> sieveOfEratosthenes(int n) {
    vector<bool> isPrime(n+1, true);
    vector<int> primes;

    for (int p=2; p*p<=n; p++) {
        if (isPrime[p]) {
            for (int i=p*p; i<=n; i+=p) {
                isPrime[i] = false;
            }
        }
    }

    for (int p=2; p<=n; p++) {
        if (isPrime[p]) {
            primes.push_back(p);
        }
    }

    return primes;
}

int main() {
    int n;
    cout << "Enter a number: ";
    cin >> n;

    vector<int> primes = sieveOfEratosthenes(n);

    cout << "Prime numbers less than or equal to " << n << ": ";
    for (int prime : primes) {
        cout << prime << " ";
    }
    cout << endl;

    return 0;
}

在上面的程序中,我们使用了一个vector<bool> isPrime来标记每个数是否为素数。初始时,我们将所有数都标记为素数(即true),然后从2开始,如果某个数p是素数,我们就将所有p的倍数标记为非素数(即false)。最后,我们遍历一遍isPrime数组,将所有为素数的数添加到一个vector<int>中,并返回该向量。

你可以通过输入一个数字n来测试程序。程序将输出小于等于n的所有素数

使用埃式筛法写一个c++筛素数的程序并不使用可变长数组

原文地址: https://www.cveoy.top/t/topic/ivUp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录