# [模板] Miller_Rabin和Pollard_Rho

### 例题

##### luogu4718 (求n的最大质因子)
 1 #include<bits/stdc++.h>
2 #include<tr1/unordered_map>
3 #define CLR(a,x) memset(a,x,sizeof(a))
4 #define MP make_pair
5 #define fi first
6 #define se second
7 using namespace std;
8 typedef long long ll;
9 typedef unsigned long long ull;
10 typedef long double ld;
11 typedef pair<int,int> pa;
12 const int maxn=233;
13
14 inline ll rd(){
15     ll x=0;char c=getchar();int neg=1;
16     while(c<'0'||c>'9'){if(c=='-') neg=-1;c=getchar();}
17     while(c>='0'&&c<='9') x=x*10+c-'0',c=getchar();
18     return x*neg;
19 }
20
21 int pri[10]={2,3,5,7,11,13,17,19,23,29};
22
23 inline ll mul(ll a,ll b,ll p){
24     return ((a*b-(ll)((ld)a*b/p)*p)%p+p)%p;
25 }
26
27 inline ll fpow(ll a,ll b,ll p){
28     ll r=1;
29     while(b){
30         if(b&1) r=mul(r,a,p);
31         a=mul(a,a,p),b>>=1;
32     }return r;
33 }
34
35 inline bool judge(ll p){
36     if(p==2) return 1;
37     else if(p==1||p%2==0) return 0;
38     ll s=0,t=p-1;
39     while(!(t&1)) s++,t>>=1;
40     for(int i=0;i<10&&pri[i]<p;i++){
41         ll x=fpow(pri[i],t,p);
42         for(int j=1;j<=s;j++){
43             ll r=mul(x,x,p);
44             if(r==1&&x!=1&&x!=p-1) return 0;
45             x=r;
46         }
47         if(x!=1) return 0;
48     }return 1;
49 }
50
51 inline ll gcd(ll a,ll b){return a?gcd(b%a,a):b;}
52 inline ll rand(ll r){
53     return (((ll)rand()<<30)|rand())%(r-1)+1;
54 }
55
56 inline ll calc(ll x){
57     if(judge(x)) return x;
58     while(1){
59         ll a=rand(x-1),c=rand(x-1),b=(mul(a,a,x)+c)%x;
60         // printf("~%lld %lld %lld\n",a,b,c);
61         bool bl=0;
62         while(a!=b){
63             ll s=1;ll aa=a,bb=b;
64             if(!bl){
65                 for(int i=1;i<=127&&aa!=bb;i++){
66                     s=mul(s,aa-bb,x);
67                     aa=(mul(aa,aa,x)+c)%x;
68                     bb=(mul(bb,bb,x)+c)%x,bb=(mul(bb,bb,x)+c)%x;
69                 }
70             }
71             ll g=gcd(s+x,x);
72             if(g>1) bl=1;
73             else a=aa,b=bb;
74             if(bl){
75                 g=gcd(a-b+x,x);
76                 if(g>1) return max(calc(g),calc(x/g));
77                 a=(mul(a,a,x)+c)%x;
78                 b=(mul(b,b,x)+c)%x,b=(mul(b,b,x)+c)%x;
79             }
80
81
82         }
83     }
84 }
85
86 int main(){
87     srand(1919810);
88     for(int T=rd();T;T--){
89         ll x=rd();
90         ll re=calc(x);
91         if(re==x) puts("Prime");
92         else printf("%lld\n",re);
93     }
94     return 0;
95 }

posted @ 2019-06-24 13:33  Ressed  阅读(216)  评论(0编辑  收藏  举报