/*
Time:2019.12.10
Author: Goven
type:pollard-rho大数分解质因子+Miller_Rabin判断质数
ref:
代码:
https://blog.csdn.net/xiaolonggezte/article/details/60965540
https://blog.csdn.net/nash142857/article/details/8274932
解释:https://www.cnblogs.com/Doggu/p/MillerRabin_PollardRho.html
*/
//Time Limit Exceeded
#include<iostream>
#include<ctime>//time
#include<cstdlib>//rand()
using namespace std;
typedef long long ll;
ll factor[100005];
int cnt = 0;
ll Mult_mod (ll a, ll b, ll mod) {//大数乘法
a %= mod;//att1:不要漏
b %= mod;
ll res = 0;
while (b) {
if (b & 1) res = (res + a) % mod;//可以用减法,速度比取模快
a = a * 2 % mod;
b >>= 1;
}
return res;
}
ll pow_mod (ll a, ll b, ll mod) {//快速幂
a = a % mod;//att2:不要漏
ll res = 1;
while (b) {
if (b & 1) res = Mult_mod(res, a, mod);
a = Mult_mod(a, a, mod);
b >>= 1;
}
return res;
}
bool Check (ll a, ll n, ll x, ll t) {//二次探测判断是否为合数
a = pow_mod(a, x, n);
ll last;
for (int i = 0; i < t; i++) {
last = a;
a = Mult_mod(a, a, n);
if (a == 1 && last != 1 && last != (n - 1)) return true;
}
if (a != 1) return true;
return false;
}
bool Miller_Rabin (ll n, int k) {//判断是否是素数
if (n < 2) return false;
if (n == 2) return true;
if ((n & 1) == 0) return false;//step1:粗筛
ll x = n - 1, t = 0;//step2:二次探测
while ((x & 1) == 0) x >>= 1, t++;
for (int i = 0; i < k; i++) {
ll a = rand() % (n - 1) + 1;
if (Check(a, n, x, t))
return false;
}
return true;
}
ll f (ll x, ll mod, ll c) {//伪随机函数生成xi
return (Mult_mod(x, x, mod) + c) % mod;
}
ll gcd (ll a, ll b) {
if (a < 0) return gcd(-a, b);
return b ? gcd(b, a % b) : a;
}
ll Pollard_rho (ll n, ll c) {//寻找x的某个质因数
ll a = rand() % n;
ll b = a;
ll i = 1, k = 2;
while (1) {
i++;
a = f(a, n, c);
ll d = gcd(a - b, n);
if (d != 1 && d != n) return d;
if (a == b) return n;//循环节
if (i == k) {
b = a;
k += k;
}
}
}
void findFac (ll n) {//分解质因子
if (Miller_Rabin(n, 5)) {
factor[cnt++] = n;
return;
}
ll p = n;
while (p >= n) p = Pollard_rho(p, (ll)rand()%(n - 1) + 1);//err1:(ll)没加
findFac(p);
findFac(n / p);
}
int main()
{
srand(time(NULL));//头文件ctime
int t;
ll n;
cin >> t;
while(t--) {
cin >> n;
cnt = 0;//err2:漏了
findFac(n);
if (cnt == 1) cout << "Prime" << endl;
else {
ll tp = factor[0];
for (int i = 1; i < cnt; i++) {
if (tp > factor[i]) tp = factor[i];
}
cout << tp << endl;
}
}
return 0;
}
poj1811 pollard-rho大数分解质因子+Miller_Rabin判断质数
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...