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 < 2 54).
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
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <algorithm>
typedef long long ll;
#define Time 15 //随机算法判定次数,Time越大,判错概率越小
using namespace std;
ll n,ans,factor[10001];//质因数分解结果(刚返回时是无序的)
ll tol;//质因数的个数,数组下标从0开始
//****************************************************************
// Miller_Rabin 算法进行素数测试
//速度快,而且可以判断 <2^63的数
//****************************************************************
long long mult_mod(ll a,ll b,ll c)//计算 (a*b)%c. a,b都是ll的数,直接相乘可能溢出的
{
a%=c;// 利用二分思想减少相乘的时间
b%=c;
ll ret=0;
while(b)
{
if(b&1)
{
ret+=a;
ret%=c;
}
a<<=1;
if(a>=c)a%=c;
b>>=1;
}
return ret;
}
ll pow_mod(ll x,ll n,ll mod)//x^n%n
{
if(n==1)return x%mod;
x%=mod;
ll tmp=x;
ll ret=1;
while(n)
{
if(n&1) ret=mult_mod(ret,tmp,mod);
tmp=mult_mod(tmp,tmp,mod);
n>>=1;
}
return ret;
}
//以a为基,n-1=x*2^t a^(n-1)=1(mod n) 验证n是不是合数
//一定是合数返回true,不一定返回false
//二次探测
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;
return false;
}
// Miller_Rabin()算法素数判定
//是素数返回true.(可能是伪素数,但概率极小)
//合数返回false;
bool Miller_Rabin(ll n)
{
if(n<2)return false;
if(n==2||n==3||n==5||n==7)return true;
if(n==1||(n%2==0)||(n%3==0)||(n%5==0)||(n%7==0)) return false;//偶数
ll x=n-1;
ll t=0;
while((x&1)==0)
{
x>>=1;
t++;
}
for(int i=0; i<Time; i++)
{
ll a=rand()%(n-1)+1;//rand()需要stdlib.h头文件
if(check(a,n,x,t))
return false;//合数
}
return true;
}
//************************************************
//pollard_rho 算法进行质因数分解
//************************************************
ll gcd(ll a,ll b)
{
if(a==0)return 1;
if(a<0) return gcd(-a,b);
while(b)
{
long long t=a%b;
a=b;
b=t;
}
return a;
}
ll Pollard_rho(ll x,ll c)
{
ll i=1,k=2;
ll x0=rand()%x;
ll y=x0;
while(1)
{
i++;
x0=(mult_mod(x0,x0,x)+c)%x;
long long d=gcd(y-x0,x);
if(d!=1&&d!=x) return d;
if(y==x0) return x;
if(i==k)
{
y=x0;
k+=k;
}
}
}
//对n进行素因子分解
void findfac(ll n)
{
if(Miller_Rabin(n))//素数
{
factor[tol++]=n;
return;
}
ll p=n;
while(p>=n) p=Pollard_rho(p,rand()%(n-1)+1);
findfac(p);//递归调用
findfac(n/p);
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%lld",&n);//(n>=2)
/*if(n==1)
{
printf("1\n");
continue;
}*/
if(Miller_Rabin(n))
{
printf("Prime\n");
continue;
}
tol=0;
findfac(n);//对n分解质因子
ll ans=factor[0];
for(int i=1; i<tol; i++)//求最小素数因子
if(factor[i]<ans)
ans=factor[i];
/*for(int i=0;i<tol;i++)
{
printf("%lld\n",factor[i]);
}*/
printf("%lld\n",ans);
}
return 0;
}