线性求逆元

1.现状与不足
众所周知,快速幂求逆元是\(O(log)\)的。
在一些无良题目中,求逆次数过多,但数不大,需要预处理。
此时,我们就需要线性求逆了。
2.推导
设模数\(p=k \times i+r\)
因此\(k \times i+r≡0(mod \ \ p)\)
同乘\((i^{-1} \times r^{-1})\)
\(k \times r^{-1}+i^{-1}≡0(mod \ \ p)\)
又得\(i^{-1}≡-k \times r^{-1}(mod \ \ p)\)
更兼\(k=\lfloor \frac{k \times i+r}{i} \rfloor=\lfloor \frac{p}{i} \rfloor\)
\(r^{-1}={(p \ \ mod \ \ i)}^{-1}\)
\(i^{-1}≡\lfloor \frac{p}{i} \rfloor \times {(p \ \ mod \ \ i)}^{-1}\)
用数组存起来,便是\(inv[i]≡\lfloor \frac{p}{i} \rfloor \times inv[(p \ \ mod \ \ i)]\)
3.更多操作
预处理\({(x!)}^{-1},x≤{10}^{7}\)
先预处理\(inv\)数组(意义如上),\({(x!)}^{-1}={((x-1)!)}^{-1} \times {x}^{-1} \ \ mod \ \ p\)

原文地址:https://www.cnblogs.com/HYDcn666/p/15535942.html