您的位置:首页 > 其它

HDU5391米勒拉宾

2015-08-16 11:56 295 查看
米勒拉宾模板直接套,主要就是一个威尔逊定理,

初等数论中,威尔逊定理给出了判定一个自然数是否为素数充分必要条件。即:当且仅当p为素数时:(
p -1 )! ≡ -1 ( mod p ),但是由于阶乘是呈爆炸增长的,其结论对于实际操作意义不大。注意特判四就行了

#include<iostream>

#include<cstdio>

#include<cstring>
#include<cstdlib>
#include<string>
#include<cctype>
#include<cmath>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<stack>
#define LL __int64
using namespace std;
const int maxn=1e9+5;
LL n,ans;
int t;
__int64 qpow(int a,int b,int r)
{
__int64 ans=1,buff=a;
while(b)
{
if(b&1)
ans=(ans*buff)%r;
buff=(buff*buff)%r;
b>>=1;
}
return ans;
}
bool Miller_Rabbin(int n,int a)
{
int r=0,s=n-1,j;
if(!(n%a))
return false;
while(!(s&1))
{
s>>=1;
r++;
}
__int64 k=qpow(a,s,n);
if(k==1)
return true;
for(j=0;j<r;j++,k=k*k%n)
if(k==n-1)
return true;
return false;
}
bool IsPrime(int n)
{
int tab[5]={2,3,5,7};
for(int i=0;i<4;i++)
{
if(n==tab[i])
return true;
if(!Miller_Rabbin(n,tab[i]))
return false;
}
return true;
}

int main()
{
cin>>t;
while(t--)
{
scanf("%I64d",&n);
if(n==4)
{
cout<<2<<endl;
continue;
}
if(!IsPrime(n))
cout<<0<<endl;
else
cout<<n-1<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: