【模板】Miller-Rabin素性測試與Pollard-Rho因數分解

#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long LL;
const int prim[]={2,3,5,7,11,13,17,19,23,29};
inline LL Add(LL a,LL b,LL mod)
{
	LL ret=0;
	while(b)
	{
		if(b&1)
			ret=(ret+a)%mod;
		a=(a+a)%mod;
		b>>=1;
	}
	return ret;
}
inline LL Pow(LL a,LL b,LL mod)
{
	LL ret=1;
	while(b)
	{
		if(b&1)
			ret=Add(ret,a,mod);
		a=Add(a,a,mod);
		b>>=1;
	}
	return ret;
}
inline LL gcd(LL x,LL y)
{
	return y==0?x:gcd(y,x%y);
}
inline bool M_R(LL x,LL p,LL y)
{
	LL x1=Pow(p,y,x);
	if(x1==1||x1==x-1)
		return 1;
	while(y!=x-1)
	{
		x1=Add(x1,x1,x);
		if(x1==x-1)
			return 1;
		if(x1==1)
			return 0;
		y<<=1;
	}
	return 0;
}
inline bool P(LL x)
{
	for(int i=0;i<10;i++)
		if(x==prim[i])
			return 1;
		else if(x%prim[i]==0)
			return 0;
	LL x1=x-1;
	while(x1%2==0)
		x1/=2;
	for(int i=0;i<10;i++)
		if(!M_R(x,prim[i],x1))
			return 0;
	return 1;
}
inline LL P_R(LL n)
{
	LL c=rand()%(n-1)+1;
	LL x=rand()%n,y=x,p=1,k=2;
	for(int i=1;p==1;i++)
	{
		x=(Add(x,x,n)+c)%n;
		p=x>y?x-y:y-x;
		p=gcd(p,n);
		if(i==k)
			y=x,k<<=1;
	}
	return p;
}
int main()
{
	
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章