逆元
- 逆元定义:给定正整数 a , p a,p a,p,如果有 a x ≡ 1 ( m o d p ) ax\equiv1\pmod{p} ax≡1(modp),且 a a a 与 p p p 互质,则称 x x x 的最小正整数解为 a a a 模 p p p 的逆元。
证明:
Δ a ≡ Δ a ( m o d p ) \frac{\Delta}{a} \equiv \frac{\Delta}{a} \pmod{p} aΔ≡aΔ(modp)
Δ a ≡ Δ ⋅ a − 1 ( m o d p ) \frac{\Delta}{a} \equiv \Delta \cdot a^{-1} \pmod{p} aΔ≡Δ⋅a−1(modp)
x = a − 1 x = a ^ {-1} x=a−1
Δ a ≡ Δ ⋅ x ( m o d p ) \frac{\Delta}{a} \equiv \Delta \cdot x \pmod{p} aΔ≡Δ⋅x(modp)
Δ ≡ Δ ⋅ x ⋅ a ( m o d p ) \Delta \equiv \Delta \cdot x \cdot a \pmod{p} Δ≡Δ⋅x⋅a(modp)
1 ≡ a ⋅ x ( m o d p ) 1 \equiv a \cdot x \pmod{p} 1≡a⋅x(modp)
1 ≡ a ⋅ a − 1 ( m o d p ) 1 \equiv a \cdot a ^ {-1}\pmod{p} 1≡a⋅a−1(modp)
a ⋅ a − 1 ≡ 1 ( m o d p ) a \cdot a ^ {-1} \equiv 1\pmod{p} a⋅a−1≡1(modp)
a x ≡ 1 ( m o d p ) ax \equiv 1\pmod{p} ax≡1(modp)
得证。
- 裴蜀定理
若 a , b a,b a,b 为整数且 g c d ( a , b ) = d gcd(a,b) = d gcd(a,b)=d,那么对于任意整数 x , y x,y x,y, a x + b y ax+by ax+by 都一定为 d d d 的倍数。特别的,一定存在 x , y x,y x,y 使得 a x + b y = d ax + by = d ax+by=d 成立。
- e x g c d exgcd exgcd
a
m
o
d
b
=
=
a
−
a
b
⋅
b
a \bmod b == a - \frac{a}{b} \cdot b
amodb==a−ba⋅b
b
⋅
x
1
+
a
m
o
d
b
⋅
y
1
=
d
b \cdot x1 + a \bmod b \cdot y1 = d
b⋅x1+amodb⋅y1=d
b
⋅
x
1
+
(
a
−
a
b
⋅
b
)
⋅
y
1
=
d
b \cdot x1 + (a - \frac{a}{b} \cdot b) \cdot y1 = d
b⋅x1+(a−ba⋅b)⋅y1=d
b
⋅
x
1
+
a
⋅
y
1
−
a
b
⋅
b
⋅
y
1
=
d
b \cdot x1 + a \cdot y1 - \frac{a}{b} \cdot b \cdot y1 = d
b⋅x1+a⋅y1−ba⋅b⋅y1=d
a
⋅
y
1
+
b
⋅
(
x
1
−
a
b
⋅
y
1
)
=
d
a \cdot y1 + b \cdot (x1 - \frac{a}{b} \cdot y1) = d
a⋅y1+b⋅(x1−ba⋅y1)=d
int exgcd(int a,int b,int &x,int &y) {
if (b == 0) {
x = 1,y = 0;
return a;
} else {
int d,x1,y1;
d = exgcd(b,a % b,x1,y1);
/*
a % b == a - (a / b) * b
b * x1 + a % b * y1 = d
b * x1 + [a - (a / b) * b] * y1 = d
b * x1 + a * y1 - (a / b) * b * y1 = d
a * y1 + b *(x1 - a / b * y1) = d
*/
x = y1,y = x1 - a / b * y1; // a * y1 + b * (x1 - a / b * y1) = d
}
}