社区讨论
求助,全部RE是为什么
P4718【模板】Pollard-Rho参与者 2已保存回复 2
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 2 条
- 当前快照
- 1 份
- 快照标识符
- @mhjif7fn
- 此快照首次捕获于
- 2025/11/04 03:05 4 个月前
- 此快照最后确认于
- 2025/11/04 03:05 4 个月前
CPP
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using i128 = __int128;
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
ll mul(ll a, ll b, ll mod) { return (i128)a * b % mod; }
ll pow(ll a, ll b, ll mod) {
ll res = 1;
for (; b; b >>= 1, a = mul(a, a, mod))
if (b & 1) res = mul(res, a, mod);
return res;
}
// Miller-Rabin素性测试
bool is_prime(ll n) {
if (n < 2) return 0;
ll d = n - 1, s = 0;
while (!(d & 1)) d >>= 1, s++;
for (ll a : {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}) {
if (n == a) return 1;
ll x = pow(a, d, n);
if (x == 1 || x == n - 1) continue;
for (int i = 0; i < s - 1; i++)
if ((x = mul(x, x, n)) == n - 1) goto next;
return 0;
next:;
}
return 1;
}
// Pollard's Rho分解
ll rho(ll n) {
if (n % 2 == 0) return 2;
if (n % 3 == 0) return 3;
if (n % 5 == 0) return 5;
while (1) {
ll c = rand() % (n - 1) + 1;
auto f = [&](ll x) { return (mul(x, x, n) + c) % n; };
ll x = 2, y = 2, d = 1;
while (d == 1) {
x = f(x);
y = f(f(y));
d = gcd(abs(x - y), n);
}
if (d != n) return d;
}
}
// 分解并收集素因子
int mx;
void factor(ll n) {
if (n == 1) return ;
if (is_prime(n)){
mx=n;
return ;
}
ll d = rho(n);
factor(d);
factor(n / d);
// v.insert(v.end(), w.begin(), w.end());
// return v;
}
bool solve(){
long long x;
cin>>x;
mx=0;
if(is_prime(x))cout<<"Prime"<<"\n";
else {
factor(x);
cout<<mx<<"\n";
}
}
signed main(){
// ios;
int t=1;
cin>>t;
while(t--)
solve();
return 0;
}
回复
共 2 条回复,欢迎继续交流。
正在加载回复...