[POJ 1811 Prime Test] Miller_Rabin + Pollard_rho 大数质数判
发布时间:2020-12-14 01:33:56 所属栏目:大数据 来源:网络整理
导读:[POJ 1811 Prime Test] Miller_Rabin + Pollard_rho 大数质数判断/质因子分解模板 题目链接 :[POJ 1811 Prime Test] 题意描述 :判断N是否为质数,如果是,求最小的质因子( 2 ≤ N 2 54 )。 解题思路 :Miller_Rabin + Pollard_rho 模板走起。 #include cti
[POJ 1811 Prime Test] Miller_Rabin + Pollard_rho 大数质数判断/质因子分解模板题目链接:[POJ 1811 Prime Test] #include <ctime>
#include <queue>
#include <cmath>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define FIN freopen("input.txt","r",stdin)
typedef long long LL;
const LL MOD = 1e9 + 7;
const LL INF = 0x3f3f3f3f3f3f3f3fLL;
const int MAXN = 100;
const int S = 20;
LL T,N;
LL tol;
LL fact[MAXN];
LL mult_mod(LL a,LL b,LL c) {
a %= c;
b %= c;
LL ret = 0;
while(b) {
if(b & 1) {
ret += a;
ret %= c;
}
a <<= 1;
if(a >= c)a %= c;
b >>= 1;
}
return ret;
}
LL quick_pow(LL x,LL n,LL mod) {
if(n == 1)return x % mod;
x %= mod;
LL tmp = x;
LL ret = 1;
while(n) {
if(n & 1) ret = mult_mod(ret,tmp,mod);
tmp = mult_mod(tmp,mod);
n >>= 1;
}
return ret;
}
bool check(LL a,LL x,LL t) {
LL ret = quick_pow(a,x,n);
LL last = ret;
for(int i = 1; i <= t; i++) {
ret = mult_mod(ret,ret,n);
if(ret == 1 && last != 1 && last != n - 1) return true;
last = ret;
}
if(ret != 1) return true;
return false;
}
bool Miller_Rabin(LL n) {
if(n < 2)return false;
if(n == 2)return true;
if((n & 1) == 0) return false;
LL x = n - 1;
LL t = 0;
while((x & 1) == 0) {
x >>= 1;
t++;
}
for(int i = 0; i < S; i++) {
LL a = rand() % (n - 1) + 1;
if(check(a,n,t))
return false;
}
return true;
}
LL gcd(LL a,LL b) {
if(a == 0)return 1;
if(a < 0) return gcd(-a,b);
while(b) {
LL t = a % b;
a = b;
b = t;
}
return a;
}
LL Pollard_rho(LL x,LL c) {
LL i = 1,k = 2;
LL x0 = rand() % x;
LL y = x0;
while(1) {
i++;
x0 = (mult_mod(x0,x0,x) + c) % x;
LL d = gcd(y - x0,x);
if(d != 1 && d != x) return d;
if(y == x0) return x;
if(i == k) {
y = x0;
k += k;
}
}
}
void findfac(LL n) {
if(Miller_Rabin(n)) {
fact[tol++] = n;
return;
}
LL p = n;
while(p >= n) p = Pollard_rho(p,rand() % (n - 1) + 1);
findfac(p);
findfac(n / p);
}
int main() {
#ifndef ONLINE_JUDGE
FIN;
#endif // ONLINE_JUDGE
LL ans;
scanf("%lld",&T);
while(T --) {
scanf("%lld",&N);
/// 要特判N==1的情况
if(N == 1 || Miller_Rabin(N)) {
printf("Primen");
continue;
}
tol = 0;
findfac(N);
ans = fact[0];
for (int i = 1; i < tol; i++) ans = min(ans,fact[i]);
printf("%lldn",ans);
}
return 0;
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |