扩展欧几里得算法
Extended Euclidean Algorithm (eGCD).
Euclidean Algorithm (辗转相除法) is one of the oldest and most widely known algorithms. It is a
According to Bezout's Identity, there exists integers
Assuming two adjacent levels in the GCD recursive process:
| current |
current |
current |
current |
|---|---|---|---|
| unknown |
unknown |
||
| known |
known |
Therefore
Code Implementation
int exgcd(int a, int b, int& x, int& y) {
if (b == 0) {
x = 1, y = 0;
return a;
}
int gcd = exgcd(b, a % b, x, y);
int _x = x;
x = y, y = _x - y * a / b; // from the above equities
return gcd;
}
Using eGCD to get Inverse
Given
Run the above function exgcd(b,N,x,y), we could obtain
不得不感叹聪明的人与时代无关。这一这么古老的算法也花了我一段时间去弄懂。
无论是 GCD 还是 exGCD,其核心在于欧几里得公式
这里提供一个非正式的证明:首先是一个基本事实:对于互质的
那么对于任意正整数