Prime Test
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 |
[Submit] [Go Back] [Status] [Discuss]
题意:给你一个不超过long long的数,让你判断是不是素数,如果不是,输出最小质因子。
题解:Pollard_rho算法模板,直接套板子即可。
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#include<math.h>
using namespace std;
#define ll long long
ll cnt, fat[101];
ll pri[2550005], a[2550005] = {1,1};
/*LL Multi(LL a, LL b, LL mod)
{
LL t;
a %= mod, b %= mod;
t = a*b-(LL)((double)a/mod*b+0.5)*mod;
t = (t+mod)%mod;
return t;
}*/
ll Multi(ll a, ll b, ll mod) //和上面一样,但比上面慢很多
{
ll ans = 0;
a %= mod;
while(b)
{
if(b%2==1) ans = (ans+a)%mod, b--;
else a = (a+a)%mod, b /= 2;
}
return ans;
}
ll Pow(ll a, ll b, ll mod)
{
ll ans = 1;
a %= mod;
while(b)
{
if(b&1) ans = Multi(ans, a, mod), b--;
else a = Multi(a, a, mod), b /= 2;
}
return ans;
}
ll Gcd(ll a, ll b)
{
if(b==0)
return a;
return Gcd(b, a%b);
}
int Miller_Rabin(ll n)
{
int i, j, k;
ll a, x, y, mod;
if(n==2) return 1;
if(n<2 || n%2==0) return 0;
k = 0, mod = n-1;
while(mod%2==0)
{
k++;
mod /= 2;
}
for(i=1;i<=15;i++)
{
a = rand()%(n-1)+1;
x = Pow(a, mod, n);
y = 0;
for(j=1;j<=k;j++)
{
y = Multi(x, x, n);
if(y==1 && x!=1 && x!=n-1)
return 0;
x = y;
}
if(y!=1)
return 0;
}
return 1;
}
ll Divi(ll n)
{
ll i, k, x, y, p, c;
if(n==1)
return 1;
k = 2, p = 1;
y = x = rand()%n, c = rand()%(n-1)+1;
for(i=1;p==1;i++)
{
x = (Multi(x, x, n)+c)%n;
p = x-y;
if(p<0)
p = -p;
p = Gcd(n, p);
if(i==k)
y = x, k *= 2;
}
return p;
}
void Pollard_rho(ll n)
{
ll p;
if(n==1)
return;
if(Miller_Rabin(n))
fat[++cnt] = n;
else
{
p = Divi(n);
Pollard_rho(p);
Pollard_rho(n/p);
}
}
int main(void)
{
ll i, j, n, x, qcnt;
qcnt = 0;
int T;
scanf("%d",&T);
for(i=2;i<2550000;i++)
{
if(a[i]==0)
pri[++qcnt] = i;
for(j=i*i;j<=2550000;j+=i)
a[j] = 1;
}
while(T--)
{
cnt = 0;
scanf("%I64d",&n);
if(Miller_Rabin(n))
printf("Prime\n");
else
{
for(i=1;i<=qcnt;i++)
{
if(n%pri[i]==0)
{
printf("%I64d\n", pri[i]);
break;
}
}
if(i==qcnt+1)
{
Pollard_rho(n);
x = fat[1];
for(i=2;i<=cnt;i++)
x = min(x, fat[i]);
printf("%I64d\n", x);
}
}
}
return 0;
}