素数判定,miller rabin

本文提供了一种高效的素性检验算法实现,用于解决HDU2138竞赛题目。通过快速幂取模计算和Miller-Rabin素性测试,该算法能够快速判断给定数值是否为素数,并支持多组数据输入。

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

点击打开链接

裸题 hdu 2138 注意多组数据

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
#define maxn 10020

typedef long long ll;
int n,num,p;

ll power(ll x,int y){
	ll res = 1;
	while ( y ){
		if ( y & 1 ) res = res * x % p;
		x = x * x % p;
		y >>= 1;
	}
	return res;
}
bool cal(ll x,ll d,ll r){
	x = power(x,d);
	if ( x == 1 || x == p - 1 ) return 1;
	for (int i = 1 ; i <= r ; i++){
	   	x = x * x % p;
		if ( x == p - 1 ) return 1;
	}
	return 0;
}
bool judge(){
	int a = p - 1,cnt = 0;
	if ( p == 2 ) return 1;
	while ( (a & 1) == 0 ) a >>= 1 , cnt++;
	for (int i = 1 ; i <= 10 ; i++){
		int cur = rand() % (p - 1) + 1;
		if ( !cal(cur,a,cnt) ) return 0;	
	}
	return 1;
}
int main(){
	while (~scanf("%d",&n)){
		num = 0;
		while ( n-- ){
			scanf("%d",&p);
			if ( judge() ) num++;
		}
		printf("%d\n",num);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值