Advertisement
aakib_alam

Miller_Rabin

Aug 15th, 2022
603
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | Source Code | 0 0
  1. /*
  2.                                 MILLER RABIN PRIMALITY TEST
  3.                                  Time Complexity : O(KlogN)
  4.                             Exploit the fact (a^(p-1))%p = 1.
  5.                        for 32 bit integer ,base array = {2,3,5,7},  K = 4
  6.               for 64 bit integer ,base array = {2,3,5,7,11,13,17,19,23,29,31,37},  K = 12
  7. */
  8.  
  9. #include <bits/stdc++.h>
  10. using namespace std;
  11. #define int long long
  12.  
  13. int exp(int a, int b, int mod)
  14. {
  15.     a %= mod;
  16.     int res = 1;
  17.     while (b)
  18.     {
  19.         if (b % 2)
  20.             res = (res * a) % mod;
  21.         a = (__uint128_t)a * a % mod;
  22.         b >>= 1;
  23.     }
  24.     return res;
  25. }
  26.  
  27. bool check_composite(int n, int b, int d, int s)
  28. {
  29.     int x = exp(b, d, n);
  30.     if (x == 1 || x == n - 1)
  31.         return false;
  32.     for (int i = 1; i < s; i++)
  33.     {
  34.         x = (__uint128_t)x * x % n;
  35.         if (x == n - 1)
  36.             return false;
  37.     }
  38.     return true;
  39. }
  40.  
  41. bool is_prime(int n)
  42. {
  43.     if (n == 1)
  44.         return false;
  45.     int s = 0, d = n - 1;
  46.     while ((d % 2) == 0)
  47.         s++, d >>= 1;
  48.     for (auto base : {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37})
  49.     {
  50.         if (n == base)
  51.             return true;
  52.         if (check_composite(n, base, d, s))
  53.             return false;
  54.     }
  55.     return true;
  56. }
  57.  
  58. int32_t main()
  59. {
  60.     int n;
  61.     cin >> n;
  62.  
  63.     is_prime(n);
  64.  
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement