poj1811,权当模板~

MATWETU posted @ 2011年8月07日 17:28 in ALGO with tags 米勒拉宾 素性测试 因子分解 rho , 1746 阅读

 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define swap(a,b) do{a=a^b;b=a^b;a=a^b;}while(0)
typedef long long LL;
LL gcd(LL a,LL b)
{
	while(b){swap(a,b);b=b%a;}
	return a>0?a:-a;
}
LL mod_mult(LL a,LL b,LL mo)//ret:a*b%mo
{
	LL ret;
	a%=mo;
	for(ret=0;b;a=(a<<1)%mo,b>>=1)
		if(b&1)
			ret=(ret+a)%mo;
	return ret;
}
LL mod_exp(LL a,LL b,LL mo)//ret:a^b%mo
{
	LL ret=1,temp=a%mo;
	for(;b;b>>=1,temp=mod_mult(temp,temp,mo))
		if(b&1)
			ret=mod_mult(ret,temp,mo);
	return ret;
}
LL pollard_rho(LL n,int c)
{
	LL x,y,d,i=1,k=2;
	x=rand()%(n-1)+1;
	y=x;
	while(1)
	{
		i++;
		x=(mod_mult(x,x,n)+c)%n;
		d=gcd(y-x,n);
		if(d>1&&d<n)return d;
		if(x==y)return n;
		if(i==k)y=x,k<<=1;
		//if(k>1<<11)return n;
	}
}

int miller_rabin(LL n,int time)
{
	if (n==2||n==3||n==5||n==7)return 1;
	if (n<2||!(n&1))return 0;
	int i,j,t=0;
	LL a,x,y,u=n-1;
	while((u&1)==0) t++,u>>=1;
	for(i=0;i<time;i++)
	{
		a=rand()%(n-1)+1;
		x=mod_exp(a,u,n);
		for(j=0;j<t;j++)
		{
			y=mod_mult(x,x,n);
			if (y==1&&x!=1&&x!=n-1)
				return 0;
			x=y;
		}
		if (x!=1)
			return 0;
	}
	return 1;
}
LL min;
void fuck(LL i)
{
	LL x;
	if(miller_rabin(i,8)){if(i<min)min=i;/*printf(" %lld ",i);*/return;}
	do{x=pollard_rho(i,rand()%15+2);}while((x==1||x==i));
	fuck(x);
	fuck(i/x);
}
int main()
{
	LL i;int t;
	scanf("%d",&t);
	while(t--){
	scanf("%lld",&i);
	min=i;
	fuck(i);
	if(i!=min)printf("%lld\n",min);
	else printf("Prime\n");}
	return 0;
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter