对于数据太大导致无法用素数筛选法打表处理(百万级),就可以用素数测试算法。
Miller-Rabin算法是目前主流的基于概率的素数测试算法,在构建密码安全体系中占有重要的地位。通过比较各种素数测试算法和对Miller-Rabin算法进行的仔细研究,证明在计算机中构建密码安全体系时, Miller-Rain算法是完成素数测试的最佳选择。通过对Miller-Rabin 算 法底层运算的优化,可以取得较以往实现更好的性能。
模板代码:
#include<iostream> #include<math.h> #include<cstdio> #include<algorithm> using namespace std; typedef unsigned long long llong; /*Miller-Rabin*/ llong mod_pro(llong x,llong y,llong n) { llong ret=0,tmp=x%n; while(y) { if(y&0x1)if((ret+=tmp)>n)ret-=n; if((tmp<<=1)>n)tmp-=n; y>>=1; } return ret; } llong mod(llong a,llong b,llong c) { llong ret=1; while(b) { if(b&0x1)ret=mod_pro(ret,a,c); a=mod_pro(a,a,c); b>>=1; } return ret; } llong ran() { llong ret=rand(); return ret*rand(); } bool is_prime(llong n,int t) { if(n<2)return false; if(n==2)return true; if(!(n&0x1))return false; llong k=0,m,a,i; for(m=n-1;!(m&1);m>>=1,k++); while(t--) { a=mod(ran()%(n-2)+2,m,n); if(a!=1) { for(i=0;i<k&&a!=n-1;i++) a=mod_pro(a,a,n); if(i>=k)return false; } } return true; } int main() { llong n; while(scanf("%I64u",&n)!=EOF) if(is_prime(n,3)) cout<<"YES\n"; else cout<<"NO\n"; return 0; }