Miller_Rabin codevs 1702 素数判定2

/*
直接费马小定理
*/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<ctime>
#define ll long long
using namespace std;
ll slow_mul(ll a,ll b,ll c)
{
ll ans=;
a=a%c;b=b%c;
while(b)
{
if(b&)
{
b--;
ans+=a;
ans%=c;
}
a<<=;a%=c;b>>=;
}
return ans;
}
ll Mi(ll p,ll a,ll mod)
{
if(p==)return ;
ll x=Mi(p/,a,mod)%mod;
x=slow_mul(x,x,mod);
if(p%==)x=slow_mul(x,a,mod);
return x;
}
int main()
{
srand(unsigned(time()));
ll p,d,a;
cin>>p;
int falg=;
if(p==)
{
printf("Yes");
return ;
}
if(p==)
{
printf("No");
return ;
}
for(int i=;i<=;i++)
{
a=rand()%(p-)+;
d=Mi(p-,a,p);
if(d!=)
{
falg=;
break;
}
else falg=;
}
if(falg==)printf("Yes");
else printf("No");
}
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<ctime>
#define ll long long
#define T 10
using namespace std;
ll slow_mul(ll a,ll b,ll c)//防止爆掉
{
ll ans=;
a=a%c;b=b%c;
while(b)
{
if(b&)
{
b--;ans+=a;
ans=ans%c;
}
a=a<<;a=a%c;
b=b>>;
}
return ans;
}
ll Mi(ll a,ll m,ll n)//快速幂 a^m%n
{
if(m==)return ;
ll x=Mi(a,m/,n)%n;
x=slow_mul(x,x,n);
if(m%==)x=slow_mul(x,a,n);
return x;
}
bool Miller_Rabin(ll n)
{
if(n<)return ;
if(n==)return ;
if(n%==)return ;
ll m=n-,j=;
while(m%==)//计算m j 使得n-1=m*2^j且j尽量大
{
j++;
m >>=;
}
srand(unsigned(time()));
for(int i=;i<=T;i++)//T次测试
{
ll a=rand()%(n-)+;
ll x=Mi(a,m,n);//计算a^m%n
ll y;
for(int k=;k<=j;k++)
{
y=slow_mul(x,x,n);
if(y==&&x!=&&x!=n-)return ;//一定不是素数
x=y;
}
if(x!=)return ;//不符合费马小定理
}
return ;
}
int main()
{
ll n;
cin>>n;
if(Miller_Rabin(n))printf("Yes\n");
else printf("No\n");
}
上一篇:(转)linux运维必会MySQL企业面试题


下一篇:codevs 3223 素数密度