We discuss the Euclidean algorithm and use it to compute the multiplicative inverse.
Multiplicative Inverse.
Given x,y∈N+, z is called the multiplicative inverse of x (module y) if
xz≡1(mody).
Theorem 1
x has a multiplicative inverse module y⟺gcd(x,y)=1.
Proof.
Define the set S={ax+by∣a,b∈Z}. Let d=a∗x+b∗y be the smallest positive integer in S. Our proof relies on the following lemma.
Lemma: gcd(x,y)=d.
First, as d is a linear combination of x and y, gcd(x,y)∣d and gcd(x,y)≤d.
Second, we claim that d∣x and d∣y. By symmetry, we prove only the former. If not, suppose that d∤x. Then ∃k∈Z,ℓ∈[1,d−1], s.t.,
x=kd+ℓ.Since ℓ=x−kd is a linear combination of x and y, it holds that ℓ∈S, contradicting d being the smallest positive element in S.
It concludes that d equals to gcd(x,y).
□
The proof of the above theorem immediately follows from the lemma.
-
gcd(x,y)=1→x has a multiplicative inverse.
In this case, d=a∗x+b∗y=1. a∗ is th multiplicative inverse of x module y.
-
x has a multiplicative inverse →gcd(x,y)=1.
If x has a multiplicative inverse, there exists some z and l, such that zx=ly+1.
■
Theorem 2
If x has a multiplicative inverse module y, it is unique.
Proof.
Let a and b both be the multiplicative inverse of x module y, then
a≡a(xb)≡(ax)b≡b(mody)■
Basic Euclidean Algorithm
Euclidean algorithm computes gcd(x,y) as follows:
unsigned gcd(unsigned x, unsigned y) {
if(y == 0) return x;
return gcd(y, x % y);
}
Correctness
If y=0, whether x=0 or not, we have gcd(x,y)=x.
If x<y, xmody=x. The algorithm exchanges x and y at the first recursion. It suffices to consider only x≥y>0.
If x≥y>0, then gcd(x,y)=gcd(y,xmody). Let d=gcd(x,y). Clearly d∣x and d∣y. We claim that
d∣(xmody)Suppose x=kd and y=ℓd, then xmody=d⋅(kmodℓ), which finishes proof.
Time
Let n be the the total number of bits to represent x and y. Then the algorithm stops after O(n) recursions.
Proof.
We can assume x≥y. Otherwise, they are swapped by a recursive call.
The key observation is that, after every two recursive calls, the first argument x shrinks at least by a factor of two.
- If y≤x/2, the observation holds after the first call.
- If y>x/2, then after two recursive call, the first argument becomes xmody, which is smaller than x/2.
□
Extended Euclidean Algorithm
We extend the basic version to return a pair a∗,b∗∈N s.t. gcd(x,y)=d=a∗x+b∗y.
std::pair<unsigned, unsigned> gcd(unsigned x, unsigned y) {
if(y == 0) return {1, 0};
auto (a', b') = gcd(y, x mod y);
return (b', a' - b' * (x / y));
}
Correctness
Suppose s=a′y+b′⋅(xmody). Then
s=a′y+b′(x−⌊x/y⌋⋅y)=b′x+(a′−b′⋅⌊x/y⌋)⋅yThis is why the algorithm work.
□
Example
gcd(9,6)=(3,1,−1)[−1=0−1∗9/6]→gcd(6,3)=(3,0,1)[1=1−0∗6/3]→gcd(3,0)=(3,1,0)