Unverified Commit a582979e authored by stevebraveman's avatar stevebraveman Committed by GitHub
Browse files

Update bsgs.md

parent 833d0503
Loading
Loading
Loading
Loading
+26 −0
Original line number Diff line number Diff line
@@ -87,3 +87,29 @@ $\therefore r = 0$.


[BZOJ-1319](http://www.lydsy.com/JudgeOnline/problem.php?id=1319) 是一道模板题,代码可以在 [Steaunk的博客](https://blog.csdn.net/Steaunk/article/details/78988376) 中看到.


### 3.0 扩展篇

上文提到的情况是 $ c $ 为素数的情况,如果 $ c $ 不是素数呢?

这就需要用到扩展BSGS算法,不要求 $ c $ 为素数!

扩展BSGS用到了同余的一条性质:

令 $ d=gcd(a,c) ,a=m \times d,b=n \times d,p=k \times d$;
则 $ m \times d \equiv b \times d (mod c \times d) $ 等价于 $ m \equiv n(mod k) $
所以我们要先消除因子:
```cpp
d=1,num=0;
while(gcd(a,c)!=1){
    if(b%gcd(a,c)!=0) \\无解
    b\=gcd(a,c);
    c\=gcd(a,c);
    d*=a/gcd(a,c);
    num++;
}
```
消除完后,就变成了 $ d \times m^{x-num} \equiv n (mod k) $,令 $ x=i \times m+j+num $,后面的做法就和普通BSGS一样了。

注意,因为 $ i,j \le 0 $,所以 $ x \le num $ ,但不排除解小于等于 $ num $ 的情况,所以在消因子之前做一下 $ \Theta(\log_2 p) $ 枚举,直接验证 $ a^i mod c = b $ ,这样就能避免这种情况。