数论二次总结

大模板在此。(可能有错)。

LL fast(LL a,LL b,LL c){LL ans=1;for(;b;a=a*a%c,b>>=1)if(b&1)ans=ans*a%c;return ans;}
LL mul(LL a,LL b,LL c){return ((a*b-((LL)((long double)a/c*b+1e-8))*c)+c)%c;}
void exgcd(LL a,LL b,LL& d,LL& x,LL& y){
	if(!b)return (void)(d=a,x=1,y=0);
	LL t=x;x=y;y=t-a/b*x;
}
LL inv(LL a,LL p){
	LL x,y,d;
	exgcd(a,p,d,x,y);
	return d>1?-1:(x%p+p)%p;
}
LL china(LL* m,LL* a,int n){//exgcd合并方程
	LL M=m[1],A=a[1],b,k,y,d;
	up(i,2,n){
		b=a[i]-A;
		exgcd(M,m[i],d,k,y);
		if(b%d)return -1;
		k*=b/d;
		A+=k*M;
		M=M*m[i]/d;
		A=(A%+M)%M;
	}
	return A;
}
LL gcd(LL a,LL b){return !b?a:gcd(b,a%b);}
bool rabin_miller(LL a,LL p){
	if(!(p&1)||p<=1)return 0;
	LL d=p-1,m;
	if(!(d&1))d>>=1;
	m=fast(a,d,p);
	if(m==1)return 1;
	for(;d<p;m=m*m%p,d<<=1)if(m==p-1)return 1;
	return 0;
}
bool isprime(LL p){
	static int prime[10]={2,3,5,7,11,13,17,19,23,29};
	up(i,0,9){
		if(prime[i]==p)return 1;
		if(!rabin_miller(prime[i],p))return 0;
	}
	return 1;
}
LL fac[maxn],cnt=0;
void get(LL x){
	if(isprime(x)){fac[++cnt]=x;return;}
	int c=3;
	while(true){
		LL x1=1,x2=1,k=2,i=1,d;
		while(true){
			x1=((x1*x1%mod)+c)%mod;
			d=gcd(abs(x1-x2),x);
			if(d>1){get(d),get(x/d);return;}
			if(x1==x2)break;
			if(++i==k)k<<=1,x2=x1;
		}
		c++;
	}
}
LL log_mod(LL a,LL b,LL mod){
	LL ret=1;
	up(i,0,50){
		if(ret==b)return i;
		ret=ret*a%mod;
	}
	LL g=0,d,D=1,tmp;
	while((d=gcd(a,mod))!=1){
		if(b%d)return -1;
		mod/=d,b/=d;
		g++;b/=D=D*(a/d)%mod;
	}
	map<LL,LL> t;
	LL m=(LL)sqrt(mod+1.0),v,e;
	v=inv(fast(a,m,mod),mod);
	t[1]=0;
	up(i,0,m-1){
		e=e*a%mod;
		if(!t.count(e))t[e]=i;
	}
	up(i,0,m-1){
		if(t.count(b))return i*m+t[b]+g;
		b=b*v%mod;
	}
	return -1;
}

  

原文地址:https://www.cnblogs.com/chadinblog/p/6406846.html