76 From the Identity to the CRT and Beta Function: One Chain

This section runs one chain from \(\mathrm {id}\) to the Chinese remainder theorem and Gödel’s \(\beta \)-function [784]. Each link names the earlier links it uses. Nothing is brought in from outside: “yes” and “no” are the two readings of link 3, the predecessor and the factorial are the same step on pairs, and the remainder and the Chinese remainder map are idempotents of the same shape as links 5 and 7.

76.1 Links 1–8: places

Link From Content
1 – \(\mathrm {id}(x) = x\)
2 1 \(\Delta (x) = (x,x)\)
3 2 \(\pi _1(x,y) = x\), \(\pi _2(x,y) = y\)
4 2, 3 place, then read: \(\pi _1(\Delta x) = x\)
5 3 read, then place: \(e(p) := (\pi _1 p, \pi _2 p)\), \(e(e\,p) = e\,p\), pairs \(= \mathrm {Fix}(e)\)
6 4, 5 \(\eta := \Delta \), \(\varepsilon := (\pi _1,\pi _2)\)
7 4 \(e_1 := \Delta \pi _1\), \(e_1 e_1 = e_1\), \(E = \mathrm {Fix}(e_1) =\) the diagonal, \(\sigma (x,y) = (y,x)\)
8 7 \(E(x,y) \Rightarrow Q(y) = Q(\pi _2(x,y)) = Q(\pi _2(x,x)) = Q(x)\)

The shape of links 4 and 5 is used again below in this general form. If \(r(s(x)) = x\) for every \(x\), then

\begin{align*} s(r(s(r\,y))) &= s(r\,y) , \end{align*}

so \(s \circ r\) is idempotent. If \(\mathrm {place}(\mathrm {read}\,n) = n\) for every \(n\), then

\begin{align*} \mathrm {read}\,m = \mathrm {read}\,n &\Rightarrow m = \mathrm {place}(\mathrm {read}\,m) = \mathrm {place}(\mathrm {read}\,n) = n . \end{align*}

76.2 Links 9–12: doing it \(n\) times

Link 9 (from 4): joining. Link 4 does one thing and then another. In general:

\begin{align*} (g \circ f)(x) &:= g(f(x)), & \mathrm {id} \circ f &= f = f \circ \mathrm {id}, & (h \circ g) \circ f &= h \circ (g \circ f) . \end{align*}

Link 10 (from 1, 9): numbers. A number joins the same thing repeatedly.

\begin{align*} 0(f) &:= \mathrm {id}, & s(n)(f) &:= f \circ n(f), & 1(f) &= f . \end{align*}

Link 11 (from 9, 10): addition and multiplication.

\begin{align*} (m+n)(f) &:= n(f) \circ m(f), & (m \cdot n)(f) &:= n(m(f)) . \end{align*}
\begin{align*} (m+0)(f) &= \mathrm {id} \circ m(f) = m(f) \\ (m+s\,n)(f) &= \bigl (f \circ n(f)\bigr ) \circ m(f) = f \circ \bigl (n(f) \circ m(f)\bigr ) = s(m+n)(f) \\ (m \cdot 0)(f) &= 0(m(f)) = \mathrm {id} = 0(f) \\ (m \cdot s\,n)(f) &= m(f) \circ n(m(f)) = m(f) \circ (m \cdot n)(f) = (m \cdot n + m)(f) \end{align*}

Link 12 (from 10): induction. \(N(n)\) holds when, for every \(P\), from \(P(0)\) and \(P(m) \Rightarrow P(s\,m)\) one gets \(P(n)\). Commutativity, associativity and distributivity of \(+\) and \(\cdot \) follow from the four equations of link 11 by induction.

76.3 Links 13–15: choosing, one before, subtraction

Link 13 (from 3, 10): choosing. The two readings are “yes” and “no”. With \(K(c)(x) := \pi _1(c,x) = c\):

\begin{align*} \mathrm {sel}(n)(x,y) &:= n(K\,y)(x) \\ \mathrm {sel}(0)(x,y) &= \mathrm {id}(x) = x \\ \mathrm {sel}(s\,n)(x,y) &= K(y)(\cdots ) = y \end{align*}

So \(\mathrm {sel}(n)\) reads the first place when \(n = 0\) and the second otherwise.

Choosing separates \(0\) from a successor. If \(s\,n = 0\), then

\begin{align*} \text {True} &= \mathrm {sel}(0)(\text {True},\text {False}) \\ &= \mathrm {sel}(s\,n)(\text {True},\text {False}) \\ &= \text {False} , \end{align*}

so \(s\,n \neq 0\).

Link 14 (from 2, 3, 10): one before. Take the step \(t(x,y) := (s\,x,\ x)\) on pairs and start at \(\Delta 0\).

\begin{align*} 0(t)(\Delta 0) &= (0,0) \\ s(n)(t)(\Delta 0) &= t\bigl (n(t)(\Delta 0)\bigr ) = (s\,n,\ n) \end{align*}
\begin{align*} p(n) &:= \pi _2\bigl (n(t)(\Delta 0)\bigr ), & p(0) &= 0, & p(s\,n) &= n . \end{align*}
\begin{align*} s\,m = s\,n &\Rightarrow m = p(s\,m) = p(s\,n) = n . \end{align*}

Link 15 (from 14): subtraction and order. Subtraction is one-before, \(n\) times.

\begin{align*} m \ominus n &:= n(p)(m), & m \ominus 0 &= m, & m \ominus s\,n &= p(m \ominus n) . \end{align*}
\begin{align*} (m+n) \ominus n &= m, & a \ominus a &= 0, & m \ominus (m+x) &= 0 . \end{align*}

Write \(r < m\) when \(r + (k+1) = m\) for some \(k\).

76.4 Links 16–18: the remainder

Link 16 (from 13, 15): the subtract-step. From \(m\) upwards, take \(m\) away; below \(m\), do nothing.

\begin{align*} t_m(n) &:= \mathrm {sel}(m \ominus n)(n \ominus m,\ n) \\ t_m(m+x) &= (m+x) \ominus m = x && (m \ominus (m+x) = 0) \\ t_m(r) &= r && (r < m) \end{align*}

Link 17 (from 10, 16): the remainder is an idempotent. Let \(m \geq 1\) and

\begin{align*} \mathrm {rem}_m(n) &:= n(t_m)(n) . \end{align*}

By induction every \(n\) is \(q\,m + r\) with \(r < m\). Since \(m \geq 1\), \(n = q + j\) for some \(j\). Then

\begin{align*} \mathrm {rem}_m(n) &= j(t_m)\bigl (q(t_m)(q\,m + r)\bigr ) \\ &= j(t_m)(r) && \text {(link 16, } q \text { times)} \\ &= r && (r \text { is fixed by } t_m) . \end{align*}

So \(\mathrm {rem}_m(n) < m\) always, and

\begin{align*} \mathrm {rem}_m(\mathrm {rem}_m\,n) &= r(t_m)(r) = r = \mathrm {rem}_m\,n . \end{align*}

The fixed points of \(\mathrm {rem}_m\) are the numbers below \(m\).

Link 18 (from 7, 17): divisibility and congruence.

\begin{align*} \mathrm {rem}_m(p\,m + x) &= \mathrm {rem}_m(p\,m + q\,m + r) \\ &= \mathrm {rem}_m((p+q)\,m + r) \\ &= r \\ &= \mathrm {rem}_m(x) . \end{align*}

Write \(m \mid n\) when \(n = q\,m\), and \(n \equiv n' \ (m)\) when \(E(\mathrm {rem}_m\,n,\ \mathrm {rem}_m\,n')\): congruence is the kernel of the remainder.

76.5 Links 19–23: the Euclid step and invertibility

Link 19 (from 7, 16): the Euclid step. The subtract-step, on the two places of a pair.

\begin{align*} u(a,b) &:= \begin {cases} (a \ominus b,\ b) & b < a \\ (a,\ b \ominus a) & a < b \\ (a,\ b) & \text {otherwise} \end {cases} & u(a,a) &= (a,a) . \end{align*}

The diagonal is fixed: this is the sameness \(E\) of link 7. The step reaches the diagonal, for example

\begin{align*} 10(u)(6,4) &= (2,2), & 5(u)(2,3) &= (1,1), & 8(u)(3,5) &= (1,1) . \end{align*}

Link 20 (from 5, 7, 11): integers. A pair \((a,b)\) of numbers read as \(a - b\):

\begin{align*} (a,b)\ k\ (c,d) &:\iff a + d = b + c, & -(a,b) &:= \sigma (a,b), & (a,b) + \sigma (a,b) &= \Delta (a+b)\ k\ \Delta 0 . \end{align*}

Link 21 (from 19, 20): the carried combination. Walk the Euclid step while carrying each place as a combination of the starting pair \((a,b)\).

\begin{align*} a &= 1 \cdot a + 0 \cdot b, \qquad b = 0 \cdot a + 1 \cdot b \\ a' \ominus b' &= (x_1 - x_2)\,a + (y_1 - y_2)\,b \end{align*}

At the diagonal \((g,g)\) this reads \(g = x\,a + y\,b\). When \(g = 1\), moving the negative term across gives the form used below:

\begin{align*} y\,b &= 1 + s\,a . \end{align*}

Say then that \(b\) is invertible along \(a\).

Link 22 (from 21): Euclid’s lemma. Let \(x\,p + y\,a = 1\) and \(a\,b = c\,p\).

\begin{align*} b &= (x\,p + y\,a)\,b \\ &= x\,b\,p + y\,(a\,b) \\ &= x\,b\,p + y\,c\,p \\ &= (x\,b + y\,c)\,p . \end{align*}

A product of invertibles is invertible: if \(y_1 b_1 = 1 + s_1 a\) and \(y_2 b_2 = 1 + s_2 a\), then

\begin{align*} (y_1 y_2)(b_1 b_2) &= (1 + s_1 a)(1 + s_2 a) \\ &= 1 + \bigl (s_1 + (1 + s_1 a)\,s_2\bigr )\,a . \end{align*}

Link 23 (from 17, 21): two pieces that split \(1\). If \(e_a + e_b = 1\) and \(e_a e_b = 0\), then

\begin{align*} e_a &= e_a \cdot 1 \\ &= e_a\,(e_a + e_b) \\ &= e_a e_a + e_a e_b \\ &= e_a e_a . \end{align*}

For the moduli \(2\) and \(3\) the pieces are \(3\) and \(4\):

\begin{align*} 3 + 4 &= 1 + 6, & \mathrm {rem}_6(3 \cdot 4) &= 0, & \mathrm {rem}_6(3 \cdot 3) &= 3, & \mathrm {rem}_6(4 \cdot 4) &= 4 . \end{align*}

76.6 Links 24–25: the Chinese remainder theorem

Link 24 (from 5, 18, 22): two moduli. Let \(a = w + 1\), let \(b\) be invertible along \(a\), \(y\,b = 1 + s\,a\), and put \(t := u + w\,v\).

\begin{align*} (v + s\,t)\,a + u &= v\,a + s\,t\,a + u \\[4pt] (y\,t)\,b + v &= (1 + s\,a)\,t + v \\ &= t + s\,t\,a + v \\ &= u + w\,v + v + s\,t\,a \\ &= u + v\,a + s\,t\,a . \end{align*}

So one number has both shapes:

\begin{align*} c &:= (v + s\,t)\,a + u = (y\,t)\,b + v . \end{align*}

By link 18, \(\mathrm {rem}_a(c) = \mathrm {rem}_a(u)\) and \(\mathrm {rem}_b(c) = \mathrm {rem}_b(v)\). With

\begin{align*} \mathrm {read}(n) &:= (\mathrm {rem}_a\,n,\ \mathrm {rem}_b\,n), & \mathrm {place}(u,v) &:= \mathrm {rem}_{ab}(c), \end{align*}

this is the shape of links 4 and 5: place and then read returns \((u,v)\) for \(u < a\), \(v < b\), and read and then place is the idempotent \(\mathrm {rem}_{ab}\) of link 17.

Link 25 (from 12, 22, 24): many moduli. Let \(m_0, \dots , m_k\) be moduli in which each later one is invertible along each earlier one, with values \(a_0, \dots , a_k\).

\begin{align*} &c' \text { agrees with } a_1, \dots , a_k \text { along } m_1, \dots , m_k && \text {(induction)} \\ &M' := m_1 \cdots m_k \text { is invertible along } m_0 && \text {(link 22, repeated)} \\ &c := \text {the number of link 24 for } (u,v) := (a_0, c'),\ (a,b) := (m_0, M') \end{align*}
\begin{align*} \mathrm {rem}_{m_0}(c) &= \mathrm {rem}_{m_0}(a_0) \\ \mathrm {rem}_{m_i}(c) &= \mathrm {rem}_{m_i}\bigl ((y\,t)\,M' + c'\bigr ) = \mathrm {rem}_{m_i}(c') = \mathrm {rem}_{m_i}(a_i) && (m_i \mid M') \end{align*}

76.7 Links 26–28: the beta function

Link 26 (from 14): the factorial. The same kind of step on pairs as in link 14: \((k,q) \mapsto (s\,k,\ s\,k \cdot q)\), started at \((0,1)\).

\begin{align*} n(\cdots )(0,1) &= (n,\ n!), & 0! &= 1, & (n+1)! &= (n+1) \cdot n! . \end{align*}
\begin{align*} 1 \leq k \leq s &\Rightarrow k \mid s!, & s &\leq s! . \end{align*}

Link 27 (from 22, 26): the moduli. Given \(a_0, \dots , a_n\), put

\begin{align*} s &:= n + a_0 + \cdots + a_n, & d &:= s!, & m_i &:= (i+1)\,d + 1 . \end{align*}

Let \(i < i + k \leq n\). Then \(1 \leq k \leq s\), so \(d = k\,e\) by link 26. Write \((i+1)\,d = w + 1\), so that \(m_i = w + 2\), and put \(y := (i+1)^2 e\).

\begin{align*} y\,m_{i+k} &= y\,(m_i + k\,d) \\ &= y\,m_i + (i+1)^2\,(k\,e)\,d \\ &= y\,m_i + \bigl ((i+1)\,d\bigr )^2 \\ &= y\,m_i + (w+1)^2 \\ &= y\,m_i + 1 + w\,(w+2) \\ &= 1 + (y + w)\,m_i . \end{align*}

So each later modulus is invertible along each earlier one, with explicit \(y\) and \(s\). For the size:

\begin{align*} a_i &\leq s \leq s! = d < (i+1)\,d + 1 = m_i . \end{align*}

Link 28 (from 17, 25, 27): the \(\beta \)-function.

\begin{align*} \beta (c,d,i) &:= \mathrm {rem}_{(i+1)d+1}(c) . \end{align*}

Link 25 gives \(c\) with \(\mathrm {rem}_{m_i}(c) = \mathrm {rem}_{m_i}(a_i)\), and \(a_i < m_i\) is fixed by the remainder, so

\begin{align*} \beta (c,d,i) &= a_i && (0 \leq i \leq n) . \end{align*}

A sequence is placed in two numbers \((c,d)\) and read back by \(\beta \). For example \(\beta (3,\,1!,\,\cdot )\) reads \((1,0)\) and \(\beta (12,\,2!,\,\cdot )\) reads \((0,2)\).

76.8 Link 29: the chain closes

Link 29 (from 10, 28). A correct record of the steps is the same as doing it \(n\) times: if \(\mathrm {tr}(0) = x\) and \(\mathrm {tr}(i+1) = f(\mathrm {tr}(i))\), then

\begin{align*} \mathrm {tr}(n) &= n(f)(x) . \end{align*}

With link 28 the record fits in two numbers:

\begin{align*} n(f)(x) = y \iff \text {for some } c, d:\quad &\beta (c,d,0) = x, \\ &\beta (c,d,i+1) = f(\beta (c,d,i)) \quad (i < n), \\ &\beta (c,d,n) = y . \end{align*}

The remainder was built from “\(n\) times” in link 17; the \(\beta \)-function writes “\(n\) times” back in terms of \(+\) and \(\cdot \).

76.9 The chain

Link From What appears
1–8 – places: \(\Delta \), \(\pi \), idempotent, sameness \(=\) diagonal, \(\sigma \)
9 4 joining
10 1, 9 numbers: joining the same thing repeatedly
11 9, 10 \(+\) and \(\cdot \)
12 10 induction
13 3, 10 choosing by the two readings
14 2, 3, 10 one before, from a step on pairs
15 14 subtraction, order
16 13, 15 the subtract-step
17 10, 16 the remainder, an idempotent
18 7, 17 divisibility, congruence as a kernel
19 7, 16 the Euclid step, fixed on the diagonal
20 5, 7, 11 integers as pairs, minus \(= \sigma \)
21 19, 20 the carried combination, \(y\,b = 1 + s\,a\)
22 21 Euclid’s lemma, products of invertibles
23 17, 21 two pieces that split \(1\)
24 5, 18, 22 Chinese remainder theorem, two moduli
25 12, 22, 24 Chinese remainder theorem, many moduli
26 14 the factorial, from a step on pairs
27 22, 26 the moduli \((i+1)\,d + 1\)
28 17, 25, 27 the \(\beta \)-function
29 10, 28 “\(n\) times” in terms of \(+\) and \(\cdot \)

76.10 Machine check

The chain is checked in one Lean 4 file, BetaChain.lean (Listing 11), run in the Lean web editor under Lean v4.37.0-rc1 with the latest Mathlib. Inside the namespace BetaChain every proof is a hand-written term: no omega, no simp, no ring. The file produces 38 messages and no warnings: 30 #print axioms reports, each “does not depend on any axioms”, and 8 #check outputs (Figure 20).

Links Lean names Checked
1–8 tri1, e1_idem, split_idem, read_inj in general
9–12 iter_add, iter_mul, nadd_comm, nmul_comm, nmul_assoc, nright_distrib in general
13 sel_zero, sel_succ, succ_ne_zero’ in general
14 pre_succ, succ_inj’ in general
15 sb_add_cancel, sb_self, sb_le_zero in general
16 tstep_add, fix_of_lt in general
17 div_exists, rem_lt, rem_idem in general
18 rem_add_mul in general
19 ustep_diag in general
19 ustep_reaches on three inputs
22 euclid_line, inv_mul in general
23 piece_idem in general
23 pieces23_idem moduli \(2\), \(3\)
24 crt_pair, crt_read in general
24 crt23_read_place, crt23_place_read moduli \(2\), \(3\)
25 prod_inv, sol_add, crt_list in general
26 fact_succ, fact_ge, dvd_fact in general
27 md_inv, lt_md in general
28 beta_lemma in general
28 beta_seq_1_0, beta_seq_0_2 two sequences
29 trace_iter in general

What the check rests on. The numbers are Lean’s Nat; iter_add and iter_mul show that its \(+\) and \(\cdot \) are the joining of link 11, and the laws of \(+\) and \(\cdot \) are proved again by hand from the defining equations. Coprimality enters only in the form \(y\,b = 1 + s\,a\). The integers of link 20 are not rebuilt in this file; they are in FundAll.lean (Listing 10). The general statement of link 21, that the Euclid step always produces such \(y\) and \(s\), is not proved here: reaching the diagonal is checked on three inputs, and where the \(\beta \)-function needs invertibility, link 27 supplies \(y\) and \(s\) explicitly. The equivalence of link 29 is checked as its two halves, trace_iter and beta_lemma. Mathlib is imported only for the last eight lines, which display the library forms of the same theorems. That a successor is not zero is proved in the file from the choosing of link 13 (succ_ne_zero’); the library lemma Nat.succ_ne_zero is not used, because with it #print axioms reports propext.

PIC

Figure 20: BetaChain.lean in the Lean web editor (Lean v4.37.0-rc1, latest Mathlib): the lower part of the message panel. The last eight #print axioms reports, from crt23_place_read to trace_iter and including crt_list, dvd_fact and beta_lemma, each read “does not depend on any axioms”. Below them are the eight #check outputs.

Listing 11: BetaChain.lean: from the identity to the Chinese remainder theorem and the \(\beta \)-function.

BetaChain.lean

import Mathlib

/-
  BetaChain.lean  (second version: the general theorems proved by hand)
  One connected chain from `id` to the Chinese remainder theorem and
  Goedel's beta function (links 1-29).

  Everything in the namespace `BetaChain` is proved by hand: no `omega`,
  no `simp`, no `ring`. Every `#print axioms` line should report no
  axioms. Mathlib is imported only for the last block.

  General theorems proved here:

    rem_lt, rem_idem   the remainder is always below the modulus and is
                       idempotent                              (link 17)
    rem_add_mul        adding a multiple does not change it    (link 18)
    crt_pair           the Chinese remainder theorem for two   (link 24)
    crt_list           ... and for any list of moduli in which each
                       later modulus is invertible along each earlier
                       one                                     (link 25)
    dvd_fact           1 <= k <= s  =>  k divides s!           (link 26)
    md_inv             the moduli (i+1) d + 1 are invertible along
                       each other, with explicit coefficients  (link 27)
    beta_lemma         for every sequence a 0, ..., a n there are c, d
                       with  beta c d i = a i  for all i <= n  (link 28)

  Coprimality is used in the form "y b = 1 + s a" (b is invertible
  along a), which is the form in which the chain states it.
-/

universe u

namespace BetaChain

/-! ## Links 1-8. Places -/

def diag {A : Type u} (x : A) : A × A := (x, x)

theorem tri1 {A : Type u} (x : A) : (diag x).1 = x := rfl

def e1 {A : Type u} (p : A × A) : A × A := diag p.1

theorem e1_idem {A : Type u} (p : A × A) : e1 (e1 p) = e1 p := rfl

theorem split_idem {A B : Type u} (r : B → A) (s : A → B)
    (h : ∀ x, r (s x) = x) (y : B) : s (r (s (r y))) = s (r y) :=
  congrArg s (h (r y))

theorem read_inj {A B : Type u} (read : A → B) (place : B → A)
    (h : ∀ n, place (read n) = n) {m n : A} (e : read m = read n) : m = n :=
  Eq.trans (Eq.symm (h m)) (Eq.trans (congrArg place e) (h n))

/-! ## Links 9-12. "Do it n times"; + and * are composition -/

def iter {A : Type u} : Nat → (A → A) → A → A
  | 0, _, a => a
  | n + 1, f, a => f (iter n f a)

theorem iter_zero {A : Type u} (f : A → A) (a : A) : iter 0 f a = a := rfl

theorem iter_succ {A : Type u} (n : Nat) (f : A → A) (a : A) :
    iter (n + 1) f a = f (iter n f a) := rfl

theorem iter_one {A : Type u} (f : A → A) (a : A) : iter 1 f a = f a := rfl

theorem iter_add {A : Type u} (f : A → A) (a : A) (m : Nat) :
    ∀ n : Nat, iter (m + n) f a = iter n f (iter m f a)
  | 0 => rfl
  | n + 1 => congrArg f (iter_add f a m n)

theorem iter_mul {A : Type u} (f : A → A) (m : Nat) :
    ∀ (n : Nat) (a : A), iter (m * n) f a = iter n (iter m f) a
  | 0, _ => rfl
  | n + 1, a =>
    Eq.trans (iter_add f a (m * n) m) (congrArg (iter m f) (iter_mul f m n a))

theorem iter_fix {A : Type u} (f : A → A) (r : A) (h : f r = r) :
    ∀ k : Nat, iter k f r = r
  | 0 => rfl
  | k + 1 => Eq.trans (congrArg f (iter_fix f r h k)) h

theorem iter_succ' {A : Type u} (f : A → A) (a : A) :
    ∀ q : Nat, iter (q + 1) f a = iter q f (f a)
  | 0 => rfl
  | q + 1 => congrArg f (iter_succ' f a q)

/-! ### The laws of + and *, from the defining equations -/

theorem nzero_add : ∀ (a : Nat), 0 + a = a
  | 0 => rfl
  | a + 1 => congrArg Nat.succ (nzero_add a)

theorem nsucc_add : ∀ (a b : Nat), Nat.succ a + b = Nat.succ (a + b)
  | _, 0 => rfl
  | a, b + 1 => congrArg Nat.succ (nsucc_add a b)

theorem nadd_assoc : ∀ (a b c : Nat), a + b + c = a + (b + c)
  | _, _, 0 => rfl
  | a, b, c + 1 => congrArg Nat.succ (nadd_assoc a b c)

theorem nadd_comm : ∀ (a b : Nat), a + b = b + a
  | a, 0 => Eq.symm (nzero_add a)
  | a, b + 1 =>
    Eq.trans (congrArg Nat.succ (nadd_comm a b)) (Eq.symm (nsucc_add b a))

theorem nadd_left_comm (a b c : Nat) : a + (b + c) = b + (a + c) :=
  Eq.trans (Eq.symm (nadd_assoc a b c))
    (Eq.trans (congrArg (fun t => t + c) (nadd_comm a b)) (nadd_assoc b a c))

theorem nadd_right_comm (a b c : Nat) : a + b + c = a + c + b :=
  Eq.trans (nadd_assoc a b c)
    (Eq.trans (congrArg (fun t => a + t) (nadd_comm b c)) (Eq.symm (nadd_assoc a c b)))

theorem mid4 (a b c d : Nat) : (a + b) + (c + d) = (a + c) + (b + d) :=
  Eq.trans (nadd_assoc a b (c + d))
    (Eq.trans
      (congrArg (fun t => a + t)
        (Eq.trans (Eq.symm (nadd_assoc b c d))
          (Eq.trans (congrArg (fun t => t + d) (nadd_comm b c)) (nadd_assoc c b d))))
      (Eq.symm (nadd_assoc a c (b + d))))

theorem nzero_mul : ∀ a : Nat, 0 * a = 0
  | 0 => rfl
  | a + 1 => nzero_mul a

theorem nsucc_mul : ∀ (a b : Nat), (a + 1) * b = a * b + b
  | _, 0 => rfl
  | a, b + 1 =>
    Eq.trans (congrArg (fun t => t + (a + 1)) (nsucc_mul a b)) (mid4 (a * b) b a 1)

theorem nmul_comm : ∀ (a b : Nat), a * b = b * a
  | a, 0 => Eq.symm (nzero_mul a)
  | a, b + 1 =>
    Eq.trans (congrArg (fun t => t + a) (nmul_comm a b)) (Eq.symm (nsucc_mul b a))

theorem nmul_one (a : Nat) : a * 1 = a :=
  Eq.trans (show a * 1 = 0 + a from rfl) (nzero_add a)

theorem nleft_distrib (a b : Nat) : ∀ c : Nat, a * (b + c) = a * b + a * c
  | 0 => rfl
  | c + 1 =>
    Eq.trans (congrArg (fun t => t + a) (nleft_distrib a b c))
      (nadd_assoc (a * b) (a * c) a)

theorem nright_distrib (a b c : Nat) : (a + b) * c = a * c + b * c :=
  Eq.trans (nmul_comm (a + b) c)
    (Eq.trans (nleft_distrib c a b)
      (Eq.trans (congrArg (fun t => t + c * b) (nmul_comm c a))
        (congrArg (fun t => a * c + t) (nmul_comm c b))))

theorem nmul_assoc (a b : Nat) : ∀ c : Nat, a * b * c = a * (b * c)
  | 0 => rfl
  | c + 1 =>
    Eq.trans (congrArg (fun t => t + a * b) (nmul_assoc a b c))
      (Eq.symm (nleft_distrib a (b * c) b))

theorem mmid4 (a b c d : Nat) : (a * b) * (c * d) = (a * c) * (b * d) :=
  Eq.trans (nmul_assoc a b (c * d))
    (Eq.trans
      (congrArg (fun t => a * t)
        (Eq.trans (Eq.symm (nmul_assoc b c d))
          (Eq.trans (congrArg (fun t => t * d) (nmul_comm b c)) (nmul_assoc c b d))))
      (Eq.symm (nmul_assoc a c (b * d))))

/-! ## Link 13. Choosing -/

def sel {A : Type u} (n : Nat) (x y : A) : A := iter n (fun _ => y) x

theorem sel_zero {A : Type u} (x y : A) : sel 0 x y = x := rfl

theorem sel_succ {A : Type u} (n : Nat) (x y : A) : sel (n + 1) x y = y := rfl

/-- A successor is not zero: choosing tells them apart.
    `sel` reads `True` at `0` and `False` at a successor, so an equation
    `n + 1 = 0` would carry `True` to `False`.
    (Proved here from `sel`, so that the library lemma
    `Nat.succ_ne_zero` is not used.) -/
theorem succ_ne_zero' (n : Nat) : Nat.succ n ≠ 0 :=
  fun h =>
    have e1 : True = sel 0 True False := Eq.symm (sel_zero True False)
    have e2 : sel 0 True False = sel (Nat.succ n) True False :=
      Eq.symm (congrArg (fun t => sel t True False) h)
    have e3 : sel (Nat.succ n) True False = False := sel_succ n True False
    Eq.mp (Eq.trans e1 (Eq.trans e2 e3)) True.intro

/-! ## Link 14. One-before, from a step on pairs -/

def pstep (p : Nat × Nat) : Nat × Nat := (p.1 + 1, p.1)

def pre (n : Nat) : Nat := (iter n pstep (0, 0)).2

theorem pstep_fst : ∀ n : Nat, (iter n pstep (0, 0)).1 = n
  | 0 => rfl
  | n + 1 => congrArg Nat.succ (pstep_fst n)

theorem pre_zero : pre 0 = 0 := rfl

theorem pre_succ (n : Nat) : pre (n + 1) = n := pstep_fst n

theorem succ_inj' {m n : Nat} (h : m + 1 = n + 1) : m = n :=
  Eq.trans (Eq.symm (pre_succ m)) (Eq.trans (congrArg pre h) (pre_succ n))

theorem pre_eq : ∀ k : Nat, pre k = Nat.pred k
  | 0 => rfl
  | k + 1 => pre_succ k

/-! ## Link 15. Subtraction: one-before, n times -/

def sb (m n : Nat) : Nat := iter n pre m

theorem sb_zero (m : Nat) : sb m 0 = m := rfl

theorem sb_succ (m n : Nat) : sb m (n + 1) = pre (sb m n) := rfl

theorem sb_add_cancel : ∀ (n m : Nat), sb (m + n) n = m
  | 0, _ => rfl
  | n + 1, m =>
    Eq.trans
      (congrArg (fun t => pre (sb t n)) (Eq.symm (nsucc_add m n)))
      (Eq.trans (congrArg pre (sb_add_cancel n (m + 1))) (pre_succ m))

theorem sb_self (a : Nat) : sb a a = 0 :=
  Eq.trans (congrArg (fun t => sb t a) (Eq.symm (nzero_add a))) (sb_add_cancel a 0)

theorem sb_eq (m : Nat) : ∀ n : Nat, sb m n = m - n
  | 0 => rfl
  | n + 1 => Eq.trans (congrArg pre (sb_eq m n)) (pre_eq (m - n))

/-- `m - (m + x) = 0`. -/
theorem sb_le_zero (m x : Nat) : sb m (m + x) = 0 :=
  Eq.trans (iter_add pre m m x)
    (Eq.trans (congrArg (iter x pre) (sb_self m)) (iter_fix pre 0 pre_zero x))

/-! ## Links 16-17. The subtract-step and the remainder -/

def tstep (m n : Nat) : Nat := sel (sb m n) (sb n m) n

def rem (m n : Nat) : Nat := iter n (tstep m) n

theorem tstep_small (m r k : Nat) (h : sb m r = k + 1) : tstep m r = r :=
  congrArg (fun t => sel t (sb r m) r) h

theorem tstep_big (m n : Nat) (h : sb m n = 0) : tstep m n = sb n m :=
  congrArg (fun t => sel t (sb n m) n) h

theorem rem_of_fix (m r : Nat) (h : tstep m r = r) : rem m r = r :=
  iter_fix (tstep m) r h r

theorem rem_small (m r k : Nat) (h : sb m r = k + 1) : rem m r = r :=
  rem_of_fix m r (tstep_small m r k h)

theorem rem_idem_of (m n : Nat) (h : tstep m (rem m n) = rem m n) :
    rem m (rem m n) = rem m n :=
  rem_of_fix m (rem m n) h

theorem rem_values :
    rem 3 10 = 1 ∧ rem 3 (rem 3 10) = rem 3 10 ∧ rem 6 11 = 5 ∧ rem 5 12 = 2 :=
  ⟨rfl, rfl, rfl, rfl⟩

/-! ### The remainder in general -/

/-- From `m` up, one step takes `m` away. -/
theorem tstep_add (m x : Nat) : tstep m (m + x) = x :=
  Eq.trans (tstep_big m (m + x) (sb_le_zero m x))
    (Eq.trans (congrArg (fun t => sb t m) (nadd_comm m x)) (sb_add_cancel m x))

/-- Below `m` (that is, `r + (k+1) = m`) the step changes nothing. -/
theorem fix_of_lt (m r k : Nat) (h : r + (k + 1) = m) : tstep m r = r :=
  tstep_small m r k
    (Eq.trans (congrArg (fun t => sb t r) (Eq.symm h))
      (Eq.trans (congrArg (fun t => sb t r) (nadd_comm r (k + 1)))
        (sb_add_cancel r (k + 1))))

/-- `r` with `m` added `q` times. -/
def up (m q r : Nat) : Nat := iter q (fun x => m + x) r

theorem up_eq (m r : Nat) : ∀ q : Nat, up m q r = q * m + r
  | 0 => Eq.symm (Eq.trans (congrArg (fun t => t + r) (nzero_mul m)) (nzero_add r))
  | q + 1 =>
    Eq.trans (congrArg (fun t => m + t) (up_eq m r q))
      (Eq.trans (Eq.symm (nadd_assoc m (q * m) r))
        (Eq.trans (congrArg (fun t => t + r) (nadd_comm m (q * m)))
          (congrArg (fun t => t + r) (Eq.symm (nsucc_mul q m)))))

/-- Taking `m` away `q` times undoes adding it `q` times. -/
theorem down_up (m r : Nat) : ∀ q : Nat, iter q (tstep m) (up m q r) = r
  | 0 => rfl
  | q + 1 =>
    Eq.trans (iter_succ' (tstep m) (up m (q + 1) r) q)
      (Eq.trans (congrArg (iter q (tstep m)) (tstep_add m (up m q r)))
        (down_up m r q))

theorem up_ge (m' r : Nat) : ∀ q : Nat, ∃ j, up (m' + 1) q r = q + j
  | 0 => ⟨r, Eq.symm (nzero_add r)⟩
  | q + 1 =>
    match up_ge m' r q with
    | ⟨j, hj⟩ =>
      ⟨m' + j,
        Eq.trans (congrArg (fun t => (m' + 1) + t) hj)
          (Eq.trans (nsucc_add m' (q + j))
            (Eq.trans (congrArg Nat.succ (nadd_left_comm m' q j))
              (Eq.symm (nsucc_add q (m' + j)))))⟩

theorem rem_up (m' r q : Nat) (hfix : tstep (m' + 1) r = r) :
    rem (m' + 1) (up (m' + 1) q r) = r :=
  match up_ge m' r q with
  | ⟨j, hj⟩ =>
    Eq.trans
      (congrArg (fun t => iter t (tstep (m' + 1)) (up (m' + 1) q r)) hj)
      (Eq.trans (iter_add (tstep (m' + 1)) (up (m' + 1) q r) q j)
        (Eq.trans (congrArg (iter j (tstep (m' + 1))) (down_up (m' + 1) r q))
          (iter_fix (tstep (m' + 1)) r hfix j)))

/-- The remainder of `q m + r` is `r` when `r` is below `m`. -/
theorem rem_div (m' q r k : Nat) (h : r + (k + 1) = m' + 1) :
    rem (m' + 1) (q * (m' + 1) + r) = r :=
  Eq.trans (congrArg (rem (m' + 1)) (Eq.symm (up_eq (m' + 1) r q)))
    (rem_up m' r q (fix_of_lt (m' + 1) r k h))

/-- Every number is `q m + r` with `r` below `m`. -/
theorem div_exists (m' : Nat) :
    ∀ n : Nat, ∃ q r k, n = q * (m' + 1) + r ∧ r + (k + 1) = m' + 1
  | 0 => ⟨0, 0, m', Eq.symm (nzero_mul (m' + 1)), nzero_add (m' + 1)⟩
  | n + 1 =>
    match div_exists m' n with
    | ⟨q, r, k, hn, hr⟩ =>
      match k, hr with
      | 0, hr =>
        ⟨q + 1, 0, m',
          Eq.trans (congrArg Nat.succ hn)
            (Eq.trans (congrArg (fun t => q * (m' + 1) + t) hr)
              (Eq.symm (nsucc_mul q (m' + 1)))),
          nzero_add (m' + 1)⟩
      | k + 1, hr =>
        ⟨q, r + 1, k, congrArg Nat.succ hn, Eq.trans (nsucc_add r (k + 1)) hr⟩

theorem rem_spec (m' n : Nat) :
    ∃ q r k, n = q * (m' + 1) + r ∧ r + (k + 1) = m' + 1 ∧ rem (m' + 1) n = r :=
  match div_exists m' n with
  | ⟨q, r, k, hn, hr⟩ =>
    ⟨q, r, k, hn, hr, Eq.trans (congrArg (rem (m' + 1)) hn) (rem_div m' q r k hr)⟩

/-- The remainder is always below the modulus. -/
theorem rem_lt (m' n : Nat) : ∃ k, rem (m' + 1) n + (k + 1) = m' + 1 :=
  match rem_spec m' n with
  | ⟨_, _, k, _, hr, hrem⟩ => ⟨k, Eq.trans (congrArg (fun t => t + (k + 1)) hrem) hr⟩

/-- The remainder is idempotent. -/
theorem rem_idem (m' n : Nat) : rem (m' + 1) (rem (m' + 1) n) = rem (m' + 1) n :=
  match rem_spec m' n with
  | ⟨_, r, k, _, hr, hrem⟩ =>
    Eq.trans (congrArg (rem (m' + 1)) hrem)
      (Eq.trans (rem_of_fix (m' + 1) r (fix_of_lt (m' + 1) r k hr)) (Eq.symm hrem))

/-- Adding a multiple of the modulus does not change the remainder. -/
theorem rem_add_mul (m' x p : Nat) :
    rem (m' + 1) (p * (m' + 1) + x) = rem (m' + 1) x :=
  match rem_spec m' x with
  | ⟨q, r, k, hx, hr, hrem⟩ =>
    Eq.trans (congrArg (fun t => rem (m' + 1) (p * (m' + 1) + t)) hx)
      (Eq.trans
        (congrArg (rem (m' + 1)) (Eq.symm (nadd_assoc (p * (m' + 1)) (q * (m' + 1)) r)))
        (Eq.trans
          (congrArg (fun t => rem (m' + 1) (t + r)) (Eq.symm (nright_distrib p q (m' + 1))))
          (Eq.trans (rem_div m' (p + q) r k hr) (Eq.symm hrem))))

/-! ## Link 19. The Euclid step -/

def ustep (p : Nat × Nat) : Nat × Nat :=
  sel (sb p.1 p.2) (sel (sb p.2 p.1) p (p.1, sb p.2 p.1)) (sb p.1 p.2, p.2)

theorem ustep_diag (a : Nat) : ustep (a, a) = (a, a) :=
  congrArg (fun t => sel t (sel t (a, a) (a, t)) (t, a)) (sb_self a)

theorem ustep_reaches :
    iter 10 ustep (6, 4) = (2, 2) ∧ iter 5 ustep (2, 3) = (1, 1) ∧
    iter 8 ustep (3, 5) = (1, 1) :=
  ⟨rfl, rfl, rfl⟩

/-! ## Link 22. Euclid's lemma line -/

theorem euclid_line {R : Type u} (add mul : R → R → R)
    (mul_assoc' : ∀ x y z, mul (mul x y) z = mul x (mul y z))
    (right_distrib' : ∀ x y z, mul (add x y) z = add (mul x z) (mul y z))
    (p a b x y c : R)
    (hb : b = add (mul (mul x b) p) (mul y (mul a b)))
    (hab : mul a b = mul c p) :
    b = mul (add (mul x b) (mul y c)) p :=
  Eq.trans hb
    (Eq.trans
      (congrArg (fun w => add (mul (mul x b) p) (mul y w)) hab)
      (Eq.trans
        (congrArg (fun w => add (mul (mul x b) p) w) (Eq.symm (mul_assoc' y c p)))
        (Eq.symm (right_distrib' (mul x b) (mul y c) p))))

/-! ## Link 23. Two pieces that split 1 -/

theorem piece_idem {R : Type u} (add mul : R → R → R) (zero one : R)
    (mul_one' : ∀ x, mul x one = x)
    (add_zero' : ∀ x, add x zero = x)
    (left_distrib' : ∀ x y z, mul x (add y z) = add (mul x y) (mul x z))
    (ea eb : R) (hsum : add ea eb = one) (horth : mul ea eb = zero) :
    mul ea ea = ea :=
  Eq.symm
    (Eq.trans (Eq.symm (mul_one' ea))
      (Eq.trans (congrArg (fun w => mul ea w) (Eq.symm hsum))
        (Eq.trans (left_distrib' ea ea eb)
          (Eq.trans (congrArg (fun w => add (mul ea ea) w) horth)
            (add_zero' (mul ea ea))))))

/-! ## Link 24. The Chinese remainder theorem for two moduli -/

theorem swap_ends (p v x u : Nat) : ((p + v) + x) + u = ((u + p) + x) + v :=
  Eq.trans (congrArg (fun t => t + u) (nadd_right_comm p v x))
    (Eq.trans (nadd_assoc (p + x) v u)
      (Eq.trans (congrArg (fun t => (p + x) + t) (nadd_comm v u))
        (Eq.trans (Eq.symm (nadd_assoc (p + x) u v))
          (congrArg (fun t => t + v)
            (Eq.trans (nadd_comm (p + x) u) (Eq.symm (nadd_assoc u p x)))))))

theorem crtL (v s t w u : Nat) :
    (v + s * t) * (w + 1) + u = ((v * w + v) + (s * t) * (w + 1)) + u :=
  congrArg (fun z => z + u) (nright_distrib v (s * t) (w + 1))

theorem crtR (y t b s w v : Nat) (hy : y * b = 1 + s * (w + 1)) :
    (y * t) * b + v = (t + (s * t) * (w + 1)) + v :=
  congrArg (fun z => z + v)
    (Eq.trans (congrArg (fun z => z * b) (nmul_comm y t))
      (Eq.trans (nmul_assoc t y b)
        (Eq.trans (congrArg (fun z => t * z) hy)
          (Eq.trans (nleft_distrib t 1 (s * (w + 1)))
            (Eq.trans (congrArg (fun z => z + t * (s * (w + 1))) (nmul_one t))
              (Eq.trans
                (congrArg (fun z => t + z) (Eq.symm (nmul_assoc t s (w + 1))))
                (congrArg (fun z => t + z * (w + 1)) (nmul_comm t s))))))))

/-- If `y b = 1 + s (w+1)` then the number on the left is
    `K (w+1) + u` and also `L b + v`: it reads as `u` along `w + 1`
    and as `v` along `b`. -/
theorem crt_pair (w b y s u v : Nat) (hy : y * b = 1 + s * (w + 1)) :
    (v + s * (u + w * v)) * (w + 1) + u = (y * (u + w * v)) * b + v :=
  Eq.trans (crtL v s (u + w * v) w u)
    (Eq.trans (swap_ends (v * w) v ((s * (u + w * v)) * (w + 1)) u)
      (Eq.trans
        (congrArg (fun z => ((u + z) + (s * (u + w * v)) * (w + 1)) + v) (nmul_comm v w))
        (Eq.symm (crtR y (u + w * v) b s w v hy))))

/-- The algebra of placing, over any addition and multiplication. -/
theorem crt_read {R : Type u} (add mul : R → R → R) (one : R)
    (mul_one' : ∀ x, mul x one = x)
    (add_assoc' : ∀ x y z, add (add x y) z = add x (add y z))
    (mul_assoc' : ∀ x y z, mul (mul x y) z = mul x (mul y z))
    (left_distrib' : ∀ x y z, mul x (add y z) = add (mul x y) (mul x z))
    (right_distrib' : ∀ x y z, mul (add x y) z = add (mul x z) (mul y z))
    (a s t u v ea eb : R)
    (hea : ea = add one (mul s a)) (heb : eb = mul t a) :
    add (mul u ea) (mul v eb) = add u (mul (add (mul u s) (mul v t)) a) :=
  have s1 : mul u ea = add u (mul (mul u s) a) :=
    Eq.trans (congrArg (fun w => mul u w) hea)
      (Eq.trans (left_distrib' u one (mul s a))
        (Eq.trans (congrArg (fun w => add w (mul u (mul s a))) (mul_one' u))
          (congrArg (fun w => add u w) (Eq.symm (mul_assoc' u s a)))))
  have s2 : mul v eb = mul (mul v t) a :=
    Eq.trans (congrArg (fun w => mul v w) heb) (Eq.symm (mul_assoc' v t a))
  Eq.trans (congrArg (fun w => add w (mul v eb)) s1)
    (Eq.trans (congrArg (fun w => add (add u (mul (mul u s) a)) w) s2)
      (Eq.trans (add_assoc' u (mul (mul u s) a) (mul (mul v t) a))
        (congrArg (fun w => add u w)
          (Eq.symm (right_distrib' (mul u s) (mul v t) a)))))

/-! ### The moduli 2 and 3, computed -/

theorem pieces23 :
    3 = 1 + 1 * 2 ∧ 3 = 1 * 3 ∧ 4 = 2 * 2 ∧ 4 = 1 + 1 * 3 ∧ 3 + 4 = 1 + 1 * 6 :=
  ⟨rfl, rfl, rfl, rfl, rfl⟩

theorem pieces23_idem :
    rem 6 (3 * 3) = 3 ∧ rem 6 (4 * 4) = 4 ∧ rem 6 (3 * 4) = 0 :=
  ⟨rfl, rfl, rfl⟩

def rd (n : Nat) : Nat × Nat := (rem 2 n, rem 3 n)

def pl (u v : Nat) : Nat := rem 6 (3 * u + 4 * v)

theorem crt23_read_place :
    rd (pl 0 0) = (0, 0) ∧ rd (pl 0 1) = (0, 1) ∧ rd (pl 0 2) = (0, 2) ∧
    rd (pl 1 0) = (1, 0) ∧ rd (pl 1 1) = (1, 1) ∧ rd (pl 1 2) = (1, 2) :=
  ⟨rfl, rfl, rfl, rfl, rfl, rfl⟩

theorem crt23_place_read :
    pl (rd 0).1 (rd 0).2 = 0 ∧ pl (rd 1).1 (rd 1).2 = 1 ∧
    pl (rd 2).1 (rd 2).2 = 2 ∧ pl (rd 3).1 (rd 3).2 = 3 ∧
    pl (rd 4).1 (rd 4).2 = 4 ∧ pl (rd 5).1 (rd 5).2 = 5 :=
  ⟨rfl, rfl, rfl, rfl, rfl, rfl⟩

/-! ## Link 25. The Chinese remainder theorem for a list of moduli

  An entry `(w, a)` stands for the modulus `w + 1` and the value `a`.
-/

/-- A product of invertibles is invertible. -/
theorem inv_mul (a b1 b2 y1 s1 y2 s2 : Nat)
    (h1 : y1 * b1 = 1 + s1 * a) (h2 : y2 * b2 = 1 + s2 * a) :
    (y1 * y2) * (b1 * b2) = 1 + (s1 + (1 + s1 * a) * s2) * a :=
  Eq.trans (mmid4 y1 y2 b1 b2)
    (Eq.trans (congrArg (fun z => z * (y2 * b2)) h1)
      (Eq.trans (congrArg (fun z => (1 + s1 * a) * z) h2)
        (Eq.trans (nleft_distrib (1 + s1 * a) 1 (s2 * a))
          (Eq.trans
            (congrArg (fun z => z + (1 + s1 * a) * (s2 * a)) (nmul_one (1 + s1 * a)))
            (Eq.trans
              (congrArg (fun z => (1 + s1 * a) + z)
                (Eq.symm (nmul_assoc (1 + s1 * a) s2 a)))
              (Eq.trans (nadd_assoc 1 (s1 * a) (((1 + s1 * a) * s2) * a))
                (congrArg (fun z => 1 + z)
                  (Eq.symm (nright_distrib s1 ((1 + s1 * a) * s2) a)))))))))

/-- Every modulus in the list is invertible along `a`. -/
def AllInv (a : Nat) : List (Nat × Nat) → Prop
  | [] => True
  | p :: rest => (∃ y s, y * (p.1 + 1) = 1 + s * a) ∧ AllInv a rest

/-- Each later modulus is invertible along each earlier one. -/
def Good : List (Nat × Nat) → Prop
  | [] => True
  | p :: rest => AllInv (p.1 + 1) rest ∧ Good rest

def prodl : List (Nat × Nat) → Nat
  | [] => 1
  | p :: rest => (p.1 + 1) * prodl rest

/-- `c` reads as the listed value along every listed modulus. -/
def Sol (c : Nat) : List (Nat × Nat) → Prop
  | [] => True
  | p :: rest => rem (p.1 + 1) c = rem (p.1 + 1) p.2 ∧ Sol c rest

theorem prod_inv (a : Nat) :
    ∀ l : List (Nat × Nat), AllInv a l → ∃ y s, y * prodl l = 1 + s * a
  | [], _ => ⟨1, 0, Eq.symm (congrArg (fun z => 1 + z) (nzero_mul a))⟩
  | p :: rest, h =>
    have h' : (∃ y s, y * (p.1 + 1) = 1 + s * a) ∧ AllInv a rest := h
    match h'.1, prod_inv a rest h'.2 with
    | ⟨y1, s1, h1⟩, ⟨y2, s2, h2⟩ =>
      ⟨y1 * y2, s1 + (1 + s1 * a) * s2,
        inv_mul a (p.1 + 1) (prodl rest) y1 s1 y2 s2 h1 h2⟩

theorem sol_add :
    ∀ (l : List (Nat × Nat)) (c x : Nat), Sol c l → Sol (x * prodl l + c) l
  | [], _, _, _ => True.intro
  | p :: rest, c, x, h =>
    have h' : rem (p.1 + 1) c = rem (p.1 + 1) p.2 ∧ Sol c rest := h
    have e1 : x * ((p.1 + 1) * prodl rest) = (x * prodl rest) * (p.1 + 1) :=
      Eq.trans (congrArg (fun z => x * z) (nmul_comm (p.1 + 1) (prodl rest)))
        (Eq.symm (nmul_assoc x (prodl rest) (p.1 + 1)))
    have e2 : (x * (p.1 + 1)) * prodl rest = x * ((p.1 + 1) * prodl rest) :=
      nmul_assoc x (p.1 + 1) (prodl rest)
    show rem (p.1 + 1) (x * ((p.1 + 1) * prodl rest) + c) = rem (p.1 + 1) p.2
        ∧ Sol (x * ((p.1 + 1) * prodl rest) + c) rest from
      And.intro
        (Eq.trans
          (congrArg (fun z => rem (p.1 + 1) (z + c)) e1)
          (Eq.trans (rem_add_mul p.1 c (x * prodl rest)) h'.1))
        (Eq.mp (congrArg (fun z => Sol (z + c) rest) e2)
          (sol_add rest c (x * (p.1 + 1)) h'.2))

/-- The Chinese remainder theorem. -/
theorem crt_list : ∀ l : List (Nat × Nat), Good l → ∃ c, Sol c l
  | [], _ => ⟨0, True.intro⟩
  | p :: rest, h =>
    have h' : AllInv (p.1 + 1) rest ∧ Good rest := h
    match crt_list rest h'.2, prod_inv (p.1 + 1) rest h'.1 with
    | ⟨c0, hc0⟩, ⟨y, s, hy⟩ =>
      ⟨(c0 + s * (p.2 + p.1 * c0)) * (p.1 + 1) + p.2,
        show rem (p.1 + 1) ((c0 + s * (p.2 + p.1 * c0)) * (p.1 + 1) + p.2)
              = rem (p.1 + 1) p.2
            ∧ Sol ((c0 + s * (p.2 + p.1 * c0)) * (p.1 + 1) + p.2) rest from
          And.intro
            (rem_add_mul p.1 p.2 (c0 + s * (p.2 + p.1 * c0)))
            (Eq.mpr
              (congrArg (fun z => Sol z rest)
                (crt_pair p.1 (prodl rest) y s p.2 c0 hy))
              (sol_add rest c0 (y * (p.2 + p.1 * c0)) hc0))⟩

/-! ## Link 26. The factorial, from a step on pairs -/

def fstep (p : Nat × Nat) : Nat × Nat := (p.1 + 1, (p.1 + 1) * p.2)

def fact (n : Nat) : Nat := (iter n fstep (0, 1)).2

theorem fstep_fst : ∀ n : Nat, (iter n fstep (0, 1)).1 = n
  | 0 => rfl
  | n + 1 => congrArg Nat.succ (fstep_fst n)

theorem fact_zero : fact 0 = 1 := rfl

theorem fact_succ (n : Nat) : fact (n + 1) = (n + 1) * fact n :=
  congrArg (fun t => (t + 1) * fact n) (fstep_fst n)

theorem fact_values : fact 1 = 1 ∧ fact 2 = 2 ∧ fact 3 = 6 := ⟨rfl, rfl, rfl⟩

def mx (m n : Nat) : Nat := sel (sb m n) n m

/-- The factorial is positive. -/
theorem fact_pos : ∀ s : Nat, ∃ f, fact s = f + 1
  | 0 => ⟨0, rfl⟩
  | s + 1 =>
    match fact_pos s with
    | ⟨f, hf⟩ =>
      ⟨(s + 1) * f + s,
        Eq.trans (fact_succ s) (congrArg (fun t => (s + 1) * t) hf)⟩

/-- `s ≤ s!`. -/
theorem fact_ge : ∀ s : Nat, ∃ j, s + j = fact s
  | 0 => ⟨1, rfl⟩
  | s + 1 =>
    match fact_pos s with
    | ⟨f, hf⟩ =>
      ⟨(s + 1) * f,
        Eq.trans (nadd_comm (s + 1) ((s + 1) * f))
          (Eq.symm (Eq.trans (fact_succ s) (congrArg (fun t => (s + 1) * t) hf)))⟩

/-- If `1 ≤ k ≤ s` then `k` divides `s!`.
    In the middle case (`j = 0`, so `k + 1 = s + 1`) the number `k`
    enters only through `h`, so its binder is `_`. -/
theorem dvd_fact : ∀ (s k j : Nat), (k + 1) + j = s → ∃ e, fact s = (k + 1) * e
  | 0, k, j, h =>
    absurd (Eq.trans (Eq.symm (nsucc_add k j)) h) (succ_ne_zero' (k + j))
  | s + 1, _, 0, h =>
    ⟨fact s, Eq.trans (fact_succ s) (congrArg (fun t => t * fact s) (Eq.symm h))⟩
  | s + 1, k, j + 1, h =>
    match dvd_fact s k j (@succ_inj' ((k + 1) + j) s h) with
    | ⟨e, he⟩ =>
      ⟨(s + 1) * e,
        Eq.trans (fact_succ s)
          (Eq.trans (congrArg (fun t => (s + 1) * t) he)
            (Eq.trans (Eq.symm (nmul_assoc (s + 1) (k + 1) e))
              (Eq.trans (congrArg (fun t => t * e) (nmul_comm (s + 1) (k + 1)))
                (nmul_assoc (k + 1) (s + 1) e))))⟩

/-! ## Link 27. The moduli `(i+1) d + 1` -/

def md (d i : Nat) : Nat := (i + 1) * d + 1

theorem sq_lemma (w : Nat) : (w + 1) * (w + 1) = 1 + w * (w + 1 + 1) :=
  Eq.trans (congrArg (fun z => z + (w + 1)) (nsucc_mul w w))
    (nadd_comm ((w * w + w) + w) 1)

/-- With `d = k e` and `(i+1) d = w + 1`, the number
    `y = (i+1)(i+1) e` satisfies `y m(i+k) = 1 + (y + w) m(i)`. -/
theorem md_inv (i k d e w y : Nat) (he : d = k * e) (hw : (i + 1) * d = w + 1)
    (hy : y = ((i + 1) * (i + 1)) * e) :
    y * md d (i + k) = 1 + (y + w) * md d i :=
  have h_md : md d (i + k) = md d i + k * d :=
    Eq.trans (congrArg (fun z => z * d + 1) (Eq.symm (nsucc_add i k)))
      (Eq.trans (congrArg (fun z => z + 1) (nright_distrib (i + 1) k d))
        (nadd_right_comm ((i + 1) * d) (k * d) 1))
  have h_sq : y * (k * d) = (w + 1) * (w + 1) :=
    Eq.trans (congrArg (fun z => z * (k * d)) hy)
      (Eq.trans (nmul_assoc ((i + 1) * (i + 1)) e (k * d))
        (Eq.trans
          (congrArg (fun z => ((i + 1) * (i + 1)) * z) (Eq.symm (nmul_assoc e k d)))
          (Eq.trans
            (congrArg (fun z => ((i + 1) * (i + 1)) * (z * d)) (nmul_comm e k))
            (Eq.trans (Eq.symm (mmid4 (i + 1) (k * e) (i + 1) d))
              (Eq.trans
                (congrArg (fun z => ((i + 1) * z) * ((i + 1) * d)) (Eq.symm he))
                (Eq.trans (congrArg (fun z => z * ((i + 1) * d)) hw)
                  (congrArg (fun z => (w + 1) * z) hw)))))))
  have h_m : md d i = w + 1 + 1 := congrArg (fun z => z + 1) hw
  Eq.trans (congrArg (fun z => y * z) h_md)
    (Eq.trans (nleft_distrib y (md d i) (k * d))
      (Eq.trans (congrArg (fun z => y * md d i + z) h_sq)
        (Eq.trans (congrArg (fun z => y * md d i + z) (sq_lemma w))
          (Eq.trans
            (congrArg (fun z => y * md d i + (1 + w * z)) (Eq.symm h_m))
            (Eq.trans (nadd_left_comm (y * md d i) 1 (w * md d i))
              (congrArg (fun z => 1 + z)
                (Eq.symm (nright_distrib y w (md d i)))))))))

/-! ## Link 28. The beta function -/

def beta (c d i : Nat) : Nat := rem (md d i) c

theorem beta_seq_1_0 : beta 3 (fact 1) 0 = 1 ∧ beta 3 (fact 1) 1 = 0 := ⟨rfl, rfl⟩

theorem beta_seq_0_2 : beta 12 (fact 2) 0 = 0 ∧ beta 12 (fact 2) 1 = 2 := ⟨rfl, rfl⟩

/-- The entries for the indices `t, t+1, ..., t+h-1`. -/
def blist (a : Nat → Nat) (d : Nat) : Nat → Nat → List (Nat × Nat)
  | _, 0 => []
  | t, h + 1 => ((t + 1) * d, a t) :: blist a d (t + 1) h

theorem allinv (a : Nat → Nat) (s : Nat) :
    ∀ (h i k j : Nat), (k + h) + j = s →
      AllInv (md (fact s) i) (blist a (fact s) (i + (k + 1)) h)
  | 0, _, _, _, _ => True.intro
  | h + 1, i, k, j, hyp =>
    have hk : (k + 1) + (h + j) = s :=
      Eq.trans (nsucc_add k (h + j))
        (Eq.trans (congrArg Nat.succ (Eq.symm (nadd_assoc k h j)))
          (Eq.trans (Eq.symm (nsucc_add (k + h) j)) hyp))
    have hrec : ((k + 1) + h) + j = s :=
      Eq.trans (congrArg (fun z => z + j) (nsucc_add k h)) hyp
    match dvd_fact s k (h + j) hk, fact_pos s with
    | ⟨e, he⟩, ⟨f, hf⟩ =>
      have hw : (i + 1) * fact s = ((i + 1) * f + i) + 1 :=
        congrArg (fun z => (i + 1) * z) hf
      show (∃ y s', y * (((i + (k + 1)) + 1) * fact s + 1) = 1 + s' * md (fact s) i)
          ∧ AllInv (md (fact s) i) (blist a (fact s) ((i + (k + 1)) + 1) h) from
        And.intro
          ⟨((i + 1) * (i + 1)) * e, ((i + 1) * (i + 1)) * e + ((i + 1) * f + i),
            md_inv i (k + 1) (fact s) e ((i + 1) * f + i)
              (((i + 1) * (i + 1)) * e) he hw rfl⟩
          (allinv a s h i (k + 1) j hrec)

theorem good_blist (a : Nat → Nat) (s : Nat) :
    ∀ (h t j : Nat), h + j = s + 1 → Good (blist a (fact s) t h)
  | 0, _, _, _ => True.intro
  | h + 1, t, j, hj =>
    have hj' : h + j = s :=
      @succ_inj' (h + j) s (Eq.trans (Eq.symm (nsucc_add h j)) hj)
    show AllInv (((t + 1) * fact s) + 1) (blist a (fact s) (t + 1) h)
        ∧ Good (blist a (fact s) (t + 1) h) from
      And.intro
        (allinv a s h t 0 j (Eq.trans (congrArg (fun z => z + j) (nzero_add h)) hj'))
        (good_blist a s h (t + 1) (j + 1) (congrArg Nat.succ hj'))

theorem sol_get (a : Nat → Nat) (d c : Nat) :
    ∀ (h t e j : Nat), Sol c (blist a d t h) → e + (j + 1) = h →
      rem (md d (t + e)) c = rem (md d (t + e)) (a (t + e))
  | 0, _, e, j, _, hh => absurd hh (succ_ne_zero' (e + j))
  | h + 1, t, 0, _, hs, _ =>
    (show rem (md d t) c = rem (md d t) (a t) ∧ Sol c (blist a d (t + 1) h) from hs).1
  | h + 1, t, e + 1, j, hs, hh =>
    have hs' : rem (md d t) c = rem (md d t) (a t) ∧ Sol c (blist a d (t + 1) h) := hs
    have hh' : e + (j + 1) = h :=
      @succ_inj' (e + (j + 1)) h (Eq.trans (Eq.symm (nsucc_add e (j + 1))) hh)
    Eq.mp
      (congrArg (fun x => rem (md d x) c = rem (md d x) (a x)) (nsucc_add t e))
      (sol_get a d c h (t + 1) e j hs'.2 hh')

/-- A bound for the sequence: the sum of its first terms. -/
def bsum (a : Nat → Nat) : Nat → Nat
  | 0 => a 0
  | n + 1 => bsum a n + a (n + 1)

theorem bsum_ge (a : Nat → Nat) : ∀ (n i e : Nat), i + e = n → ∃ j, a i + j = bsum a n
  | 0, 0, _, _ => ⟨0, rfl⟩
  | 0, i + 1, e, h =>
    absurd (Eq.trans (Eq.symm (nsucc_add i e)) h) (succ_ne_zero' (i + e))
  | n + 1, i, 0, h =>
    ⟨bsum a n,
      Eq.trans (nadd_comm (a i) (bsum a n)) (congrArg (fun t => bsum a n + a t) h)⟩
  | n + 1, i, e + 1, h =>
    match bsum_ge a n i e (@succ_inj' (i + e) n h) with
    | ⟨j, hj⟩ =>
      ⟨j + a (n + 1),
        Eq.trans (Eq.symm (nadd_assoc (a i) j (a (n + 1))))
          (congrArg (fun t => t + a (n + 1)) hj)⟩

/-- If `x ≤ d` then `x` is below `(i+1) d + 1`. -/
theorem lt_md (i d x g : Nat) (hd : x + g = d) : x + ((i * d + g) + 1) = md d i :=
  Eq.trans (congrArg Nat.succ (nadd_left_comm x (i * d) g))
    (Eq.trans (congrArg (fun z => (i * d + z) + 1) hd)
      (congrArg (fun z => z + 1) (Eq.symm (nsucc_mul i d))))

/-- Goedel's beta function lemma. -/
theorem beta_lemma (a : Nat → Nat) (n : Nat) :
    ∃ c d, ∀ (i e : Nat), i + e = n → beta c d i = a i :=
  match crt_list (blist a (fact (n + bsum a n)) 0 (n + 1))
      (good_blist a (n + bsum a n) (n + 1) 0 (bsum a n) (nsucc_add n (bsum a n))) with
  | ⟨c, hc⟩ =>
    ⟨c, fact (n + bsum a n), fun i e hie =>
      match bsum_ge a n i e hie, fact_ge (n + bsum a n) with
      | ⟨j1, hj1⟩, ⟨j2, hj2⟩ =>
        have hd : a i + ((j1 + n) + j2) = fact (n + bsum a n) :=
          Eq.trans (Eq.symm (nadd_assoc (a i) (j1 + n) j2))
            (Eq.trans (congrArg (fun z => z + j2) (Eq.symm (nadd_assoc (a i) j1 n)))
              (Eq.trans (congrArg (fun z => (z + n) + j2) hj1)
                (Eq.trans (congrArg (fun z => z + j2) (nadd_comm (bsum a n) n)) hj2)))
        have hlt : a i + ((i * fact (n + bsum a n) + ((j1 + n) + j2)) + 1)
            = md (fact (n + bsum a n)) i :=
          lt_md i (fact (n + bsum a n)) (a i) ((j1 + n) + j2) hd
        have hsol : rem (md (fact (n + bsum a n)) (0 + i)) c
            = rem (md (fact (n + bsum a n)) (0 + i)) (a (0 + i)) :=
          sol_get a (fact (n + bsum a n)) c (n + 1) 0 i e hc (congrArg Nat.succ hie)
        have hsol' : rem (md (fact (n + bsum a n)) i) c
            = rem (md (fact (n + bsum a n)) i) (a i) :=
          Eq.mp
            (congrArg
              (fun x => rem (md (fact (n + bsum a n)) x) c
                        = rem (md (fact (n + bsum a n)) x) (a x))
              (nzero_add i))
            hsol
        Eq.trans hsol'
          (rem_of_fix (md (fact (n + bsum a n)) i) (a i)
            (fix_of_lt (md (fact (n + bsum a n)) i) (a i)
              (i * fact (n + bsum a n) + ((j1 + n) + j2)) hlt))⟩

/-! ## Link 29. A correct record of the steps is "n times" -/

theorem trace_iter {A : Type u} (f : A → A) (x : A) (tr : Nat → A)
    (h0 : tr 0 = x) (hs : ∀ i, tr (i + 1) = f (tr i)) :
    ∀ n : Nat, tr n = iter n f x
  | 0 => h0
  | n + 1 => Eq.trans (hs n) (congrArg f (trace_iter f x tr h0 hs n))

/-! ## Axiom check (all should report no axioms) -/

#print axioms e1_idem
#print axioms split_idem
#print axioms read_inj
#print axioms iter_add
#print axioms iter_mul
#print axioms nmul_comm
#print axioms nmul_assoc
#print axioms nright_distrib
#print axioms succ_inj'
#print axioms sb_add_cancel
#print axioms sb_eq
#print axioms rem_values
#print axioms rem_lt
#print axioms rem_idem
#print axioms rem_add_mul
#print axioms ustep_diag
#print axioms ustep_reaches
#print axioms euclid_line
#print axioms piece_idem
#print axioms crt_pair
#print axioms crt_read
#print axioms crt23_read_place
#print axioms crt23_place_read
#print axioms crt_list
#print axioms dvd_fact
#print axioms md_inv
#print axioms beta_seq_1_0
#print axioms beta_seq_0_2
#print axioms beta_lemma
#print axioms trace_iter

end BetaChain

/-! ## The same theorems as they stand in the library -/

#check @Nat.mod_mod
#check @Nat.gcd_eq_gcd_ab
#check @Nat.Coprime.dvd_of_dvd_mul_left
#check @Nat.chineseRemainder
#check @Nat.coprime_mul_succ
#check @Nat.beta
#check @Nat.unbeta
#check @Nat.beta_unbeta_coe