埃氏筛法筛质数(c++实现)

这篇文章展示了如何使用C++编写一个函数get_primes()来生成一定范围内的所有素数,通过SieveofEratosthenes算法,最后在main函数中统计并输出素数的数量。
#include<iostream>
using namespace std;
const int N=1e6+10;
int cnt;
bool st[N];
int primes[N];

void get_primes(int n){
    for(int i=2;i<=n;i++){
        if(!st[i]){
            primes[cnt++]=i;
            for(int j=i+i;j<=n;j+=i) st[j]=true;
        }
    }
    
}

int main(){
    int n;
    scanf("%d",&n);
    get_primes(n);
    printf("%d",cnt);
}

### 关于优化埃氏筛法求素数的C++实现 #### 使用布尔数组减少空间占用 为了提高效率,可以采用布尔类型的数组来标记哪些数字是素数。相比于整型或其他更大类型的数据结构,布尔数组能够显著降低内存消耗。 ```cpp #include <vector> using namespace std; vector<int> optimizedSieve(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; } ``` 此方法通过仅遍历奇数以及从 \(p^2\) 开始选倍数的方式减少了不必要的运算次数[^1]。 #### 并行化处理提升性能 对于大规模数据集而言,并行执行能有效缩短运行时间。利用多线程技术可以在支持并发操作的硬件平台上进一步加速计算过程。 ```cpp #include <thread> #include <mutex> void parallelMarkNonPrimes(vector<bool>& isPrime, int start, int end, mutex& m) { for (int p = start; p*p <= end; ++p) { if (!isPrime[p]) continue; lock_guard<mutex> guard(m); // Ensure thread safety when accessing shared resource for (int multiple = max(start, p*p); multiple <= end; multiple+=p){ isPrime[multiple]=false; } } } // Split work among threads based on available hardware concurrency level. const unsigned numThreads = thread::hardware_concurrency(); vector<thread> workers(numThreads); for(unsigned t=0;t<numThreads;++t){ const auto begin=(minValue+t*chunkSize)+((t==numThreads-1)?(n-(minValue+numThreads*chunkSize)):0); workers[t]=thread(parallelMarkNonPrimes,isPrime,begin,end,std::ref(m)); } for(auto &work :workers ) work.join(); ``` 上述代码展示了如何分割任务给多个线程并让它们各自负责一部分范围内的非质数标记工作[^2]。 #### 减少冗余检查以加快速度 另一个重要的优化手段是在主循环中跳过偶数(除了2),因为所有大于2的偶数都不是质数。这不仅简化了逻辑也提高了程序的整体表现。 ```cpp if (number >= 2) { primes.push_back(2); } for (long long candidate = 3; candidate <= number; candidate += 2) { bool still_prime = true; for (auto factor : primes) { if ((candidate % factor == 0)) { still_prime = false; break; } if (factor * factor > candidate) break; } if (still_prime) primes.push_back(candidate); } ``` 这种方法避免了大量的除法运算,从而提升了算法的速度和效率[^3].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值