Explanation : According to Fermat's little theorem, the time complexity is very low. However, there is a certain probability that the judgment will be wrong. Generally, when count==5, the judgment probability is 99%.
code
#include<cstdlib> #include<ctime> #include<cstdio> using namespace std; const int count=10; //Improve the accuracy of judgment 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; } intmain() { srand(time(NULL));//Random number seed int n; while(~scanf("%d",&n)) { if(Miller_Rabin(n)) printf("YES\n"); else printf("NO\n"); } return 0; }