素数判定,miller rabin

点击打开链接

裸题 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;
}

猜你喜欢

转载自blog.csdn.net/weixin_42484877/article/details/80880889