c++求质数

#include 
using namespace std;
const int N = 1e6+10;

int prime[N], cnt;
bool st[N];

//朴素筛法-O(nlogn)
void get_primes(int x) {
    for(int i = 2; i <= n; i++) {
        if(!st[i]) prime[cnt++] = i;
        for(int j = i+i; j <= n; j += i) 
            st[j] = true;
    }
}

//埃式筛法-O(nloglogn)
void get_primes(int n) {
    for(int i = 2; i <= n; i++) {
        if(!st[i]){ 
            prime[cnt++] = i;
            for(int j = i; j <= n; j += i)
                st[j] = true;
        }
    } 
}

//线性筛法-O(n), n = 1e7的时候基本就比埃式筛法快一倍了
//算法核心:x仅会被其最小质因子筛去
void get_prime(int x) {
    for(int i = 2; i <= x; i++) {
        if(!st[i]) prime[cnt++] = i;
        for(int j = 0; prime[j] <= x / i; j++) {
            //对于任意一个合数x,假设pj为x最小质因子,当i> x;
    get_primes(x);
    cout << cnt << endl;
    return 0;
}

 

你可能感兴趣的:(c++求质数)