C++米勒拉宾算法模板

//我也忘了从哪找来的板子,不过对于2^63级的数据请考虑使用java内置的米勒拉宾算法。
1
#include <iostream> 2 #include <string> 3 #include <cstdio> 4 #include <cmath> 5 #include <cstring> 6 #include <algorithm> 7 #define range(i,a,b) for(int i=a;i<=b;++i) 8 #define rerange(i,a,b) for(int i=a;i>=b;--i) 9 #define LL long long 10 #define fill(arr,tmp) memset(arr,tmp,sizeof(arr)) 11 using namespace std; 12 const int S=20; 13 LL mult_mod(LL a,LL b,LL c){ 14 a%=c; 15 b%=c; 16 long long ret=0; 17 while(b){ 18 if(b&1){ret+=a;ret%=c;} 19 a<<=1; 20 if(a>=c)a%=c; 21 b>>=1; 22 } 23 return ret; 24 } 25 LL pow_mod(LL x,LL n,LL mod){ 26 if(n==1)return x%mod; 27 x%=mod; 28 LL tmp=x; 29 LL ret=1; 30 while(n){ 31 if(n&1) ret=mult_mod(ret,tmp,mod); 32 tmp=mult_mod(tmp,tmp,mod); 33 n>>=1; 34 } 35 return ret; 36 } 37 bool check(LL a,LL n,LL x,LL t){ 38 LL ret=pow_mod(a,x,n); 39 LL last=ret; 40 range(i,1,t){ 41 ret=mult_mod(ret,ret,n); 42 if(ret==1&&last!=1&&last!=n-1) return true; 43 last=ret; 44 } 45 if(ret!=1) return true; 46 return false; 47 } 48 bool Miller_Rabin(LL n){ 49 if(n<2)return false; 50 if(n==2)return true; 51 if((n&1)==0) return false; 52 LL x=n-1; 53 LL t=0; 54 while((x&1)==0){x>>=1;t++;} 55 range(i,0,S-1){ 56 LL a=rand()%(n-1)+1; 57 if(check(a,n,x,t))return false; 58 } 59 return true; 60 } 61 LL factor[100]; 62 int tol; 63 LL gcd(LL a,LL b){ 64 if(a==0)return 1; 65 if(a<0) return gcd(-a,b); 66 while(b){ 67 long long t=a%b; 68 a=b; 69 b=t; 70 } 71 return a; 72 } 73 LL Pollard_rho(LL x,LL c){ 74 LL i=1,k=2; 75 LL x0=rand()%x; 76 LL y=x0; 77 while(1){ 78 i++; 79 x0=(mult_mod(x0,x0,x)+c)%x; 80 LL d=gcd(y-x0,x); 81 if(d!=1&&d!=x) return d; 82 if(y==x0) return x; 83 if(i==k){y=x0;k+=k;} 84 } 85 } 86 void findfac(LL n){ 87 if(Miller_Rabin(n)){ 88 factor[tol++]=n; 89 return; 90 } 91 LL p=n; 92 while(p>=n)p=Pollard_rho(p,rand()%(n-1)+1); 93 findfac(p); 94 findfac(n/p); 95 } 96 int main(){ 97 long long n; 98 while(scanf("%lld",&n)!=EOF){ 99 tol=0; 100 /* 101 findfac(n); 102 for(int i=0;i<tol;++i)cout<<factor[i]<<" "; 103 printf("\n"); 104 */ 105 if(Miller_Rabin(n))printf("Yes\n"); 106 else printf("No\n"); 107 } 108 return 0; 109 }

猜你喜欢

转载自www.cnblogs.com/Rhythm-/p/9253800.html