# 欧几里得算法(GCD)

$gcd(a,b) = gcd(b, a \% b)$

# 扩展欧几里得算法(EXGCD)

## 求特解

$b = 0$时，$gcd(a,0) = a$，故解得$x = 1, y = 0$

$\begin{cases} ax_1 + by_1 = gcd(a,b) \\ bx_2 + (a\%b)y_2 = gcd(b,a\%b) \end{cases}$

\begin{aligned} ax_1 + by_1 &= bx_2 + (a\%b)y_2 \\ &= bx_2 + (a - \left \lfloor a / b \right \rfloor*b)y_2 \\ &= bx_2 + ay_2 - \left \lfloor a / b \right \rfloor*by_2 \\ &= ay_2 + b(x_2 - \left \lfloor a / b \right \rfloor y_2) \end{aligned}

$\begin{cases} x_1 = y_2 \\ y_1 = x_2 - \left \lfloor a / b \right \rfloor * y_2 \\ \end{cases}$

void exgcd(int a, int b, int &g, int &x, int &y){
if(!b){
g = a; x = 1, y = 0;
return;
}
exgcd(b,a%b,g,y,x);
y -= x*(a/b);
}


## 求线性不定方程

$ax + by = c$

### 裴蜀定理

$ax+by=c$有解当且仅当$gcd(a,b)|c$

### 求特解

$\begin{cases} x' = x * c / gcd(a,b) \\ y' = y * c / gcd(a,b) \end{cases}$

## 求线性同余方程

$ax≡b\ (mod\ m)$

# 费马小定理

$P$为质数时，对正整数$a$

$a^{P-1} \equiv 1 \pmod P$

# 欧拉定理

$a^{\varphi(P)} \equiv 1 \pmod P, a \perp P$

$a^b \bmod P = a^{b \bmod \varphi(P)} \bmod P$

# 扩展欧拉定理

$a^b \bmod P = \begin{cases}a^b \bmod P & b < \varphi(P) \\a^{\left (b \bmod \varphi(P) \right ) + \varphi(P)} \bmod P & b \geq \varphi(P)\end{cases}$

# 乘法逆元

$P = k \ast i + r$，有$$k * i + r ≡ 0 \pmod P$$。记为$a^{-1}$$inv(a)$

\begin{aligned} k * i * i^{-1} * r ^ {-1} + r * i^{-1} * r^{-1} ≡ 0 \pmod P \\ k * r^{-1} + i^{-1} ≡ 0 \pmod P \\ i^{-1} ≡ -\left \lfloor \dfrac{p}{i} \right \rfloor * (p \% i)^{-1} \pmod P \\ \end{aligned}

# 扩展中国剩余定理(EXCRT)

$\left \{ \begin{matrix} x ≡ a_1 \pmod {m_1} \\ x ≡ a_2 \pmod {m_2} \\ \cdots \\ x ≡ a_r \pmod {m_r} \\ \end{matrix}\right.$

$ans+k \ast M \equiv a_i \pmod {m_i}$

inline int EXCRT(){
int ans=a[1],M=m[1],g,x,y,c;
for(int i = 2; i <= n; ++i){
c = (a[i]-ans%m[i]+m[i])%m[i];
exgcd(M,m[i],g,x,y);
if(c%g != 0) return -1;
x = qmul(x,c/g,m[i]);
ans += x*M;
M *= m[i]/g;
ans = (ans+M)%M;
}
return ans;
}

posted @ 2019-11-08 07:56  DennyQi  阅读(213)  评论(0编辑  收藏  举报