传送门:http://poj.org/problem?id=1811
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
题意
&enmsp;t组样例,每组一个long long 级别的数 n,让你判断n是不是质数,是则输出Prime,不是输出它的最小质因子
详情算法介绍:https://blog.csdn.net/qq_43724031/article/details/100145417
AC代码:
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
#include<ctime>
#define ll long long
#define ld long double
#define ull unsigned long long
using namespace std;
const int maxn = 100010;
const ll lnf = 0x3f3f3f3f3f3f3f;
int t,tot;
ll a[] = {2,3,5,7,11,61,13,17};
ll n,ans[maxn];
ll mul(ll x,ll y,ll z)
{
ll sm=(ld)x/z*y;
return ((ull)x*y-(ull)sm*z+z)%z;
}
ll ksm(ll x,ll y,ll z)
{
ll ans=1;
for(ll i=y;i;i>>=1){
if(i&1) ans=mul(ans,x,z);
x=mul(x,x,z);
}
return ans%z;
}
ll gcd(ll x,ll y)
{
return y==0 ? x : gcd(y,x%y);
}
bool rabin(ll x,ll y)
{
if(ksm(x,y-1,y)!=1)
return 0;
ll z=y-1,sm;
while(!(z&1)){
z>>=1;
sm=ksm(x,z,y);
if(sm!=1&&sm!=y-1) return 0;
if(sm==y-1) return 1;
}
return 1;
}
bool miller(ll x)
{
bool ans = true;
for(int i=0;i<8;i++){
if(a[i]==x) return 1;
ans &= rabin(a[i],x);
}
return ans;
}
ll Pollard(ll x)
{
ll a,b,d,g,y,i,j;
while(1){
a = b = rand()%x;
g = rand()%x;
y=1;i=0;j=1;
while(++i){
a = (mul(a,a,x)+g) % x;
if(a>b) y = mul(y,a-b,x);
else y = mul(y,b-a,x);
if(a==b||!y) break;
if(i<127||i==j){
d=gcd(x,y);
if(d>1&&d!=x) return d;
if(i==j){
b=a;
j<<=1;
}
}
}
}
}
void Find(ll x)
{
if(x<=1) return ;
if(miller(x)){
ans[tot++] = x;
return;
}
ll y=Pollard(x);
while(x%y==0) x/=y;
Find(y);Find(x);
}
int main()
{
scanf("%d",&t);
while(t--){
scanf("%lld",&n);
if(miller(n)){
printf("Prime\n");
continue;
}
else{
tot = 0;
Find(n);
ll _min = ans[0];
for(int i=1;i<tot;i++)
if(ans[i]<_min) _min = ans[i];
printf("%lld\n",_min);
}
}
return 0;
}