Advertisement
Dang_Quan_10_Tin

MIiller

Nov 8th, 2020
378
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  1. ll mul(ll a, ll b, ll mod){
  2.     a %= mod;
  3.     b %= mod;
  4.     ll q = (ld) a * b / mod;
  5.     ll r = a * b - q * mod;
  6.     return (r % mod + mod) % mod;
  7. }
  8.  
  9. ll pow(ll a, ll n, ll m) {
  10.     ll result = 1;
  11.     a %= m;
  12.     while (n > 0) {
  13.         if (n & 1) result = mul(result, a, m);
  14.         n >>= 1;
  15.         a = mul(a, a, m);
  16.     }
  17.     return result;
  18. }
  19.  
  20. pair<ll, ll> factor(ll n) {
  21.     ll s = 0;
  22.     while ((n & 1) == 0) {
  23.         s++;
  24.         n >>= 1;
  25.     }
  26.     return {s, n};
  27. }
  28.  
  29. bool test(ll s, ll d, ll n, ll witness) {
  30.     if (n == witness) return true;
  31.     ll p = pow(witness, d, n);
  32.     if (p == 1) return true;
  33.     for (; s > 0; s--) {
  34.         if (p == n-1) return true;
  35.         p = mul(p, p, n);
  36.     }
  37.     return false;
  38. }
  39.  
  40. bool miller(ll n) {
  41.     if (n < 2) return false;
  42.     if ((n & 1) == 0) return n == 2;
  43.     ll s, d;
  44.     tie(s, d) = factor(n-1);
  45.     return test(s, d, n, 2) && test(s, d, n, 3) && test(s, d, n, 5) &&
  46.     test(s, d, n, 7) && test(s, d, n, 11) && test(s, d, n, 13) &&
  47.     test(s, d, n, 17) && test(s, d, n, 19) && test(s, d, n, 23);
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement