跳到正文

算法·理论

乘法逆元

IKUN314约 31 分钟
原文
文章信息与版本

文章信息

发布
2023年7月12日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 31 分钟
获赞
6

版本

  1. v1当前

upd at 2023/12/232023/12/23 21:3021:30:

  1. 删去了伪代码中的 (new)⁡_{\operatorname{(new)}},它们太多余;
  2. 更改了伪代码中 for 循环的表现方式,使其更像数学而非代码;
  3. 添加了筛法求逆元。

乘法逆元

定义

数 aa 模 pp 意义下的乘法逆元(Modular Multiplicative Inverse\texttt{Modular Multiplicative Inverse})被定义为 线性同余方程 ax≡1(modp)ax\equiv 1 \pmod p的解。

条件

gcd⁡(a,p)=1\gcd(a,p)=1是数 aa 在模 pp 意义下存在乘法逆元的充分必要条件。

求法

1.扩展欧几里得法

既然乘法逆元是线性同余方程的解,那么使用扩展欧几里得算法(Extended Euclidean algorithm, EXGCD)(\texttt{Extended Euclidean algorithm, EXGCD})求出方程的通解。再经转换即可求出特解。

过程

将同余方程 ax≡1(modp)ax\equiv 1 \pmod p 改写为如下形式

ax+py=1(1)\begin{aligned} ax+py &=1 &(1) \end{aligned}

其中x,yx,y是未知数。显然,这两个方程是等价的。

由裴蜀定理可得,方程ax≡b(modp)ax\equiv b \pmod p 有整数解的充分必要条件是 gcd⁡(a,p)∣1\gcd(a,p)\mid 1 ,且容易将其转换为: gcd⁡(a,p)=1\gcd(a,p)=1

也就是说,满足如下条件时,才能使用扩展欧几里得算法求解逆元:

gcd⁡(a,p)=1\gcd(a,p)=1

即需要 a,pa,p 互质。

所以我们可将等式(1)(1)再次改写为

ax+py=gcd⁡(a,p)ax+py=\gcd(a,p)

这就化为扩欧求解方程的一般形式 ax+by=gcd⁡(a,b)ax+by=\gcd(a,b) 了。接下来使用扩欧求解即可

