线性筛素数模板(4种方法)

1朴素方法(时间复杂度o(sqrt(n))

#include <bits/stdc++.h>
#define maxn 200005
typedef long long ll;
using namespace std;
ll prime(ll n)
{
    if(n < 2)return 0;
    for(ll i = 2; i * i <= n; i ++)
    if(n%i == 0)
    return 0;
    return 1;
}
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    ll n,m;
    cin >> n >> m;
    while(m--)
    {
        ll x;
        cin >> x;
        if(prime(x))cout << "Yes" << endl;
        else cout << "No" << endl;
    }
    return 0;
}

 

2 筛除倍数,一个素数的倍数一定不是素数;时间复杂度(o(nloglogn)

#include <bits/stdc++.h>

typedef long long ll;

using namespace std;

const ll maxn = 10000005;
const ll mod = 1e9 + 7;
bool a[maxn];
ll n,m;
void prime()
{
    a[1] = a[0] = 1;
    for(int i = 2; i <= n; i ++)
    {
        if(a[i] == 0)
        {
            for(int j = 2 * i; j <= n; j += i)
            {
                a[j] = 1;
            } 
        }
    }
}
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);

    
    cin >> n >> m;
    prime();
    while(m--)
    {
		ll p;
		cin >> p;
		if(!a[p])cout << "Yes" << endl;
		else cout << "No" << endl;
    }
    return 0;
}

3一个大于5的素数一定在6的倍数周围(时间复杂度小于sqrt(n))

#include <bits/stdc++.h>
#define maxn 10000005
typedef long long ll;
using namespace std;
ll n,m;
ll prime(ll n)
{
    if(n < 2)return 0;
    if(n ==2 || n == 3)return 1;
    if(n % 6 != 1 && n % 6 != 5)return 0;
    for(ll i = 5; i * i <= n; i += 6)
    {
        if(n % i == 0 || n % (i + 2) == 0)
        return 0;
    }
    return 1;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    cin >> n >> m;
    while(m--)
    {
        ll x;
        cin >> x;
        if(prime(x))
            cout << "Yes" << endl;
        else
            cout << "No" << endl;
    }
    return 0;
}

4 欧拉筛法 时间复杂度(o(n))

const ll maxn=100000001;
ll prime[maxn];      //就是个素数表
bool sf[maxn];        //判断这个数是不是素数,sf[i]中的i是从1到maxn的数
void sushu()
{         //核心 欧拉筛代码
    ll num=0;        //num 用来记筛到第几个质数
    memset(sf,true,sizeof(sf));
	sf[1] = false;
    sf[0] = false;  //1 0 特判 
    for(int i = 2;i <= maxn; i ++)
	{          //外层枚举1~maxn
        if(sf[i]) prime[++num] = i;      //如果是质数就加入素数表
        for(int j = 1;j <= num;j ++)
		{       //内层枚举num以内的质数
            if(i * prime[j] > maxn) break; //筛完结束
            sf[i * prime[j]] = false;      //筛掉...
            if(i % prime[j] == 0) break;   //避免重复筛
        }
    } 
}

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值