题目链接:http://poj.org/problem?id=1811
题意:给出一个n判断是否为素数,不是的话找出最小质因子。
博客:
http://blog.csdn.net/cqbztsy/article/details/47190325
https://www.cnblogs.com/kuangbin/archive/2012/08/19/2646404.html
http://blog.csdn.net/f_zyj/article/details/51812958
我比着别人代码敲都会超时,直接粘上别人代码吧,反正也会当做模板。
代码:
#include <iostream>
#include <cstdio>
#include <ctime>
#include <algorithm>
#define LL long long int
#define min(a,b) ((a)<(b)?(a):(b))
#define abs(a) ((a)>0?(a):(-(a)))
using namespace std;
LL n ,factor[10050] ,tot ;
LL mul(LL a,LL pos,LL p)
{
LL ans=0 ;
a%=p ,pos%=p ;
while(pos)
{
if(pos&1)
{
ans+=a;
if(ans>=p)ans-=p;
}
a<<=1;
if(a>=p)a-=p;
pos>>=1;
}
return ans;
}
LL power(LL a,LL pos,LL p)
{
LL ans=1;
while(pos>0)
{
if(pos&1)
ans=mul(ans,a,p);
a=mul(a,a,p);
pos>>=1;
}
return ans;
}
bool Miller_Rabin(LL n)
{
if(n==2||n==3)return 1;
if(n<2||!(n&1))return 0;
LL code=0 ,k=n-1 ;
while(!(k&1))
{
k>>=1;
++code;
}
LL a ,temp ,tmp ;
for(int i=1;i<21;++i)
{
a=rand()%(n-1)+1;
temp=power(a,k,n);
tmp=temp;
for(int j=0;j<code;++j)
{
temp=mul(temp,temp,n);
if(temp==1)
{
if(tmp!=1&&tmp!=n-1)
return 0;
break;
}
tmp=temp;
}
if(temp!=1)
return 0;
}
return 1;
}
LL gcd(LL a,LL b)
{
if(!b) return a;
return gcd(b,a%b);
}
LL Pollard_rho(LL a,LL b)
{
LL code=1 ,k=2 ,x0=rand()%a ,y=x0 ,d ;
while(1)
{
++code;
x0=(mul(x0,x0,a)+b)%a;
d=gcd(abs(y-x0),a);
if(d!=1&&d!=a)
return d;
if(y==x0)
return a;
if(code==k)
y=x0 ,k+=k ;
}
}
void dfs(LL n)
{
if(Miller_Rabin(n))
{
factor[++tot]=n;
return;
}
LL p=n;
while(p>=n)
p=Pollard_rho(p,rand()%(n-1)+1);
dfs(p);
dfs(n/p);
}
int main()
{
//srand(time(NULL));
int T ;
scanf("%d",&T);
LL ans ;
while(T--)
{
scanf("%I64d",&n);
if(Miller_Rabin(n))
puts("Prime");
else
{
tot=0;
dfs(n);
ans=n;
for(int i=1;i<=tot;++i)
ans=min(ans,factor[i]);
printf("%I64d\n",ans);
}
}
return 0;
}