链接
http://codevs.cn/problem/1702/
题解
费马小定理认为,
ap−1 mod p=1
,当
p
为素数成立,其逆定理是假命题,但是在底数随机的情况下期望正确率是
那就可以随机生成一些底数,如果进行
n
次判定,其错误率就能降到
代码
//miller rabin
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#define ll long long
using namespace std;
inline ll mult(ll a, ll b, ll p)
{
ll ans=0, t=a;
for(;b;b>>=1,t=(t<<1)%p)if(b&1)ans=(ans+t)%p;
return ans;
}
inline ll pow(ll a, ll b, ll p)
{
ll ans=1, t=a;
for(;b;b>>=1,t=mult(t,t,p))if(b&1)ans=mult(ans,t,p);
return ans;
}
bool miller_rabin(ll p)
{
ll i, a;
for(i=1;i<=10;i++)
{
for(;a%p==0;a=(ll)rand()*rand()*rand());
if(pow(a,p-1,p)!=1)return false;
}
return true;
}
int main()
{
ll p;
srand(123);
scanf("%lld",&p);
if(miller_rabin(p))printf("Yes");
else printf("No");
return 0;
}