定理:
(
∏
i
=
1
n
a
i
)
−
1
≡
∏
i
=
1
n
a
i
−
1
(
m
o
d
p
)
{\left(\prod\limits_{i=1}^{n}a_i\right)}^{-1}\equiv \prod\limits_{i=1}^{n}{a_i}^{-1} \pmod{p}
(i=1∏nai)−1≡i=1∏nai−1(modp)
证明:
∏
i
=
1
n
a
i
⋅
∏
i
=
1
n
a
i
−
1
=
∏
i
=
1
n
a
i
⋅
a
i
−
1
≡
∏
i
=
1
n
1
=
1
n
=
1
(
m
o
d
p
)
\prod\limits_{i=1}^{n}a_i\cdot\prod\limits_{i=1}^{n}{a_i}^{-1}= \prod\limits_{i=1}^{n}a_i\cdot {a_i}^{-1}\equiv \prod\limits_{i=1}^{n}1=1^n=1\pmod{p}
i=1∏nai⋅i=1∏nai−1=i=1∏nai⋅ai−1≡i=1∏n1=1n=1(modp)
(以上写法不正规,大致能理解就行)
于是就有定理成立。
应用:
给出 n n n个正整数 a i a_i ai,在线性时间内求出它们各自的乘法逆元。
令 s i = ∏ j = 1 i a j s_i=\prod\limits_{j=1}^{i}a_j si=j=1∏iaj,其递推式为 s i = s i − 1 ⋅ a i s_i=s_{i-1}\cdot a_i si=si−1⋅ai、 s 1 = a 1 s_1=a_1 s1=a1。
于是有: s i − 1 = ( ∏ j = 1 i a j ) − 1 {s_i}^{-1}={\left(\prod\limits_{j=1}^{i}a_j\right)}^{-1} si−1=(j=1∏iaj)−1, s i − 1 − 1 = ( ∏ j = 1 i − 1 a j ) − 1 ≡ ∏ j = 1 i − 1 a j − 1 ≡ a i ∏ j = 1 i a j − 1 ≡ a i ( ∏ j = 1 i a j ) − 1 = a i ⋅ s i − 1 ( m o d p ) {s_{i-1}}^{-1}={\left(\prod\limits_{j=1}^{i-1}a_j\right)}^{-1}\equiv\prod\limits_{j=1}^{i-1}{a_j}^{-1}\equiv a_i\prod\limits_{j=1}^{i}{a_j}^{-1}\equiv a_i{\left(\prod\limits_{j=1}^{i}a_j\right)}^{-1}=a_i\cdot{s_i}^{-1} \pmod{p} si−1−1=(j=1∏i−1aj)−1≡j=1∏i−1aj−1≡aij=1∏iaj−1≡ai(j=1∏iaj)−1=ai⋅si−1(modp)
(以上写法不正规,大概能理解就行)
也即: s i − 1 − 1 ≡ a i ⋅ s i − 1 ( m o d p ) {s_{i-1}}^{-1}\equiv a_i\cdot {s_i}^{-1} \pmod{p} si−1−1≡ai⋅si−1(modp)。
两边同时乘以 a i − 1 ⋅ s i − 1 {a_i}^{-1}\cdot s_{i-1} ai−1⋅si−1,得到 a i − 1 ≡ s i − 1 ⋅ s i − 1 ( m o d p ) {a_i}^{-1}\equiv s_{i-1}\cdot{s_i}^{-1}\pmod{p} ai−1≡si−1⋅si−1(modp)。
由于 s i s_i si是线性递推的,可以先求出 s n − 1 {s_n}^{-1} sn−1,再倒回来递推出所有的 a i − 1 {a_i}^{-1} ai−1和 s i − 1 {s_i}^{-1} si−1,即可。