Perhaps a better reading experience
\(Description\)
Given \ (A, B, P \) , seeking a \ (X \) to satisfy \ (a ^ x \ equiv b \ \ left (mod \ p \ right) \)
\(BSGS\)
\ (BSGS \) can be solved \ (P \) is a prime condition
so \ (m = \ lceil \ sqrt p \ rceil \)
令 \(x=i\cdot m-k\)
有 \(a^{i\cdot m-k} \equiv b\ (mod\ p)\)
Both sides of the passenger \ (a ^ k \) to give \ (a ^ {i \ cdot m} \ equiv b \ cdot a ^ k \ (mod \ p) \)
We first right \ (b \ cdot a ^ k \) all to seek out a stored table, the time complexity is thus pretreated \ (\ sqrt p \)
After the re-enumeration \ (I \) to \ (\ sqrt P \) , see table there is no \ (^ A {I \ CDOT m} \ MOD \ P \) , there is available a set of solutions
Then reverse calculated \ (x \) to
\(EXBSGS\)
When \ (P \) is not a prime number upon
command \ (g = gcd (a,
p) \) has \ (a ^ {x-1 } \ cdot \ dfrac {a} {g} \ cdot g \ equiv \ dfrac { b} {g} \ cdot g
\ \ left (mod \ \ dfrac {p} {g} \ cdot g \ right) \) to the \ (G \) remove
\ (a ^ {x-1 } \ cdot \ dfrac {a} {g}
\ equiv \ dfrac {b} {g} \ \ left (mod \ \ dfrac {p} {g} \ right) \) and repeat the process until \ (a, p \) mutual quality
\ (P \) remove \ (gcd (a, p) \) after and may still \ (A \) has a common divisor, and \ (\ frac {a} { gcd (a, p)} \) coprime
Obviously, in this process if \ (p \) can not be \ (b \) is divisible no solution
Finally, to get this equation
\ (XI A ^ {} \ CDOT C \ equiv T \ \ left (MOD \ P \ right) \)
\ (C \) is \ (A \) divided by a power of several the resulting factor \ (c, t \) definitely prime
sides multiplied by \ (C ^ {-}. 1 \) (inverse)
\ (XI a ^ {} \ equiv T \ CDOT C ^ {-}. 1 \ \ left (mod \ p \ right)
\) with \ (BSGS \) to \ (xi \) solver can
finally remember plus \ (i \)
\(Code\)
\(BSGS\)
ksm(a,b);//return a^b
gcd(a,b);//return gcd(a,b)
//{{{bsgs
int bsgs (int a,int b,int p)//return a^x ≡ b mod p 's x
{
a%=p;
if (!a&&!b) return 1;
if (!a) return -1;
int m=sqrt(p);
map <int,int> mp;//这里用的map 也可以自己打个哈希
int t=b%p;
mp[t]=0;
for (int i=1;i<=m;++i) mp[t=1ll*t*a%p]=i;
t=1;
int mi=ksm(a,m);
for (int i=1;1ll*i*i<=p+1;++i){
t=1ll*t*mi%p;
if (mp.count(t)) return ((1ll*i*m%p-mp[t])%p+p)%p;
}
return -1;
}
//}}}
\(EXBSGS\)
//{{{exbsgs
int exbsgs (int a,int b,int p)//a^x ≡ b mod p 's x
{
if (b==1) return 0;
int cnt=0,t=1;
for (int g=gcd(a,p);g!=1;g=gcd(a,p)){
if (b%g) return -1;
++cnt,b/=g,p/=g;
t=1ll*t*a/g%p;
if (b==t) return cnt;
}
int x=bsgs(a,1ll*ksm(t,p-2)*b%p,p);
if (x!=-1) x+=cnt;
return x;
}
//}}}
If not quite understand where to put it or there is an error, please correct me
if you like, you may wish to point a collection of praise about it