RedHotChiliPepper

Тест Миллера — Рабина

Nov 8th, 2020
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <string>
  4. #include <map>
  5. #include <random>
  6. #include <cmath>
  7. #include <algorithm>
  8. #include <chrono>
  9.  
  10. using namespace std;
  11.  
  12. #define ll long long
  13.  
  14. mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
  15.  
  16. ll mod;
  17.  
  18. ll add(ll a, ll b) { return (a + b) % mod; }
  19.  
  20. ll mul(ll a, ll b) {
  21.     ll ret = 0;
  22.     while (b) {
  23.         if (!(b & 1))
  24.             a = add(a, a), b >>= 1;
  25.         ret = add(ret, a), --b;
  26.     }
  27.  
  28.     return ret;
  29. };
  30.  
  31. ll get(ll n, ll m) {
  32.     ll ret = 1;
  33.     while (m) {
  34.         if (!(m & 1))
  35.             n = mul(n, n), m >>= 1;
  36.         ret = mul(ret, n), --m;
  37.     }
  38.  
  39.     return ret;
  40. }
  41.  
  42. ll prec[63];
  43.  
  44. bool stress(ll n) {
  45.     for (ll i = 2; i * i <= n; ++i) {
  46.         if (n % i == 0)
  47.             return false;
  48.     }
  49.     return true;
  50. }
  51.  
  52. void brik() {
  53.     cout << "NO";
  54.     exit(0);
  55. }
  56.  
  57. void sech() {
  58.     if ((double)clock() / CLOCKS_PER_SEC > 1.9) {
  59.         cout << "YES";
  60.         exit(0);
  61.     }
  62. }
  63.  
  64. void $main()
  65. {
  66.     prec[0] = 1;
  67.     for (ll i = 1; i < 63; ++i)
  68.         prec[i] = (prec[i - 1] << 1);
  69.  
  70.     cin >> mod;
  71.  
  72.     if (mod == 2)
  73.     {
  74.         cout << "YES";
  75.         exit(0);
  76.     }
  77.  
  78.     if ((mod & 1) == 0 || mod == 1) {
  79.         brik();
  80.     }
  81.  
  82.     ll d = mod - 1, s = 0;
  83.     while ((d & 1) == 0)
  84.         ++s, d >>= 1;
  85.  
  86.     while (true) {
  87.         sech();
  88.  
  89.         ll a = rng() % mod;
  90.         if (!a)++a;
  91.  
  92.         ll cur = get(a, d);
  93.         if (cur == 1 || cur == -1)
  94.             continue;
  95.  
  96.         bool fl = 0;
  97.         for (ll i = 0; i < s; ++i) {
  98.             sech();
  99.  
  100.             cur = mul(cur, cur);
  101.             if (cur == 1 || cur == -1) {
  102.                 fl = true;
  103.                 break;
  104.             }
  105.         }
  106.  
  107.         if (!fl)
  108.             brik();
  109.     }
  110. }
  111.  
  112. int main()
  113. {
  114.     ios_base::sync_with_stdio(0);
  115.     cin.tie(0), cout.tie(0);
  116.  
  117.     $main();
  118.  
  119.     return 0;
  120. }
Advertisement
Add Comment
Please, Sign In to add comment