P4718 【模板】Pollard-Rho算法

 

P4718 【模板】Pollard-Rho算法

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 typedef __int128 lll;
 5 char buf[700000000];
 6 int cnt = 0;
 7 ll ans;
 8 template<typename T> inline T read(T a) {
 9     T res = 0, f = 1;
10     char ch = buf[cnt++];
11     while (!isdigit(ch)) {
12         if (ch == '-') f = -1;
13         ch = buf[cnt++];
14     }
15     while (isdigit(ch)) {
16         res = (res<<3)+(res<<1) + ch - 48;
17         ch = buf[cnt++];
18     }
19     return res*f;
20 }
21 template<typename T> inline void write(T x) {
22     if (x < 0) {
23         putchar('-');
24         write(-x);
25         return;
26     }
27     if (x > 9) write(x/10);
28     putchar(x%10+48);
29 }
30 inline ll gcd(ll a, ll b) {
31     if (b == 0) return a;
32     return gcd(b,a%b);
33 }
34 inline ll qpow(ll a, ll b, ll mod) {
35     ll res = 1;
36     while (b) {
37         if (b&1) res = (lll)res*a%mod;
38         a = (lll)a*a%mod;
39         b >>= 1;
40     }
41     return res;
42 }
43 inline bool test(ll x, ll b) {
44     ll k = x-1;
45     while (k) {
46         ll cur = qpow(b,k,x);
47         if (cur!=1 && cur!=x-1) return false;
48         if ((k&1)==1 || cur==x-1) return true;
49         k >>= 1;
50     }
51     return true;
52 }
53 inline bool Miller_Rabin(ll x) {
54     if (x==46856248255981LL || x<2) return false;
55     if (x==2 || x==3 || x==7 || x==61 || x==24251) return true;
56     return test(x,2)&&test(x,61);
57 }
58 inline ll pollard_rho(ll x) {
59     ll s = 0, t = 0, c = 1LL*rand()%(x-1)+1;
60     ll val = 1;
61     for (int goal = 1;; goal<<=1, s=t, val=1) {
62         for (int stp = 1; stp<=goal; ++stp) {
63             t = ((lll)t*t+c)%x;
64             val = (lll)val*abs(t-s)%x;
65             if ((stp%127) == 0) {
66                 ll d = gcd(val,x);
67                 if (d>1) return d;
68             }
69         }
70         ll d = gcd(val,x);
71         if (d>1) return d;
72     }
73 }
74 inline void findfac(ll x) {
75     if (x <= ans || x < 2) return;
76     if (Miller_Rabin(x)) {
77         ans = ans > x ? ans : x;
78         return;
79     }
80     ll p = x;
81     while (p >= x) p = pollard_rho(x);
82     while ((x%p) == 0) x /= p;
83     findfac(x), findfac(p);
84 }
85 int main() {
86     fread(buf,1,700000000,stdin);
87     int t; t = read(t);
88     while (t--) {
89         ll n; n = read(n);
90         ans = 0;
91         findfac(n);
92         if (ans == n) puts("Prime");
93         else write(ans), putchar('\n'); 
94     }
95     return 0; 
96 }

 

posted @ 2019-10-31 16:28  麻辣猪仔  阅读(169)  评论(0编辑  收藏  举报