设:ax1+py1=gcd⁡(a,p)px2+(a mod p)y2=gcd⁡(p,a mod p)∵ 由欧几里得定理知 gcd⁡(a,p)=gcd⁡(p,a mod p)∴ ax2+py1=px2+(a mod p)y2∵ a mod p=a−⌊ap⌋p∴ ax1+py1=px2+(a−⌊ap⌋p)y2∴ ax1+py1=ay2+p(x2−⌊ap⌋y2)∵ a=a,p=p∴ 比对法可得{x1=y2,y1=x2−⌊ap⌋y2.\begin{aligned} \text{设}&:\\ &ax_{1}+py_{1}=\gcd(a,p)\\ &px_2+(a\bmod p)y_2=\gcd(p,a\bmod p)\\ \because&\space\text{由欧几里得定理知}\ \gcd(a,p)=\gcd(p,a\bmod p)\\ \therefore&\space ax_{2}+py_{1}=px_2+(a\bmod p)y_2\\ \because&\space a\bmod p=a-\lfloor\frac{a}{p}\rfloor p\\ \therefore&\space ax_1+py_1=px_2+\left(a-\lfloor\frac{a}{p}\rfloor p\right)y_2\\ \therefore\space &ax_1+py_1=ay_2+p\left(x_2-\lfloor\frac{a}{p}\rfloor y_2\right)\\ \because&\space a=a,p=p\\ \therefore&\space \text{比对法可得}\\ &\begin{cases} x_1=y_2,\\ y_1=x_2-\lfloor\frac{a}{p}\rfloor y_2. \end{cases} \end{aligned}

由此我们得到了 x1,y1x_1,y_1 与 x2,y2x_2,y_2之间的关系,又因为它们都与 gcd⁡(a,p)\gcd(a,p) 有关,所以只需要将 x2,y2x_2,y_2 在求gcd⁡(a,p)\gcd(a,p)的过程中一并计算,辗转相除直到 pi=0,gcd⁡(ai,pi)=aip_i=0,\gcd(a_i,p_i)=a_i 时返回x2=1,y2=0x_2=1,y_2=0 来递归求解即可求出在线性同余方程 ax≡1(modp)ax\equiv 1 \pmod p 中 xx 的通解。

求出通解 x0x_0 后,一个特解(最小正整数解 )即为

x=(x0 mod pgcd⁡(a,p)+pgcd⁡(a,p)) mod pgcd⁡(a,p)=(x0 mod p1+p1) mod p1=(x0 mod p+p) mod p.\begin{aligned} x&=\left(x_0\bmod \frac{p}{\gcd(a,p)}+\frac{p}{\gcd(a,p)}\right)\bmod \frac{p}{\gcd(a,p)}\\ &=\left(x_0\bmod \frac{p}{1}+\frac{p}{1}\right)\bmod \frac{p}{1}\\ &=\left(x_0\bmod p+p\right)\bmod p. \end{aligned}

aa 在模 pp 意义下的乘法逆元即为 xx 的值。

实现

以下是扩展欧几里得算法的伪代码

Extended Euclidean algorithm exgcd⁡(a,b,⇒x,⇒y):1Parameters. a,b∈Z+,b≠0. x and y are bit references.Denoting the a,b,x and y in the equation ax+by=gcd⁡(a,b).Initialize x←∅,y←∅2Return value. The GCD between a and b.Accompanying results x and y is the solution to the equation.3Method. 4if b=05x←16y←07return  a8result←exgcd⁡(b,a mod b,x,y)(At this point the values of x and y have changed.)9x2←x11y2←y12x←y213y←x2−⌊ab⌋y214return  result\begin{array}{ll} &\textbf{Extended Euclidean algorithm }\operatorname{exgcd}(\mathbf{a}, \mathbf{b}, ⇒{\mathbf{x}}, ⇒\mathbf{y})\text{:} \\ 1 & \textbf{Parameters. } a,b\in\mathbb{Z}^+,b\ne0.\space x \text{ and } y \text{ are bit references}.\\ & \text{Denoting the }a,b,x\text{ and }y\text{ in the equation } \boxed{ax+by=\operatorname{gcd}(a,b)}. \\ &\text{Initialize } x\gets\varnothing,y\gets\varnothing\\ 2 & \textbf{Return value. } \text{The GCD between }a\text{ and }b.\\ & \textbf{Accompanying results }x\text{ and }y \text{ is the solution to the equation}.\\ 3 & \textbf{Method. } \\ 4 & \textbf{if }b=0 \\ 5 & \qquad x\gets1 \\ 6 & \qquad y\gets0\\ 7 & \qquad \textbf{return }\ a \\ 8 & {result}\gets\operatorname{exgcd}\left(b,a\bmod b,x,y\right) \\ & (\texttt{At this point the values of }x\texttt{ and }y\texttt{ have changed}.)\\ 9 & x_{2 }\gets x\\ 11 & y_{2 }\gets y\\ 12 & x\gets y_2\\ 13 & y\gets x_2-\lfloor\dfrac{a}{b}\rfloor y_2\\ 14 & \textbf{return }\ result\\ \end{array}
复杂度

扩展欧几里得算法的时间复杂度与欧几里得算法(辗转相除法)无异,均为

O(log⁡p)\text{O}(\log p)
优劣
优势

扩展欧几里得法求解乘法逆元只需满足 gcd⁡(a,p)=1,\gcd(a,p)=1, 即原数与模数互质即可,而后文提到其他算法均,需另外要求 pp 为质数,即模数要为质数。

劣势
  • 扩展欧几里得法求解乘法逆元的过程较为复杂,记忆较困难。

  • 速度:大多使用递归实现辗转相除法,比其他迭代实现的算法常数要高一些,跑得慢。

  • 在求多个数逆元时必须多次运算,复杂度高,所以一般只能用于求出单个数的逆元。


2.快速幂法

当 gcd⁡(a,p)=1,\gcd(a,p)=1,p\boldsymbol{p}为质数 时,借助费马小定理(Fermat’s Little Theorem)(\texttt{Fermat's Little Theorem})可转化同余方程 ax≡1(modp)ax\equiv 1 \pmod p,得其通解 x0=ap−2x_0=a^{p-2}

费马小定理

若 pp 为质数,gcd⁡(a,p)=1\gcd(a,p)=1,则 ap−1≡1(modp).a^{p-1}\equiv1\pmod p.

要证明它需要两个引理


引理 1 在费马小定理的条件下,对于整数 a mod p,2a mod p,3a mod p,⋯ ,(p−1)a mod pa\bmod p,2a \bmod p,3a \bmod p,\cdots,(p-1)a \bmod p,它们正好组成一个 1∼p−11\sim p-1 的排列。

也就是说 a,2a,3a,⋯ ,(p−1)aa,2a,3a,\cdots,(p-1)a 这些整数对 pp 的余数互不相等,也不等于 00。否则,有

ja≡ka(modp),1≤j<k<p ja\equiv ka \pmod p,1\le j<k< p

由于 pp 为质数且 gcd⁡(a,p)=1\gcd(a,p)=1,可两边同时除以 aa 得到 j≡k(modp)j\equiv k\pmod p,这是不可能的。故引理得证。


引理 2:威尔逊定理 (p−1)!≡−1(modp)  ⟺  p 是质数(p-1)!\equiv -1\pmod p\iff p\text{ 是质数}

先证(左边对右边的)充分性。采用反证法,假设存在合数 pp 满足 (p−1)!≡−1(modp)(p-1)!\equiv -1\pmod p。合数一定可以分解因数,即

 d∣p (d∈[2,p−1])⇒(p−1)!≡0≢−1(modd)⇒(∗)(p−1)!≢−1(modp)\begin{aligned}&\space d\mid p\space(d\in[2,p-1])\\&\xRightarrow{} (p-1)!\equiv0\not\equiv-1&\pmod d \\&\xRightarrow{(\ast)} (p-1)!\not\equiv -1&\pmod p\end{aligned}

与已知矛盾,故假设不成立,定理充分性得证。

再证必要性。若 p=2p=2,显然成立。接下来讨论 p≥3p\ge 3 的情况。我们需要证明若 pp 是质数,1,2,…,p−11,2,\dots,p-1 内所有整数(实际上,这就是 pp 的一个除去 00 的简化剩余系)模 pp 意义下的乘积为 −1-1。

由于 pp 是质数,根据之前的讨论,任给 a∈[1,p−1]a\in [1,p-1],在同样的范围 [1,p−1][1,p-1] 内也存在其逆元 a−1a^{-1} 使得 aa−1≡1(modp)aa^{-1}\equiv 1\pmod p。同时注意到其中到还有逆元为本身的情况,解同余方程 a2≡1a^2 \equiv 1 得 a1=1≡1,a2=p−1≡−1a_1=1\equiv 1,a_2=p-1\equiv -1。

这也就是说,在[1,p−1][1,p-1] 内,1≡1, p−1≡−11\equiv 1,\space p-1\equiv -1,而 2,(3,)p≥4…,p−22,\underset{p\ge 4}{(3,)}\dots,p-2 内的任意一个整数都能在同样的范围内找到另一个整数——它的逆元,两两配对相乘得 aa−1≡1aa^{-1}\equiv 1。那么,1,2,…,p−11,2,\dots,p-1 内所有整数相乘,最后的结果就是 −1-1。定理必要性得证。

故证得威尔逊定理。

(∗)(*) 理由是同余式性质 a≡b(modp)d∣p}  ⟹  a≡b(modd)\left.\begin{matrix} a\equiv b \pmod p \\ d\mid p \end{matrix}\right\}\implies a\equiv b\pmod d 的逆否命题。


有了这两个引理,我们就能证明费马小定理。首先构造出引理 1中的序列 a,2a,3a,⋯ ,(p−1)aa,2a,3a,\cdots,(p-1)a,由引理 1与乘法运算的交换律可知,

∏k=1p−1ka≡∏k=1p−1k(modp)\prod_{k=1}^{p-1} ka\equiv \prod_{k=1}^{p-1} k {\pmod p}

即

ap−1(p−1)!≡(p−1)!(modp)a^{p-1}(p-1)!\equiv (p-1)! {\pmod p}

根据威尔逊定理,可推出 gcd⁡((p−1)!,p)=1\gcd\left(\left(p-1\right)!,p\right)=1,于是在上式可两边同时除以 (p−1)!(p-1)!,得到费马小定理

ap−1≡1(modp)a^{p-1}\equiv 1 {\pmod p}
过程
∵ 当 p 为质数时: ap−1≡1(modp) (费马小定理)又 ax≡1(modp)∴ ax≡ap−1(modp)∵ gcd⁡(a,p)=1∴ x≡ap−2(modp)\begin{aligned} \because&\space\text{当 } p\text{ 为质数时}:\\ &\space a^{p-1}\equiv1{\pmod p}\text{ (费马小定理)}\\ \text{又}&\space ax\equiv 1 \pmod p\\ \therefore&\space ax\equiv a^{p-1}\pmod{p}\\ \because&\space \gcd(a,p)=1\\ \therefore&\space x\equiv a^{p-2}\pmod{p} \end{aligned}

然后即可用快速幂求出 ap−2a^{p-2} 的值,即求出一个通解 x0x_0 了

在大部分情况下,a>0,,a>0, 所以此时 ap−2>0a^{p-2}>0 ,求不求特解都无所谓了。

实现

以下是快速幂法求解逆元的伪代码

Modular Multiplicative Inverse Solving Algorithm by Exponentiation‾‾1Fast Power Algorithm exponentiation⁡(a,b,p):2Parameters. a,b,p∈N+.Denoting the base a,the exponent b and the modulus p.3Returned value. the value of ab mod p4Method.5base←a6result←17while b>0 do8if 2∤b then9result←result⋅base mod p10base←base2 mod p11b←⌊b2⌋12end13return result14Multiplicative Inverse Solving Algorithm getInverse(a,p):15Parameters. a,p∈N+,a≠0,gcd⁡(a,p)=1,p is a prime.Denoting the coefficient a and the modulus p in the congruence equationax≡1(modp).16Returned value. the modular multiplicative inverse of a:  a−1,which is the solution to the congruence equationax≡1(modp).17Method.18result←exponentiation⁡(a,p−2,p) mod preturn result\begin{array}{ll} &\overline{\underline{\textbf{Modular Multiplicative Inverse Solving Algorithm by Exponentiation}}}\\ 1 & \textbf{Fast Power Algorithm } \operatorname{exponentiation}(\mathbf{a},\mathbf{b},\mathbf{p})\text{:}\\ 2 & \textbf{Parameters. } a,b,p\in\mathbb{N}^+.\\ & \text{Denoting the base } a,\text{the exponent }b\text{ and the modulus }p.\\ 3 & \textbf{Returned value. }\text{the value of }\boxed{a^b\bmod{p}}\\ 4 & \textbf{Method.}\\ 5 & {base}\gets a\\ 6 & result\gets 1\\ 7 & \textbf{while}\space b>0\space\textbf{do}\\ 8 & \qquad \textbf{if }2\nmid b\textbf{ then}\\ 9 & \qquad \qquad result\gets result\cdot base\bmod{p}\\ 10 & \qquad base\gets {base}^{2}\bmod p\\ 11 & \qquad b\gets\lfloor\dfrac{b}{2}\rfloor\\ 12 & \textbf{end}\\ 13 & \textbf{return } result\\\\ 14 & \textbf{Multiplicative Inverse Solving Algorithm }\text{getInverse(\textbf{a},\textbf{p}):}\\ 15 & \textbf{Parameters. } a,p\in\mathbb{N}^+,a\ne 0,\gcd(a,p)=1,p\text{ is a prime}.\\ & \text{Denoting the coefficient } a\text{ and the modulus }p \text{ in the congruence equation}\boxed{ax\equiv 1\pmod{p}}.\\ 16 & \textbf{Returned value. }\text{the modular multiplicative inverse of $a$: }\space a^{-1},\\ & \text{which is the solution to the congruence equation}\boxed{ax\equiv 1\pmod{p}}.\\ 17 & \textbf{Method.}\\ 18 & result\gets\operatorname{exponentiation}(a,p-2,p)\bmod{p}\\ & \textbf{return }result \end{array}
复杂度

快速幂求逆元的复杂度就是快速幂的复杂度,即

O(log⁡p)\text{O}(\log p)
优劣
优势

快速幂法求逆元十分容易记忆理解,代码难度小。使用迭代实现快速幂,常数小。

劣势
  • 局限性:只能用于求模数为质数情况下的逆元,局限性较大。

  • 还是只在求单个数逆元时快。


3.线性迭代法

为求出1,2,…,n1,2,\dots,n这nn个数中每个数 aa 在模 pp 意义下的逆元 a−1a^{-1} ,上文两种方法就很慢了,我们需要使用线性方法在O(n)\text{O}(n) 复杂度内求出每个数的逆元才不会超时。

过程
 对于正整数 a (1≤a≤n),有 p=a⌊pa⌋+p mod a∵ p≡0(modp)∴ a⌊pa⌋+p mod a≡0(modp) 将同余式两边同时乘以 a−1(p mod a)−1得到 ⌊pa⌋(p mod a)−1+a−1≡0(modp)∴ a−1≡−⌊pa⌋(p mod a)−1(modp)∵ 显然 1−1≡1(modp),且 p mod a<a 也就是说,正向递推求解a−1是可行的.∴ 可得出从a=1开始,a−1的递推式: a−1≡{1if a=1,−⌊pa⌋(p mod a)−1otherwise.\begin{aligned} &\space \text{对于正整数 }a\ (1\leq a\leq n),\text{有}\\ &\space p=a\lfloor\frac{p}{a}\rfloor+p\bmod a\\ \because&\space p\equiv 0\pmod{p}\\ \therefore&\space a\lfloor\frac{p}{a}\rfloor+p\bmod a\equiv 0\pmod{p}\\ &\space \text{将同余式两边同时乘以 }a^{-1}(p\bmod a)^{-1}\text{得到}\\ &\space \lfloor\frac{p}{a}\rfloor\left(p\bmod a\right)^{-1}+a^{-1}\equiv 0\pmod{p}\\ \therefore&\space a^{-1}\equiv - \lfloor\frac{p}{a}\rfloor\left(p\bmod a\right)^{-1}\pmod{p}\\ \because&\space \text{显然 }1^{-1}\equiv 1\pmod p,\text{且 }p\bmod a< a\\ &\space \text{也就是说,正向递推求解$a^{-1}$是可行的.}\\ \therefore&\space \text{可得出从$a=1$开始,$a^{-1}$的递推式}:\\ &\space a^{-1}\equiv\begin{cases} 1&\text{if }a=1,\\ -\lfloor\dfrac{p}{a}\rfloor\left(p\bmod a\right)^{-1}&\text{otherwise.} \end{cases} \end{aligned}

这样我们在已经迭代求出所有i−1(i<a)i^{-1}(i<a)的情况下就可以求出a−1a^{-1}的值了。

(!)(\textbf{!})但是,有一点需要注意:由于 C++ 取模运算的特殊性,被负数取模得到的值还是负数,这是我们绝对不想看到的,所以我们在具体代码实现时,需要将 −⌊pa⌋-\lfloor\dfrac{p}{a}\rfloor 改写为 (p−⌊pa⌋)\left(p-\lfloor\dfrac{p}{a}\rfloor\right) 来实现等价而不会出现负数的操作。

实现

以下是线性递推迭代求解逆元方法的伪代码

Linear Modular Multiplicative Inverse Solving Algorithm getInverses⁡(n,p):1Parameters. n,p∈N+,p is a prime.Denoting the number of factors n ,the modulus b2Returned value. An array that holds the inverse of each a.3Method.4inv(new)⁡1=1Note: invi=i−1,which denotes the inverse of i.5for i=2→n do6invi←(p−⌊pi⌋)⋅inv(p mod i) mod p7end8return inv\begin{array}{ll} & \textbf{Linear Modular Multiplicative Inverse Solving Algorithm }\operatorname{getInverses}(\textbf{n},\textbf{p}):\\ 1 & \textbf{Parameters. } n,p\in\mathbb{N}^+,p\text{ is a prime}.\\ & \text{Denoting the number of factors $n$ ,the modulus $b$}\\ 2 & \textbf{Returned value. } \text{An array that holds the inverse of each a}.\\ 3 & \textbf{Method.}\\ 4 & {inv}_{\operatorname{\textbf{(new)}}1}=1\\ & \texttt{Note:}\ {inv}_{i}=i^{-1}\texttt{,which denotes the inverse of }i.\\ 5 & \textbf{for }i=2\to n\textbf{ do}\\ 6 & \qquad {inv}_i\gets\left(p-\lfloor\dfrac{p}{i}\rfloor\right)\cdot{inv}_{(p\bmod i)}\bmod p\\ 7 & \textbf{end}\\ 8 & \textbf{return }inv \end{array}
复杂度

显然为

O⁡(n)\operatorname{O}(n)
优劣
优势

在要求序列1,2,…,n1,2,\ldots,n里每个数的乘法逆元时,扩欧法和快速幂法都需要O⁡(nlog⁡p)\operatorname{O}(n\log p)的复杂度来解决,此时O⁡(n)\operatorname{O}(n)的线性算法就占很大优势。另外线性递推算法在数据范围小且模数确定时还可以用于打表,贴到代码上O⁡(1)\operatorname{O}(1)就行了,嘻嘻。

劣势
  • 局限性:仅当模数为质数时,线性递推法才可用
  • 仅在求1,2,…,n1,2,\ldots,n的逆元时才占优势,偏要将递推式转为递归求解单个数逆元已知的复杂度上界仅为O(n3)⁡\operatorname{O(\sqrt[3]{n})},更优的算法有扩欧法和快速幂法。

4.阶乘逆推法

同样是求1,2,…,n1,2,\dots,n这nn个数中每个数 aa 在模 pp 意义下的逆元 a−1a^{-1},有没有一种更易于理解的方法呢?答案是肯定的。我们只需要利用逆元与原数相乘抵消成单位元的性质,即可利用阶乘求解。

过程
显然 i!−1=(i+1)!−1×(i+1),(1) i−1=(i−1)!i!=(i−1)!⋅i!−1(2)\begin{aligned} \text{显然}&\space{i!}^{-1}={(i+1)!}^{-1}\times(i+1),&(1)\\ &\space i^{-1}=\frac{(i-1)!}{i!}=(i-1)!\cdot {i!}^{-1}&(2) \end{aligned}

所以对于1,2,…,n1,2,\dots,n,我们先处理出11至nn的阶乘(模 pp 意义下),然后只需要跑一遍 扩展欧几里得 或 快速幂( pp 为质数时) 求出 n!−1n!^{-1},然后依据(1)(1)逆推就能依次求出(n−1)!−1,(n−2)!−1,…,2!−1,1!−1(n-1)!^{-1},(n-2)!^{-1},\ldots,2!^{-1},1!^{-1}的值,同时在迭代求出i!−1i!^{-1}后,由于i!,(i−1)!i!,(i-1)!已经被预处理出来了,即可用(2)(2)求出i−1i^{-1}.

实现

以下是阶乘逆推法求逆元的伪代码

Factorial Modular Multiplicative Inverse Solving Algorithm getInverses⁡(n,p):1Parameters. n,p∈N+,p is a prime.Denoting the number of factors n and the modulus p2Returned value. An array that holds the inverse of each a∈N+∩[1,n].3Method.4fac0←15fac1←1Note: faci=i!,which denotes the factorial of i.6for i=2→n do8faci=faci−1×i mod p9end9G←exgcd⁡(facn,p,x,y)10invfacn←(x mod p+p) mod p(i)It’s equivalent to the code below.‾10invfacn←facnp−2 mod p‾Note: invfaci=i!−1,which denotes the inverse of the factorial of i.11invn←invfacn×facn−1 mod pNote: invi=i−1,which denotes the inverse of i.12for i=n−1→1 do13invfaci=invfaci+1(i+1) mod p14invi=invfaci×faci−1 mod p15end16return inv\begin{array}{ll} & \textbf{Factorial Modular Multiplicative Inverse Solving Algorithm }\operatorname{getInverses}(\textbf{n},\textbf{p}):\\ 1 & \textbf{Parameters. } n,p\in\mathbb{N}^+,p\text{ is a prime}.\\ & \text{Denoting the number of factors $n$ and the modulus $p$}\\ 2 & \textbf{Returned value. } \text{An array that holds the inverse of each }a\in\mathbb{N_+}\cap[1,n].\\ 3 & \textbf{Method.}\\ 4 & {fac}_{0}\gets 1\\ 5 & {fac}_{1}\gets 1\\ & \mathtt{Note:}\ {fac}_{i}=i!\texttt{,which denotes the factorial of }i.\\ 6 & \textbf{for }i=2\to n\textbf{ do}\\ 8 & \qquad fac_i=fac_{i-1}\times i\bmod p\\ 9 & \textbf{end}\\ 9 & G_{}\gets\operatorname{exgcd}(fac_{n},p,x_{},y_{})\\ 10 & {invfac}_{n}\gets(x\bmod p+p)\bmod p\\ {(\mathbf{i})} &\overline{\texttt{It's equivalent to the code below.}}\\ \mathit{10} & \underline{invfac_{n}\gets fac_n^{p-2}\bmod p\hspace{1.3cm}}\\ & \mathtt{Note:}\ {invfac}_{i}=i!^{-1}\texttt{,which denotes the inverse of the factorial of }i.\\ 11 & inv_{n}\gets invfac_{n}\times fac_{n-1}\bmod p\\ & \mathtt{Note:}\ {inv}_{i}=i^{-1}\texttt{,which denotes the inverse of }i.\\ 12 & \textbf{for } i=n-1\to 1\textbf{ do}\\ 13 & \qquad invfac_i={invfac}_{i+1}(i+1)\bmod p\\ 14 & \qquad inv_i={invfac}_{i}\times {fac}_{i-1}\bmod p\\ 15 & \textbf{end}\\ 16 & \textbf{return }inv \end{array}
复杂度

求 n!−1n!^{-1} 的复杂度是O⁡(log⁡p)\operatorname{O}(\log p),求 n!n! 与迭代逆推的复杂度均为O⁡(n)\operatorname{O}(n),所以总复杂度是

O⁡(n+log⁡p)\operatorname{O}(n+\log p)
优劣

同线性迭代法.


5.前缀积逆推-求任意n个数逆元

首先我们注意到,使用阶乘逆推法时,由于是从 nn 开始逆推,并不依赖从 11 开始到 nn 的条件。其次,我们使用阶乘只是为了利用逆元与原数相消的性质,完全可以把阶乘 i!i! 看成是1,2,…,i1,2,\ldots,i的前缀积,那么我们就可以用前缀积的方式,将阶乘法推广,来求任意 nn 个数 a1,a2,…,ana_1,a_2,\ldots,a_n 各自的逆元.

过程
显然 (∏k=1iak)−1=(∏k=1i+1ak)−1×ai+1,(1) ai−1=∏k=1i−1ak∏k=1iak=(∏k=1i−1ak)(∏k=1iak)−1(2)\begin{aligned} \text{显然}&\space{\left({\prod_{k=1}^i{a_k}}\right)}^{-1}={{\left({\prod_{k=1}^{i+1}a_k}\right)}^{-1}}\times a_{i+1},&(1)\\ &\space a_i^{-1}=\frac{\prod_{k=1}^{i-1}a_k}{\prod_{k=1}^ia_k}=\left(\prod_{k=1}^{i-1}a_k\right)\left({\prod_{k=1}^{i}a_k}\right)^{-1}&(2) \end{aligned}

只需据(1)(2)(1)(2)逆推即可。我们把求积改为前缀积实现,即可大大优化算法。

实现

以下是前缀积逆推的伪代码

Prefix product Modular Multiplicative Inverse Solving Algorithm getInverses⁡(n,p,∗a):1Parameters. n,p∈N+,p is a prime,a is a pointer to the address of the first element of an array of n factors.Denoting the number of factors n ,the modulus p and the sequence a.2Returned value. An array that holds the inverse of each ai.3Method.4prod0←1Note: prodi=∏k=1iak,which denotes the ith⁡ prefix product in a.5for i=1→n do6prodi=prodi−1×ai mod p7end8G←exgcd⁡(prodn,p,x,y)9invprodn←(x mod p+p) mod p(i)It’s equivalent to the code below.‾9invprodn←prodnp−2 mod p‾Note: invprodi=(∏k=1iak)−1,which denotes the inverse of the prefix product of ai.10invn←invprodn×prodn−1 mod pNote: invi=ai−1,which denotes the inverse of ai.11for i=n−1→1 do12invprodi=invprodi+1⋅ai+1 mod p13invi=invprodi×prodi−1 mod p14end15return inv\begin{array}{ll} & \textbf{Prefix product Modular Multiplicative Inverse Solving Algorithm }\operatorname{getInverses}(\textbf{n},\textbf{p},\mathbf{{^*}a}):\\ 1 & \textbf{Parameters. } n,p\in\mathbb{N}^+,p\text{ is a {prime}},\text{$a$ is a \textbf{pointer} to the address of the first element of \textbf{an array of $n$ factors}}.\\ & \text{Denoting the number of factors $n$ ,the modulus $p$ and the sequence $a$.}\\ 2 & \textbf{Returned value. } \text{An array that holds the inverse of each }a_i.\\ 3 & \textbf{Method.}\\ 4 & {prod}_{0}\gets 1\\ & \texttt{Note:}\ prod_i={\prod_{k=1}^ia_k}\texttt{,which denotes the }i^{\operatorname{th}} \texttt{ prefix product in } a.\\ 5 & \textbf{for }i=1\to n\textbf{ do}\\ 6 & \qquad prod_i=prod_{i-1}\times a_i\bmod p\\ 7 & \textbf{end}\\ 8 & G\gets\operatorname{exgcd}(prod_{n},p,x,y)\\ 9 & {invprod}_{n}\gets(x\bmod p+p)\bmod p\\ {(\mathbf{i})} &\overline{\texttt{It's equivalent to the code below.}}\\ \mathit9 & \underline{invprod_{n}\gets prod_n^{p-2}\bmod p\hspace{1.3cm}}\\ & \texttt{Note:}\ {invprod}_{i}={\left(\prod_{k=1}^ia_k\right)}^{-1}\texttt{,which denotes the inverse of the prefix product of }a_i.\\ 10 & inv_{n}\gets invprod_{n}\times prod_{n-1}\bmod p\\ & \texttt{Note:}\ {inv}_{i}=a_i^{-1}\texttt{,which denotes the inverse of }a_i.\\ 11 & \textbf{for } i=n-1\to 1\textbf{ do}\\ 12 & \qquad invprod_i={invprod}_{i+1}\cdot a_{i+1}\bmod p\\ 13 & \qquad inv_i={invprod}_{i}\times {prod}_{i-1}\bmod p\\ 14 & \textbf{end}\\ 15 & \textbf{return }inv \end{array}
复杂度

类似阶乘法,为

O⁡(n+log⁡p)\operatorname{O}(n+\log p)
优劣
优势

前缀积逆推法能够快速求解任意 nn 个数的逆元,十分灵活。前文提到的所有。

劣势
  • 局限性:仅能模数为素数。
  • 需要用到单个数求逆元。

6.筛法求逆元

我们还有另外一种求 [1,n][1,n] 内所有数逆元,且只要求 gcd⁡(a,p)=1\gcd(a,p)=1 的方法。

因为 f(x)=x−1f(x)=x^{-1} 显然是一个完全积性函数,所以可以用筛法求出 [1,n][1,n] 内所有数的逆元。一般采用线性筛。

过程

具体地,首先初始化 inv1=1inv_1=1,然后在线性筛的过程中,使用扩展欧几里得算法求出质数的逆元 invpriiinv_{pri_i},然后使用完全积性转移到所有合数

invi⋅prij=invi⋅invprijinv_{i\cdot pri_j}=inv_i\cdot inv_{pri_j}

细节可见伪代码。

实现

以下是筛法求逆元的伪代码,使用线性筛(欧拉筛)。

Modular Multiplicative Inverse Solving Algorithm by Eular’s SievegetInverses⁡(n,p):1Parameters. n,p∈N+,p is a prime.Denoting the number of factors n and the modulus p2Returned value. An array that holds the inverse of each a∈N+∩[1,n].3Method.4invi←1Note: invi=i−1,which denotes the inverse of i.5for i=2→n do6if i is not marked then7put i in the end of P8G←exgcd⁡(i,p,x,y)9invi←(x mod p+p) mod p10endif11for j=P1,P2,⋯→Pn∧(i⋅j≤n) do12mark i⋅j13invi⋅j←invi⋅invj14if j∣i then15break this loop15endif16end17end18return inv\begin{array}{ll} & \textbf{Modular Multiplicative Inverse Solving Algorithm by Eular's Sieve}\operatorname{getInverses}(\textbf{n},\textbf{p}):\\ 1 & \textbf{Parameters. } n,p\in\mathbb{N}^+,p\text{ is a prime}.\\ & \text{Denoting the number of factors $n$ and the modulus $p$}\\ 2 & \textbf{Returned value. } \text{An array that holds the inverse of each }a\in\mathbb{N_+}\cap[1,n].\\ 3 & \textbf{Method.}\\ 4 & inv_i\gets 1\\ & \texttt{Note:}\ {inv}_{i}=i^{-1}\texttt{,which denotes the inverse of }i.\\ 5 & \textbf{for } i=2\to n \textbf{ do} \\ 6 & \qquad \textbf{if } i \text{ is not marked}\textbf{ then}\\ 7 & \qquad\qquad \text{put } i \text{ in the end of } P\\ 8 & \qquad\qquad G\gets \operatorname{exgcd}(i,p,x,y)\\ 9 & \qquad\qquad inv_i\gets (x\bmod p+p)\bmod p\\ 10 & \qquad \textbf{endif}\\ 11 & \qquad \textbf{for }j=P_1,P_2,\cdots\to P_n \wedge (i\cdot j\le n) \textbf{ do}\\ 12 & \qquad\qquad \text{mark } i\cdot j\\ 13 & \qquad\qquad inv_{i\cdot j}\gets inv_i\cdot inv_j\\ 14 & \qquad\qquad \textbf{if }j\mid i \textbf{ then}\\ 15 & \qquad\qquad\qquad \text{break this loop}\\ 15 & \qquad\qquad \textbf{endif}\\ 16 & \qquad \textbf{end}\\ 17 & \textbf{end}\\ 18 & \textbf{return } inv \end{array}
复杂度

线性筛本身是 O(n)\text{O}(n) 的,其中的 π(n)\pi(n) 个质数都要进行一次 O(log⁡p)\text{O}(\log p) 的 exgcd,因而总时间复杂度为

 Θ(n−π(n))+Θ(π(n)log⁡p)=Θ(n+π(n)log⁡p)=Θ(nlog⁡pln⁡n)≈O(n)\begin{aligned} &\space \Theta(n-\pi(n))+\Theta(\pi(n)\log p)\\ &=\Theta(n+\pi(n)\log p)\\ &=\Theta\left(\dfrac{n\log p}{\ln n}\right)\\ &≈\text{O}(n) \end{aligned}
优劣
优势

具有通用性,仅要求 gcd⁡(a,p)=1\gcd(a,p)=1,对 pp 的素性不设限。

劣势

常数大:相对于线性迭代法与阶乘逆推法,筛法的 log⁡pln⁡n\dfrac{\log p}{\ln n} 是一个不小的常数。

7.在线Θ(1)\Theta(1)逆元

TODO\text{TODO}