【POJ1811】Prime Test

【题目大意】

若n是素数,输出“Prime”,否则输出n的最小素因子,(n<=2^54)

 

【题解】

和bzoj3667差不多,知识这道题没那么坑。

直接上Pollord_Rho和Rabin_Miller就行了。

 1 /*************
 2   POJ 1811
 3   by chty
 4   2016.11.7
 5 *************/
 6 #include<iostream>
 7 #include<cstdio>
 8 #include<cstdlib>
 9 #include<cstring>
10 #include<ctime>
11 #include<cmath>
12 #include<algorithm>
13 using namespace std;
14 typedef long long ll;
15 const ll INF=1000000000000000000LL;
16 const ll prime[10]={2,3,5,7,11,13,17,19,23};
17 ll T,minn;
18 inline ll read()
19 {
20     ll x=0,f=1;  char ch=getchar();
21     while(!isdigit(ch))  {if(ch=='-')  f=-1;  ch=getchar();}
22     while(isdigit(ch))  {x=x*10+ch-'0';  ch=getchar();}
23     return x*f;
24 }
25 ll gcd(ll a,ll b) {return !b?a:gcd(b,a%b);}
26 ll mul(ll x,ll y,ll mod) {return ((x*y-(ll)(((long double)x*y+0.5)/mod)*mod)%mod+mod)%mod;}
27 ll fast(ll a,ll b,ll mod) {ll sum=1;for(;b;b>>=1,a=mul(a,a,mod))if(b&1)sum=mul(sum,a,mod);return sum;}
28 bool Rabin_Miller(ll p,ll a)
29 {
30     if(p==2)  return 1;
31     if(!(p&1)||p==1)  return 0;
32     ll d=p-1;
33     while(!(d&1))  d>>=1;
34     ll m=fast(a,d,p);
35     if(m==1)  return 1;
36     for(;d<p;d<<=1,m=mul(m,m,p)) if(m==p-1)  return 1;
37     return 0;
38 }
39 bool isprime(ll x)
40 {
41     for(ll i=0;i<9;i++)
42     {
43         if(prime[i]==x)  return 1;
44         if(!Rabin_Miller(x,prime[i]))  return 0;
45     }
46     return 1;
47 }
48 void Pollord_Rho(ll x)
49 {
50     if(isprime(x))  {minn=min(minn,x);  return;}
51     ll c=3;
52     while(1)
53     {
54         ll x1(1),x2(1),i(1),k(2);
55         while(1)
56         {
57             x1=(mul(x1,x1,x)+c)%x;
58             ll d=gcd(x1>x2?x1-x2:x2-x1,x);
59             if(d>1&&d<x)  
60             {
61                 Pollord_Rho(d);
62                 Pollord_Rho(x/d);
63                 return;
64             }
65             if(x1==x2)  break;
66             if(++i==k)  x2=x1,k<<=1;
67         }
68         c++;
69     }
70 }
71 void solve(ll x)
72 {
73     if(isprime(x))  {puts("Prime"); return;}
74     minn=INF;
75     Pollord_Rho(x);
76     printf("%lld\n",minn);
77 }
78 int main()
79 {
80     freopen("cin.in","r",stdin);
81     freopen("cout.out","w",stdout);
82     T=read();
83     while(T--){ll x=read();solve(x);}
84     return 0;    
85 }

 

posted @ 2016-11-07 19:56  chty  阅读(201)  评论(0编辑  收藏  举报