素数筛——Eratosthenes 素数筛、Euler 素数筛

/***************************************************** > File Name: liner_filter.cpp > Author: Yuji CAO > Mail: [email protected] > Created Time: 二 6/13 12:11:11 2017 ****************************************************/

#include<map>
#include<vector>
#include<unordered_set>
#include<unordered_map>
#include<list>
#include<queue>
#include<deque>
#include<stack>
#include<iostream>
#include<set>
using namespace std;
/** * Eratosthenes 素数筛 **/
int prime_nlogn(int n) {
    vector<int> prime;
    unordered_set<int> checkout;
    for (int i = 2; i <= n; ++i) {
        if (!checkout.count(i)) prime.push_back(i);
        for (int j = i * 2; j <= n; j += i) {
            checkout.insert(j);
        }
    }
    return prime.size();
}
/** * Euler 素数筛 **/
int prime_n(int n) {
    vector<int> prime;
    unordered_set<int> checkout;
    for (int i = 2; i <= n; ++i) {
        if (!checkout.count(i)) prime.push_back(i);
        for (int j = 0; j < prime.size(); ++j) {
            if (prime[j] * i > n) break;
            checkout.insert(prime[j] * i);
            if (i % prime[j] == 0) break;
        }
    }
    return (int) prime.size();
}

int main() {
    while (true) {
        int n;
        cin>>n;
        int a = prime_n(n);
        int b = prime_nlogn(n);
        cout<<a<<":"<<b<<endl;
    }
    return 0;
}
点赞