Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. ll mulmod(ll a, ll b, ll mod) {
  2.     ll x = 0,y = a % mod;
  3.     while (b > 0) {
  4.         if (b % 2 == 1) {    
  5.             x = (x + y) % mod;
  6.         }
  7.         y = (y * 2) % mod;
  8.         b /= 2;
  9.     }
  10.     return x % mod;
  11. }
  12. /*
  13. ll modpow(ll base, ll exponent, ll mod) {
  14.     ll x = 1LL;
  15.     ll y = base;
  16.     while (exponent > 0) {
  17.         cout << x << endl;
  18.         if (exponent % 2 == 1)
  19.             x = (x * y) % mod;
  20.         y = (y * y) % mod;
  21.         exponent = exponent / 2;
  22.     }
  23.     return x % mod;
  24. }
  25. */
  26. unsigned long long modpow(unsigned long long num, unsigned long long pow, unsigned long long mod)
  27. {
  28.     unsigned long long test;
  29.     unsigned long long n = num;
  30.     for(test = 1; pow; pow >>= 1)
  31.     {
  32.    //     cout << test << " " << n << endl;
  33.         if (pow & 1)
  34.             test = mulmod(test, n, mod);
  35.         n = mulmod(n, n, mod);
  36.     }
  37.  
  38.     return test; /* note this is potentially lossy */
  39. }
  40.  
  41. const ll big = 9223372036854775807;
  42. const ll zero = 0LL;
  43. const ll one = 1LL;
  44. const ll two = 2LL;
  45. const ll k[12] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37};
  46.  
  47. bool prime(ll n) {
  48.     if (n < two) {
  49.         return false;
  50.     }
  51.     if (n == 2) {
  52.         return true;
  53.     }
  54.     if (n % two == zero) {
  55.         return false;
  56.     }
  57.     ll s = n - one;
  58.     ll r = zero;
  59.     while (s % two == zero) {
  60.         r += one;
  61.         s /= two;
  62.     }
  63.     ll d = s;
  64.     for (int i = 0; i < 12; i++) {
  65.         if (k[i] > n - two)
  66.             continue;
  67.         ll a = k[i];
  68.         ll x = modpow(a, d, n);
  69.         bool contflag = false;
  70.         if (x == one || x == n - one)
  71.             continue;
  72.         for (int j = 0; j < r - one; j++) {
  73.             x = mulmod(x, x, n);
  74.             if (x == 1)
  75.                 return false;
  76.             if (x == n - one) {
  77.                 contflag = true;
  78.                 break;
  79.             }
  80.         }
  81.         if (contflag)
  82.             continue;
  83.         return false;
  84.     }
  85.     return true;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement