Advertisement
Guest User

Untitled

a guest
Nov 14th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. /**This won't work if the number is a big prime. So before running this algorithm check whether the number is a prime or not using Rabin Miller algorithm**/
  2.  
  3. //Pollard rho
  4. //Copied from _Ash__
  5.  
  6. const long long LIM = LLONG_MAX;
  7.  
  8. long long mul(long long a, long long b, long long m){
  9.     long long x, res;
  10.     if (a < b) swap(a, b);
  11.     if (!b) return 0;
  12.     if (a < (LIM / b)) return ((a * b) % m);
  13.     res = 0, x = (a % m);
  14.     while (b){
  15.         if (b & 1){
  16.             res = res + x;
  17.             if (res >= m) res -= m;
  18.         }
  19.         b >>= 1;
  20.         x <<= 1;
  21.         if (x >= m) x -= m;
  22.     }
  23.     return res;
  24. }
  25.  
  26. long long pollard_rho(long long n, long long c) {
  27.     long long x = 2, y = 2, i = 1, k = 2, d;
  28.     while(true) {
  29.         x = (mul(x, x, n) + c);
  30.         if (x >= n) x -= n;
  31.         d = __gcd(abs(x-y),n);
  32.         if (d > 1) return d;
  33.         if (++i == k) {
  34.             y = x, k <<= 1;
  35.         }
  36.     }
  37.     return n;
  38. }
  39.  
  40. int main() {
  41.     long long d = n;
  42.     for(int i = 2; d == n; i++){
  43.         d = pollard_rho(n, i);
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement