Prime Test
Time Limit: 6000MS | Memory Limit: 65536K | |
Total Submissions: 27892 | Accepted: 6953 | |
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 < 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
Source
给你一个数判读是否是素数,如果不是输出它的最小质因数。此数的范围是2 <= N < 254
判断是否为素数需要用Miller-Rabin素数测试。用Pollard rho方法进行整数分解,求出所有质因数取其最小。
//400K 860MS
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#define Times 11
#define inf ((long long)1<<61)
#define C 201
long long jl[501],mini;//jl里面存的是大数的所有质因子
int ct;
long long gcd(long long a,long long b)//最大公约数
{
return b==0?a:gcd(b,a%b);
}
long long random(long long n)//生成随机数
{
return (long long)((double)rand()/RAND_MAX*n+0.5);
}
long long multi(long long a,long long b,long long m)//a*b%m
{
long long ret=0;
while(b>0)
{
if(b&1)ret=(ret+a)%m;
b>>=1;
a=(a<<1)%m;
}
return ret;
}
long long quick_mod(long long a,long long b,long long m)//a^b%m
{
long long ans=1;
a%=m;
while(b)
{
if(b&1)
{
ans=multi(ans,a,m);
b--;
}
b/=2;
a=multi(a,a,m);
}
return ans;
}
bool Witness(long long a,long long n)
{
long long m=n-1;
int j=0;
while(!(m&1))
{
j++;
m>>=1;
}
long long x=quick_mod(a,m,n);
if(x==1||x==n-1)return false;
while(j--)
{
x=x*x%n;
if(x==n-1)return false;
}
return true;
}
bool miller_rabin(long long n)//素数测试
{
if(n<2)return false;
if(n==2)return true;
if(!(n&1))return false;
for(int i=1; i<=Times; i++)
{
long long a=random(n-2)+1;
if(Witness(a,n))return false;
}
return true;
}
long long pollard_rho(long long n,int c)//整数分解
{
long long x,y,d,i=1,k=2;
x=random(n-1)+1;
y=x;
while(1)
{
i++;
x=(multi(x,x,n)+c)%n;
d=gcd(y-x,n);
if(1<d&&d<n)return d;
if(y==x)return n;
if(i==k)
{
y=x;
k<<=1;
}
}
}
void find(long long n,int k)
{
if(n==1)return;
if(miller_rabin(n))
{
jl[++ct]=n;
if(n<mini)mini=n;
return;
}
long long p=n;
while(p>=n)p=pollard_rho(p,k--);
find(p,k);
find(n/p,k);
}
int main()
{
int cas;
long long n;
scanf("%d",&cas);
while(cas--)
{
ct=0;
mini=inf;
scanf("%lld",&n);
if(miller_rabin(n))printf("Prime\n");
else{find(n,C);printf("%lld\n",mini);}
}
return 0;
}