abinash_hstu

Rabin-Miller Prime Test

Jan 20th, 2016
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. // C++ program Miller-Rabin primality test
  2. #include <bits/stdc++.h>
  3. #define MAX 10000
  4. #define long long long
  5.  
  6. using namespace std;
  7. long mul(long a, long b, long mod) {
  8.     long ans = 0;
  9.     while (b) {
  10.         if (b & 1)
  11.             ans = (ans + a) % mod;
  12.         a = (a + a) % mod;
  13.         b >>= 1;
  14.     }
  15.     return ans;
  16. }
  17. long binByMod(long a, long to, long mod) {
  18.     long ans = 1;
  19.     while (to) {
  20.         if (to & 1)
  21.             ans = mul(ans, a, mod);
  22.         a = mul(a, a, mod);
  23.         to >>= 1;
  24.     }
  25.     return ans;
  26. }
  27. long randomLong() {
  28.     long ans = 0;
  29.     for (int i = 0; i < 4; ++i)
  30.         ans = (ans << 16) ^ rand();
  31.     return ans;
  32. }
  33.  
  34. bool isPrime(long n) {
  35.     if (n % 2 == 0 && n != 2||n==1)
  36.         return false;
  37.     for (int i = 0; i < 20; ++i) {
  38.         long a = (randomLong() % (n - 1));
  39.         if (a < 0)
  40.             a += n - 1;
  41.         a += 1;
  42.  
  43.         a = binByMod(a, (n - 1) / 2, n);
  44.         if (a != n - 1 && a != 1)
  45.             return false;
  46.     }
  47.  
  48.     return true;
  49. }
  50. int main()
  51. {
  52.  
  53.     long  n=1;
  54.     if(isPrime(n))
  55.         cout<<"PRIME"<<endl;
  56.     else
  57.         cout<<"NOT"<<endl;
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment