Euclidean algorithm for ℕ #
THIS FILE IS SYNCHRONIZED WITH MATHLIB4. Any changes to this file require a corresponding PR to mathlib4.
This file sets up a version of the Euclidean algorithm that only works with natural numbers.
Given 0 < a, b
, it computes the unique (w, x, y, z, d)
such that the following identities hold:
a = (w + x) d
b = (y + z) d
w * z = x * y + 1
d
is then the gcd ofa
andb
, anda' := a / d = w + x
andb' := b / d = y + z
are coprime.
This story is closely related to the structure of SL₂(ℕ) (as a free monoid on two generators) and the theory of continued fractions.
Main declarations #
xgcd_type
: Helper type in defining the gcd. Encapsulates(wp, x, y, zp, ap, bp)
. wherewp
zp
,ap
,bp
are the variables getting changed through the algorithm.is_special
: Stateswp * zp = x * y + 1
is_reduced
: Statesap = a ∧ bp = b
Notes #
See nat.xgcd
for a very similar algorithm allowing values in ℤ
.
A term of xgcd_type is a system of six naturals. They should be thought of as representing the matrix [[w, x], [y, z]] = [[wp + 1, x], [y, zp + 1]] together with the vector [a, b] = [ap + 1, bp + 1].
Instances for pnat.xgcd_type
- pnat.xgcd_type.has_sizeof_inst
- pnat.xgcd_type.inhabited
- pnat.xgcd_type.has_sizeof
- pnat.xgcd_type.has_repr
Equations
- pnat.xgcd_type.has_sizeof = {sizeof := λ (u : pnat.xgcd_type), u.bp}
The has_repr instance converts terms to strings in a way that reflects the matrix/vector interpretation as above.
The map v gives the product of the matrix [[w, x], [y, z]] = [[wp + 1, x], [y, zp + 1]] and the vector [a, b] = [ap + 1, bp + 1]. The map vp gives [sp, tp] such that v = [sp + 1, tp + 1].
is_reduced holds if the two entries in the vector are the same. The reduction algorithm will produce a system with this property, whose product vector is the same as for the original system.
Equations
- u.is_reduced = (u.ap = u.bp)
Equations
- u.is_reduced' = (u.a = u.b)
The following function provides the starting point for our algorithm. We will apply an iterative reduction process to it, which will produce a system satisfying is_reduced. The gcd can be read off from this final system.
We will apply the above step recursively. The following result is used to ensure that the process terminates.
The reduction step does not change the product vector.
We can now define the full reduction function, which applies step as long as possible, and then applies finish. Note that the "have" statement puts a fact in the local context, and the equation compiler uses this fact to help construct the full definition in terms of well-founded recursion. The same fact needs to be introduced in all the inductive proofs of properties given below.
Equations
- a.xgcd b = (pnat.xgcd_type.start a b).reduce