素数相关操作

本文介绍两种高效的素数处理方法:一是通过筛法快速生成100万以内的所有素数;二是利用Miller-Rabin算法进行大素数的准确性检验,该算法在实际竞赛中具有很高的实用性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先介绍几种常用模板。

1.素数的高效打表(这里打了100万以内的素数表)

const int maxn=1000005;
const int _maxn=78499+5; //1000000内拥有的素数

int prime[_maxn];
bool vis[maxn];//待打表完成后,vis数组中将保存素数的直接判断

int sum[maxn];

int get_prime() { //高效素数打表
    me(vis,true);
    vis[0]=vis[1]=false;
    int cnt=0;
    for(int i=2;i<maxn;i++) {
        if(vis[i]) prime[cnt++]=i;

        for(int j=0;(j<cnt)&&(i*prime[j]<maxn);j++) {
            vis[i*prime[j]]=false;
            if(i%prime[j]==0)break;
        }
    }
    return cnt;
}

 

2.MR大素数检验(一次icpc网络赛用到的,貌似挺有用的)

const int MAX_N=100000;
const int INF = 0x3f3f3f3f;
#define eps 1e-7

ll mod_mul(ll a, ll b, ll n) {
	ll res = 0;
	while (b) {
		if (b & 1)    res = (res + a) % n;
		a = (a + a) % n;
		b >>= 1;
	}
	return res;
}
ll mod_exp(ll a, ll b, ll n) {
	ll res = 1;
	while (b) {
		if (b & 1)    res = mod_mul(res, a, n);
		a = mod_mul(a, a, n);
		b >>= 1;
	}
	return res;
}

bool miller_rabin(ll n) {
	if (n == 2 || n == 3 || n == 5 || n == 7 || n == 11)    return true;
	if (n == 1 || !(n % 2) || !(n % 3) || !(n % 5) || !(n % 7) || !(n % 11))    return false;

	ll x, pre, u;
	ll i, j, k = 0;
	u = n - 1; 
	while (!(u & 1)) {
		k++;
		u >>= 1;
	}
	srand((ll)time(0));
	for (i = 0; i <5; ++i) {
		x = rand() % (n - 1) + 1;
		if ((n%x) == 0)    continue;
		x = mod_exp(x, u, n);
		pre = x;
		for (j = 0; j < k; ++j) {
			x = mod_mul(x, x, n);
			if (x == 1 && pre != 1 && pre != n - 1)    return false;
			pre = x;
		}
		if (x != 1)    return false;
	}
	return true;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水能zai舟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值