Guest User

Prime Test

a guest
Oct 9th, 2015
366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cstdlib>
  4. #include <cmath>
  5. #include <vector>
  6.  
  7. using namespace std;
  8. typedef long long ll;
  9.  
  10. ll n,s,t,k;
  11. ll p[3]={2,7,61};
  12.  
  13. ll mulmod(ll x,ll y,ll n)
  14. {
  15.     ll res=0;
  16.     while(y)
  17.     {
  18.         if(y&1) res=(res+x)%n;
  19.         x=(x+x)%n;
  20.         y>>=1;
  21.     }
  22.     return res;
  23. }
  24.  
  25. ll powmod(ll x,ll y,ll n)
  26. {
  27.     ll res=1;
  28.     while(y)
  29.     {
  30.         if(y&1) res=mulmod(res,x,n);
  31.         x=mulmod(x,x,n);
  32.         y>>=1;
  33.     }
  34.     return res;
  35. }
  36.  
  37.  
  38. bool miller(ll s,ll t,ll a)
  39. {
  40.     ll x=powmod(a,t,n);
  41.     if(x==1 || x==n-1)  return true;
  42.     for(ll j=1;j<s;++j)
  43.     {
  44.         x=mulmod(x,x,n);
  45.         if(x==1)    return false;
  46.         if(x==n-1)  return true;
  47.     }
  48.     return false;
  49. }
  50.  
  51. bool del()
  52. {
  53.     ll temp=sqrt(n);
  54.     for(ll i=2;i<=temp;++i)
  55.         if(n%i==0)
  56.             return false;
  57.     return true;
  58. }
  59.  
  60. bool check()
  61. {
  62.     if(n<=1)    return false;
  63.     if(n==2)    return true;
  64.     if(n<=100)  return del();
  65.     t=n-1;
  66.     while(!(t&1))
  67.     {
  68.         ++s;
  69.         t>>=1;
  70.     }
  71.     bool ok=true;
  72.     for(ll j=0;j<3 && ok;++j)
  73.         ok=miller(s,t,p[j]);
  74.     return ok;
  75. }
  76.  
  77.  
  78. int main()
  79. {
  80.     cin>>n;
  81.     cout<<check()<<endl;
  82.     system("pause");
  83.     return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment