poj1811 Prime Test Pollard_rho法+miller素数测试法

题意很简单,给你一个数会很大 但是小于2^54,问你这个数是不是素数,是的话输出Prime,不是 输出它最小的素因子

数很大  所以素数测试  要用到 Miller素数测试法,算法是 miller_rabin,直接套模版就可以,分解大数因子用Pollard_rho法,

http://hi.baidu.com/yangchenhao/item/29f475d492ef424efb5768bd  这里是介绍


#include<iostream>
#include<cstdio>
#include<list>
#include<algorithm>
#include<cstring>
#include<string>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<cmath>
#include<memory.h>
#include<set>

#define ll long long
#define LL __int64
#define eps 1e-8

#define inf 0xfffffff
const ll INF = 1ll<<61;

using namespace std;

//vector<pair<int,int> > G;
//typedef pair<int,int> P;
//vector<pair<int,int>> ::iterator iter;
//
//map<ll,int>mp;
//map<ll,int>::iterator p;
//

const int Times=12;

#define IN freopen("c:\\Users\\linzuojun\\desktop\\input.txt", "r", stdin)
#define OUT freopen("c:\\Users\\linzuojun\\desktop\\output.txt", "w", stdout)

ll ans;

ll random(ll n)
{
	return (ll)((double)rand()/RAND_MAX*n+0.5);
}

ll multi(ll a,ll b,ll m)
{
	ll ans=0;
	while(b>0)
	{
		if(b&1)
			ans=(ans+a)%m;
		b>>=1;
		a=(a<<1)%m;
	}
	return ans;
}

ll quick(ll a,ll b,ll m)
{
	ll ans=1;
	a%=m;
	while(b)
	{
		if(b&1)
		{
			ans=multi(ans,a,m);
			b--;
		}
		b>>=1;
		a=multi(a,a,m);
	}
	return ans;
}

bool witness(ll a,ll n)
{
	ll m=n-1;
	int j=0;
	while(!(m&1))
	{
		j++;
		m>>=1;
	}
	ll x=quick(a,m,n);
	if(x == 1 || x == n-1)
		return 0;
	while(j--)
	{
		x=x*x%n;
		if(x == n-1)
			return 0;
	}
	return 1;
}

bool miller_rabin(ll n)
{
	if(n<2)return 0;
	if(n==2)return 1;
	if(!(n&1))return 0;
	for(int i=1;i<=Times;i++)
	{
		ll a=rand()%(n-2)+1;
		if(witness(a,n))return 0;
	}
	return 1;
}

/*********************以上为miller素数测试法************************/
ll Gcd(ll a,ll b)
{
	return b==0?a:Gcd(b,a%b);
}

ll Pollard_rho(ll n,ll c)
{
	ll i=1,k=2,x=random(n),y=x;
	while(1)
	{
		i++;
		x=(multi(x,x,n)+c)%n;
		ll gcd=Gcd(y-x,n);
		if(gcd > 1 && gcd < n)return gcd;
		if(x==y)return n;
		if(i==k)
		{
			y=x;
			k<<=1;
		}
	}
}

void dfs(ll n,ll c)
{
	if(n==1)return;
	if(miller_rabin(n))
	{
		if(ans>n)
			ans=n;
		return;
	}
	ll m=n;
	while(m==n)
	{
		m=Pollard_rho(n,c--);
	}
	dfs(m,c);
	dfs(n/m,c);
}

int main(void)
{
	int t;
	ll n;
	cin>>t;
	while(t--)
	{
		cin>>n;
		if(miller_rabin(n))
		{
			puts("Prime");
			continue;
		}
		ans=inf;
		dfs(n,240);
		cout<<ans<<endl;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值