说明:根据费马小定理做的,时间复杂度很低。但是有一定概率判断出错,一般count==5时判断几率有99%。
代码
#include<cstdlib>
#include<ctime>
#include<cstdio>
using namespace std;
const int count=10; //提高判断精确度
int modular_exp(int a,int m,int n)
{
if(m==0)
return 1;
if(m==1)
return (a%n);
long long w=modular_exp(a,m/2,n);
w=w*w%n;
if(m&1)
w=w*a%n;
return w;
}
bool Miller_Rabin(int n)
{
if(n==2)
return true;
for(int i=0;i<count;i++)
{
int a=rand()%(n-2)+2;
if(modular_exp(a,n,n)!=a)
return false;
}
return true;
}
int main()
{
srand(time(NULL));//随机数种子
int n;
while(~scanf("%d",&n))
{
if(Miller_Rabin(n))
printf("YES\n");
else
printf("NO\n");
}
return 0;
}