浅谈逆元
Ruiqun2009
·
·
个人记录
逆元,是求解分数模模数问题的关键之一。比如下图:
\begin{matrix}
(1+2)\bmod7=3\\
(3-6)\bmod7=4\\
(2\times9)\bmod7=4\\
\dfrac25\bmod7=???
\end{matrix}
\color{#FADB14}{\text{Compile Error}}!
然而,\dfrac25\bmod7=6。
因为 \dfrac25=2\times5^{-1},又因为 5^{-1}\equiv3(\bmod7),所以 \dfrac25\bmod7=6。
\colorbox{#E74C3C}{\color{#ffffff}\text{为什么?}}
\begin{aligned}&
\because5\times3\equiv1(\bmod7)\\&
\therefore3\equiv\dfrac15(\bmod7)
\end{aligned}
等式两边同乘以 2 即可得到结论。
有两种 \Theta(\log p) 的求逆元的方法,详见此。
但是洛谷的这道模板题就卡扩展欧几里得和费马小定理,必须要线性:(我用 \Theta(n\log p) 的时间复杂度卡过了)
线性递推
这是一种 \Theta(n) 求 1\sim n 在 \bmod p 意义下的逆元方法。
第一种方法:
设
k=\lfloor\dfrac pi\rfloor,r=p\bmod i。
\begin{aligned}
\therefore p&=k\times i+r(1<i<r<p)\\
\therefore k\times i+r&\equiv 0(\bmod p)\\
\therefore k\times r^{-1}+i^{-1}&\equiv0(\bmod p)\\
\therefore i^{-1}&\equiv-k\times r^{-1}(\bmod p)\\
\therefore i^{-1}&\equiv-\lfloor\dfrac pi\rfloor\times(p\bmod i)^{-1}(\bmod p)
\end{aligned}
由于 p\bmod i<i,所以在求 i 的逆元时 p\bmod i 的逆元肯定已经求过了。
注意特判!1^{-1}\equiv1(\bmod p)。
提交记录
第二种方法:
阶乘逆元,也可以 \Theta(n) 求出。
公式:
\begin{matrix}
\text{若}\\
\begin{aligned}
fac[i]&\equiv(fac[i-1]\times i)\bmod p\\
ifac[i]&\equiv(ifac[i+1]\times(i+1))\bmod p\\
\end{aligned}\\
\text{则}\\
i^{-1}\equiv(fac[i-1]\times ifac[i])\bmod p\\
\end{matrix}
于是就做到了:\Theta(n) 阶乘逆元求法。
不知道还有没有什么做法。
如果是逆元求和的话分块应该也可以做,需要使用卷积,可以将时间复杂度压到 \Theta(\sqrt n\log n)。那个我还会发布文章让你们看看到底是如何解出来的。
最后提醒您:十年OI一场空,不开long long见祖宗。