质数的模板

试除法判断质数

题面

传送门
在这里插入图片描述

Code

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;

typedef long long ll;

const int N = 1e5 + 10;

bool jg(int x){
    if(x < 2) return false;
    for(int i=2;i<=x/i;++i){
        if(x % i == 0) return false;
    }
    return true;
}
bool solve(){
    int n;
    cin >> n;
    return jg(n);
}

int main(){
    std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    int t;
    cin >> t;
    while(t--){
        bool f = solve();
        if(f) cout << "Yes\n";
        else cout << "No\n";
    }
    return 0;
}

分解质因数

题面

传送门
在这里插入图片描述

原理

每个数(记为x xx),至多有一个质数比x \sqrt{x}x大;

Code

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;

typedef long long ll;

const int N = 1e5 + 10;

void solve(){
    int n;
    cin >> n;
    for(int i=2;i<=n/i;++i){
        if(n%i == 0){
            int cnt = 0;
            while(n%i == 0){
                n/=i;
                ++cnt;
            }
            cout << i << ' ' << cnt << '\n';
        }
    }
    if(n > 1) cout << n << ' ' << 1 << '\n';
    cout << '\n';
}

int main(){
    std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    int t;
    cin >> t;
    while(t--){
        solve();
    }
    return 0;
}

质数筛法

题面

传送门
在这里插入图片描述

埃筛

思路

这种筛法的时间复杂度为O ( n l o g ( l o g n ) ) O(nlog(logn))O(nlog(logn)),接近线性了;

这种算法就是枚举每个数的倍数去筛素数;

Code

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>

using namespace std;

typedef long long ll;

const int N = 1e6 + 10;

int n;

vector<int> primes;

bool vis[N];

void solve(){
    cin >> n;
    for(int i=2;i<=n;++i){
        if(!vis[i]){
            primes.push_back(i);
            for(int j=2;j*i<=n;++j){
                vis[i*j] = 1;
            }
        }
    }
    cout << primes.size() << '\n';
}

int main(){
    std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    solve();
    return 0;
}

线性筛

原理

每个数都只会被筛它的最小质因子筛掉;

i % primes[j] == 0

  • primes[j]一定是i的最小质因子;
  • primes[j]也一定是i*primes[j]的最小质因子

i % primes[j] != 0;

  • primes[j]小于i的所有质因子
  • primes[j]是primes[j]*i的最小质因子

Code

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>

using namespace std;

typedef long long ll;

const int N = 1e6 + 10;

int n;

vector<int> primes;

bool vis[N];

void solve(){
    cin >> n;
    for(int i=2;i<=n;++i){
        if(!vis[i]){
            primes.push_back(i);
        }
        for(auto p : primes){
            if(p * i > n) break;
            vis[p*i] = 1;
            //被最小质因子筛去
            if(i % p == 0) break;
        }
    }
    cout << primes.size() << '\n';
}

int main(){
    std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    solve();
    return 0;
}

版权声明:本文为weixin_45724872原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。