POJ 1811 Prime Test

Description

Given a big integer number, you are required to find out whether it's a prime number.

Input

The first line contains the number of test cases T (1 <= T <= 20 ), then the following T lines each contains an integer number N (2 <= N < 254).

Output

For each test case, if N is a prime number, output a line containing the word "Prime", otherwise, output a line containing the smallest prime factor of N.

Sample Input

2

5

10

Sample Output

Prime

2

Pollard Rho大数分解算法+Miller_Rabin判素数法模板

  1 #include<iostream>
  2 #include<cstdio>
  3 #include<cstring>
  4 #include<algorithm>
  5 #include<cmath>
  6 #include<ctime>
  7 using namespace std;
  8 typedef long long lol;
  9 int prime[11]={2,3,5,7,11,13,17,19,23,29};
 10 lol ans,inf=1e18;
 11 lol gcd(lol a,lol b)
 12 {
 13   if (!b) return a;
 14   return gcd(b,a%b);
 15 }
 16 lol multi(lol x,lol y,lol Mod)
 17 {
 18   lol res=0;
 19   x%=Mod;
 20   while (y)
 21     {
 22       if (y&1)
 23     {
 24       res=(res+x)%Mod;
 25     }
 26       x=(x+x)%Mod;
 27       y>>=1;
 28     }
 29   return res;
 30 }
 31 lol qpow(lol x,lol y,lol Mod)
 32 {
 33   lol res=1;
 34   while (y)
 35     {
 36       if (y&1)
 37     {
 38       res=multi(res,x,Mod);
 39     }
 40       x=multi(x,x,Mod);
 41       y>>=1;
 42     }
 43   return res;
 44 }
 45 bool Miller_Rabin(lol n)
 46 {int i,j;
 47   if (n==2) return 1;
 48   if (n<2||n%2==0) return 0;
 49   for (i=0;i<10;i++)
 50     {
 51       if (n==prime[i]) return 1;
 52       if (n%prime[i]==0) return 0;
 53     }
 54   lol m=n-1,k=0;
 55   while (m%2==0)
 56     {
 57       m>>=1;
 58       k++;
 59     }
 60   for (i=0;i<10;i++)
 61     {
 62       lol a=rand()%(n-2)+2;
 63       lol x=qpow(a,m,n);
 64       lol y=0;
 65       for (j=0;j<k;j++)
 66     {
 67       y=multi(x,x,n);
 68       if (y==1&&x!=1&&x!=n-1) return 0;
 69       x=y;
 70     }
 71       if (y!=1) return 0;
 72     }
 73   return 1;
 74 }
 75 lol pollard_rho(lol n,lol c)
 76 {
 77   lol i=1,k=2;
 78   lol x=rand()%(n-1)+1,y=x;
 79   while (1)
 80     {
 81       ++i;
 82       x=(multi(x,x,n)+c)%n;
 83       lol d=gcd((y-x+n)%n,n);
 84       if (d>1&&d<n) return d;
 85       if (y==x) return n;
 86       if (i==k)
 87     {
 88       y=x;
 89       k<<=1;
 90     }
 91     }
 92 }
 93 void find(lol n,lol c)
 94 {
 95   if (n==1) return;
 96   if (Miller_Rabin(n))
 97     {
 98       ans=min(ans,n);
 99       return;
100     }
101   lol p=n;
102   lol k=c;
103   while (p==n) p=pollard_rho(p,c--);
104   find(p,k);
105   find(n/p,k);
106 }
107 int main()
108 {int T;
109   lol n;
110   cin>>T;
111   srand(time(0));
112   while (T--)
113     {
114       cin>>n;
115       ans=inf;
116       if (Miller_Rabin(n)) printf("Prime\n");
117       else
118     {
119       find(n,120);
120       printf("%lld\n",ans);
121     }
122     }
123 }

 



posted @ 2018-02-04 08:49  Z-Y-Y-S  阅读(250)  评论(0编辑  收藏  举报