目录
题目:
Prime Test
Time Limit: 6000MS | Memory Limit: 65536K | |
Total Submissions: 37982 | Accepted: 10195 | |
Case Time Limit: 4000MS |
Description
Given a big integer number, you are required to find out whether it's a prime number.
Input
The first line contains the number of test cases T (1 <= T <= 20 ), then the following T lines each contains an integer number N (2 <= N < 254).
Output
For each test case, if N is a prime number, output a line containing the word "Prime", otherwise, output a line containing the smallest prime factor of N.
Sample Input
2
5
10
Sample Output
Prime
2
题目大意:
给出一个2^54范围内的一个数判断其是否为素数。
关于Miller_Rabin探测:
关于Pollard_rho:
Pollard_rho算法是基于概率的算法。
Pollard_rho算法的大致流程是 先判断当前数是否是素数(Miller_rabin)了,如果是则直接返回。如果不是素数的话,试图找到当前数的一个因子(可以不是质因子)。然后递归对该因子和约去这个因子的另一个因子进行分解。
那么自然的疑问就是,怎么找到当前数n的一个因子?当然不是一个一个慢慢试验,而是一种神奇的想法。其实这个找因子的过程我理解的不是非常透彻,感觉还是有一点儿试的意味,但不是盲目的枚举,而是一种随机化算法。我们假设要找的因子为p,他是随机取一个x1,由x1构造x2,使得{p可以整除x1-x2 && x1-x2不能整除n}则p=gcd(x1-x2,n),结果可能是1也可能不是1。如果不是1就找寻成功了一个因子,返回因子;如果是1就寻找失败,那么我们就要不断调整x2,具体的办法通常是x2=x2*x2+c(c是自己定的)直到出现x2出现了循环==x1了表示x1选取失败重新选取x1重复上述过程。
AC代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<ctime>
using namespace std;
typedef long long ll;
const int times = 10;
ll minn;
ll prime[11] = {2,3,5,7,11,13,17,19,23,29,31};
ll fast_mul_mod(ll a,ll b,ll mod)
{
ll res = 0;
while(b){
if(b & 1){
res += a;
if(res >= mod) res -= mod;
}
a <<= 1;
if(a >= mod) a -= mod;
b >>= 1;
}
return res;
}
ll fast_pow_mod(ll a,ll b,ll mod)
{
ll res = 1;
while(b){
if(b & 1) res = fast_mul_mod(res,a,mod);
a = fast_mul_mod(a,a,mod);
b >>= 1;
}
return res;
}
bool check(ll n,ll a){
ll p = fast_pow_mod(a,n - 1,n);
if(p != 1) return false;
ll s = n - 1;
while(!(s & 1) && p == 1){
s >>= 1;
p = fast_pow_mod(a,s,n);
}
if(p == 1 || p == n - 1) return true;
return false;
}
bool Miller_Pabin(ll n)
{
if (n < 32){
for(int i = 0; i < 11; ++i)
if(n == prime[i]) return true;
return false;
}
for(ll i = 0;i < 10;++i){
if(!check(n,prime[i])) return false;
}
return true;
}
ll gcd(ll a,ll b)
{
return b ? gcd(b,a % b) : a;
}
ll pollard_rho(ll n,ll c)
{
ll i = 1,k = 2;
//srand(time(NULL));
ll x0 = rand() % n;
ll y = x0,d;
while(true){
i++;
x0 = (fast_mul_mod(x0,x0,n) + c) % n;
d = gcd(n + y - x0,n);
if(d > 1 && d < n) return d;
if(y == x0) return n;
if(i == k){y = x0;k <<= 1;}
}
}
void find_factor(ll n)
{
//srand(time(NULL));
if(Miller_Pabin(n)){
minn = min(minn,n);
return ;
}
ll p = n;
while(p >= n) p = pollard_rho(n,rand() % (n - 1) + 1);
find_factor(p);
find_factor(n / p);
}
int main()
{
int t;
scanf("%d",&t);
while(t--){
ll n;
scanf("%lld",&n);
if(Miller_Pabin(n)) printf("Prime\n");
else{
minn = n;
find_factor(n);
printf("%lld\n",minn);
}
}
return 0;
}