朴素筛,埃氏筛,线性筛

  • 朴素筛:本质就是每一个合数n都可以被2-n-1里的数筛掉,这里就发现了一个问题就是,一个合数可能会被多次筛多次,这步可以进行优化。
  • 埃氏筛:本质就是每一个合数n都可以被2-n-1里的素数筛掉,这里就是对朴素筛进行了优化,因为合数都会被素数筛掉,这样一来确实提升了时间复杂度,但是还是存在重复筛的情况
  • 线性筛:本质是把它的合数用某一个质因子筛掉,这样时间复杂度大大降低,时间复杂度为0(n)

1.朴素筛:

  • 时间复杂度:0(nlogn)
  • 缺点:一个合数可能会被重复筛选多次,费时间
  • 改进:争取让一个合数只被少数甚至一个数筛掉
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
bool st[maxn];               //st[i]标记数字i是否被筛过
int primes[maxn], cnt, n;
void get_ans1() {
    for (int i = 2; i <= n; i++) {
        if(!st[i]) primes[++cnt] = i;
        for (int j = i; j <= n; j += i) {
            st[j] = true;
        }
    }
}
int main(void) {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n;
    get_ans1();
    cout << cnt << endl;
    return 0;
}

2.埃氏筛:

  • 时间复杂度:0(nloglogn)
  • 缺点:一个合数可能会被素数重复筛选多次,费时间
  • 改进:争取让一个合数只被一个数筛掉
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
bool st[maxn];              //st[i]标记数字i是否被筛过
int primes[maxn], n, cnt;
void get_ans2() {
    for (int i = 2; i <= n; i++) {
        if(!st[i]) {
            primes[++cnt] = i;
            for (int j = i; j <= n; j += i) st[j] = true;     //放在循环内,只用素数筛
        }
    }
}
int main(void) {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n;
    get_ans2();
    cout << cnt << endl;
    return 0;
}
posted @ 2022-07-05 11:30  SL霸霸  阅读(76)  评论(0编辑  收藏  举报