隐藏
「bsoj1630」素数 - Pollard-Rho | Bill Yang's Blog

路终会有尽头,但视野总能看到更远的地方。

0%

「bsoj1630」素数 - Pollard-Rho

题目大意

    给你一个数$N$,判断$N$是否为素数。
    如果$N$是素数,直接输出Prime,否则输出$N$的最小质因数。


题目分析

复习重新学习一下Pollard-Rho。
模板题,学习笔记见这里


代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include<algorithm>
#include<iostream>
#include<iomanip>
#include<cstring>
#include<cstdlib>
#include<climits>
#include<vector>
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;

typedef long long LL;

inline const LL Get_Int() {
LL num=0,bj=1;
char x=getchar();
while(x<'0'||x>'9') {
if(x=='-')bj=-1;
x=getchar();
}
while(x>='0'&&x<='9') {
num=num*10+x-'0';
x=getchar();
}
return num*bj;
}

const int TIMES=10;

LL Quick_Mul(LL a,LL b,LL p) {
LL tmp=(a*b-(LL)((long double)a/p*b+1e-8)*p);
if(tmp<0)return tmp+p;
else return tmp;
}

LL Quick_Pow(LL a,LL b,LL p) {
LL sum=1;
for(a%=p; b; b>>=1,a=Quick_Mul(a,a,p))if(b&1)sum=Quick_Mul(sum,a,p);
return sum;
}

mt19937 g(rand());

bool Witness(LL a,LL n) {
LL u=n-1,t=0;
while(u%2==0)t++,u>>=1;
LL x=Quick_Pow(a,u,n);
if(x==1)return false;
for(int i=1; i<=t; i++,x=Quick_Mul(x,x,n))
if(x!=n-1&&x!=1&&Quick_Mul(x,x,n)==1)return true;
return x!=1;
}

bool Miller_Rabin(LL n) {
if(n==2)return true;
if(n<2||!(n&1))return false;
for(int i=1; i<=TIMES; i++)
if(Witness(g()%(n-1)+1,n))return false;
return true;
}

LL Pollar_Rho(LL n) {
if(!(n&1))return 2;
while(true) {
LL a=g()%(n-1)+1,b=a,c=g()%(n-1)+1;
if(c==2)c=3;
while(true) {
a=(Quick_Mul(a,a,n)+c)%n;
b=(Quick_Mul(b,b,n)+c)%n;
b=(Quick_Mul(b,b,n)+c)%n;
if(a==b)break; //环
LL d=__gcd(abs(b-a),n);
if(d>1)return d;
}
}
}

LL Find_Frac(LL n) {
if(Miller_Rabin(n))return n;
LL p=Pollar_Rho(n);
return min(Find_Frac(p),Find_Frac(n/p));
}

LL n;

int main() {
srand(time(NULL));
int t=Get_Int();
while(t--) {
n=Get_Int();
LL ans=Find_Frac(n);
if(ans==n)puts("Prime");
else printf("%lld\n",ans);
}
return 0;
}
姥爷们赏瓶冰阔落吧~