以下是使用埃式筛法写的C++程序,不使用vector:

#include <iostream>
#include <cmath>

void sieveOfEratosthenes(int n) {
    bool *prime = new bool[n + 1];
    std::memset(prime, true, sizeof(bool) * (n + 1));
    
    for (int p = 2; p <= std::sqrt(n); p++) {
        if (prime[p] == true) {
            for (int i = p * p; i <= n; i += p)
                prime[i] = false;
        }
    }
    
    for (int p = 2; p <= n; p++) {
        if (prime[p])
            std::cout << p << " ";
    }
    
    delete[] prime;
}

int main() {
    int n;
    std::cout << "Enter the value of n: ";
    std::cin >> n;
    
    std::cout << "Prime numbers up to " << n << " are: ";
    sieveOfEratosthenes(n);
    
    return 0;
}

该程序使用埃式筛法找出从2到给定数n之间的所有素数。它首先创建一个大小为n+1的布尔数组prime,并将所有元素初始化为true。然后,它从2开始迭代到sqrt(n),对于每个素数p,将数组中所有p的倍数标记为false。最后,它输出数组中为true的索引位置,即素数。

请注意,为了避免使用vector,我们使用了动态分配的布尔数组,并在程序结束时释放了内存

使用埃式筛法写一个c++筛素数的程序并不使用vector

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

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