1. 程式人生 > >51nod 1106 質數檢測——Mr判素數

51nod 1106 質數檢測——Mr判素數

blog turn std etc pmo get return pan style

質數檢測一般都是根號n的寫法 當然Mr判素數的方法可以實現log的復雜度2333

Mr判素數的話 我們根據費馬小定理只要P是素數 那麽另一個素數x 滿足 x^P-1≡1(mod P)

同時 x^2%P==1 的解只有 x==1||x==P-1 可以利用這第二個式子做二次探測

利用 2 3 5 7 11 13 17 這七個素數可以保證int內正確性QAQ

當然記得判斷2 3 5 7 11 13 17 因為費馬小定理成立的條件是 x和P 互質

技術分享
#include<cstdio>
#include<cstring>
#include<algorithm>
#define
LL long long int read(){ int ans=0,f=1,c=getchar(); while(c<0||c>9){if(c==-) f=-1; c=getchar();} while(c>=0&&c<=9){ans=ans*10+(c-0); c=getchar();} return ans*f; } int T,n; int num[7]={2,3,5,7,11,13,17}; LL pmod(LL a,LL b,LL c){ LL ans=1; while(b){
if(b&1) ans=ans*a%c; b>>=1; a=a*a%c; } return ans; } bool calc(LL x,LL P){ LL ly=P-1,yy,last; while(ly%2==0) ly/=2; last=yy=pmod(x,ly,P); while(ly!=P-1){ yy=yy*yy%P; if(yy==1&&last!=1&&last!=P-1) return 0; ly*=2; last=yy; }
return yy==1; } bool pd(LL n){ if(n==2||n==3||n==5||n==7||n==11||n==13||n==17) return 1; for(int i=0;i<7;i++)if(!calc(num[i],n)) return 0; return 1; } int main(){ T=read(); while(T--){ n=read(); if(pd(n)) printf("Yes\n"); else printf("No\n"); } return 0; }
View Code

51nod 1106 質數檢測——Mr判素數