大數分解 pollard_rho

來源:互聯網
上載者:User

 

#include<iostream>
#include<algorithm>
using namespace std;
long long factor[110], cnt;
long long Mul_Mod(long long a, long long b, long long c) {
if (b == 0)
return 0;
long long ans = Mul_Mod(a, b / 2, c);
ans = (ans * 2) % c;
if (b % 2)
ans = (ans + a) % c;
return ans;
}
long long Pow_Mod(long long a, long long b, long long c) {
if (b == 0)
return 1;
long long x = Pow_Mod(a, b / 2, c);
if (x == 0)
return 0;
long long y = Mul_Mod(x, x, c);
if (y == 1 && x != 1 && x != c - 1)
return 0;
if (b % 2)
y = Mul_Mod(y, a, c);
return y;
}
bool Miller_rabin(long long n, int timenum = 10) {
if (n < 2)
return false;
if (n == 2)
return true;
while (timenum--) {
if (Pow_Mod(rand() % (n - 2) + 2, n - 1, n) != 1)
return false;
}
return true;
}
long long Gcd(long long a, long long b) {
long long t;
while (b) {
t = a;
a = b;
b = t % b;
}
return a;
}
void Pollard(long long n);

void Factor(long long n) {
long long d = 2;
while (true) {
if (n % d == 0) {
Pollard(d);
Pollard(n / d);
return;
}
d++;
}
}
void Pollard(long long n) {
if (n <= 0)
printf("error\n");
if (n == 1)
return;
if (Miller_rabin(n)) {
factor[cnt++] = n;
return;
}
long long i = 0, k = 2, x, y, d;
x = y = rand() % (n - 1) + 1;
while (i++ < 123456) {
x = (Mul_Mod(x, x, n) + n - 1) % n;
d = Gcd((y - x + n) % n, n);
if (d != 1) {
Pollard(d);
Pollard(n / d);
return;
}
if (i == k) {
y = x;
k *= 2;
}
}
Factor(n);
}
int main() {
int Case;
long long n;
scanf("%d", &Case);
while (Case--) {
scanf("%lld", &n);
if (Miller_rabin(n))
printf("Prime\n");
else {
cnt = 0;
Pollard(n);
sort(factor, factor + cnt);
printf("%lld\n", factor[0]);
}
}
return 0;
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.