朴素筛法
O(nlogn)
#include <iostream>
using namespace std;
const int N = 1e6 + 10;
int primes[N], cnt;
bool st[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;
cin >> n;
get_primes(n);
cout << cnt << endl;
for (int i = 0; i < cnt; i++) cout << primes[i] << ' ' << endl;
return 0;
}
埃式筛法
O(n)
O(nloglogn)
#include <iostream>
using namespace std;
const int N = 1e6 + 10;
int primes[N] ,cnt;
bool st[N]; // st[x] 存储x是否被筛掉
void get_primes(int n)
{
for (int i = 2; i <= n; i++)
{
if (st[i]) continue;
primes[cnt++] = i;
for (int j = i; j <= n; j += i)
st[j] = true;
}
}
int main()
{
int n;
cin >> n;
get_primes(n);
cout << cnt << endl;
return 0;
}
线性筛
核心:n只会被他的最小质因子筛掉
#include <iostream>
using namespace std;
const int N = 1e6 + 10;
int primes[N] ,cnt;
bool st[N]; // st[x] 存储x是否被筛掉
void get_primes(int n)
{
for (int i = 2; i <= n; i++)
{
if (!st[i]) primes[cnt++] = i;
for (int j = 0; primes[j] <= n / i; j++)
{
st[primes[j] * i] = true;
if (i % primes[j] == 0) break;
}
}
}
int main()
{
int n;
cin >> n;
get_primes(n);
cout << cnt << endl;
return 0;
}