Skip to content

Instantly share code, notes, and snippets.

@Chillee
Last active April 30, 2019 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Chillee/a6b1e61523a8d83f65d2bdb62be66d4b to your computer and use it in GitHub Desktop.
Save Chillee/a6b1e61523a8d83f65d2bdb62be66d4b to your computer and use it in GitHub Desktop.
Pollard Rho (Factoring algorithm)
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