-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpollard_rho.cpp
More file actions
59 lines (48 loc) · 1.2 KB
/
pollard_rho.cpp
File metadata and controls
59 lines (48 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
-> Pollard's Rho Algorithm for fast integer factorization
-> works in O(n^(1/4))
-> ref: 1. https://cp-algorithms.com/algebra/factorization.html
2. http://morris821028.github.io/2015/07/11/uva-11476/ (for implementation)
-> tested on SPOJ/FACT0 (15 digits)
*/
int pollardRho(int n, int c) {
int x = 2, y = 2, i = 1, k = 2, d;
while (1) {
x = (mulmod(x, x, n) + c);
if (x >= n)
x -= n;
d = __gcd(x - y, n);
if (d > 1)
return d;
if (++i == k)
y = x, k <<= 1;
}
return n;
}
void trialDivision(int n, vi &factors) {
for (int i = 2; i * i <= n; ++i) {
while (n % i == 0) {
factors.pb(i);
n /= i;
}
}
if (n > 1)
factors.pb(n);
}
void factorize(int n, vi &factors) {
if (n == 1)
return;
if (n < inf) {
trialDivision(n, factors);
return;
}
if (millerRabin(n)) {
factors.pb(n);
return;
}
int d = n;
for (int i = 2; d == n; ++i)
d = pollardRho(n, i);
factorize(d, factors);
factorize(n / d, factors);
}