HDU2138 & 米勒拉宾模板

题意:

  给出n个数,判断它是不是素数.

SOL:

  米勒拉宾裸题,思想方法略懂,并不能完全理解,所以实现只能靠背模板....

  好在不是很长...

Code:

  

/*==========================================================================
# Last modified: 2016-03-21 10:09
# Filename: miller-rabin.cpp
# Description: 
==========================================================================*/
#define me AcrossTheSky 
#include <cstdio> 
#include <cmath> 
#include <ctime> 
#include <string> 
#include <cstring> 
#include <cstdlib> 
#include <iostream> 
#include <algorithm> 
  
#include <set> 
#include <map> 
#include <stack> 
#include <queue> 
#include <vector> 
 
#define lowbit(x) (x)&(-x) 
#define FOR(i,a,b) for((i)=(a);(i)<=(b);(i)++) 
#define FORP(i,a,b) for(int i=(a);i<=(b);i++) 
#define FORM(i,a,b) for(int i=(a);i>=(b);i--) 
#define ls(a,b) (((a)+(b)) << 1) 
#define rs(a,b) (((a)+(b)) >> 1) 
#define getlc(a) ch[(a)][0] 
#define getrc(a) ch[(a)][1] 
 
#define maxn 100000 
#define maxm 100000 
#define pi 3.1415926535898 
#define _e 2.718281828459 
#define INF 1070000000 
using namespace std; 
typedef long long ll; 
typedef unsigned long long ull; 
 
template<class T> inline 
void read(T& num) { 
    bool start=false,neg=false; 
    char c; 
    num=0; 
    while((c=getchar())!=EOF) { 
        if(c=='-') start=neg=true; 
        else if(c>='0' && c<='9') { 
            start=true; 
            num=num*10+c-'0'; 
        } else if(start) break; 
    } 
    if(neg) num=-num; 
} 
/*==================split line==================*/ 
int c[7]={2,3,5,7,11,13};
ll pow(ll a,ll k,ll mod){
	ll s=1;
	for (;k;a=(a*a)%mod,k>>=1)
		if (k&1) s*=a,s%=mod;
	return s;
}
bool check(int x,int a){
	if (!x%a) return false;
	int r=0,s=x-1;
	while (!(s&1)) s>>=1,r++;
	ll k=pow(a,s,x);
	if (k==1) return true;
	for (int j=0;j<r;j++,k=k*k%x)
		if (k==x-1) return true;
	return false;
}
bool miller_rabin(ll x){
	FORP(i,0,5) if (x==c[i]) return true;
	FORP(i,0,5){ 
			if (!check(x,c[i])) return false;
	}
	return true;
}
int main(){
	int n;
	while (scanf("%d",&n)!=EOF){ 
		 int ans=0;
		 FORP(i,1,n) {
		 	ll x; read(x);
		 	if (miller_rabin(x)) ans++;
		 }
		 printf("%d\n",ans);
	}
}

 

你可能感兴趣的:(HDU2138 & 米勒拉宾模板)