Last active
April 30, 2019 09:25
-
-
Save Chillee/a6b1e61523a8d83f65d2bdb62be66d4b to your computer and use it in GitHub Desktop.
Pollard Rho (Factoring algorithm)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ull f(ull x, ull n) { return (mod_mul(x, x, n) + 1) % n; } | |
ull Pollard(ull n) { | |
if (isPrime(n)) return n; | |
if (!(n & 1)) return 2; | |
for(int i = 1; i < 50; i++) { | |
ull x = i, y = f(x, n), p = __gcd(n + y - x, n); | |
while (p == 1) | |
x = f(x, n), y = f(f(y, n), n), p = __gcd(n + y - x, n); | |
if (p == n) continue; | |
return p; | |
} | |
return 0; | |
} | |
vector<ull> factor(ull n) { | |
if (n==1) return {}; | |
ull x = Pollard(n); | |
if (x == n) | |
return {x}; | |
auto l = factor(x), r = factor(n / x); | |
l.insert(l.end(), all(r)); | |
return l; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment