本文介紹\(O(n)\)處理\([1, n]\)在模\(P\)意義下的逆元的方法。ui
\[inv_i \equiv -\lfloor \frac{P}{i} \rfloor * inv_{(P \bmod i)} \pmod P\]spa
如今要求\(i\)的逆元:class
設\(a = \lfloor \frac{P}{i} \rfloor, b = P \bmod i\),則方法
\[a * i + b \equiv 0 \pmod P\]
\[-a * i \equiv b \pmod P\]di
等式兩邊同除\(i * b\)得display
\[-a * inv[b] = inv[i]\]math
將\(a = \lfloor \frac{P}{i} \rfloor, b = P \bmod i\)代入上式得play
\[inv_i \equiv -\lfloor \frac{P}{i} \rfloor * inv_{(P \bmod i)} \pmod P\]