[模板] BSGS/扩展BSGS

简介

前置知识: 快速幂&&O(1)快速乘 [模板] 数学基础:快速幂/乘/逆元/exGCD/(ex)CRT/(ex)Lucas定理

[A^x≡B pmod p ]

的最小非负整数解. 容易发现 (x le phi (p)).

BSGS

((A,p) = 1).

代码

ll hb=25;
ll qmul(ll a,ll b){
	ll l=a*(b>>hb)%m*(1ll<<hb)%m;
	ll r=a*(b&((1<<hb)-1))%m;
	return (l+r)%m;
}
ll qp(ll a,ll b){
	ll res=1;
	while(b){
		if(b&1)res=qmul(res,a);
		a=qmul(a,a),b>>=1;
	}
	return res;
}

unordered_map<ll,ll> ha;

ll bsgs(ll a,ll b){//a^res = b mod m
	ll len=ceil(sqrt(m)),tmp=b;
	rep(i,0,len-1){
		ha[tmp]=i;
		tmp=qmul(tmp,a);
	}
	a=qp(a,len),tmp=a;
	rep(i,1,len){
		if(ha.find(tmp)!=ha.end()){
//			ll s=ha[tmp];
			return i*len-ha[tmp];
		}
		tmp=qmul(tmp,a);
	}
	return -1;
}
原文地址:https://www.cnblogs.com/ubospica/p/10284490.html