题目:Prime Test POJ - 1811
咱也不知道啥原理,会用就行了。
代码:
#include<stdio.h>
#include<string>
#include<algorithm>
#include <stdlib.h>
#include<iostream>
#include<time.h>
using namespace std;
#define LL long long
const int S = 8;
LL factor[100];
int tol;
LL mult_mod(LL a, LL b, LL c)
{
a %= c;
b %= c;
LL ret = 0;
LL tmp = a;
while(b)
{
if(b&1)
{
ret += tmp;
if(ret > c)ret -= c;
}
tmp <<= 1;
if(tmp > c) tmp -= c;
b >>= 1;
}
return ret;
}
LL pow_mod(LL a, LL n, LL mod)
{
LL ret = 1;
LL temp = a % mod;
while(n)
{
if(n & 1)ret = mult_mod(ret, temp, mod);
temp = mult_mod(temp, temp, mod);
n >>= 1;
}
return ret;
}
bool check(LL a, LL n, LL x, LL t)
{
LL ret = pow_mod(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;
else 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++;
}
srand(time(NULL));
for(int i = 0; i < S; i++ )
{
LL a = rand()%(n-1)+1;
if(check(a, n, x, t))
return false;
}
return true;
}
LL gcd(LL a, LL b)
{
LL t;
while(b)
{
t = a;
a = b;
b = t % b;
}
if(a >= 0)return a;
else return -a;
}
LL pollard_rho(LL x, LL c)
{
LL i = 1, k = 2;
srand(time(NULL));
LL x0 = rand() % (x - 1) + 1;
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, int k)
{
if(n == 1)return;
if(Miller_Rabin(n))
{
factor[tol++] = n;
return;
}
LL p = n;
int c= k;
while(p >= n)p = pollard_rho(p, c--);
findfac(p, k);
findfac(n/p, k);
}
int main()
{
int T;
cin>>T;
while(T--)
{
LL n;
scanf("%I64d", &n);
if(Miller_Rabin(n))printf("Prime\n");
else
{
tol = 0;
findfac(n, 107);
LL ans = factor[0];
for(int i = 1; i < tol; i++)
{
ans = min(ans, factor[i]);
}
printf("%I64d\n", ans);
}
}
return 0;
}
本文介绍了一种基于Miller-Rabin素性测试的算法,用于判断一个大整数是否为素数,并通过Pollard's Rho算法进行质因数分解。代码实现包括了快速幂取模、扩展欧几里得算法等关键数学操作。
657

被折叠的 条评论
为什么被折叠?



