source stringlengths 17 118 | lean4 stringlengths 0 335k |
|---|---|
.lake/packages/mathlib/Mathlib/Algebra/ContinuedFractions/Computation/Basic.lean | import Mathlib.Algebra.ContinuedFractions.Basic
import Mathlib.Algebra.Order.Floor.Defs
/-!
# Computable Continued Fractions
## Summary
We formalise the standard computation of (regular) continued fractions for linear ordered floor
fields. The algorithm is rather simple. Here is an outline of the procedure adapted from Wikipedia:
Take a value `v`. We call `⌊v⌋` the *integer part* of `v` and `v - ⌊v⌋` the *fractional part* of
`v`. A continued fraction representation of `v` can then be given by `[⌊v⌋; b₀, b₁, b₂,...]`, where
`[b₀; b₁, b₂,...]` recursively is the continued fraction representation of `1 / (v - ⌊v⌋)`. This
process stops when the fractional part hits 0.
In other words: to calculate a continued fraction representation of a number `v`, write down the
integer part (i.e. the floor) of `v`. Subtract this integer part from `v`. If the difference is 0,
stop; otherwise find the reciprocal of the difference and repeat. The procedure will terminate if
and only if `v` is rational.
For an example, refer to `IntFractPair.stream`.
## Main definitions
- `GenContFract.IntFractPair.stream`: computes the stream of integer and fractional parts of a given
value as described in the summary.
- `GenContFract.of`: computes the generalised continued fraction of a value `v`.
In fact, it computes a regular continued fraction that terminates if and only if `v` is rational.
## Implementation Notes
There is an intermediate definition `GenContFract.IntFractPair.seq1` between
`GenContFract.IntFractPair.stream` and `GenContFract.of` to wire up things. Users should not
(need to) directly interact with it.
The computation of the integer and fractional pairs of a value can elegantly be
captured by a recursive computation of a stream of option pairs. This is done in
`IntFractPair.stream`. However, the type then does not guarantee the first pair to always be
`some` value, as expected by a continued fraction.
To separate concerns, we first compute a single head term that always exists in
`GenContFract.IntFractPair.seq1` followed by the remaining stream of option pairs. This sequence
with a head term (`seq1`) is then transformed to a generalized continued fraction in
`GenContFract.of` by extracting the wanted integer parts of the head term and the stream.
## References
- https://en.wikipedia.org/wiki/Continued_fraction
## Tags
numerics, number theory, approximations, fractions
-/
assert_not_exists Finset
namespace GenContFract
-- Fix a carrier `K`.
variable (K : Type*)
/-- We collect an integer part `b = ⌊v⌋` and fractional part `fr = v - ⌊v⌋` of a value `v` in a pair
`⟨b, fr⟩`.
-/
structure IntFractPair where
b : ℤ
fr : K
variable {K}
/-! Interlude: define some expected coercions and instances. -/
namespace IntFractPair
/-- Make an `IntFractPair` printable. -/
instance [Repr K] : Repr (IntFractPair K) :=
⟨fun p _ => "(b : " ++ repr p.b ++ ", fract : " ++ repr p.fr ++ ")"⟩
instance inhabited [Inhabited K] : Inhabited (IntFractPair K) :=
⟨⟨0, default⟩⟩
/-- Maps a function `f` on the fractional components of a given pair.
-/
def mapFr {β : Type*} (f : K → β) (gp : IntFractPair K) : IntFractPair β :=
⟨gp.b, f gp.fr⟩
section coe
/-! Interlude: define some expected coercions. -/
-- Fix another type `β` which we will convert to.
variable {β : Type*} [Coe K β]
/-- The coercion between integer-fraction pairs happens componentwise. -/
@[coe]
def coeFn : IntFractPair K → IntFractPair β := mapFr (↑)
/-- Coerce a pair by coercing the fractional component. -/
instance coe : Coe (IntFractPair K) (IntFractPair β) where
coe := coeFn
@[simp, norm_cast]
theorem coe_to_intFractPair {b : ℤ} {fr : K} :
(↑(IntFractPair.mk b fr) : IntFractPair β) = IntFractPair.mk b (↑fr : β) :=
rfl
end coe
-- Fix a discrete linear ordered division ring with `floor` function.
variable [DivisionRing K] [LinearOrder K] [FloorRing K]
/-- Creates the integer and fractional part of a value `v`, i.e. `⟨⌊v⌋, v - ⌊v⌋⟩`. -/
protected def of (v : K) : IntFractPair K :=
⟨⌊v⌋, Int.fract v⟩
/-- Creates the stream of integer and fractional parts of a value `v` needed to obtain the continued
fraction representation of `v` in `GenContFract.of`. More precisely, given a value `v : K`, it
recursively computes a stream of option `ℤ × K` pairs as follows:
- `stream v 0 = some ⟨⌊v⌋, v - ⌊v⌋⟩`
- `stream v (n + 1) = some ⟨⌊frₙ⁻¹⌋, frₙ⁻¹ - ⌊frₙ⁻¹⌋⟩`,
if `stream v n = some ⟨_, frₙ⟩` and `frₙ ≠ 0`
- `stream v (n + 1) = none`, otherwise
For example, let `(v : ℚ) := 3.4`. The process goes as follows:
- `stream v 0 = some ⟨⌊v⌋, v - ⌊v⌋⟩ = some ⟨3, 0.4⟩`
- `stream v 1 = some ⟨⌊0.4⁻¹⌋, 0.4⁻¹ - ⌊0.4⁻¹⌋⟩ = some ⟨⌊2.5⌋, 2.5 - ⌊2.5⌋⟩ = some ⟨2, 0.5⟩`
- `stream v 2 = some ⟨⌊0.5⁻¹⌋, 0.5⁻¹ - ⌊0.5⁻¹⌋⟩ = some ⟨⌊2⌋, 2 - ⌊2⌋⟩ = some ⟨2, 0⟩`
- `stream v n = none`, for `n ≥ 3`
-/
protected def stream (v : K) : Stream' <| Option (IntFractPair K)
| 0 => some (IntFractPair.of v)
| n + 1 =>
(IntFractPair.stream v n).bind fun ap_n =>
if ap_n.fr = 0 then none else some (IntFractPair.of ap_n.fr⁻¹)
/-- Shows that `IntFractPair.stream` has the sequence property, that is once we return `none` at
position `n`, we also return `none` at `n + 1`.
-/
theorem stream_isSeq (v : K) : (IntFractPair.stream v).IsSeq := by
intro _ hyp
simp [IntFractPair.stream, hyp]
/--
Uses `IntFractPair.stream` to create a sequence with head (i.e. `seq1`) of integer and fractional
parts of a value `v`. The first value of `IntFractPair.stream` is never `none`, so we can safely
extract it and put the tail of the stream in the sequence part.
This is just an intermediate representation and users should not (need to) directly interact with
it. The setup of rewriting/simplification lemmas that make the definitions easy to use is done in
`Mathlib/Algebra/ContinuedFractions/Computation/Translations.lean`.
-/
protected def seq1 (v : K) : Stream'.Seq1 <| IntFractPair K :=
⟨IntFractPair.of v, -- the head
-- take the tail of `IntFractPair.stream` since the first element is already in the head
Stream'.Seq.tail
-- create a sequence from `IntFractPair.stream`
⟨IntFractPair.stream v, -- the underlying stream
stream_isSeq v⟩⟩ -- the proof that the stream is a sequence
end IntFractPair
/-- Returns the `GenContFract` of a value. In fact, the returned gcf is also a `ContFract` that
terminates if and only if `v` is rational
(see `Mathlib/Algebra/ContinuedFractions/Computation/TerminatesIffRat.lean`).
The continued fraction representation of `v` is given by `[⌊v⌋; b₀, b₁, b₂,...]`, where
`[b₀; b₁, b₂,...]` recursively is the continued fraction representation of `1 / (v - ⌊v⌋)`. This
process stops when the fractional part `v - ⌊v⌋` hits 0 at some step.
The implementation uses `IntFractPair.stream` to obtain the partial denominators of the continued
fraction. Refer to said function for more details about the computation process.
-/
protected def of [DivisionRing K] [LinearOrder K] [FloorRing K] (v : K) : GenContFract K :=
let ⟨h, s⟩ := IntFractPair.seq1 v -- get the sequence of integer and fractional parts.
⟨h.b, -- the head is just the first integer part
s.map fun p => ⟨1, p.b⟩⟩ -- the sequence consists of the remaining integer parts as the partial
-- denominators; all partial numerators are simply 1
end GenContFract |
.lake/packages/mathlib/Mathlib/Algebra/ContinuedFractions/Computation/CorrectnessTerminating.lean | import Mathlib.Algebra.ContinuedFractions.Computation.Translations
import Mathlib.Algebra.ContinuedFractions.TerminatedStable
import Mathlib.Algebra.ContinuedFractions.ContinuantsRecurrence
import Mathlib.Order.Filter.AtTopBot.Basic
import Mathlib.Tactic.FieldSimp
import Mathlib.Tactic.Ring
/-!
# Correctness of Terminating Continued Fraction Computations (`GenContFract.of`)
## Summary
We show the correctness of the algorithm computing continued fractions (`GenContFract.of`)
in case of termination in the following sense:
At every step `n : ℕ`, we can obtain the value `v` by adding a specific residual term to the last
denominator of the fraction described by `(GenContFract.of v).convs' n`.
The residual term will be zero exactly when the continued fraction terminated; otherwise, the
residual term will be given by the fractional part stored in `GenContFract.IntFractPair.stream v n`.
For an example, refer to
`GenContFract.compExactValue_correctness_of_stream_eq_some` and for more
information about the computation process, refer to `Algebra.ContinuedFractions.Computation.Basic`.
## Main definitions
- `GenContFract.compExactValue` can be used to compute the exact value approximated by the
continued fraction `GenContFract.of v` by adding a residual term as described in the summary.
## Main Theorems
- `GenContFract.compExactValue_correctness_of_stream_eq_some` shows that
`GenContFract.compExactValue` indeed returns the value `v` when given the convergent and
fractional part as described in the summary.
- `GenContFract.of_correctness_of_terminatedAt` shows the equality
`v = (GenContFract.of v).convs n` if `GenContFract.of v` terminated at position `n`.
-/
assert_not_exists Finset
namespace GenContFract
open GenContFract (of)
-- `compExactValue_correctness_of_stream_eq_some` does not trivially generalize to `DivisionRing`
variable {K : Type*} [Field K] [LinearOrder K] {v : K} {n : ℕ}
/-- Given two continuants `pconts` and `conts` and a value `fr`, this function returns
- `conts.a / conts.b` if `fr = 0`
- `exactConts.a / exactConts.b` where `exactConts = nextConts 1 fr⁻¹ pconts conts`
otherwise.
This function can be used to compute the exact value approximated by a continued fraction
`GenContFract.of v` as described in lemma `compExactValue_correctness_of_stream_eq_some`.
-/
protected def compExactValue (pconts conts : Pair K) (fr : K) : K :=
-- if the fractional part is zero, we exactly approximated the value by the last continuants
if fr = 0 then
conts.a / conts.b
else -- otherwise, we have to include the fractional part in a final continuants step.
let exactConts := nextConts 1 fr⁻¹ pconts conts
exactConts.a / exactConts.b
variable [FloorRing K]
/-- Just a computational lemma we need for the next main proof. -/
protected theorem compExactValue_correctness_of_stream_eq_some_aux_comp {a : K} (b c : K)
(fract_a_ne_zero : Int.fract a ≠ 0) :
((⌊a⌋ : K) * b + c) / Int.fract a + b = (b * a + c) / Int.fract a := by
field_simp
rw [Int.fract]
ring
open GenContFract
(compExactValue compExactValue_correctness_of_stream_eq_some_aux_comp)
/-- Shows the correctness of `compExactValue` in case the continued fraction
`GenContFract.of v` did not terminate at position `n`. That is, we obtain the
value `v` if we pass the two successive (auxiliary) continuants at positions `n` and `n + 1` as well
as the fractional part at `IntFractPair.stream n` to `compExactValue`.
The correctness might be seen more readily if one uses `convs'` to evaluate the continued
fraction. Here is an example to illustrate the idea:
Let `(v : ℚ) := 3.4`. We have
- `GenContFract.IntFractPair.stream v 0 = some ⟨3, 0.4⟩`, and
- `GenContFract.IntFractPair.stream v 1 = some ⟨2, 0.5⟩`.
Now `(GenContFract.of v).convs' 1 = 3 + 1/2`, and our fractional term at position `2` is `0.5`.
We hence have `v = 3 + 1/(2 + 0.5) = 3 + 1/2.5 = 3.4`.
This computation corresponds exactly to the one using the recurrence equation in `compExactValue`.
-/
theorem compExactValue_correctness_of_stream_eq_some :
∀ {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n →
v = compExactValue ((of v).contsAux n) ((of v).contsAux <| n + 1) ifp_n.fr := by
let g := of v
induction n with
| zero =>
intro ifp_zero stream_zero_eq
obtain rfl : IntFractPair.of v = ifp_zero := by
have : IntFractPair.stream v 0 = some (IntFractPair.of v) := rfl
simpa only [this, Option.some.injEq] using stream_zero_eq
cases eq_or_ne (Int.fract v) 0 with
| inl fract_eq_zero =>
-- Int.fract v = 0; we must then have `v = ⌊v⌋`
suffices v = ⌊v⌋ by
simpa [nextConts, nextNum, nextDen, compExactValue, IntFractPair.of, fract_eq_zero]
calc
v = Int.fract v + ⌊v⌋ := by rw [Int.fract_add_floor]
_ = ⌊v⌋ := by simp [fract_eq_zero]
| inr fract_ne_zero =>
-- Int.fract v ≠ 0; the claim then easily follows by unfolding a single computation step
simp [field, contsAux, nextConts, nextNum, nextDen, of_h_eq_floor, compExactValue,
IntFractPair.of, fract_ne_zero]
| succ n IH =>
intro ifp_succ_n succ_nth_stream_eq
obtain ⟨ifp_n, nth_stream_eq, nth_fract_ne_zero, -⟩ :
∃ ifp_n, IntFractPair.stream v n = some ifp_n ∧
ifp_n.fr ≠ 0 ∧ IntFractPair.of ifp_n.fr⁻¹ = ifp_succ_n :=
IntFractPair.succ_nth_stream_eq_some_iff.1 succ_nth_stream_eq
-- introduce some notation
let conts := g.contsAux (n + 2)
set pconts := g.contsAux (n + 1) with pconts_eq
set ppconts := g.contsAux n with ppconts_eq
cases eq_or_ne ifp_succ_n.fr 0 with
| inl ifp_succ_n_fr_eq_zero =>
-- ifp_succ_n.fr = 0
suffices v = conts.a / conts.b by simpa [compExactValue, ifp_succ_n_fr_eq_zero]
-- use the IH and the fact that ifp_n.fr⁻¹ = ⌊ifp_n.fr⁻¹⌋ to prove this case
obtain ⟨ifp_n', nth_stream_eq', ifp_n_fract_inv_eq_floor⟩ :
∃ ifp_n, IntFractPair.stream v n = some ifp_n ∧ ifp_n.fr⁻¹ = ⌊ifp_n.fr⁻¹⌋ :=
IntFractPair.exists_succ_nth_stream_of_fr_zero succ_nth_stream_eq ifp_succ_n_fr_eq_zero
have : ifp_n' = ifp_n := by injection Eq.trans nth_stream_eq'.symm nth_stream_eq
cases this
have s_nth_eq : g.s.get? n = some ⟨1, ⌊ifp_n.fr⁻¹⌋⟩ :=
get?_of_eq_some_of_get?_intFractPair_stream_fr_ne_zero nth_stream_eq nth_fract_ne_zero
rw [← ifp_n_fract_inv_eq_floor] at s_nth_eq
suffices v = compExactValue ppconts pconts ifp_n.fr by
simpa [conts, contsAux, s_nth_eq, compExactValue, nth_fract_ne_zero] using this
exact IH nth_stream_eq
| inr ifp_succ_n_fr_ne_zero =>
-- ifp_succ_n.fr ≠ 0
-- use the IH to show that the following equality suffices
suffices
compExactValue ppconts pconts ifp_n.fr = compExactValue pconts conts ifp_succ_n.fr by grind
-- get the correspondence between ifp_n and ifp_succ_n
obtain ⟨ifp_n', nth_stream_eq', ifp_n_fract_ne_zero, ⟨refl⟩⟩ :
∃ ifp_n, IntFractPair.stream v n = some ifp_n ∧
ifp_n.fr ≠ 0 ∧ IntFractPair.of ifp_n.fr⁻¹ = ifp_succ_n :=
IntFractPair.succ_nth_stream_eq_some_iff.1 succ_nth_stream_eq
have : ifp_n' = ifp_n := by injection Eq.trans nth_stream_eq'.symm nth_stream_eq
cases this
-- get the correspondence between ifp_n and g.s.nth n
have s_nth_eq : g.s.get? n = some ⟨1, (⌊ifp_n.fr⁻¹⌋ : K)⟩ :=
get?_of_eq_some_of_get?_intFractPair_stream_fr_ne_zero nth_stream_eq ifp_n_fract_ne_zero
-- the claim now follows by unfolding the definitions and tedious calculations
-- some shorthand notation
let ppA := ppconts.a
let ppB := ppconts.b
let pA := pconts.a
let pB := pconts.b
have : compExactValue ppconts pconts ifp_n.fr =
(ppA + ifp_n.fr⁻¹ * pA) / (ppB + ifp_n.fr⁻¹ * pB) := by
-- unfold compExactValue and the convergent computation once
simp only [compExactValue, ifp_n_fract_ne_zero, ↓reduceIte, nextConts, nextNum, one_mul,
nextDen, ppA, ppB]
ac_rfl
rw [this]
-- two calculations needed to show the claim
have tmp_calc :=
compExactValue_correctness_of_stream_eq_some_aux_comp pA ppA ifp_succ_n_fr_ne_zero
have tmp_calc' :=
compExactValue_correctness_of_stream_eq_some_aux_comp pB ppB ifp_succ_n_fr_ne_zero
let f := Int.fract (1 / ifp_n.fr)
have f_ne_zero : f ≠ 0 := by simpa [f] using ifp_succ_n_fr_ne_zero
-- now unfold the recurrence one step and simplify both sides to arrive at the conclusion
dsimp only [conts, pconts, ppconts]
have hfr : (IntFractPair.of (1 / ifp_n.fr)).fr = f := rfl
simp [compExactValue, contsAux_recurrence s_nth_eq ppconts_eq pconts_eq,
nextConts, nextNum, nextDen]
grind
open GenContFract (of_terminatedAt_n_iff_succ_nth_intFractPair_stream_eq_none)
/-- The convergent of `GenContFract.of v` at step `n - 1` is exactly `v` if the
`IntFractPair.stream` of the corresponding continued fraction terminated at step `n`. -/
theorem of_correctness_of_nth_stream_eq_none (nth_stream_eq_none : IntFractPair.stream v n = none) :
v = (of v).convs (n - 1) := by
induction n with
| zero => contradiction
-- IntFractPair.stream v 0 ≠ none
| succ n IH =>
let g := of v
change v = g.convs n
obtain ⟨nth_stream_eq_none⟩ | ⟨ifp_n, nth_stream_eq, nth_stream_fr_eq_zero⟩ :
IntFractPair.stream v n = none ∨ ∃ ifp, IntFractPair.stream v n = some ifp ∧ ifp.fr = 0 :=
IntFractPair.succ_nth_stream_eq_none_iff.1 nth_stream_eq_none
· cases n with
| zero => contradiction
| succ n' =>
-- IntFractPair.stream v 0 ≠ none
have : g.TerminatedAt n' :=
of_terminatedAt_n_iff_succ_nth_intFractPair_stream_eq_none.2
nth_stream_eq_none
have : g.convs (n' + 1) = g.convs n' :=
convs_stable_of_terminated n'.le_succ this
rw [this]
exact IH nth_stream_eq_none
· simpa [nth_stream_fr_eq_zero, compExactValue] using
compExactValue_correctness_of_stream_eq_some nth_stream_eq
/-- If `GenContFract.of v` terminated at step `n`, then the `n`th convergent is exactly `v`. -/
theorem of_correctness_of_terminatedAt (terminatedAt_n : (of v).TerminatedAt n) :
v = (of v).convs n :=
have : IntFractPair.stream v (n + 1) = none :=
of_terminatedAt_n_iff_succ_nth_intFractPair_stream_eq_none.1 terminatedAt_n
of_correctness_of_nth_stream_eq_none this
/-- If `GenContFract.of v` terminates, then there is `n : ℕ` such that the `n`th convergent is
exactly `v`.
-/
theorem of_correctness_of_terminates (terminates : (of v).Terminates) :
∃ n : ℕ, v = (of v).convs n :=
Exists.elim terminates fun n terminatedAt_n =>
Exists.intro n (of_correctness_of_terminatedAt terminatedAt_n)
open Filter
/-- If `GenContFract.of v` terminates, then its convergents will eventually always be `v`. -/
theorem of_correctness_atTop_of_terminates (terminates : (of v).Terminates) :
∀ᶠ n in atTop, v = (of v).convs n := by
rw [eventually_atTop]
obtain ⟨n, terminatedAt_n⟩ : ∃ n, (of v).TerminatedAt n := terminates
use n
intro m m_geq_n
rw [convs_stable_of_terminated m_geq_n terminatedAt_n]
exact of_correctness_of_terminatedAt terminatedAt_n
end GenContFract |
.lake/packages/mathlib/Mathlib/Algebra/ContinuedFractions/Computation/TerminatesIffRat.lean | import Mathlib.Algebra.ContinuedFractions.Computation.Approximations
import Mathlib.Algebra.ContinuedFractions.Computation.CorrectnessTerminating
import Mathlib.Data.Rat.Floor
/-!
# Termination of Continued Fraction Computations (`GenContFract.of`)
## Summary
We show that the continued fraction for a value `v`, as defined in
`Mathlib/Algebra/ContinuedFractions/Basic.lean`, terminates if and only if `v` corresponds to a
rational number, that is `↑v = q` for some `q : ℚ`.
## Main Theorems
- `GenContFract.coe_of_rat_eq` shows that
`GenContFract.of v = GenContFract.of q` for `v : α` given that `↑v = q` and `q : ℚ`.
- `GenContFract.terminates_iff_rat` shows that
`GenContFract.of v` terminates if and only if `↑v = q` for some `q : ℚ`.
## Tags
rational, continued fraction, termination
-/
namespace GenContFract
open GenContFract (of)
variable {K : Type*} [Field K] [LinearOrder K] [IsStrictOrderedRing K] [FloorRing K]
/-
We will have to constantly coerce along our structures in the following proofs using their provided
map functions.
-/
attribute [local simp] Pair.map IntFractPair.mapFr
section RatOfTerminates
/-!
### Terminating Continued Fractions Are Rational
We want to show that the computation of a continued fraction `GenContFract.of v`
terminates if and only if `v ∈ ℚ`. In this section, we show the implication from left to right.
We first show that every finite convergent corresponds to a rational number `q` and then use the
finite correctness proof (`of_correctness_of_terminates`) of `GenContFract.of` to show that
`v = ↑q`.
-/
variable (v : K) (n : ℕ)
nonrec theorem exists_gcf_pair_rat_eq_of_nth_contsAux :
∃ conts : Pair ℚ, (of v).contsAux n = (conts.map (↑) : Pair K) :=
Nat.strong_induction_on n
(by
clear n
let g := of v
intro n IH
rcases n with (_ | _ | n)
-- n = 0
· suffices ∃ gp : Pair ℚ, Pair.mk (1 : K) 0 = gp.map (↑) by simpa [contsAux]
use Pair.mk 1 0
simp
-- n = 1
· suffices ∃ conts : Pair ℚ, Pair.mk g.h 1 = conts.map (↑) by simpa [contsAux]
use Pair.mk ⌊v⌋ 1
simp [g]
-- 2 ≤ n
· obtain ⟨pred_conts, pred_conts_eq⟩ := IH (n + 1) <| lt_add_one (n + 1)
-- invoke the IH
rcases s_ppred_nth_eq : g.s.get? n with gp_n | gp_n
-- option.none
· use pred_conts
have : g.contsAux (n + 2) = g.contsAux (n + 1) :=
contsAux_stable_of_terminated (n + 1).le_succ s_ppred_nth_eq
simp only [g, this, pred_conts_eq]
-- option.some
· -- invoke the IH a second time
obtain ⟨ppred_conts, ppred_conts_eq⟩ :=
IH n <| lt_of_le_of_lt n.le_succ <| lt_add_one <| n + 1
obtain ⟨a_eq_one, z, b_eq_z⟩ : gp_n.a = 1 ∧ ∃ z : ℤ, gp_n.b = (z : K) :=
of_partNum_eq_one_and_exists_int_partDen_eq s_ppred_nth_eq
-- finally, unfold the recurrence to obtain the required rational value.
simp only [g, a_eq_one, b_eq_z,
contsAux_recurrence s_ppred_nth_eq ppred_conts_eq pred_conts_eq]
use nextConts 1 (z : ℚ) ppred_conts pred_conts
cases ppred_conts; cases pred_conts
simp [nextConts, nextNum, nextDen])
theorem exists_gcf_pair_rat_eq_nth_conts :
∃ conts : Pair ℚ, (of v).conts n = (conts.map (↑) : Pair K) := by
rw [nth_cont_eq_succ_nth_contAux]; exact exists_gcf_pair_rat_eq_of_nth_contsAux v <| n + 1
theorem exists_rat_eq_nth_num : ∃ q : ℚ, (of v).nums n = (q : K) := by
rcases exists_gcf_pair_rat_eq_nth_conts v n with ⟨⟨a, _⟩, nth_cont_eq⟩
use a
simp [num_eq_conts_a, nth_cont_eq]
theorem exists_rat_eq_nth_den : ∃ q : ℚ, (of v).dens n = (q : K) := by
rcases exists_gcf_pair_rat_eq_nth_conts v n with ⟨⟨_, b⟩, nth_cont_eq⟩
use b
simp [den_eq_conts_b, nth_cont_eq]
/-- Every finite convergent corresponds to a rational number. -/
theorem exists_rat_eq_nth_conv : ∃ q : ℚ, (of v).convs n = (q : K) := by
rcases exists_rat_eq_nth_num v n with ⟨Aₙ, nth_num_eq⟩
rcases exists_rat_eq_nth_den v n with ⟨Bₙ, nth_den_eq⟩
use Aₙ / Bₙ
simp [nth_num_eq, nth_den_eq, conv_eq_num_div_den]
variable {v}
/-- Every terminating continued fraction corresponds to a rational number. -/
theorem exists_rat_eq_of_terminates (terminates : (of v).Terminates) : ∃ q : ℚ, v = ↑q := by
obtain ⟨n, v_eq_conv⟩ : ∃ n, v = (of v).convs n := of_correctness_of_terminates terminates
obtain ⟨q, conv_eq_q⟩ : ∃ q : ℚ, (of v).convs n = (↑q : K) := exists_rat_eq_nth_conv v n
have : v = (↑q : K) := Eq.trans v_eq_conv conv_eq_q
use q, this
end RatOfTerminates
section RatTranslation
/-!
### Technical Translation Lemmas
Before we can show that the continued fraction of a rational number terminates, we have to prove
some technical translation lemmas. More precisely, in this section, we show that, given a rational
number `q : ℚ` and value `v : K` with `v = ↑q`, the continued fraction of `q` and `v` coincide.
In particular, we show that
```lean
(↑(GenContFract.of q : GenContFract ℚ) : GenContFract K) = GenContFract.of v
```
in `GenContFract.coe_of_rat_eq`.
To do this, we proceed bottom-up, showing the correspondence between the basic functions involved in
the Computation first and then lift the results step-by-step.
-/
-- The lifting works for arbitrary linear ordered fields with a floor function.
variable {v : K} {q : ℚ}
/-! First, we show the correspondence for the very basic functions in
`GenContFract.IntFractPair`. -/
namespace IntFractPair
theorem coe_of_rat_eq (v_eq_q : v = (↑q : K)) :
((IntFractPair.of q).mapFr (↑) : IntFractPair K) = IntFractPair.of v := by
simp [IntFractPair.of, v_eq_q]
theorem coe_stream_nth_rat_eq (v_eq_q : v = (↑q : K)) (n : ℕ) :
((IntFractPair.stream q n).map (mapFr (↑)) : Option <| IntFractPair K) =
IntFractPair.stream v n := by
induction n with
| zero =>
simp only [IntFractPair.stream, Option.map_some, coe_of_rat_eq v_eq_q]
| succ n IH =>
rw [v_eq_q] at IH
cases stream_q_nth_eq : IntFractPair.stream q n with
| none => simp [IntFractPair.stream, IH.symm, v_eq_q, stream_q_nth_eq]
| some ifp_n =>
obtain ⟨b, fr⟩ := ifp_n
rcases Decidable.em (fr = 0) with fr_zero | fr_ne_zero
· simp [IntFractPair.stream, IH.symm, v_eq_q, stream_q_nth_eq, fr_zero]
· replace IH : some (IntFractPair.mk b (fr : K)) = IntFractPair.stream (↑q) n := by
rwa [stream_q_nth_eq] at IH
have : (fr : K)⁻¹ = ((fr⁻¹ : ℚ) : K) := by norm_cast
have coe_of_fr := coe_of_rat_eq this
simpa [IntFractPair.stream, IH.symm, v_eq_q, stream_q_nth_eq, fr_ne_zero]
theorem coe_stream'_rat_eq (v_eq_q : v = (↑q : K)) :
((IntFractPair.stream q).map (Option.map (mapFr (↑))) : Stream' <| Option <| IntFractPair K) =
IntFractPair.stream v := by
funext n; exact IntFractPair.coe_stream_nth_rat_eq v_eq_q n
end IntFractPair
/-! Now we lift the coercion results to the continued fraction computation. -/
theorem coe_of_h_rat_eq (v_eq_q : v = (↑q : K)) : (↑((of q).h : ℚ) : K) = (of v).h := by
simp_all
theorem coe_of_s_get?_rat_eq (v_eq_q : v = (↑q : K)) (n : ℕ) :
(((of q).s.get? n).map (Pair.map (↑)) : Option <| Pair K) = (of v).s.get? n := by
simp only [of, IntFractPair.seq1, Stream'.Seq.map_get?, Stream'.Seq.get?_tail]
simp only [Stream'.Seq.get?]
rw [← IntFractPair.coe_stream'_rat_eq v_eq_q]
rcases succ_nth_stream_eq : IntFractPair.stream q (n + 1) with (_ | ⟨_, _⟩) <;>
simp [Stream'.map, Stream'.get, succ_nth_stream_eq]
theorem coe_of_s_rat_eq (v_eq_q : v = (↑q : K)) :
((of q).s.map (Pair.map ((↑))) : Stream'.Seq <| Pair K) = (of v).s := by
ext n; rw [← coe_of_s_get?_rat_eq v_eq_q]; rfl
/-- Given `(v : K), (q : ℚ), and v = q`, we have that `of q = of v` -/
theorem coe_of_rat_eq (v_eq_q : v = (↑q : K)) :
(⟨(of q).h, (of q).s.map (Pair.map (↑))⟩ : GenContFract K) = of v := by
rcases gcf_v_eq : of v with ⟨h, s⟩; subst v
obtain rfl : ↑⌊(q : K)⌋ = h := by injection gcf_v_eq
simp [coe_of_s_rat_eq rfl, gcf_v_eq]
theorem of_terminates_iff_of_rat_terminates {v : K} {q : ℚ} (v_eq_q : v = (q : K)) :
(of v).Terminates ↔ (of q).Terminates := by
constructor <;> intro h <;> obtain ⟨n, h⟩ := h <;> use n <;>
simp only [Stream'.Seq.TerminatedAt, (coe_of_s_get?_rat_eq v_eq_q n).symm] at h ⊢ <;>
cases h' : (of q).s.get? n <;>
simp only [h'] at h <;>
trivial
end RatTranslation
section TerminatesOfRat
/-!
### Continued Fractions of Rationals Terminate
Finally, we show that the continued fraction of a rational number terminates.
The crucial insight is that, given any `q : ℚ` with `0 < q < 1`, the numerator of `Int.fract q` is
smaller than the numerator of `q`. As the continued fraction computation recursively operates on
the fractional part of a value `v` and `0 ≤ Int.fract v < 1`, we infer that the numerator of the
fractional part in the computation decreases by at least one in each step. As `0 ≤ Int.fract v`,
this process must stop after finite number of steps, and the computation hence terminates.
-/
namespace IntFractPair
variable {q : ℚ} {n : ℕ}
/-- Shows that for any `q : ℚ` with `0 < q < 1`, the numerator of the fractional part of
`IntFractPair.of q⁻¹` is smaller than the numerator of `q`.
-/
theorem of_inv_fr_num_lt_num_of_pos (q_pos : 0 < q) : (IntFractPair.of q⁻¹).fr.num < q.num :=
Rat.fract_inv_num_lt_num_of_pos q_pos
/-- Shows that the sequence of numerators of the fractional parts of the stream is strictly
antitone. -/
theorem stream_succ_nth_fr_num_lt_nth_fr_num_rat {ifp_n ifp_succ_n : IntFractPair ℚ}
(stream_nth_eq : IntFractPair.stream q n = some ifp_n)
(stream_succ_nth_eq : IntFractPair.stream q (n + 1) = some ifp_succ_n) :
ifp_succ_n.fr.num < ifp_n.fr.num := by
obtain ⟨ifp_n', stream_nth_eq', ifp_n_fract_ne_zero, IntFractPair.of_eq_ifp_succ_n⟩ :
∃ ifp_n',
IntFractPair.stream q n = some ifp_n' ∧
ifp_n'.fr ≠ 0 ∧ IntFractPair.of ifp_n'.fr⁻¹ = ifp_succ_n :=
succ_nth_stream_eq_some_iff.mp stream_succ_nth_eq
have : ifp_n = ifp_n' := by injection Eq.trans stream_nth_eq.symm stream_nth_eq'
cases this
rw [← IntFractPair.of_eq_ifp_succ_n]
obtain ⟨zero_le_ifp_n_fract, _⟩ := nth_stream_fr_nonneg_lt_one stream_nth_eq
have : 0 < ifp_n.fr := lt_of_le_of_ne zero_le_ifp_n_fract <| ifp_n_fract_ne_zero.symm
exact of_inv_fr_num_lt_num_of_pos this
theorem stream_nth_fr_num_le_fr_num_sub_n_rat :
∀ {ifp_n : IntFractPair ℚ},
IntFractPair.stream q n = some ifp_n → ifp_n.fr.num ≤ (IntFractPair.of q).fr.num - n := by
induction n with
| zero =>
intro ifp_zero stream_zero_eq
have : IntFractPair.of q = ifp_zero := by injection stream_zero_eq
simp [le_refl, this.symm]
| succ n IH =>
intro ifp_succ_n stream_succ_nth_eq
suffices ifp_succ_n.fr.num + 1 ≤ (IntFractPair.of q).fr.num - n by
rw [Int.natCast_succ, sub_add_eq_sub_sub]
solve_by_elim [le_sub_right_of_add_le]
rcases succ_nth_stream_eq_some_iff.mp stream_succ_nth_eq with ⟨ifp_n, stream_nth_eq, -⟩
have : ifp_succ_n.fr.num < ifp_n.fr.num :=
stream_succ_nth_fr_num_lt_nth_fr_num_rat stream_nth_eq stream_succ_nth_eq
exact le_trans this (IH stream_nth_eq)
theorem exists_nth_stream_eq_none_of_rat (q : ℚ) : ∃ n : ℕ, IntFractPair.stream q n = none := by
let fract_q_num := (Int.fract q).num; let n := fract_q_num.natAbs + 1
rcases stream_nth_eq : IntFractPair.stream q n with ifp | ifp
· use n, stream_nth_eq
· -- arrive at a contradiction since the numerator decreased num + 1 times but every fractional
-- value is nonnegative.
have ifp_fr_num_le_q_fr_num_sub_n : ifp.fr.num ≤ fract_q_num - n :=
stream_nth_fr_num_le_fr_num_sub_n_rat stream_nth_eq
have : fract_q_num - n = -1 := by
have : 0 ≤ fract_q_num := Rat.num_nonneg.mpr (Int.fract_nonneg q)
simp only [n, Nat.cast_add, Int.natAbs_of_nonneg this, Nat.cast_one,
sub_add_eq_sub_sub_swap, sub_right_comm, sub_self, zero_sub]
have : 0 ≤ ifp.fr := (nth_stream_fr_nonneg_lt_one stream_nth_eq).left
have : 0 ≤ ifp.fr.num := Rat.num_nonneg.mpr this
cutsat
end IntFractPair
/-- The continued fraction of a rational number terminates. -/
theorem terminates_of_rat (q : ℚ) : (of q).Terminates :=
Exists.elim (IntFractPair.exists_nth_stream_eq_none_of_rat q) fun n stream_nth_eq_none =>
Exists.intro n
(have : IntFractPair.stream q (n + 1) = none := IntFractPair.stream_isSeq q stream_nth_eq_none
of_terminatedAt_n_iff_succ_nth_intFractPair_stream_eq_none.mpr this)
end TerminatesOfRat
/-- The continued fraction `GenContFract.of v` terminates if and only if `v ∈ ℚ`. -/
theorem terminates_iff_rat (v : K) : (of v).Terminates ↔ ∃ q : ℚ, v = (q : K) :=
Iff.intro
(fun terminates_v : (of v).Terminates =>
show ∃ q : ℚ, v = (q : K) from exists_rat_eq_of_terminates terminates_v)
fun exists_q_eq_v : ∃ q : ℚ, v = (↑q : K) =>
Exists.elim exists_q_eq_v fun q => fun v_eq_q : v = ↑q =>
have : (of q).Terminates := terminates_of_rat q
(of_terminates_iff_of_rat_terminates v_eq_q).mpr this
end GenContFract |
.lake/packages/mathlib/Mathlib/Algebra/ContinuedFractions/Computation/Translations.lean | import Mathlib.Algebra.ContinuedFractions.Computation.Basic
import Mathlib.Algebra.ContinuedFractions.Translations
import Mathlib.Algebra.Order.Floor.Ring
/-!
# Basic Translation Lemmas Between Structures Defined for Computing Continued Fractions
## Summary
This is a collection of simple lemmas between the different structures used for the computation
of continued fractions defined in `Mathlib/Algebra/ContinuedFractions/Computation/Basic.lean`.
The file consists of three sections:
1. Recurrences and inversion lemmas for `IntFractPair.stream`: these lemmas give us inversion
rules and recurrences for the computation of the stream of integer and fractional parts of
a value.
2. Translation lemmas for the head term: these lemmas show us that the head term of the computed
continued fraction of a value `v` is `⌊v⌋` and how this head term is moved along the structures
used in the computation process.
3. Translation lemmas for the sequence: these lemmas show how the sequences of the involved
structures (`IntFractPair.stream`, `IntFractPair.seq1`, and `GenContFract.of`) are connected,
i.e. how the values are moved along the structures and the termination of one sequence implies
the termination of another sequence.
## Main Theorems
- `succ_nth_stream_eq_some_iff` gives a recurrence to compute the `n + 1`th value of the sequence
of integer and fractional parts of a value in case of non-termination.
- `succ_nth_stream_eq_none_iff` gives a recurrence to compute the `n + 1`th value of the sequence
of integer and fractional parts of a value in case of termination.
- `get?_of_eq_some_of_succ_get?_intFractPair_stream` and
`get?_of_eq_some_of_get?_intFractPair_stream_fr_ne_zero` show how the entries of the sequence
of the computed continued fraction can be obtained from the stream of integer and fractional
parts.
-/
assert_not_exists Finset
namespace GenContFract
open GenContFract (of)
-- Fix a discrete linear ordered division ring with `floor` function and a value `v`.
variable {K : Type*} [DivisionRing K] [LinearOrder K] [FloorRing K] {v : K}
namespace IntFractPair
/-!
### Recurrences and Inversion Lemmas for `IntFractPair.stream`
Here we state some lemmas that give us inversion rules and recurrences for the computation of the
stream of integer and fractional parts of a value.
-/
theorem stream_zero (v : K) : IntFractPair.stream v 0 = some (IntFractPair.of v) :=
rfl
variable {n : ℕ}
theorem stream_eq_none_of_fr_eq_zero {ifp_n : IntFractPair K}
(stream_nth_eq : IntFractPair.stream v n = some ifp_n) (nth_fr_eq_zero : ifp_n.fr = 0) :
IntFractPair.stream v (n + 1) = none := by
obtain ⟨_, fr⟩ := ifp_n
change fr = 0 at nth_fr_eq_zero
simp [IntFractPair.stream, stream_nth_eq, nth_fr_eq_zero]
/-- Gives a recurrence to compute the `n + 1`th value of the sequence of integer and fractional
parts of a value in case of termination.
-/
theorem succ_nth_stream_eq_none_iff :
IntFractPair.stream v (n + 1) = none ↔
IntFractPair.stream v n = none ∨ ∃ ifp, IntFractPair.stream v n = some ifp ∧ ifp.fr = 0 := by
rw [IntFractPair.stream]
cases IntFractPair.stream v n <;> simp [imp_false]
/-- Gives a recurrence to compute the `n + 1`th value of the sequence of integer and fractional
parts of a value in case of non-termination.
-/
theorem succ_nth_stream_eq_some_iff {ifp_succ_n : IntFractPair K} :
IntFractPair.stream v (n + 1) = some ifp_succ_n ↔
∃ ifp_n : IntFractPair K,
IntFractPair.stream v n = some ifp_n ∧
ifp_n.fr ≠ 0 ∧ IntFractPair.of ifp_n.fr⁻¹ = ifp_succ_n := by
simp [IntFractPair.stream, ite_eq_iff, Option.bind_eq_some_iff]
/-- An easier to use version of one direction of
`GenContFract.IntFractPair.succ_nth_stream_eq_some_iff`. -/
theorem stream_succ_of_some {p : IntFractPair K} (h : IntFractPair.stream v n = some p)
(h' : p.fr ≠ 0) : IntFractPair.stream v (n + 1) = some (IntFractPair.of p.fr⁻¹) :=
succ_nth_stream_eq_some_iff.mpr ⟨p, h, h', rfl⟩
/-- The stream of `IntFractPair`s of an integer stops after the first term.
-/
theorem stream_succ_of_int [IsStrictOrderedRing K] (a : ℤ) (n : ℕ) :
IntFractPair.stream (a : K) (n + 1) = none := by
induction n with
| zero =>
refine IntFractPair.stream_eq_none_of_fr_eq_zero (IntFractPair.stream_zero (a : K)) ?_
simp only [IntFractPair.of, Int.fract_intCast]
| succ n ih => exact IntFractPair.succ_nth_stream_eq_none_iff.mpr (Or.inl ih)
theorem exists_succ_nth_stream_of_fr_zero {ifp_succ_n : IntFractPair K}
(stream_succ_nth_eq : IntFractPair.stream v (n + 1) = some ifp_succ_n)
(succ_nth_fr_eq_zero : ifp_succ_n.fr = 0) :
∃ ifp_n : IntFractPair K, IntFractPair.stream v n = some ifp_n ∧ ifp_n.fr⁻¹ = ⌊ifp_n.fr⁻¹⌋ := by
-- get the witness from `succ_nth_stream_eq_some_iff` and prove that it has the additional
-- properties
rcases succ_nth_stream_eq_some_iff.mp stream_succ_nth_eq with
⟨ifp_n, seq_nth_eq, _, rfl⟩
refine ⟨ifp_n, seq_nth_eq, ?_⟩
simpa only [IntFractPair.of, Int.fract, sub_eq_zero] using succ_nth_fr_eq_zero
/-- A recurrence relation that expresses the `(n+1)`th term of the stream of `IntFractPair`s
of `v` for non-integer `v` in terms of the `n`th term of the stream associated to
the inverse of the fractional part of `v`.
-/
theorem stream_succ (h : Int.fract v ≠ 0) (n : ℕ) :
IntFractPair.stream v (n + 1) = IntFractPair.stream (Int.fract v)⁻¹ n := by
induction n with
| zero =>
have H : (IntFractPair.of v).fr = Int.fract v := by simp [IntFractPair.of]
rw [stream_zero, stream_succ_of_some (stream_zero v) (ne_of_eq_of_ne H h), H]
| succ n ih =>
rcases eq_or_ne (IntFractPair.stream (Int.fract v)⁻¹ n) none with hnone | hsome
· rw [hnone] at ih
rw [succ_nth_stream_eq_none_iff.mpr (Or.inl hnone),
succ_nth_stream_eq_none_iff.mpr (Or.inl ih)]
· obtain ⟨p, hp⟩ := Option.ne_none_iff_exists'.mp hsome
rw [hp] at ih
rcases eq_or_ne p.fr 0 with hz | hnz
· rw [stream_eq_none_of_fr_eq_zero hp hz, stream_eq_none_of_fr_eq_zero ih hz]
· rw [stream_succ_of_some hp hnz, stream_succ_of_some ih hnz]
end IntFractPair
section Head
/-!
### Translation of the Head Term
Here we state some lemmas that show us that the head term of the computed continued fraction of a
value `v` is `⌊v⌋` and how this head term is moved along the structures used in the computation
process.
-/
/-- The head term of the sequence with head of `v` is just the integer part of `v`. -/
@[simp]
theorem IntFractPair.seq1_fst_eq_of : (IntFractPair.seq1 v).fst = IntFractPair.of v :=
rfl
theorem of_h_eq_intFractPair_seq1_fst_b : (of v).h = (IntFractPair.seq1 v).fst.b := by
cases aux_seq_eq : IntFractPair.seq1 v
simp [of, aux_seq_eq]
/-- The head term of the gcf of `v` is `⌊v⌋`. -/
@[simp]
theorem of_h_eq_floor : (of v).h = ⌊v⌋ := by
simp [of_h_eq_intFractPair_seq1_fst_b, IntFractPair.of]
end Head
section sequence
/-!
### Translation of the Sequences
Here we state some lemmas that show how the sequences of the involved structures
(`IntFractPair.stream`, `IntFractPair.seq1`, and `GenContFract.of`) are connected, i.e. how the
values are moved along the structures and how the termination of one sequence implies the
termination of another sequence.
-/
variable {n : ℕ}
theorem IntFractPair.get?_seq1_eq_succ_get?_stream :
(IntFractPair.seq1 v).snd.get? n = (IntFractPair.stream v) (n + 1) :=
rfl
section Termination
/-!
#### Translation of the Termination of the Sequences
Let's first show how the termination of one sequence implies the termination of another sequence.
-/
theorem of_terminatedAt_iff_intFractPair_seq1_terminatedAt :
(of v).TerminatedAt n ↔ (IntFractPair.seq1 v).snd.TerminatedAt n :=
Option.map_eq_none_iff
theorem of_terminatedAt_n_iff_succ_nth_intFractPair_stream_eq_none :
(of v).TerminatedAt n ↔ IntFractPair.stream v (n + 1) = none := by
rw [of_terminatedAt_iff_intFractPair_seq1_terminatedAt, Stream'.Seq.TerminatedAt,
IntFractPair.get?_seq1_eq_succ_get?_stream]
end Termination
section Values
/-!
#### Translation of the Values of the Sequence
Now let's show how the values of the sequences correspond to one another.
-/
theorem IntFractPair.exists_succ_get?_stream_of_gcf_of_get?_eq_some {gp_n : Pair K}
(s_nth_eq : (of v).s.get? n = some gp_n) :
∃ ifp : IntFractPair K, IntFractPair.stream v (n + 1) = some ifp ∧ (ifp.b : K) = gp_n.b := by
obtain ⟨ifp, stream_succ_nth_eq, gp_n_eq⟩ :
∃ ifp, IntFractPair.stream v (n + 1) = some ifp ∧ Pair.mk 1 (ifp.b : K) = gp_n := by
unfold of IntFractPair.seq1 at s_nth_eq
simpa [Stream'.Seq.get?_tail, Stream'.Seq.map_get?] using s_nth_eq
cases gp_n_eq
simp_all only [Option.some.injEq, exists_eq_left']
/-- Shows how the entries of the sequence of the computed continued fraction can be obtained by the
integer parts of the stream of integer and fractional parts.
-/
theorem get?_of_eq_some_of_succ_get?_intFractPair_stream {ifp_succ_n : IntFractPair K}
(stream_succ_nth_eq : IntFractPair.stream v (n + 1) = some ifp_succ_n) :
(of v).s.get? n = some ⟨1, ifp_succ_n.b⟩ := by
unfold of IntFractPair.seq1
simp [Stream'.Seq.map_tail, Stream'.Seq.get?_tail, Stream'.Seq.map_get?, stream_succ_nth_eq]
/-- Shows how the entries of the sequence of the computed continued fraction can be obtained by the
fractional parts of the stream of integer and fractional parts.
-/
theorem get?_of_eq_some_of_get?_intFractPair_stream_fr_ne_zero {ifp_n : IntFractPair K}
(stream_nth_eq : IntFractPair.stream v n = some ifp_n) (nth_fr_ne_zero : ifp_n.fr ≠ 0) :
(of v).s.get? n = some ⟨1, (IntFractPair.of ifp_n.fr⁻¹).b⟩ :=
get?_of_eq_some_of_succ_get?_intFractPair_stream <|
IntFractPair.stream_succ_of_some stream_nth_eq nth_fr_ne_zero
open Int IntFractPair
theorem of_s_head_aux (v : K) : (of v).s.get? 0 = (IntFractPair.stream v 1).bind (some ∘ fun p =>
{ a := 1
b := p.b }) := by
rw [of, IntFractPair.seq1]
simp only [Stream'.Seq.map, Stream'.Seq.tail, Stream'.Seq.get?, Stream'.map]
rw [← Stream'.get_succ, Stream'.get, Option.map.eq_def]
split <;> simp_all only [Option.bind_some, Option.bind_none, Function.comp_apply]
/-- This gives the first pair of coefficients of the continued fraction of a non-integer `v`.
-/
theorem of_s_head (h : fract v ≠ 0) : (of v).s.head = some ⟨1, ⌊(fract v)⁻¹⌋⟩ := by
change (of v).s.get? 0 = _
rw [of_s_head_aux, stream_succ_of_some (stream_zero v) h, Option.bind]
rfl
variable (K)
variable [IsStrictOrderedRing K]
/-- If `a` is an integer, then the coefficient sequence of its continued fraction is empty.
-/
theorem of_s_of_int (a : ℤ) : (of (a : K)).s = Stream'.Seq.nil :=
haveI h : ∀ n, (of (a : K)).s.get? n = none := by
intro n
induction n with
| zero => rw [of_s_head_aux, stream_succ_of_int, Option.bind]
| succ n ih => exact (of (a : K)).s.prop ih
Stream'.Seq.ext fun n => (h n).trans (Stream'.Seq.get?_nil n).symm
variable {K} (v)
/-- Recurrence for the `GenContFract.of` an element `v` of `K` in terms of that of the inverse of
the fractional part of `v`.
-/
theorem of_s_succ (n : ℕ) : (of v).s.get? (n + 1) = (of (fract v)⁻¹).s.get? n := by
rcases eq_or_ne (fract v) 0 with h | h
· obtain ⟨a, rfl⟩ : ∃ a : ℤ, v = a := ⟨⌊v⌋, eq_of_sub_eq_zero h⟩
rw [fract_intCast, inv_zero, of_s_of_int, ← cast_zero, of_s_of_int,
Stream'.Seq.get?_nil, Stream'.Seq.get?_nil]
rcases eq_or_ne ((of (fract v)⁻¹).s.get? n) none with h₁ | h₁
· rwa [h₁, ← terminatedAt_iff_s_none,
of_terminatedAt_n_iff_succ_nth_intFractPair_stream_eq_none, stream_succ h, ←
of_terminatedAt_n_iff_succ_nth_intFractPair_stream_eq_none, terminatedAt_iff_s_none]
· obtain ⟨p, hp⟩ := Option.ne_none_iff_exists'.mp h₁
obtain ⟨p', hp'₁, _⟩ := exists_succ_get?_stream_of_gcf_of_get?_eq_some hp
have Hp := get?_of_eq_some_of_succ_get?_intFractPair_stream hp'₁
rw [← stream_succ h] at hp'₁
rw [Hp, get?_of_eq_some_of_succ_get?_intFractPair_stream hp'₁]
/-- This expresses the tail of the coefficient sequence of the `GenContFract.of` an element `v` of
`K` as the coefficient sequence of that of the inverse of the fractional part of `v`.
-/
theorem of_s_tail : (of v).s.tail = (of (fract v)⁻¹).s :=
Stream'.Seq.ext fun n => Stream'.Seq.get?_tail (of v).s n ▸ of_s_succ v n
variable (K) (n)
/-- If `a` is an integer, then the `convs'` of its continued fraction expansion
are all equal to `a`.
-/
theorem convs'_of_int (a : ℤ) : (of (a : K)).convs' n = a := by
induction n with
| zero => simp only [zeroth_conv'_eq_h, of_h_eq_floor, floor_intCast]
| succ =>
rw [convs', of_h_eq_floor, floor_intCast, add_eq_left]
exact convs'Aux_succ_none ((of_s_of_int K a).symm ▸ Stream'.Seq.get?_nil 0) _
variable {K}
/-- The recurrence relation for the `convs'` of the continued fraction expansion
of an element `v` of `K` in terms of the convergents of the inverse of its fractional part.
-/
theorem convs'_succ :
(of v).convs' (n + 1) = ⌊v⌋ + 1 / (of (fract v)⁻¹).convs' n := by
rcases eq_or_ne (fract v) 0 with h | h
· obtain ⟨a, rfl⟩ : ∃ a : ℤ, v = a := ⟨⌊v⌋, eq_of_sub_eq_zero h⟩
rw [convs'_of_int, fract_intCast, inv_zero, ← cast_zero, convs'_of_int, cast_zero,
div_zero, add_zero, floor_intCast]
· rw [convs', of_h_eq_floor, add_right_inj, convs'Aux_succ_some (of_s_head h)]
exact congr_arg (1 / ·) (by rw [convs', of_h_eq_floor, add_right_inj, of_s_tail])
end Values
end sequence
end GenContFract |
.lake/packages/mathlib/Mathlib/Algebra/ContinuedFractions/Computation/ApproximationCorollaries.lean | import Mathlib.Algebra.ContinuedFractions.Computation.Approximations
import Mathlib.Algebra.ContinuedFractions.ConvergentsEquiv
import Mathlib.Algebra.Order.Archimedean.Basic
import Mathlib.Tactic.GCongr
import Mathlib.Topology.Order.LeftRightNhds
/-!
# Corollaries From Approximation Lemmas (`Algebra.ContinuedFractions.Computation.Approximations`)
## Summary
Using the equivalence of the convergents computations
(`GenContFract.convs` and `GenContFract.convs'`) for
continued fractions (see `Algebra.ContinuedFractions.ConvergentsEquiv`), it follows that the
convergents computations for `GenContFract.of` are equivalent.
Moreover, we show the convergence of the continued fractions computations, that is
`(GenContFract.of v).convs` indeed computes `v` in the limit.
## Main Definitions
- `ContFract.of` returns the (regular) continued fraction of a value.
## Main Theorems
- `GenContFract.of_convs_eq_convs'` shows that the convergents computations for
`GenContFract.of` are equivalent.
- `GenContFract.of_convergence` shows that `(GenContFract.of v).convs` converges to `v`.
## Tags
convergence, fractions
-/
variable {K : Type*} (v : K) [Field K] [LinearOrder K] [IsStrictOrderedRing K] [FloorRing K]
open GenContFract (of)
open scoped Topology
namespace GenContFract
theorem of_convs_eq_convs' : (of v).convs = (of v).convs' :=
ContFract.convs_eq_convs' (c := ContFract.of v)
/-- The recurrence relation for the convergents of the continued fraction expansion
of an element `v` of `K` in terms of the convergents of the inverse of its fractional part.
-/
theorem convs_succ (n : ℕ) :
(of v).convs (n + 1) = ⌊v⌋ + 1 / (of (Int.fract v)⁻¹).convs n := by
rw [of_convs_eq_convs', convs'_succ, of_convs_eq_convs']
section Convergence
/-!
### Convergence
We next show that `(GenContFract.of v).convs n` converges to `v`.
-/
variable [Archimedean K]
open Nat
theorem of_convergence_epsilon :
∀ ε > (0 : K), ∃ N : ℕ, ∀ n ≥ N, |v - (of v).convs n| < ε := by
intro ε ε_pos
-- use the archimedean property to obtain a suitable N
rcases (exists_nat_gt (1 / ε) : ∃ N' : ℕ, 1 / ε < N') with ⟨N', one_div_ε_lt_N'⟩
let N := max N' 5
-- set minimum to 5 to have N ≤ fib N work
exists N
intro n n_ge_N
let g := of v
rcases Decidable.em (g.TerminatedAt n) with terminatedAt_n | not_terminatedAt_n
· have : v = g.convs n := of_correctness_of_terminatedAt terminatedAt_n
have : v - g.convs n = 0 := sub_eq_zero.mpr this
rw [this]
exact mod_cast ε_pos
· let B := g.dens n
let nB := g.dens (n + 1)
have abs_v_sub_conv_le : |v - g.convs n| ≤ 1 / (B * nB) :=
abs_sub_convs_le not_terminatedAt_n
suffices 1 / (B * nB) < ε from lt_of_le_of_lt abs_v_sub_conv_le this
-- show that `0 < (B * nB)` and then multiply by `B * nB` to get rid of the division
have nB_ineq : (fib (n + 2) : K) ≤ nB :=
haveI : ¬g.TerminatedAt (n + 1 - 1) := not_terminatedAt_n
succ_nth_fib_le_of_nth_den (Or.inr this)
have B_ineq : (fib (n + 1) : K) ≤ B :=
haveI : ¬g.TerminatedAt (n - 1) := mt (terminated_stable n.pred_le) not_terminatedAt_n
succ_nth_fib_le_of_nth_den (Or.inr this)
have zero_lt_B : 0 < B := B_ineq.trans_lt' <| mod_cast fib_pos.2 n.succ_pos
have nB_pos : 0 < nB := nB_ineq.trans_lt' <| mod_cast fib_pos.2 <| succ_pos _
have zero_lt_mul_conts : 0 < B * nB := by positivity
suffices 1 < ε * (B * nB) from (div_lt_iff₀ zero_lt_mul_conts).mpr this
-- use that `N' ≥ n` was obtained from the archimedean property to show the following
calc 1 < ε * (N' : K) := (div_lt_iff₀' ε_pos).mp one_div_ε_lt_N'
_ ≤ ε * (B * nB) := ?_
-- cancel `ε`
gcongr
calc
(N' : K) ≤ (N : K) := by exact_mod_cast le_max_left _ _
_ ≤ n := by exact_mod_cast n_ge_N
_ ≤ fib n := by exact_mod_cast le_fib_self <| le_trans (le_max_right N' 5) n_ge_N
_ ≤ fib (n + 1) := by exact_mod_cast fib_le_fib_succ
_ ≤ fib (n + 1) * fib (n + 1) := by exact_mod_cast (fib (n + 1)).le_mul_self
_ ≤ fib (n + 1) * fib (n + 2) := by gcongr; exact_mod_cast fib_le_fib_succ
_ ≤ B * nB := by gcongr
theorem of_convergence [TopologicalSpace K] [OrderTopology K] :
Filter.Tendsto (of v).convs Filter.atTop <| 𝓝 v := by
simpa [LinearOrderedAddCommGroup.tendsto_nhds, abs_sub_comm] using of_convergence_epsilon v
end Convergence
end GenContFract |
.lake/packages/mathlib/Mathlib/Deprecated/Order.lean | import Mathlib.Algebra.Order.GroupWithZero.Unbundled.Basic
import Mathlib.Order.RelClasses
import Mathlib.Tactic.Linter.DeprecatedModule
deprecated_module (since := "2025-09-02") |
.lake/packages/mathlib/Mathlib/Deprecated/Estimator.lean | import Mathlib.Data.Set.Operations
import Mathlib.Order.Heyting.Basic
import Mathlib.Order.RelClasses
import Mathlib.Order.Hom.Basic
import Mathlib.Lean.Thunk
/-!
# Improvable lower bounds.
Note: this entire file is deprecated.
The typeclass `Estimator a ε`, where `a : Thunk α` and `ε : Type`,
states that `e : ε` carries the data of a lower bound for `a.get`,
in the form `bound_le : bound a e ≤ a.get`,
along with a mechanism for asking for a better bound `improve e : Option ε`,
satisfying
```
match improve e with
| none => bound e = a.get
| some e' => bound e < bound e'
```
i.e. it returns `none` if the current bound is already optimal,
and otherwise a strictly better bound.
(The value in `α` is hidden inside a `Thunk` to prevent evaluating it:
the point of this typeclass is to work with cheap-to-compute lower bounds for expensive values.)
An appropriate well-foundedness condition would then ensure that repeated improvements reach
the exact value.
-/
variable {α ε : Type*}
/--
Given `[EstimatorData a ε]`
* a term `e : ε` can be interpreted via `bound a e : α` as a lower bound for `a`, and
* we can ask for an improved lower bound via `improve a e : Option ε`.
The value `a` in `α` that we are estimating is hidden inside a `Thunk` to avoid evaluation.
-/
class EstimatorData (a : Thunk α) (ε : Type*) where
/-- The value of the bound for `a` representation by a term of `ε`. -/
bound : ε → α
/-- Generate an improved lower bound. -/
improve : ε → Option ε
/--
Given `[Estimator a ε]`
* we have `bound a e ≤ a.get`, and
* `improve a e` returns none iff `bound a e = a.get`,
and otherwise it returns a strictly better bound.
-/
@[deprecated "No replacement: this was only used \
in the implementation of the removed `rw_search` tactic." (since := "2025-09-11")]
class Estimator [Preorder α] (a : Thunk α) (ε : Type*) extends EstimatorData a ε where
/-- The calculated bounds are always lower bounds. -/
bound_le e : bound e ≤ a.get
/-- Calling `improve` either gives a strictly better bound,
or a proof that the current bound is exact. -/
improve_spec e : match improve e with
| none => bound e = a.get
| some e' => bound e < bound e'
-- Everything in this file is deprecated,
-- but we'll just add the deprecation attribute to the main class.
set_option linter.deprecated false
open EstimatorData Set
section trivial
variable [Preorder α]
/-- A trivial estimator, containing the actual value. -/
abbrev Estimator.trivial.{u} {α : Type u} (a : α) : Type u := { b : α // b = a }
instance {a : α} : Bot (Estimator.trivial a) := ⟨⟨a, rfl⟩⟩
instance : WellFoundedGT Unit where
wf := ⟨fun .unit => ⟨Unit.unit, nofun⟩⟩
instance (a : α) : WellFoundedGT (Estimator.trivial a) :=
let f : Estimator.trivial a ≃o Unit := RelIso.ofUniqueOfRefl _ _
let f' : Estimator.trivial a ↪o Unit := f.toOrderEmbedding
f'.wellFoundedGT
instance {a : α} : Estimator (Thunk.pure a) (Estimator.trivial a) where
bound b := b.val
improve _ := none
bound_le b := b.prop.le
improve_spec b := b.prop
end trivial
section improveUntil
variable [Preorder α]
attribute [local instance] WellFoundedGT.toWellFoundedRelation in
/-- Implementation of `Estimator.improveUntil`. -/
def Estimator.improveUntilAux
(a : Thunk α) (p : α → Bool) [Estimator a ε]
[WellFoundedGT (range (bound a : ε → α))]
(e : ε) (r : Bool) : Except (Option ε) ε :=
if p (bound a e) then
return e
else
match improve a e, improve_spec e with
| none, _ => .error <| if r then none else e
| some e', _ =>
improveUntilAux a p e' true
termination_by (⟨_, mem_range_self e⟩ : range (bound a))
/--
Improve an estimate until it satisfies a predicate,
or else return the best available estimate, if any improvement was made.
-/
def Estimator.improveUntil (a : Thunk α) (p : α → Bool)
[Estimator a ε] [WellFoundedGT (range (bound a : ε → α))] (e : ε) :
Except (Option ε) ε :=
Estimator.improveUntilAux a p e false
attribute [local instance] WellFoundedGT.toWellFoundedRelation in
/--
If `Estimator.improveUntil a p e` returns `some e'`, then `bound a e'` satisfies `p`.
Otherwise, that value `a` must not satisfy `p`.
-/
theorem Estimator.improveUntilAux_spec (a : Thunk α) (p : α → Bool)
[Estimator a ε] [WellFoundedGT (range (bound a : ε → α))] (e : ε) (r : Bool) :
match Estimator.improveUntilAux a p e r with
| .error _ => ¬ p a.get
| .ok e' => p (bound a e') := by
rw [Estimator.improveUntilAux]
by_cases h : p (bound a e)
· simp only [h]; exact h
· simp only [h]
match improve a e, improve_spec e with
| none, eq =>
simp only [Bool.not_eq_true]
rw [eq] at h
exact Bool.bool_eq_false h
| some e', _ =>
exact Estimator.improveUntilAux_spec a p e' true
termination_by (⟨_, mem_range_self e⟩ : range (bound a))
/--
If `Estimator.improveUntil a p e` returns `some e'`, then `bound a e'` satisfies `p`.
Otherwise, that value `a` must not satisfy `p`.
-/
theorem Estimator.improveUntil_spec
(a : Thunk α) (p : α → Bool) [Estimator a ε] [WellFoundedGT (range (bound a : ε → α))] (e : ε) :
match Estimator.improveUntil a p e with
| .error _ => ¬ p a.get
| .ok e' => p (bound a e') :=
Estimator.improveUntilAux_spec a p e false
end improveUntil
/-! Estimators for sums. -/
section add
variable [Preorder α]
@[simps]
instance [Add α] {a b : Thunk α} (εa εb : Type*) [EstimatorData a εa] [EstimatorData b εb] :
EstimatorData (a + b) (εa × εb) where
bound e := bound a e.1 + bound b e.2
improve e := match improve a e.1 with
| some e' => some { e with fst := e' }
| none => match improve b e.2 with
| some e' => some { e with snd := e' }
| none => none
instance (a b : Thunk ℕ) {εa εb : Type*} [Estimator a εa] [Estimator b εb] :
Estimator (a + b) (εa × εb) where
bound_le e :=
Nat.add_le_add (Estimator.bound_le e.1) (Estimator.bound_le e.2)
improve_spec e := by
dsimp
have s₁ := Estimator.improve_spec (a := a) e.1
have s₂ := Estimator.improve_spec (a := b) e.2
grind
end add
/-! Estimator for the first component of a pair. -/
section fst
variable {β : Type*} [PartialOrder α] [PartialOrder β]
/--
An estimator for `(a, b)` can be turned into an estimator for `a`,
simply by repeatedly running `improve` until the first factor "improves".
The hypothesis that `>` is well-founded on `{ q // q ≤ (a, b) }` ensures this terminates.
-/
structure Estimator.fst
(p : Thunk (α × β)) (ε : Type*) [Estimator p ε] where
/-- The wrapped bound for a value in `α × β`,
which we will use as a bound for the first component. -/
inner : ε
variable [∀ a : α, WellFoundedGT { x // x ≤ a }]
instance {a : Thunk α} [Estimator a ε] : WellFoundedGT (range (bound a : ε → α)) :=
let f : range (bound a : ε → α) ↪o { x // x ≤ a.get } :=
Subtype.orderEmbedding (by rintro _ ⟨e, rfl⟩; exact Estimator.bound_le e)
f.wellFoundedGT
instance [DecidableLT α] {a : Thunk α} {b : Thunk β}
(ε : Type*) [Estimator (a.prod b) ε] [∀ (p : α × β), WellFoundedGT { q // q ≤ p }] :
EstimatorData a (Estimator.fst (a.prod b) ε) where
bound e := (bound (a.prod b) e.inner).1
improve e :=
let bd := (bound (a.prod b) e.inner).1
Estimator.improveUntil (a.prod b) (fun p => bd < p.1) e.inner
|>.toOption |>.map Estimator.fst.mk
/-- Given an estimator for a pair, we can extract an estimator for the first factor. -/
-- This isn't an instance as at the sole use case we need to provide
-- the instance arguments by hand anyway.
def Estimator.fstInst [DecidableLT α] [∀ (p : α × β), WellFoundedGT { q // q ≤ p }]
(a : Thunk α) (b : Thunk β) (i : Estimator (a.prod b) ε) :
Estimator a (Estimator.fst (a.prod b) ε) where
bound_le e := (Estimator.bound_le e.inner : bound (a.prod b) e.inner ≤ (a.get, b.get)).1
improve_spec e := by
let bd := (bound (a.prod b) e.inner).1
have := Estimator.improveUntil_spec (a.prod b) (fun p => bd < p.1) e.inner
revert this
simp only [EstimatorData.improve, decide_eq_true_eq]
match Estimator.improveUntil (a.prod b) _ _ with
| .error _ =>
simp only
exact fun w =>
eq_of_le_of_not_lt
(Estimator.bound_le e.inner : bound (a.prod b) e.inner ≤ (a.get, b.get)).1 w
| .ok e' => exact fun w => w
end fst |
.lake/packages/mathlib/Mathlib/Deprecated/RingHom.lean | import Mathlib.Algebra.Divisibility.Hom
import Mathlib.Algebra.Ring.Hom.Defs
import Mathlib.Data.Set.Insert
/-!
# Additional lemmas about homomorphisms of semirings and rings
These lemmas were in `Mathlib/Algebra/Hom/Ring/Defs.lean` and have now been deprecated.
-/
assert_not_exists RelIso Field
open Function
variable {α β : Type*}
namespace RingHom
section
variable {_ : NonAssocSemiring α} {_ : NonAssocSemiring β} (f : α →+* β)
/-- `f : α →+* β` has a trivial codomain iff its range is `{0}`. -/
@[deprecated "Use range_eq_singleton_iff and codomain_trivial_iff_range_trivial"
(since := "2025-06-09")]
theorem codomain_trivial_iff_range_eq_singleton_zero : (0 : β) = 1 ↔ Set.range f = {0} :=
f.codomain_trivial_iff_range_trivial.trans
⟨fun h =>
Set.ext fun y => ⟨fun ⟨x, hx⟩ => by simp [← hx, h x], fun hy => ⟨0, by simpa using hy.symm⟩⟩,
fun h x => Set.mem_singleton_iff.mp (h ▸ Set.mem_range_self x)⟩
end
section Semiring
variable [Semiring α] [Semiring β]
@[deprecated map_dvd (since := "2025-06-09")]
protected theorem map_dvd (f : α →+* β) {a b : α} : a ∣ b → f a ∣ f b :=
map_dvd f
end Semiring
end RingHom |
.lake/packages/mathlib/Mathlib/Deprecated/Aliases.lean | import Mathlib.Init
/-!
Deprecated aliases can be dumped here if they are no longer used in Mathlib,
to avoid needing their imports if they are otherwise unnecessary.
-/ |
.lake/packages/mathlib/Mathlib/Deprecated/MLList/BestFirst.lean | import Batteries.Data.MLList.Basic
import Mathlib.Data.Prod.Lex
import Mathlib.Data.Set.Finite.Range
import Mathlib.Deprecated.Estimator
/-!
# Best first search
Note: this entire file is deprecated.
We perform best first search of a tree or graph,
where the neighbours of a vertex are provided by a lazy list `α → MLList m α`.
We maintain a priority queue of visited-but-not-exhausted nodes,
and at each step take the next child of the highest priority node in the queue.
This is useful in meta code for searching for solutions in the presence of alternatives.
It can be nice to represent the choices via a lazy list,
so the later choices don't need to be evaluated while we do depth first search on earlier choices.
Options:
* `maxDepth` allows bounding the search depth
* `maxQueued` implements "beam" search,
by discarding elements from the priority queue when it grows too large
* `removeDuplicatesBy?` maintains an `RBSet` of previously visited nodes;
otherwise if the graph is not a tree nodes may be visited multiple times.
-/
open Batteries EstimatorData Estimator Set
/-!
We begin by defining a best-first queue of `MLList`s.
This is a somewhat baroque data structure designed for the application in this file
(and in particularly for the implementation of `rewrite_search`).
If someone would like to generalize appropriately that would be great.
We want to maintain a priority queue of `MLList m β`, each indexed by some `a : α` with a priority.
(One could simplify matters here by simply flattening this out to a priority queue of pairs `α × β`,
with the priority determined by the `α` factor.
However the laziness of `MLList` is essential to performance here:
we will extract elements from these lists one at a time,
and only when they at the head of the queue.
If another item arrives at the head of the queue,
we may not need to continue calculate the previous head's elements.)
To complicate matters, the priorities might be expensive to calculate,
so we instead keep track of a lower bound (where less is better) for each such `a : α`.
The priority queue maintains the `MLList m β` in order of the current best lower bound for the
corresponding `a : α`.
When we insert a new `α × MLList m β` into the queue, we have to provide a lower bound,
and we just insert it at a position depending on the estimate.
When it is time to pop a `β` off the queue, we iteratively improve the lower bound for the
front element of the queue, until we decide that either it must be the least element,
or we can exchange it with the second element of the queue and continue.
A `BestFirstQueue prio ε m β maxSize` consists of an `TreeMap`,
where the keys are in `BestFirstNode prio ε`
and the values are `MLList m β`.
A `BestFirstNode prio ε` consists of a `key : α` and an estimator `ε : key`.
Here `ε` provides the current best lower bound for `prio key : Thunk ω`.
(The actual priority is hidden behind a `Thunk` to avoid evaluating it, in case it is expensive.)
We ask for the type classes `LinearOrder ω` and `∀ a : α, Estimator (prio a) (ε a)`.
This later typeclass ensures that we can always produce progressively better estimates
for a priority. We also need a `WellFounded` instance to ensure that improving estimates terminates.
This whole structure is designed around the problem of searching rewrite graphs,
prioritising according to edit distances (either between sides of an equation,
or from a goal to a target). Edit distance computations are particularly suited to this design
because the usual algorithm for computing them produces improving lower bounds at each step.
With this design, it is okay if we visit nodes with very large edit distances:
while these would be expensive to compute, we never actually finish the computation
except in cases where the node arrives at the front of the queue.
-/
set_option linter.deprecated false
open Std (TreeMap TreeSet)
section
/-- A node in a `BestFirstQueue`. -/
structure BestFirstNode {α : Sort*} {ω : Type*} (prio : α → Thunk ω) (ε : α → Type) where
/-- The data to store at a node, from which we can calculate a priority using `prio`. -/
key : α
/-- An estimator for the priority of the key.
(We will assume we have `[∀ a : α, Estimator (prio a) (ε a)]`.) -/
estimator : ε key
variable {ω α : Type} {prio : α → Thunk ω} {ε : α → Type} [LinearOrder ω]
[∀ a, Estimator (prio a) (ε a)]
[I : ∀ a : α, WellFoundedGT (range (bound (prio a) : ε a → ω))]
{m : Type → Type} [Monad m] {β : Type}
/-- Calculate the current best lower bound for the priority of a node. -/
def BestFirstNode.estimate (n : BestFirstNode prio ε) : ω := bound (prio n.key) n.estimator
instance [Ord ω] [Ord α] : Ord (BestFirstNode prio ε) where
compare :=
compareLex
(compareOn BestFirstNode.estimate)
(compareOn BestFirstNode.key)
set_option linter.unusedVariables false in
variable (prio ε m β) [Ord ω] [Ord α] in
/-- A queue of `MLList m β`s, lazily prioritized by lower bounds. -/
@[nolint unusedArguments]
def BestFirstQueue (maxSize : Option Nat) := TreeMap (BestFirstNode prio ε) (MLList m β) compare
variable [Ord ω] [Ord α] {maxSize : Option Nat}
namespace BestFirstQueue
/--
Add a new `MLList m β` to the `BestFirstQueue`, and if this takes the size above `maxSize`,
eject a `MLList` from the tail of the queue.
-/
-- Note this ejects the element with the greatest estimated priority,
-- not necessarily the greatest priority!
def insertAndEject
(q : BestFirstQueue prio ε m β maxSize) (n : BestFirstNode prio ε) (l : MLList m β) :
BestFirstQueue prio ε m β maxSize :=
match maxSize with
| none => q.insert n l
| some max =>
if q.size < max then
q.insert n l
else
match q.maxEntry? with
| none => TreeMap.empty
| some m => q.insert n l |>.erase m.1
/--
By improving priority estimates as needed, and permuting elements,
ensure that the first element of the queue has the greatest priority.
-/
partial def ensureFirstIsBest (q : BestFirstQueue prio ε m β maxSize) :
m (BestFirstQueue prio ε m β maxSize) := do
match q.entryAtIdx? 0 with
| none =>
-- The queue is empty, nothing to do.
return q
| some (n, l) => match q.entryAtIdx? 1 with
| none => do
-- There's only one element in the queue, no reordering necessary.
return q
| some (m, _) =>
-- `n` is the first index, `m` is the second index.
-- We need to improve our estimate of the priority for `n` to make sure
-- it really should come before `m`.
match improveUntil (prio n.key) (m.estimate < ·) n.estimator with
| .error none =>
-- If we couldn't improve the estimate at all, it is exact, and hence the best element.
return q
| .error (some e') =>
-- If we improve the estimate, but it is still at most the estimate for `m`,
-- this is the best element, so all we need to do is store the updated estimate.
return q.erase n |>.insert ⟨n.key, e'⟩ l
| .ok e' =>
-- If we improved the estimate and it becomes greater than the estimate for `m`,
-- we re-insert `n` with its new estimate, and then try again.
ensureFirstIsBest (q.erase n |>.insert ⟨n.key, e'⟩ l)
/--
Pop a `β` off the `MLList m β` with lowest priority,
also returning the index in `α` and the current best lower bound for its priority.
This may require improving estimates of priorities and shuffling the queue.
-/
partial def popWithBound (q : BestFirstQueue prio ε m β maxSize) :
m (Option (((a : α) × (ε a) × β) × BestFirstQueue prio ε m β maxSize)) := do
let q' ← ensureFirstIsBest q
match q'.minEntry? with
| none =>
-- The queue is empty, nothing to return.
return none
| some (n, l) =>
match ← l.uncons with
| none =>
-- The `MLList` associated to `n` was actually empty, so we remove `n` and try again.
popWithBound (q'.erase n)
| some (b, l') =>
-- Return the initial element `b` along with the current estimator,
-- and replace the `MLList` associated with `n` with its tail.
return some (⟨n.key, n.estimator, b⟩, q'.modify n fun _ => l')
/--
Pop a `β` off the `MLList m β` with lowest priority,
also returning the index in `α` and the value of the current best lower bound for its priority.
-/
def popWithPriority (q : BestFirstQueue prio ε m β maxSize) :
m (Option (((α × ω) × β) × BestFirstQueue prio ε m β maxSize)) := do
match ← q.popWithBound with
| none => pure none
| some (⟨a, e, b⟩, q') => pure (some (((a, bound (prio a) e), b), q'))
/--
Pop a `β` off the `MLList m β` with lowest priority.
-/
def pop (q : BestFirstQueue prio ε m β maxSize) :
m (Option ((α × β) × BestFirstQueue prio ε m β maxSize)) := do
match ← q.popWithBound with
| none => pure none
| some (⟨a, _, b⟩, q') => pure (some ((a, b), q'))
/--
Convert a `BestFirstQueue` to a `MLList ((α × ω) × β)`, by popping off all elements,
recording also the values in `ω` of the best current lower bounds.
-/
-- This is not used in the algorithms below, but can be useful for debugging.
partial def toMLListWithPriority (q : BestFirstQueue prio ε m β maxSize) : MLList m ((α × ω) × β) :=
.squash fun _ => do
match ← q.popWithPriority with
| none => pure .nil
| some (p, q') => pure <| MLList.cons p q'.toMLListWithPriority
/--
Convert a `BestFirstQueue` to a `MLList (α × β)`, by popping off all elements.
-/
def toMLList (q : BestFirstQueue prio ε m β maxSize) : MLList m (α × β) :=
q.toMLListWithPriority.map fun t => (t.1.1, t.2)
end BestFirstQueue
open MLList
variable {m : Type → Type} [Monad m] [Alternative m] [∀ a, Bot (ε a)] (prio ε)
/--
Core implementation of `bestFirstSearch`, that works by iteratively updating an internal state,
consisting of a priority queue of `MLList m α`.
At each step we pop an element off the queue,
compute its children (lazily) and put these back on the queue.
-/
def impl (maxSize : Option Nat) (f : α → MLList m α) (a : α) : MLList m α :=
let init : BestFirstQueue prio ε m α maxSize := TreeMap.empty.insert ⟨a, ⊥⟩ (f a)
cons a (iterate go |>.runState' init)
where
/-- A single step of the best first search.
Pop an element, and insert its children back into the queue,
with a trivial estimator for their priority. -/
go : StateT (BestFirstQueue prio ε m α maxSize) m α := fun s => do
match ← s.pop with
| none => failure
| some ((_, b), s') => pure (b, s'.insertAndEject ⟨b, ⊥⟩ (f b))
/--
Wrapper for `impl` implementing the `maxDepth` option.
-/
def implMaxDepth (maxSize : Option Nat) (maxDepth : Option Nat) (f : α → MLList m α) (a : α) :
MLList m α :=
match maxDepth with
| none => impl prio ε maxSize f a
| some max =>
let f' : α ×ₗ Nat → MLList m (α × Nat) := fun ⟨a, n⟩ =>
if max < n then
nil
else
(f a).map fun a' => (a', n + 1)
impl (fun p : α ×ₗ Nat => prio p.1) (fun p : α ×ₗ Nat => ε p.1) maxSize f' (a, 0) |>.map (·.1)
/--
A lazy list recording the best first search of a graph generated by a function
`f : α → MLList m α`.
We maintain a priority queue of visited-but-not-exhausted nodes,
and at each step take the next child of the highest priority node in the queue.
The option `maxDepth` limits the search depth.
The option `maxQueued` bounds the size of the priority queue,
discarding the lowest priority nodes as needed.
This implements a "beam" search, which may be incomplete but uses bounded memory.
The option `removeDuplicates` keeps an `RBSet` of previously visited nodes.
Otherwise, if the graph is not a tree then nodes will be visited multiple times.
This version allows specifying a custom priority function `prio : α → Thunk ω`
along with estimators `ε : α → Type` equipped with `[∀ a, Estimator (prio a) (ε a)]`
that control the behaviour of the priority queue.
This function returns values `a : α` that have
the lowest possible `prio a` amongst unvisited neighbours of visited nodes,
but lazily estimates these priorities to avoid unnecessary computations.
-/
def bestFirstSearchCore (f : α → MLList m α) (a : α)
(β : Type _) [Ord β] (removeDuplicatesBy? : Option (α → β) := none)
(maxQueued : Option Nat := none) (maxDepth : Option Nat := none) :
MLList m α :=
match removeDuplicatesBy? with
| some g =>
let f' : α → MLList (StateT (TreeSet β compare) m) α := fun a =>
(f a).liftM >>= fun a' => do
let b := g a'
guard !(← get).contains b
modify fun s => s.insert b
pure a'
implMaxDepth prio ε maxQueued maxDepth f' a |>.runState' (TreeSet.empty.insert (g a))
| none =>
implMaxDepth prio ε maxQueued maxDepth f a
end
variable {m : Type → Type} {α : Type} [Monad m] [Alternative m] [LinearOrder α]
/-- A local instance that enables using "the actual value" as a priority estimator,
for simple use cases. -/
local instance instOrderBotEq {a : α} : OrderBot { x : α // x = a } where
bot := ⟨a, rfl⟩
bot_le := by simp
/--
A lazy list recording the best first search of a graph generated by a function
`f : α → MLList m α`.
We maintain a priority queue of visited-but-not-exhausted nodes,
and at each step take the next child of the highest priority node in the queue.
The option `maxDepth` limits the search depth.
The option `maxQueued` bounds the size of the priority queue,
discarding the lowest priority nodes as needed.
This implements a "beam" search, which may be incomplete but uses bounded memory.
The option `removeDuplicates` keeps an `RBSet` of previously visited nodes.
Otherwise, if the graph is not a tree then nodes will be visited multiple times.
This function returns values `a : α` that are least in the `[LinearOrder α]`
amongst unvisited neighbours of visited nodes.
-/
-- Although the core implementation lazily computes estimates of priorities,
-- this version does not take advantage of those features.
@[deprecated "No replacement: this was only used \
in the implementation of the removed `rw_search` tactic." (since := "2025-09-11")]
def bestFirstSearch (f : α → MLList m α) (a : α)
(maxQueued : Option Nat := none) (maxDepth : Option Nat := none) (removeDuplicates := true) :
MLList m α :=
bestFirstSearchCore Thunk.pure (fun a : α => { x // x = a }) f a
(β := α) (removeDuplicatesBy? := if removeDuplicates then some id else none)
maxQueued maxDepth |
.lake/packages/mathlib/Counterexamples/IrrationalPowerOfIrrational.lean | import Mathlib.Analysis.SpecialFunctions.Pow.NNReal
import Mathlib.NumberTheory.Real.Irrational
/-
# Irrational power of irrational numbers are not necessarily irrational.
Prove that there exist irrational numbers `a`, `b` such that `a^b` is rational.
We use the following famous argument (based on the law of excluded middle and irrationality of √2).
Consider `c = √2^√2`. If `c` is rational, we are done.
If `c` is irrational, then `c^√2 = 2` is rational, so we are done.
-/
open Real
namespace Counterexample
/--
There exist irrational `a`, `b` with rational `a^b`.
Note that the positivity assumption on `a` is imposed because of the definition of `rpow` for
negative bases. See `Real.rpow_def_of_neg` for more details.
-/
theorem not_irrational_rpow :
¬ ∀ a b : ℝ, Irrational a → Irrational b → 0 < a → Irrational (a ^ b) := by
push_neg
by_cases hc : Irrational (√2 ^ √2)
· use (√2 ^ √2), √2, hc, irrational_sqrt_two, by positivity
rw [← rpow_mul, mul_self_sqrt, rpow_two, sq_sqrt] <;> norm_num
· use √2, √2, irrational_sqrt_two, irrational_sqrt_two, by positivity, hc
end Counterexample |
.lake/packages/mathlib/Counterexamples/SorgenfreyLine.lean | import Mathlib.Order.Interval.Set.Monotone
import Mathlib.Topology.Instances.Irrational
import Mathlib.Topology.Algebra.Order.Archimedean
import Mathlib.Topology.Compactness.Paracompact
import Mathlib.Topology.Metrizable.Urysohn
import Mathlib.Topology.EMetricSpace.Paracompact
import Mathlib.Topology.Separation.NotNormal
import Mathlib.Topology.Baire.Lemmas
import Mathlib.Topology.Baire.LocallyCompactRegular
/-!
# Sorgenfrey line
In this file we define `SorgenfreyLine` (notation: `ℝₗ`) to be the Sorgenfrey line. It is the real
line with the topology space structure generated by half-open intervals `Set.Ico a b`.
We prove that this line is a completely normal Hausdorff space but its product with itself is not a
normal space. In particular, this implies that the topology on `ℝₗ` is neither metrizable, nor
second countable.
## Notation
- `ℝₗ`: Sorgenfrey line.
## TODO
Prove that the Sorgenfrey line is a paracompact space.
-/
open Set Filter TopologicalSpace
open scoped Topology Filter Cardinal
namespace Counterexample
noncomputable section
/-- The Sorgenfrey line (denoted as `ℝₗ` within the `SorgenfreyLine` namespace).
It is the real line with the topology space structure generated by
half-open intervals `Set.Ico a b`. -/
def SorgenfreyLine : Type := ℝ
deriving ConditionallyCompleteLinearOrder, Field, IsStrictOrderedRing, Archimedean
@[inherit_doc]
scoped[SorgenfreyLine] notation "ℝₗ" => Counterexample.SorgenfreyLine
open scoped SorgenfreyLine
namespace SorgenfreyLine
/-- Ring homomorphism between the Sorgenfrey line and the standard real line. -/
def toReal : ℝₗ ≃+* ℝ :=
RingEquiv.refl ℝ
instance : TopologicalSpace ℝₗ :=
TopologicalSpace.generateFrom {s : Set ℝₗ | ∃ a b : ℝₗ, Ico a b = s}
theorem isOpen_Ico (a b : ℝₗ) : IsOpen (Ico a b) :=
TopologicalSpace.GenerateOpen.basic _ ⟨a, b, rfl⟩
theorem isOpen_Ici (a : ℝₗ) : IsOpen (Ici a) :=
iUnion_Ico_right a ▸ isOpen_iUnion (isOpen_Ico a)
theorem nhds_basis_Ico (a : ℝₗ) : (𝓝 a).HasBasis (a < ·) (Ico a ·) := by
rw [TopologicalSpace.nhds_generateFrom]
haveI : Nonempty { x // x ≤ a } := Set.nonempty_Iic_subtype
have : (⨅ x : { i // i ≤ a }, 𝓟 (Ici ↑x)) = 𝓟 (Ici a) := by
refine (IsLeast.isGLB ?_).iInf_eq
exact ⟨⟨⟨a, le_rfl⟩, rfl⟩, forall_mem_range.2 fun b => principal_mono.2 <| Ici_subset_Ici.2 b.2⟩
simp only [mem_setOf_eq, iInf_and, iInf_exists, @iInf_comm _ (_ ∈ _), @iInf_comm _ (Set ℝₗ),
iInf_iInf_eq_right, mem_Ico]
simp_rw [@iInf_comm _ ℝₗ (_ ≤ _), iInf_subtype', ← Ici_inter_Iio, ← inf_principal,
← inf_iInf, ← iInf_inf, this, iInf_subtype]
suffices (⨅ x ∈ Ioi a, 𝓟 (Iio x)).HasBasis (a < ·) Iio from this.principal_inf _
refine hasBasis_biInf_principal ?_ nonempty_Ioi
exact directedOn_iff_directed.2 <| Monotone.directed_ge fun x y hxy ↦ Iio_subset_Iio hxy
theorem nhds_basis_Ico_rat (a : ℝₗ) :
(𝓝 a).HasCountableBasis (fun r : ℚ => a < r) fun r => Ico a r := by
refine ⟨(nhds_basis_Ico a).to_hasBasis (fun b hb => ?_) fun r hr => ⟨_, hr, Subset.rfl⟩,
Set.to_countable _⟩
rcases exists_rat_btwn hb with ⟨r, har, hrb⟩
exact ⟨r, har, Ico_subset_Ico_right hrb.le⟩
theorem nhds_basis_Ico_inv_pnat (a : ℝₗ) :
(𝓝 a).HasBasis (fun _ : ℕ+ => True) fun n => Ico a (a + (n : ℝₗ)⁻¹) := by
refine (nhds_basis_Ico a).to_hasBasis (fun b hb => ?_) fun n hn =>
⟨_, lt_add_of_pos_right _ (inv_pos.2 <| Nat.cast_pos.2 n.pos), Subset.rfl⟩
rcases exists_nat_one_div_lt (sub_pos.2 hb) with ⟨k, hk⟩
rw [one_div] at hk
rw [← Nat.cast_add_one] at hk
exact ⟨k.succPNat, trivial, Ico_subset_Ico_right (le_sub_iff_add_le'.1 hk.le)⟩
theorem nhds_countable_basis_Ico_inv_pnat (a : ℝₗ) :
(𝓝 a).HasCountableBasis (fun _ : ℕ+ => True) fun n => Ico a (a + (n : ℝₗ)⁻¹) :=
⟨nhds_basis_Ico_inv_pnat a, Set.to_countable _⟩
theorem nhds_antitone_basis_Ico_inv_pnat (a : ℝₗ) :
(𝓝 a).HasAntitoneBasis fun n : ℕ+ => Ico a (a + (n : ℝₗ)⁻¹) :=
⟨nhds_basis_Ico_inv_pnat a, monotone_const.Ico <| Antitone.const_add
(fun k _l hkl => inv_anti₀ (Nat.cast_pos.2 k.2)
(Nat.mono_cast <| Subtype.coe_le_coe.2 hkl)) _⟩
theorem isOpen_iff {s : Set ℝₗ} : IsOpen s ↔ ∀ x ∈ s, ∃ y > x, Ico x y ⊆ s :=
isOpen_iff_mem_nhds.trans <| forall₂_congr fun x _ => (nhds_basis_Ico x).mem_iff
theorem isClosed_iff {s : Set ℝₗ} : IsClosed s ↔ ∀ x, x ∉ s → ∃ y > x, Disjoint (Ico x y) s := by
simp only [← isOpen_compl_iff, isOpen_iff, mem_compl_iff, subset_compl_iff_disjoint_right]
theorem exists_Ico_disjoint_closed {a : ℝₗ} {s : Set ℝₗ} (hs : IsClosed s) (ha : a ∉ s) :
∃ b > a, Disjoint (Ico a b) s :=
isClosed_iff.1 hs a ha
@[simp]
theorem map_toReal_nhds (a : ℝₗ) : map toReal (𝓝 a) = 𝓝[≥] toReal a := by
refine ((nhds_basis_Ico a).map _).eq_of_same_basis ?_
simpa only [toReal.image_eq_preimage_symm] using nhdsGE_basis_Ico (toReal a)
theorem nhds_eq_map (a : ℝₗ) : 𝓝 a = map toReal.symm (𝓝[≥] (toReal a)) := by
simp_rw [← map_toReal_nhds, map_map, Function.comp_def, toReal.symm_apply_apply, map_id']
theorem nhds_eq_comap (a : ℝₗ) : 𝓝 a = comap toReal (𝓝[≥] (toReal a)) := by
rw [← map_toReal_nhds, comap_map toReal.injective]
@[continuity]
theorem continuous_toReal : Continuous toReal :=
continuous_iff_continuousAt.2 fun x => by
rw [ContinuousAt, Tendsto, map_toReal_nhds]
exact inf_le_left
instance : OrderClosedTopology ℝₗ :=
⟨isClosed_le_prod.preimage (continuous_toReal.prodMap continuous_toReal)⟩
instance : ContinuousAdd ℝₗ := by
refine ⟨continuous_iff_continuousAt.2 ?_⟩
rintro ⟨x, y⟩
rw [ContinuousAt, nhds_prod_eq, nhds_eq_comap (x + y), tendsto_comap_iff,
nhds_eq_map, nhds_eq_map, prod_map_map_eq, ← nhdsWithin_prod_eq, Ici_prod_Ici]
exact (continuous_add.tendsto _).inf (MapsTo.tendsto fun x hx => add_le_add hx.1 hx.2)
theorem isClopen_Ici (a : ℝₗ) : IsClopen (Ici a) :=
⟨isClosed_Ici, isOpen_Ici a⟩
theorem isClopen_Iio (a : ℝₗ) : IsClopen (Iio a) := by
simpa only [compl_Ici] using (isClopen_Ici a).compl
theorem isClopen_Ico (a b : ℝₗ) : IsClopen (Ico a b) :=
(isClopen_Ici a).inter (isClopen_Iio b)
instance : TotallyDisconnectedSpace ℝₗ :=
⟨fun _ _ hs x hx y hy =>
le_antisymm (hs.subset_isClopen (isClopen_Ici x) ⟨x, hx, left_mem_Ici⟩ hy)
(hs.subset_isClopen (isClopen_Ici y) ⟨y, hy, left_mem_Ici⟩ hx)⟩
instance : FirstCountableTopology ℝₗ :=
⟨fun x => (nhds_basis_Ico_rat x).isCountablyGenerated⟩
/-- Sorgenfrey line is a completely normal topological space.
(Hausdorff follows as TotallyDisconnectedSpace → T₁) -/
instance : CompletelyNormalSpace ℝₗ := by
/-
Let `s` and `t` be disjoint closed sets.
For each `x ∈ s` we choose `X x` such that `Set.Ico x (X x)` is disjoint with `t`.
Similarly, for each `y ∈ t` we choose `Y y` such that `Set.Ico y (Y y)` is disjoint with `s`.
Then `⋃ x ∈ s, Ico x (X x)` and `⋃ y ∈ t, Ico y (Y y)` are
disjoint open sets that include `s` and `t`.
-/
refine ⟨fun s t hd₁ hd₂ => ?_⟩
choose! X hX hXd using fun x (hx : x ∈ s) =>
exists_Ico_disjoint_closed isClosed_closure (disjoint_left.1 hd₂ hx)
choose! Y hY hYd using fun y (hy : y ∈ t) =>
exists_Ico_disjoint_closed isClosed_closure (disjoint_right.1 hd₁ hy)
refine disjoint_of_disjoint_of_mem ?_
(bUnion_mem_nhdsSet fun x hx => (isOpen_Ico x (X x)).mem_nhds <| left_mem_Ico.2 (hX x hx))
(bUnion_mem_nhdsSet fun y hy => (isOpen_Ico y (Y y)).mem_nhds <| left_mem_Ico.2 (hY y hy))
simp only [disjoint_iUnion_left, disjoint_iUnion_right, Ico_disjoint_Ico]
intro y hy x hx
rcases le_total x y with hle | hle
· calc
min (X x) (Y y) ≤ X x := min_le_left _ _
_ ≤ y := (not_lt.1 fun hyx => (hXd x hx).le_bot ⟨⟨hle, hyx⟩, subset_closure hy⟩)
_ ≤ max x y := le_max_right _ _
· calc
min (X x) (Y y) ≤ Y y := min_le_right _ _
_ ≤ x := (not_lt.1 fun hxy => (hYd y hy).le_bot ⟨⟨hle, hxy⟩, subset_closure hx⟩)
_ ≤ max x y := le_max_left _ _
theorem denseRange_ratCast : DenseRange ((↑) : ℚ → ℝₗ) := by
refine dense_iff_inter_open.2 ?_
rintro U Uo ⟨x, hx⟩
rcases isOpen_iff.1 Uo _ hx with ⟨y, hxy, hU⟩
rcases exists_rat_btwn hxy with ⟨z, hxz, hzy⟩
exact ⟨z, hU ⟨hxz.le, hzy⟩, mem_range_self _⟩
instance : SeparableSpace ℝₗ :=
⟨⟨_, countable_range _, denseRange_ratCast⟩⟩
theorem isClosed_antidiagonal (c : ℝₗ) : IsClosed {x : ℝₗ × ℝₗ | x.1 + x.2 = c} :=
isClosed_singleton.preimage continuous_add
theorem isClopen_Ici_prod (x : ℝₗ × ℝₗ) : IsClopen (Ici x) :=
(Ici_prod_eq x).symm ▸ (isClopen_Ici _).prod (isClopen_Ici _)
theorem cardinal_antidiagonal (c : ℝₗ) : #{x : ℝₗ × ℝₗ | x.1 + x.2 = c} = 𝔠 := by
rw [← Cardinal.mk_real]
exact Equiv.cardinal_eq ⟨fun x ↦ toReal x.1.1,
fun x ↦ ⟨(toReal.symm x, c - toReal.symm x), by simp⟩,
fun ⟨x, hx⟩ ↦ by ext <;> simp [← hx.out], fun x ↦ rfl⟩
/-- Any subset of an antidiagonal `{(x, y) : ℝₗ × ℝₗ| x + y = c}` is a closed set. -/
theorem isClosed_of_subset_antidiagonal {s : Set (ℝₗ × ℝₗ)} {c : ℝₗ} (hs : ∀ x ∈ s, x.1 + x.2 = c) :
IsClosed s := by
rw [← closure_subset_iff_isClosed]
rintro ⟨x, y⟩ H
obtain rfl : x + y = c := by
change (x, y) ∈ {p : ℝₗ × ℝₗ | p.1 + p.2 = c}
exact closure_minimal (hs : s ⊆ {x | x.1 + x.2 = c}) (isClosed_antidiagonal c) H
rcases mem_closure_iff.1 H (Ici (x, y)) (isClopen_Ici_prod _).2 left_mem_Ici with
⟨⟨x', y'⟩, ⟨hx : x ≤ x', hy : y ≤ y'⟩, H⟩
convert H
· refine hx.antisymm ?_
rwa [← add_le_add_iff_right, hs _ H, add_le_add_iff_left]
· refine hy.antisymm ?_
rwa [← add_le_add_iff_left, hs _ H, add_le_add_iff_right]
open Subtype in
instance (c : ℝₗ) : DiscreteTopology {x : ℝₗ × ℝₗ | x.1 + x.2 = c} :=
discreteTopology_iff_forall_isClosed.2 fun C ↦ isClosed_induced_iff.2
⟨val '' C, isClosed_of_subset_antidiagonal <| coe_image_subset _ C,
preimage_image_eq _ val_injective⟩
/-- The Sorgenfrey plane `ℝₗ × ℝₗ` is not a normal space. -/
theorem not_normalSpace_prod : ¬NormalSpace (ℝₗ × ℝₗ) :=
(isClosed_antidiagonal 0).not_normal_of_continuum_le_mk (cardinal_antidiagonal _).ge
/-- An antidiagonal is a separable set but is not a separable space. -/
theorem isSeparable_antidiagonal (c : ℝₗ) : IsSeparable {x : ℝₗ × ℝₗ | x.1 + x.2 = c} :=
.of_separableSpace _
/-- An antidiagonal is a separable set but is not a separable space. -/
theorem not_separableSpace_antidiagonal (c : ℝₗ) :
¬SeparableSpace {x : ℝₗ × ℝₗ | x.1 + x.2 = c} := by
rw [separableSpace_iff_countable, ← Cardinal.mk_le_aleph0_iff, cardinal_antidiagonal, not_le]
exact Cardinal.aleph0_lt_continuum
theorem nhds_prod_antitone_basis_inv_pnat (x y : ℝₗ) :
(𝓝 (x, y)).HasAntitoneBasis fun n : ℕ+ => Ico x (x + (n : ℝₗ)⁻¹) ×ˢ Ico y (y + (n : ℝₗ)⁻¹) := by
rw [nhds_prod_eq]
exact (nhds_antitone_basis_Ico_inv_pnat x).prod (nhds_antitone_basis_Ico_inv_pnat y)
/-- The sets of rational and irrational points of the antidiagonal `{(x, y) | x + y = 0}` cannot be
separated by open neighborhoods. This implies that `ℝₗ × ℝₗ` is not a normal space. -/
theorem not_separatedNhds_rat_irrational_antidiag :
¬SeparatedNhds {x : ℝₗ × ℝₗ | x.1 + x.2 = 0 ∧ ∃ r : ℚ, ↑r = x.1}
{x : ℝₗ × ℝₗ | x.1 + x.2 = 0 ∧ Irrational (toReal x.1)} := by
have h₀ : ∀ {n : ℕ+}, 0 < (n : ℝ)⁻¹ := inv_pos.2 (Nat.cast_pos.2 (PNat.pos _))
have h₀' : ∀ {n : ℕ+} {x : ℝ}, x < x + (n : ℝ)⁻¹ := lt_add_of_pos_right _ h₀
/- Let `S` be the set of points `(x, y)` on the line `x + y = 0` such that `x` is rational.
Let `T` be the set of points `(x, y)` on the line `x + y = 0` such that `x` is irrational.
These sets are closed, see `SorgenfreyLine.isClosed_of_subset_antidiagonal`, and disjoint. -/
set S := {x : ℝₗ × ℝₗ | x.1 + x.2 = 0 ∧ ∃ r : ℚ, ↑r = x.1}
set T := {x : ℝₗ × ℝₗ | x.1 + x.2 = 0 ∧ Irrational (toReal x.1)}
-- Consider disjoint open sets `U ⊇ S` and `V ⊇ T`.
rintro ⟨U, V, Uo, Vo, SU, TV, UV⟩
/- For each point `(x, -x) ∈ T`, choose a neighborhood
`Ico x (x + k⁻¹) ×ˢ Ico (-x) (-x + k⁻¹) ⊆ V`. -/
have : ∀ x : ℝₗ, Irrational (toReal x) →
∃ k : ℕ+, Ico x (x + (k : ℝₗ)⁻¹) ×ˢ Ico (-x) (-x + (k : ℝₗ)⁻¹) ⊆ V := fun x hx ↦ by
have hV : V ∈ 𝓝 (x, -x) := Vo.mem_nhds (@TV (x, -x) ⟨add_neg_cancel x, hx⟩)
exact (nhds_prod_antitone_basis_inv_pnat _ _).mem_iff.1 hV
choose! k hkV using this
/- Since the set of irrational numbers is a dense Gδ set in the usual topology of `ℝ`, there
exists `N > 0` such that the set `C N = {x : ℝ | Irrational x ∧ k x = N}` is dense in a nonempty
interval. In other words, the closure of this set has a nonempty interior. -/
set C : ℕ+ → Set ℝ := fun n => closure {x | Irrational x ∧ k (toReal.symm x) = n}
have H : {x : ℝ | Irrational x} ⊆ ⋃ n, C n := fun x hx =>
mem_iUnion.2 ⟨_, subset_closure ⟨hx, rfl⟩⟩
have Hd : Dense (⋃ n, interior (C n)) :=
IsGδ.setOf_irrational.dense_iUnion_interior_of_closed dense_irrational
(fun _ => isClosed_closure) H
obtain ⟨N, hN⟩ : ∃ n : ℕ+, (interior <| C n).Nonempty := nonempty_iUnion.mp Hd.nonempty
/- Choose a rational number `r` in the interior of the closure of `C N`, then choose `n ≥ N > 0`
such that `Ico r (r + n⁻¹) × Ico (-r) (-r + n⁻¹) ⊆ U`. -/
rcases Rat.denseRange_cast.exists_mem_open isOpen_interior hN with ⟨r, hr⟩
have hrU : ((r, -r) : ℝₗ × ℝₗ) ∈ U := @SU (r, -r) ⟨add_neg_cancel _, r, rfl⟩
obtain ⟨n, hnN, hn⟩ :
∃ n, N ≤ n ∧ Ico (r : ℝₗ) (r + (n : ℝₗ)⁻¹) ×ˢ Ico (-r : ℝₗ) (-r + (n : ℝₗ)⁻¹) ⊆ U :=
((nhds_prod_antitone_basis_inv_pnat _ _).hasBasis_ge N).mem_iff.1 (Uo.mem_nhds hrU)
/- Finally, choose `x ∈ Ioo (r : ℝ) (r + n⁻¹) ∩ C N`. Then `(x, -r)` belongs both to `U` and `V`,
so they are not disjoint. This contradiction completes the proof. -/
obtain ⟨x, hxn, hx_irr, rfl⟩ :
∃ x : ℝ, x ∈ Ioo (r : ℝ) (r + (n : ℝ)⁻¹) ∧ Irrational x ∧ k (toReal.symm x) = N := by
have : (r : ℝ) ∈ closure (Ioo (r : ℝ) (r + (n : ℝ)⁻¹)) := by
rw [closure_Ioo h₀'.ne, left_mem_Icc]
exact h₀'.le
rcases mem_closure_iff_nhds.1 this _ (mem_interior_iff_mem_nhds.1 hr) with ⟨x', hx', hx'ε⟩
exact mem_closure_iff.1 hx' _ isOpen_Ioo hx'ε
refine UV.le_bot (?_ : (toReal.symm x, -(r : ℝₗ)) ∈ _)
refine ⟨hn ⟨?_, ?_⟩, hkV (toReal.symm x) hx_irr ⟨?_, ?_⟩⟩
· exact Ioo_subset_Ico_self hxn
· exact left_mem_Ico.2 h₀'
· exact left_mem_Ico.2 h₀'
· refine (nhds_antitone_basis_Ico_inv_pnat (-x)).2 hnN ⟨neg_le_neg hxn.1.le, ?_⟩
simp only [add_neg_lt_iff_le_add', lt_neg_add_iff_add_lt]
exact hxn.2
/-- Topology on the Sorgenfrey line is not metrizable. -/
theorem not_metrizableSpace : ¬MetrizableSpace ℝₗ := by
intro
letI := metrizableSpaceMetric ℝₗ
exact not_normalSpace_prod inferInstance
/-- Topology on the Sorgenfrey line is not second countable. -/
theorem not_secondCountableTopology : ¬SecondCountableTopology ℝₗ :=
fun _ ↦ not_metrizableSpace (metrizableSpace_of_t3_secondCountable _)
end SorgenfreyLine
end
end Counterexample |
.lake/packages/mathlib/Counterexamples/QuadraticForm.lean | import Mathlib.LinearAlgebra.QuadraticForm.Basic
/-!
# `QuadraticForm R M` and `Subtype LinearMap.IsSymm` are distinct notions in characteristic 2
The main result of this file is `LinearMap.BilinForm.not_injOn_toQuadraticForm_isSymm`.
The counterexample we use is $B (x, y) (x', y') ↦ xy' + x'y$ where `x y x' y' : ZMod 2`.
-/
variable (F : Type*) [CommRing F]
open LinearMap
open LinearMap.BilinForm
open LinearMap (BilinForm)
open LinearMap.BilinMap
namespace Counterexample
/-- The bilinear form we will use as a counterexample, over some field `F` of characteristic two. -/
def B : BilinForm F (F × F) :=
(mul F F).compl₁₂ (fst _ _ _) (snd _ _ _) + (mul F F).compl₁₂ (snd _ _ _) (fst _ _ _)
@[simp]
theorem B_apply (x y : F × F) : B F x y = x.1 * y.2 + x.2 * y.1 :=
rfl
theorem isSymm_B : (B F).IsSymm := ⟨fun x y => by simp [mul_comm, add_comm]⟩
theorem isAlt_B [CharP F 2] : (B F).IsAlt := fun x => by
simp [mul_comm, CharTwo.add_self_eq_zero (x.1 * x.2)]
theorem B_ne_zero [Nontrivial F] : B F ≠ 0 := fun h => by
simpa using LinearMap.congr_fun₂ h (1, 0) (1, 1)
/-- `LinearMap.BilinForm.toQuadraticForm` is not injective on symmetric bilinear forms.
This disproves a weaker version of `QuadraticForm.associated_left_inverse`.
-/
theorem LinearMap.BilinForm.not_injOn_toQuadraticForm_isSymm.{u} :
¬∀ {R M : Type u} [CommSemiring R] [AddCommMonoid M], ∀ [Module R M],
Set.InjOn (toQuadraticMap : BilinForm R M → QuadraticForm R M) {B | B.IsSymm} := by
intro h
let F := ULift.{u} (ZMod 2)
apply B_ne_zero F
apply h (isSymm_B F) isSymm_zero
rw [toQuadraticMap_zero, toQuadraticMap_eq_zero]
exact isAlt_B F
end Counterexample |
.lake/packages/mathlib/Counterexamples/Girard.lean | import Mathlib.Logic.Basic
import Mathlib.Data.Set.Defs
/-!
# Girard's paradox
Girard's paradox is a proof that `Type : Type` entails a contradiction. We can't say this directly
in Lean because `Type : Type 1` and it's not possible to give `Type` a different type via an axiom,
so instead we axiomatize the behavior of the Pi type and application if the typing rule for Pi was
`(Type → Type) → Type` instead of `(Type → Type) → Type 1`.
Furthermore, we don't actually want false axioms in mathlib, so rather than introducing the axioms
using `axiom` or `constant` declarations, we take them as assumptions to the `girard` theorem.
Based on Watkins' LF implementation of Hurkens' simplification of Girard's paradox:
<http://www.cs.cmu.edu/~kw/research/hurkens95tlca.elf>.
## Main statements
* `girard`: there are no Girard universes.
-/
namespace Counterexample
/-- **Girard's paradox**: there are no universes `u` such that `Type u : Type u`.
Since we can't actually change the type of Lean's `Π` operator, we assume the existence of
`pi`, `lam`, `app` and the `beta` rule equivalent to the `Π` and `app` constructors of type theory.
-/
theorem girard.{u} (pi : (Type u → Type u) → Type u)
(lam : ∀ {A : Type u → Type u}, (∀ x, A x) → pi A) (app : ∀ {A}, pi A → ∀ x, A x)
(beta : ∀ {A : Type u → Type u} (f : ∀ x, A x) (x), app (lam f) x = f x) : False :=
let F (X) := (Set (Set X) → X) → Set (Set X)
let U := pi F
let G (T : Set (Set U)) (X) : F X := fun f => {p | {x : U | f (app x X f) ∈ p} ∈ T}
let τ (T : Set (Set U)) : U := lam (G T)
let σ (S : U) : Set (Set U) := app S U τ
have στ : ∀ {s S}, s ∈ σ (τ S) ↔ {x | τ (σ x) ∈ s} ∈ S := fun {s S} =>
iff_of_eq (congr_arg (fun f : F U => s ∈ f τ) (beta (G S) U) :)
let ω : Set (Set U) := {p | ∀ x, p ∈ σ x → x ∈ p}
let δ (S : Set (Set U)) := ∀ p, p ∈ S → τ S ∈ p
have : δ ω := fun _p d => d (τ ω) <| στ.2 fun x h => d (τ (σ x)) (στ.2 h)
this {y | ¬δ (σ y)} (fun _x e f => f _ e fun _p h => f _ (στ.1 h)) fun _p h => this _ (στ.1 h)
end Counterexample |
.lake/packages/mathlib/Counterexamples/CharPZeroNeCharZero.lean | import Mathlib.Algebra.CharP.Lemmas
import Mathlib.Algebra.Ring.PUnit
/-! # `CharP R 0` and `CharZero R` need not coincide for semirings
For rings, the two notions coincide.
In fact, `CharP.ofCharZero` shows that `CharZero R` implies `CharP R 0` for any `CharZero`
`AddMonoid R` with `1`.
The reverse implication holds for any `AddLeftCancelMonoid R` with `1`, by `charP_to_charZero`.
This file shows that there are semirings `R` for which `CharP R 0` holds and `CharZero R` does not.
The example is `{0, 1}` with saturating addition.
-/
namespace Counterexample
@[simp]
theorem add_one_eq_one (x : WithZero Unit) : x + 1 = 1 :=
WithZero.cases_on x (by rfl) fun h => by rfl
theorem withZero_unit_charP_zero : CharP (WithZero Unit) 0 :=
⟨fun x => by cases x <;> simp⟩
theorem withZero_unit_not_charZero : ¬CharZero (WithZero Unit) := fun ⟨h⟩ =>
h.ne (by simp : 1 + 1 ≠ 0 + 1) (by simp [-Nat.reduceAdd])
end Counterexample |
.lake/packages/mathlib/Counterexamples/CliffordAlgebraNotInjective.lean | import Mathlib.Algebra.CharP.Pi
import Mathlib.Algebra.CharP.Quotient
import Mathlib.LinearAlgebra.CliffordAlgebra.Contraction
import Mathlib.RingTheory.MvPolynomial.Basic
import Mathlib.RingTheory.MvPolynomial.Ideal
import Mathlib.Tactic.Ring.NamePolyVars
/-! # `algebraMap R (CliffordAlgebra Q)` is not always injective.
A formalization of [Darij Grinberg's answer](https://mathoverflow.net/questions/60596/clifford-pbw-theorem-for-quadratic-form/87958#87958)
to a "Clifford PBW theorem for quadratic form" post on MathOverflow, that provides a counterexample
to `Function.Injective (algebraMap R (CliffordAlgebra Q))`.
The outline is that we define:
* $k$ (`Q60596.K`) as the commutative ring $𝔽₂[α, β, γ] / (α², β², γ²)$
* $L$ (`Q60596.L`) as the $k$-module $⟨x,y,z⟩ / ⟨αx + βy + γz⟩$
* $Q$ (`Q60596.Q`) as the quadratic form sending $Q(\overline{ax + by + cz}) = a² + b² + c²$
and discover that $αβγ ≠ 0$ as an element of $K$, but $αβγ = 0$ as an element of $𝒞l(Q)$.
Some Zulip discussion at https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/.F0.9D.94.BD.E2.82.82.5B.CE.B1.2C.20.CE.B2.2C.20.CE.B3.5D.20.2F.20.28.CE.B1.C2.B2.2C.20.CE.B2.C2.B2.2C.20.CE.B3.C2.B2.29/near/222716333.
As a bonus result, we also show `BilinMap.not_forall_toQuadraticMap_surjective`: that there
are quadratic forms that cannot be expressed via even non-symmetric bilinear forms.
-/
noncomputable section
open LinearMap (BilinForm)
open LinearMap (BilinMap)
name_poly_vars X, Y, Z over ZMod 2
namespace Q60596
open MvPolynomial
/-- The monomial ideal generated by terms of the form $x_ix_i$. -/
def kIdeal : Ideal (MvPolynomial (Fin 3) (ZMod 2)) :=
Ideal.span (Set.range fun i =>
(MvPolynomial.X i * MvPolynomial.X i : MvPolynomial (Fin 3) (ZMod 2)))
theorem mem_kIdeal_iff (x : MvPolynomial (Fin 3) (ZMod 2)) :
x ∈ kIdeal ↔ ∀ m : Fin 3 →₀ ℕ, m ∈ x.support → ∃ i, 2 ≤ m i := by
have :
kIdeal = Ideal.span ((monomial · (1 : ZMod 2)) '' Set.range (Finsupp.single · 2)) := by
simp_rw [kIdeal, MvPolynomial.X, monomial_mul, one_mul, ← Finsupp.single_add, ← Set.range_comp,
Function.comp_def]
rw [this, mem_ideal_span_monomial_image]
simp
theorem X_Y_Z_notMem_kIdeal : (X * Y * Z : MvPolynomial (Fin 3) (ZMod 2)) ∉ kIdeal := by
intro h
simp_rw [mem_kIdeal_iff, support_mul_X, support_X, Finset.map_singleton, addRightEmbedding_apply,
Finset.mem_singleton, forall_eq, ← Fin.sum_univ_three fun i => Finsupp.single i 1,
← Finsupp.equivFunOnFinite_symm_eq_sum] at h
contradiction
@[deprecated (since := "2025-05-23")] alias X_Y_Z_not_mem_kIdeal := X_Y_Z_notMem_kIdeal
theorem mul_self_mem_kIdeal_of_X_Y_Z_mul_mem {x : MvPolynomial (Fin 3) (ZMod 2)}
(h : X * Y * Z * x ∈ kIdeal) : x * x ∈ kIdeal := by
rw [mem_kIdeal_iff] at h
have : x ∈ Ideal.span ((MvPolynomial.X : Fin 3 → MvPolynomial _ (ZMod 2)) '' Set.univ) := by
rw [mem_ideal_span_X_image]
intro m hm
simp_rw [mul_assoc, support_X_mul, Finset.map_map, Finset.mem_map,
Function.Embedding.trans_apply, addLeftEmbedding_apply, forall_exists_index,
and_imp, forall_apply_eq_imp_iff₂, ← add_assoc, ←
Fin.sum_univ_three fun i => Finsupp.single i 1, ← Finsupp.equivFunOnFinite_symm_eq_sum,
Finsupp.add_apply, Finsupp.equivFunOnFinite_symm_apply_toFun] at h
refine (h _ hm).imp fun i hi => ⟨Set.mem_univ _, ?_⟩
rintro hmi
rw [hmi] at hi
norm_num at hi
rw [as_sum x, CharTwo.sum_mul_self]
refine sum_mem fun m hm => ?_
rw [mem_kIdeal_iff, monomial_mul]
intro m' hm'
obtain rfl := Finset.mem_singleton.1 (support_monomial_subset hm')
rw [mem_ideal_span_X_image] at this
obtain ⟨i, _, hi⟩ := this m hm
simp_rw [← one_add_one_eq_two]
refine ⟨i, Nat.add_le_add ?_ ?_⟩ <;> rwa [Nat.one_le_iff_ne_zero]
/-- `𝔽₂[α, β, γ] / (α², β², γ²)` -/
def K : Type _ := _ ⧸ kIdeal
instance : CommRing K := Ideal.Quotient.commRing _
theorem comap_C_kIdeal : kIdeal.comap (C : ZMod 2 →+* MvPolynomial (Fin 3) (ZMod 2)) = ⊥ := by
refine bot_unique ?_
refine (Ideal.comap_le_map_of_inverse _ _ _ (constantCoeff_C _)).trans ?_
rw [kIdeal, Ideal.map_span]
refine (Ideal.span_le).2 ?_
rintro x ⟨_, ⟨i, rfl⟩, rfl⟩
rw [RingHom.map_mul, constantCoeff_X, mul_zero, Submodule.bot_coe,
Set.mem_singleton_iff]
/-- `k` has characteristic 2. -/
instance K.charP : CharP K 2 := by
dsimp only [K]
rw [CharP.quotient_iff_le_ker_natCast]
have : Nat.castRingHom (MvPolynomial (Fin 3) (ZMod 2)) = C.comp (Nat.castRingHom _) := by
ext1 r; rfl
rw [this, ← Ideal.comap_comap, ← RingHom.comap_ker, comap_C_kIdeal]
exact Ideal.comap_mono bot_le
/-- The generators of `K`. -/
def K.gen (i : Fin 3) : K := Ideal.Quotient.mk _ (MvPolynomial.X i)
local notation "α" => K.gen 0
local notation "β" => K.gen 1
local notation "γ" => K.gen 2
/-- The elements above square to zero -/
@[simp]
theorem X_sq (i : Fin 3) : K.gen i * K.gen i = (0 : K) := by
change Ideal.Quotient.mk _ _ = _
rw [Ideal.Quotient.eq_zero_iff_mem]
exact Ideal.subset_span ⟨i, rfl⟩
/-- If an element multiplied by `αβγ` is zero then it squares to zero. -/
theorem sq_zero_of_αβγ_mul {x : K} : α * β * γ * x = 0 → x * x = 0 := by
induction x using Quotient.inductionOn'
change Ideal.Quotient.mk _ _ = 0 → Ideal.Quotient.mk _ _ = 0
rw [Ideal.Quotient.eq_zero_iff_mem, Ideal.Quotient.eq_zero_iff_mem]
exact mul_self_mem_kIdeal_of_X_Y_Z_mul_mem
/-- Though `αβγ` is not itself zero -/
theorem αβγ_ne_zero : α * β * γ ≠ 0 := fun h =>
X_Y_Z_notMem_kIdeal <| Ideal.Quotient.eq_zero_iff_mem.1 h
/-- The 1-form on $K^3$, the kernel of which we will take a quotient by.
Our source uses $αx - βy - γz$, though since this is characteristic two we just use $αx + βy + γz$.
-/
@[simps!]
def lFunc : (Fin 3 → K) →ₗ[K] K :=
letI proj : Fin 3 → (Fin 3 → K) →ₗ[K] K := LinearMap.proj
α • proj 0 + β • proj 1 + γ • proj 2
/-- The quotient of `K^3` by the specified relation. -/
abbrev L : Type _ := _ ⧸ LinearMap.ker lFunc
/-- The quadratic form corresponding to squaring a single coefficient. -/
def sq {ι R : Type*} [CommRing R] (i : ι) : QuadraticForm R (ι → R) :=
QuadraticMap.sq.comp <| LinearMap.proj i
theorem sq_map_add_char_two {ι R : Type*} [CommRing R] [CharP R 2] (i : ι) (a b : ι → R) :
sq i (a + b) = sq i a + sq i b :=
CharTwo.add_mul_self _ _
theorem sq_map_sub_char_two {ι R : Type*} [CommRing R] [CharP R 2] (i : ι) (a b : ι → R) :
sq i (a - b) = sq i a - sq i b := by
haveI : Nonempty ι := ⟨i⟩
rw [CharTwo.sub_eq_add, CharTwo.sub_eq_add, sq_map_add_char_two]
/-- The quadratic form (metric) is just Euclidean -/
def Q' : QuadraticForm K (Fin 3 → K) :=
∑ i, sq i
theorem Q'_add (x y : Fin 3 → K) : Q' (x + y) = Q' x + Q' y := by
simp only [Q', QuadraticMap.sum_apply, sq_map_add_char_two, Finset.sum_add_distrib]
theorem Q'_sub (x y : Fin 3 → K) : Q' (x - y) = Q' x - Q' y := by
simp only [Q', QuadraticMap.sum_apply, sq_map_sub_char_two, Finset.sum_sub_distrib]
theorem Q'_apply (a : Fin 3 → K) : Q' a = a 0 * a 0 + a 1 * a 1 + a 2 * a 2 :=
calc
Q' a = a 0 * a 0 + (a 1 * a 1 + (a 2 * a 2 + 0)) := rfl
_ = _ := by ring
theorem Q'_apply_single (i : Fin 3) (x : K) : Q' (Pi.single i x) = x * x :=
calc
Q' (Pi.single i x) = ∑ j : Fin 3, (Pi.single i x * Pi.single i x : Fin 3 → K) j := by
simp [Q', sq]
_ = _ := by simp_rw [← Pi.single_mul, Finset.sum_pi_single', Finset.mem_univ, if_pos]
theorem Q'_zero_under_ideal (v : Fin 3 → K) (hv : v ∈ LinearMap.ker lFunc) : Q' v = 0 := by
rw [LinearMap.mem_ker, lFunc_apply] at hv
have h0 : α * β * γ * v 0 = 0 := by
have := congr_arg (β * γ * ·) hv
simp only [mul_zero, mul_add, ← mul_assoc] at this
rw [mul_comm (β * γ) α, ← mul_assoc, mul_right_comm β γ β, mul_assoc β γ γ, X_sq, X_sq] at this
simpa only [mul_zero, zero_mul, add_zero, zero_add] using this
have h1 : α * β * γ * v 1 = 0 := by
have := congr_arg (α * γ * ·) hv
simp only [mul_zero, mul_add, ← mul_assoc] at this
rw [mul_right_comm α γ α, mul_assoc α γ γ, mul_right_comm α γ β, X_sq, X_sq] at this
simpa only [mul_zero, zero_mul, add_zero, zero_add] using this
have h2 : α * β * γ * v 2 = 0 := by
have := congr_arg (α * β * ·) hv
simp only [mul_zero, mul_add, ← mul_assoc] at this
rw [mul_right_comm α β α, mul_assoc α β β, X_sq, X_sq] at this
simpa only [mul_zero, zero_mul, add_zero, zero_add] using this
rw [Q'_apply, sq_zero_of_αβγ_mul h0, sq_zero_of_αβγ_mul h1, sq_zero_of_αβγ_mul h2, add_zero,
add_zero]
/-- `Q'`, lifted to operate on the quotient space `L`. -/
@[simps!]
def Q : QuadraticForm K L :=
QuadraticMap.ofPolar
(fun x =>
Quotient.liftOn' x Q' fun a b h => by
rw [Submodule.quotientRel_def] at h
suffices Q' (a - b) = 0 by rwa [Q'_sub, sub_eq_zero] at this
apply Q'_zero_under_ideal (a - b) h)
(fun a x => by
induction x using Quotient.inductionOn
exact Q'.toFun_smul a _)
(by rintro ⟨x⟩ ⟨x'⟩ ⟨y⟩; exact Q'.polar_add_left x x' y)
(by rintro c ⟨x⟩ ⟨y⟩; exact Q'.polar_smul_left c x y)
open CliffordAlgebra
/-- Basis vectors in the Clifford algebra -/
def gen (i : Fin 3) : CliffordAlgebra Q := ι Q <| Submodule.Quotient.mk (Pi.single i 1)
local notation "x'" => gen 0
local notation "y'" => gen 1
local notation "z'" => gen 2
/-- The basis vectors square to one -/
@[simp]
theorem gen_mul_gen (i) : gen i * gen i = 1 := by
dsimp only [gen]
simp_rw [CliffordAlgebra.ι_sq_scalar, Q_apply, ← Submodule.Quotient.mk''_eq_mk,
Quotient.liftOn'_mk'', Q'_apply_single, mul_one, map_one]
/-- By virtue of the quotient, terms of this form are zero -/
theorem quot_obv : α • x' - β • y' - γ • z' = 0 := by
dsimp only [gen]
simp_rw [← LinearMap.map_smul, ← LinearMap.map_sub, ← Submodule.Quotient.mk_smul _ (_ : K),
← Submodule.Quotient.mk_sub]
convert LinearMap.map_zero _ using 2
rw [Submodule.Quotient.mk_eq_zero]
simp +decide [sub_zero]
/-- The core of the proof - scaling `1` by `α * β * γ` gives zero -/
theorem αβγ_smul_eq_zero : (α * β * γ) • (1 : CliffordAlgebra Q) = 0 := by
suffices α • 1 - β • (y' * x') - γ • (z' * x') = 0 by
have := congr_arg (fun x => (β * γ) • x) this
dsimp only at this
simp_rw [smul_sub, smul_smul] at this
rwa [mul_assoc β γ γ, mul_right_comm β γ β, mul_right_comm β γ α, mul_comm β α, X_sq, X_sq,
zero_mul, mul_zero, zero_smul, zero_smul, sub_zero, sub_zero, smul_zero] at this
have : (α • x' - β • y' - γ • z') * x' = α • 1 - β • (y' * x') - γ • (z' * x') := by
simp_rw [sub_mul, smul_mul_assoc, gen_mul_gen]
rw [← this]
rw [quot_obv, zero_mul]
theorem algebraMap_αβγ_eq_zero : algebraMap K (CliffordAlgebra Q) (α * β * γ) = 0 := by
rw [Algebra.algebraMap_eq_smul_one, αβγ_smul_eq_zero]
/-- Our final result: for the quadratic form `Q60596.Q`, the algebra map to the Clifford algebra
is not injective, as it sends the non-zero `α * β * γ` to zero. -/
theorem algebraMap_not_injective : ¬Function.Injective (algebraMap K <| CliffordAlgebra Q) :=
fun h => αβγ_ne_zero <| h <| by rw [algebraMap_αβγ_eq_zero, RingHom.map_zero]
/-- Bonus counterexample: `Q` is a quadratic form that has no bilinear form. -/
theorem Q_not_in_range_toQuadraticForm : Q ∉ Set.range BilinMap.toQuadraticMap := by
rintro ⟨B, hB⟩
rw [← sub_zero Q] at hB
apply algebraMap_not_injective
eta_expand
simp_rw [← changeForm_algebraMap hB, ← changeFormEquiv_apply]
refine (LinearEquiv.injective _).comp ?_
exact (ExteriorAlgebra.algebraMap_leftInverse _).injective
end Q60596
open Q60596 in
/-- The general statement: not every Clifford algebra over a module has an injective algebra map. -/
theorem CliffordAlgebra.not_forall_algebraMap_injective.{v} :
-- TODO: make `R` universe polymorphic
¬∀ (R : Type) (M : Type v) [CommRing R] [AddCommGroup M] [Module R M] (Q : QuadraticForm R M),
Function.Injective (algebraMap R <| CliffordAlgebra Q) :=
fun h => algebraMap_not_injective fun x y hxy => by
let uU := ULift.moduleEquiv (R := K) (M := L)
let uQ := Q.comp uU.toLinearMap
let f : Q →qᵢ uQ := { uU.symm with map_app' := fun _ => rfl }
refine h K (ULift L) (Q.comp uU.toLinearMap) ?_
let uC := CliffordAlgebra.map f
have := uC.congr_arg hxy
rwa [AlgHom.commutes, AlgHom.commutes] at this
open Q60596 in
/-- The general bonus statement: not every quadratic form is the diagonal of a bilinear form. -/
theorem BilinMap.not_forall_toQuadraticMap_surjective.{v} :
-- TODO: make `R` universe polymorphic
¬∀ (R : Type) (M : Type v) [CommRing R] [AddCommGroup M] [Module R M],
Function.Surjective (BilinMap.toQuadraticMap : BilinForm R M → QuadraticForm R M) :=
fun h => Q_not_in_range_toQuadraticForm <| by
let uU := ULift.moduleEquiv (R := K) (M := L)
obtain ⟨x, hx⟩ := h K (ULift L) (Q.comp uU)
refine ⟨x.compl₁₂ uU.symm uU.symm, ?_⟩
ext
simp [BilinMap.toQuadraticMap_comp_same, hx] |
.lake/packages/mathlib/Counterexamples/TopologistsSineCurve.lean | import Mathlib.Analysis.SpecialFunctions.Trigonometric.Inverse
import Mathlib.Topology.Connected.PathConnected
/-!
# The "topologist's sine curve" is connected but not path-connected
We give an example of a closed subset `T` of `ℝ × ℝ` which is connected but not path-connected: the
closure of the set `{ (x, sin x⁻¹) | x ∈ Ioi 0 }`.
## Main results
* `TopologistsSineCurve.isConnected_T`: the set `T` is connected.
* `TopologistsSineCurve.not_isPathConnected_T`: the set `T` is not path-connected.
This formalization is part of the UniDistance Switzerland bachelor thesis of Daniele Bolla. A
similar result has also been independently formalized by Vlad Tsyrklevich
(https://leanprover.zulipchat.com/#narrow/channel/113489-new-members/topic/golf.20request.3A.20Topologist's.20sine.20curve).
-/
open Topology Filter Set Real
namespace TopologistsSineCurve
/-- The topologist's sine curve, i.e. the graph of `y = sin (x⁻¹)` for `0 < x`. -/
def S : Set (ℝ × ℝ) := (fun x ↦ (x, sin x⁻¹)) '' Ioi 0
/-- The vertical line segment `{ (0, y) | -1 ≤ y ≤ 1 }`, which is the set of limit points of `S`
not contained in `S` itself. -/
def Z : Set (ℝ × ℝ) := (fun y ↦ (0, y)) '' Icc (-1) 1
/-- The union of `S` and `Z` (which we will show is the closure of `S`). -/
def T : Set (ℝ × ℝ) := S ∪ Z
/-- A sequence of `x`-values tending to 0 at which the sine curve has a given `y`-coordinate. -/
noncomputable def xSeq (y : ℝ) (k : ℕ) := 1 / (arcsin y + (k + 1) * (2 * π))
lemma xSeq_pos (y : ℝ) (k : ℕ) : 0 < xSeq y k := by
rw [xSeq, one_div_pos]
nlinarith [pi_pos, neg_pi_div_two_le_arcsin y]
lemma sin_inv_xSeq {y : ℝ} (hy : y ∈ Icc (-1) 1) (k : ℕ) : sin (xSeq y k)⁻¹ = y := by
simpa [xSeq, -Nat.cast_add, ← Nat.cast_succ] using sin_arcsin' hy
lemma xSeq_tendsto (y : ℝ) : Tendsto (xSeq y) atTop (𝓝 0) := by
refine .comp (g := fun k : ℝ ↦ 1 / (arcsin y + (k + 1) * (2 * π))) ?_ tendsto_natCast_atTop_atTop
simp only [div_eq_mul_inv, show 𝓝 0 = 𝓝 (1 * (0 : ℝ)) by simp]
refine (tendsto_inv_atTop_zero.comp <| tendsto_atTop_add_const_left _ _ ?_).const_mul _
exact (tendsto_atTop_add_const_right _ _ tendsto_id).atTop_mul_const (by positivity)
/-!
## `T` is closed
-/
/-- The closure of the topologist's sine curve `S` is the set `T`. -/
lemma closure_S : closure S = T := by
ext ⟨x, y⟩
-- Use sequential characterization of closure.
simp only [mem_closure_iff_seq_limit, Prod.tendsto_iff]
constructor
· -- Show that if a sequence in `S` has a limit in `ℝ ^ 2`, the limit must be in `T`.
rintro ⟨f, hf_mem, hf_lim⟩
have x_nonneg : 0 ≤ x := by
refine isClosed_Ici.mem_of_tendsto hf_lim.1 (.of_forall fun n ↦ ?_)
obtain ⟨y, hy⟩ := hf_mem n
simpa [← hy.2] using le_of_lt hy.1
-- Case split on whether limit point `(x, y)` has `x = 0`.
rcases x_nonneg.eq_or_lt with rfl | h
· -- If the limit has `x = 0`, show `y`-coord must be in `[-1, 1]` using closedness
right
simp only [Z, mem_image, Prod.mk.injEq, true_and, exists_eq_right]
refine isClosed_Icc.mem_of_tendsto hf_lim.2 (.of_forall fun n ↦ ?_)
obtain ⟨y, hy⟩ := hf_mem n
simpa only [Function.comp_apply, ← hy.2] using sin_mem_Icc ..
· -- If the limit has `0 < x`, show `y`-coord must be `sin x⁻¹` using continuity
refine .inl ⟨x, h, ?_⟩
simp only [Prod.mk.injEq, true_and]
have : ContinuousAt (fun x ↦ sin x⁻¹) x :=
continuous_sin.continuousAt.comp <| continuousAt_inv₀ h.ne'
refine tendsto_nhds_unique ?_ hf_lim.2
convert this.tendsto.comp hf_lim.1 with n
obtain ⟨y, hy⟩ := hf_mem n
simp [← hy.2]
· -- Show that every `p ∈ T` is the limit of a sequence in `S`.
rintro (hz | ⟨z, hz⟩)
· -- Point is in `S`: use constant sequence
exact ⟨_, fun _ ↦ hz, tendsto_const_nhds, tendsto_const_nhds⟩
· -- Point is in `Z`: use sequence from `xSeq`
simp only [Prod.mk.injEq] at hz
rcases hz with ⟨hz, ⟨rfl, rfl⟩⟩
refine ⟨fun n ↦ (xSeq z n, z), fun n ↦ ⟨_, xSeq_pos z n, ?_⟩, xSeq_tendsto z,
tendsto_const_nhds⟩
simpa using sin_inv_xSeq hz n
lemma isClosed_T : IsClosed T := by simpa only [← closure_S] using isClosed_closure
/-!
## `T` is connected
-/
/-- `T` is connected, being the closure of the set `S` (which is obviously connected since it
is a continuous image of the positive real line). -/
theorem isConnected_T : IsConnected T := by
rw [← closure_S]
refine (isConnected_Ioi.image _ <| continuousOn_id.prodMk ?_).closure
exact continuous_sin.comp_continuousOn <| continuousOn_inv₀.mono fun _ hx ↦ hx.ne'
/-!
## `T` is not path-connected
-/
lemma zero_mem_T : (0, 0) ∈ T := by
refine .inr ⟨0, ⟨?_, ?_⟩, rfl⟩ <;>
linarith
/-- A point in the `body` of the topologist's sine curve. -/
noncomputable def w : ℝ × ℝ := (1, sin 1⁻¹)
lemma w_mem_T : w ∈ T := .inl ⟨1, ⟨zero_lt_one' ℝ, rfl⟩⟩
private lemma norm_ge_abs_snd {a b : ℝ} : |b| ≤ ‖(a, b)‖ := by simp
private lemma exists_unitInterval_gt {t₀ : unitInterval} (ht₀ : t₀ < 1) {δ : ℝ} (hδ : 0 < δ) :
∃ t₁, t₀ < t₁ ∧ dist t₀ t₁ < δ := by
let s₀ := (t₀ : ℝ) -- t₀ is in unitInterval
let s₁ := min (s₀ + δ / 2) 1
have h_s₀_delta_pos : 0 ≤ s₀ + δ / 2 := add_nonneg t₀.2.1 (by positivity)
have hs₁ : 0 ≤ s₁ := le_min h_s₀_delta_pos zero_le_one
have hs₁': s₁ ≤ 1 := min_le_right ..
refine ⟨⟨s₁, hs₁, hs₁'⟩, lt_min ((lt_add_iff_pos_right _).mpr (half_pos hδ)) ht₀, ?_⟩
have h_le : s₁ ≤ s₀ + δ / 2 := min_le_left _ _
have h_ge : s₀ ≤ s₁ := le_min (by linarith) t₀.2.2
rw [Subtype.dist_eq, dist_comm, dist_eq, abs_of_nonneg (by linarith)]
linarith
private lemma mem_S_of_x_pos {p : ℝ × ℝ} (hx : 0 < p.1) (hT : p ∈ T) : p.2 = sin (p.1)⁻¹ := by
obtain ⟨x, -, hx⟩ : p ∈ S := by
cases hT with
| inl hT => trivial
| inr hZ => obtain ⟨y, ⟨-, rfl⟩⟩ := hZ; exact (lt_irrefl _ hx).elim
simp [← hx]
/-- For any `0 < a` and any `y ∈ Icc (-1) 1`, we can find `x ∈ Ioc a 0` with `sin x⁻¹ = y`. -/
lemma exists_mem_Ioc_of_y {y : ℝ} (hy : y ∈ Icc (-1) 1) {a : ℝ} (ha : 0 < a) :
∃ x ∈ Ioc 0 a, sin x⁻¹ = y := by
obtain ⟨N, h_dist⟩ := (Metric.tendsto_nhds.mp (xSeq_tendsto y) (a / 2) (by positivity)).exists
refine ⟨xSeq y N, ⟨xSeq_pos y N, ?_⟩, sin_inv_xSeq hy _⟩
rw [dist_eq, sub_zero, abs_of_pos (xSeq_pos _ N)] at h_dist
linarith
/-- The set `T` is not path-connected. -/
theorem not_isPathConnected_T : ¬ IsPathConnected T := by
-- **Step 1**:
-- Assume for contradiction we have a path from `z = (0, 0)` to `w = (1, sin 1)`.
-- Let t₀ be the last time the path is on the y-axis. By continuity of the path, we
-- can find a `δ > 0` such that for all `t ∈ [t₀, t₀ + δ]`, we have `‖p(t) - p(t₀)‖ < 1`.
intro h_pathConn
replace h_pathConn := h_pathConn.joinedIn (0, 0) zero_mem_T w w_mem_T
let p := h_pathConn.somePath
have xcoord_pathContinuous : Continuous fun t ↦ (p t).1 := continuous_fst.comp p.continuous
let t₀ : unitInterval := sSup {t | (p t).1 = 0}
have h_pt₀_x : (p t₀).1 = 0 :=
(isClosed_singleton.preimage xcoord_pathContinuous).sSup_mem ⟨0, by aesop⟩
obtain ⟨δ , hδ, ht⟩ : ∃ δ, 0 < δ ∧ ∀ t, dist t t₀ < δ → dist (p t) (p t₀) < 1 :=
Metric.eventually_nhds_iff.mp <| Metric.tendsto_nhds.mp (p.continuousAt t₀) _ one_pos
-- **Step 2**:
-- Choose a time t₁ in (t₀, t₀ + δ) and let `a = x(p(t₁))`. Using the fact that every
-- connected subset of `ℝ` is an interval, we have `[0, a] ⊂ x(p([t0, t1]))`.
obtain ⟨t₁, ht₁⟩ : ∃ t₁, t₀ < t₁ ∧ dist t₀ t₁ < δ := by
refine exists_unitInterval_gt (lt_of_le_of_ne (unitInterval.le_one t₀) fun ht₀' ↦ ?_) hδ
have w_x_path : (p 1).1 = 1 := by simp [w]
have x_eq_zero : (p 1).1 = 0 := by rwa [ht₀'] at h_pt₀_x
linarith
let a := (p t₁).1
have ha : 0 < a := by
obtain ⟨x, hxI, hx_eq⟩ : p t₁ ∈ S := by
refine (h_pathConn.somePath_mem t₁).elim id fun ⟨y, hy⟩ ↦ ?_
have : (p t₁).1 = 0 := by simp only [p, ← hy.2]
exact ((show t₁ ≤ t₀ from le_sSup this).not_gt ht₁.1).elim
simpa only [a, ← hx_eq] using hxI
have intervalAZeroSubOfT₀T₁Xcoord : Icc 0 a ⊆ (fun t ↦ (p t).1) '' Icc t₀ t₁ :=
(isPreconnected_Icc.image _ <| xcoord_pathContinuous.continuousOn).Icc_subset
(show 0 ∈ (fun t ↦ (p t).1) '' Icc t₀ t₁ from ⟨t₀, ⟨le_rfl, ht₁.1.le⟩, ‹_›⟩)
(show a ∈ (fun t ↦ (p t).1) '' Icc t₀ t₁ from ⟨t₁, ⟨ht₁.1.le, le_rfl⟩, rfl⟩)
-- **Step 3**: For every `y ∈ [-1, 1]`, there exists a `t` with `p t = y` and `dist t₀ t < δ`.
have exists_close {y : ℝ} (hy : y ∈ Icc (-1) 1) : ∃ t, dist t t₀ < δ ∧ (p t).2 = y := by
-- first find a `t ∈ [t₀, t₁]` with this property
obtain ⟨x, hx, hx'⟩ := exists_mem_Ioc_of_y hy ha
obtain ⟨t, ht⟩ : ∃ t ∈ Icc t₀ t₁, (p t).1 = x := intervalAZeroSubOfT₀T₁Xcoord ⟨hx.1.le, hx.2⟩
have hp : (p t).2 = sin (p t).1⁻¹ := mem_S_of_x_pos (ht.2 ▸ hx.1) (h_pathConn.somePath_mem t)
refine ⟨t, ?_, by rw [← hx', hp, ht.2]⟩
calc -- now show `t ∈ Icc t₀ t₁` implies `dist t t₀ < δ`
dist t t₀ ≤ dist t₁ t₀ := dist_right_le_of_mem_uIcc (Icc_subset_uIcc' ht.1)
_ = dist t₀ t₁ := by rw [dist_comm]
_ < δ := ht₁.2
-- **Step 4**:
-- Now the final contradiction: there are times within `δ` of `t₀` with `p t = 1`, and with
-- `p t = -1`; but both must have distance `< 1` from `p t₀`, contradicting the triangle
-- inequality.
obtain ⟨x₁, hx₁, h_pathx₁⟩ : ∃ x₁, dist x₁ t₀ < δ ∧ (p x₁).2 = 1 := exists_close (by simp)
obtain ⟨x₂, hx₂, h_pathx₂⟩ : ∃ x₂, dist x₂ t₀ < δ ∧ (p x₂).2 = -1 := exists_close (by simp)
have : dist (p x₁) (p x₂) < 2 := by
refine (dist_triangle_right _ _ (p t₀)).trans_lt ?_
exact (add_lt_add (ht _ hx₁) (ht _ hx₂)).trans_eq (by norm_num)
have := norm_ge_abs_snd.trans_lt this
rw [h_pathx₁, h_pathx₂, abs_of_nonneg (by norm_num)] at this
linarith
end TopologistsSineCurve |
.lake/packages/mathlib/Counterexamples/LinearOrderWithPosMulPosEqZero.lean | import Mathlib.Algebra.Order.Monoid.Defs
import Mathlib.Algebra.Order.GroupWithZero.Canonical
/-!
An example of a `LinearOrderedCommMonoidWithZero` in which the product of two positive
elements vanishes.
This is the monoid with 3 elements `0, ε, 1` where `ε ^ 2 = 0` and everything else is forced.
The order is `0 < ε < 1`. Since `ε ^ 2 = 0`, the product of strictly positive elements can vanish.
Relevant Zulip chat:
https://leanprover.zulipchat.com/#narrow/stream/116395-maths/topic/mul_pos
-/
namespace Counterexample
/-- The three element monoid. -/
inductive Foo
| zero
| eps
| one
deriving DecidableEq
namespace Foo
instance inhabited : Inhabited Foo :=
⟨zero⟩
instance : Zero Foo :=
⟨zero⟩
instance : One Foo :=
⟨one⟩
local notation "ε" => eps
/-- The order on `Foo` is the one induced by the natural order on the image of `aux1`. -/
def aux1 : Foo → ℕ
| 0 => 0
| ε => 1
| 1 => 2
/-- A tactic to prove facts by cases. -/
macro (name := boom) "boom" : tactic => `(tactic| (repeat' rintro ⟨⟩) <;> decide)
theorem aux1_inj : Function.Injective aux1 := by boom
instance linearOrder : LinearOrder Foo :=
LinearOrder.lift' aux1 aux1_inj
/-- Multiplication on `Foo`: the only external input is that `ε ^ 2 = 0`. -/
def mul : Foo → Foo → Foo
| 1, x => x
| x, 1 => x
| _, _ => 0
instance commMonoid : CommMonoid Foo where
mul := mul
one_mul := by boom
mul_one := by boom
mul_comm := by boom
mul_assoc := by boom
instance : LinearOrderedCommMonoidWithZero Foo where
__ := linearOrder
__ := commMonoid
zero_mul := by boom
mul_zero := by boom
mul_le_mul_left := by rintro ⟨⟩ ⟨⟩ h ⟨⟩ <;> revert h <;> decide
zero_le_one := by decide
bot := 0
bot_le := by boom
theorem not_mul_pos : ¬∀ {M : Type} [LinearOrderedCommMonoidWithZero M],
∀ a b : M, 0 < a → 0 < b → 0 < a * b := by
intro h
specialize h ε ε (by boom) (by boom)
exact (lt_irrefl 0 (h.trans_le (by boom))).elim
example : 0 < ε ∧ ε * ε = 0 := by boom
end Foo
end Counterexample |
.lake/packages/mathlib/Counterexamples/DimensionPolynomial.lean | import Mathlib.RingTheory.KrullDimension.Polynomial
import Mathlib.RingTheory.KrullDimension.LocalRing
import Mathlib.FieldTheory.RatFunc.AsPolynomial
import Mathlib.RingTheory.PowerSeries.Inverse
/-!
# Krull dimension of polynomial ring
We show that not all commutative rings `R` satisfy `ringKrullDim R[X] = ringKrullDim R + 1`,
following the construction in the reference link.
We define the commutative ring `A` as `{f ∈ k(t)⟦Y⟧ | f(0) ∈ k}` for a field $k$, and show that
`ringKrullDim A = 1` but `ringKrullDim A[X] = 3`.
## References
<https://math.stackexchange.com/questions/1267419/examples-of-rings-whose-polynomial-rings-have-large-dimension>
-/
namespace Counterexample
namespace DimensionPolynomial
open PowerSeries Polynomial
variable (k : Type*) [Field k]
/-- We define the commutative ring `A` as `{f ∈ k(t)⟦Y⟧ | f(0) ∈ k}` for a field `k`. -/
abbrev A : Subring (RatFunc k)⟦X⟧ := (RatFunc.C (K := k)).range.comap PowerSeries.constantCoeff
theorem ringKrullDim_A_eq_one : ringKrullDim (A k) = 1 := by
have h_unit : ∀ (x : (RatFunc k)⟦X⟧) (hx : x ∈ A k), IsUnit x → IsUnit (⟨x, hx⟩ : A k) := by
intro x ⟨z, hz⟩ ⟨y, hxy⟩
refine ⟨⟨⟨y.val, hxy ▸ ⟨z, hz⟩⟩, ⟨y.inv, ⟨z⁻¹, ?_⟩⟩, Subtype.ext y.3, Subtype.ext y.4⟩,
Subtype.ext hxy⟩
have := hxy ▸ congr(PowerSeries.constantCoeff $(y.3))
simp only [map_mul, ← hz, constantCoeff_one] at this
have hz : z ≠ 0 := by
intro rfl
simp at this
simpa only [← mul_assoc, ← RatFunc.C.map_mul, inv_mul_cancel₀ hz, RatFunc.C.map_one,
one_mul, mul_one] using congr(RatFunc.C z⁻¹ * $this.symm)
have : IsLocalRing (A k) := Subring.isLocalRing_of_unit (A k) h_unit
have : ¬ IsField (A k) := fun h ↦ by
let Y : A k := ⟨PowerSeries.X, by simp [A]⟩
have : Y ≠ 0 := fun h ↦ PowerSeries.X_ne_zero congr(Subtype.val $h)
obtain ⟨Y_inv, h'⟩ := h.mul_inv_cancel this
have := congr(PowerSeries.constantCoeff (Subtype.val $(h')))
simp [Y] at this
refine ringKrullDim_eq_one_iff_of_isLocalRing_isDomain.mpr ⟨this, fun x hx y hy ↦ ?_⟩
have : ringKrullDim (RatFunc k)⟦X⟧ = 1 := IsPrincipalIdealRing.ringKrullDim_eq_one _
PowerSeries.not_isField
have hy_mem : y.val ∈ IsLocalRing.maximalIdeal (RatFunc k)⟦X⟧ :=
fun h ↦ hy (h_unit y.val y.prop h)
have hy_const : PowerSeries.constantCoeff y.val = 0 := by
simpa [← PowerSeries.ker_coeff_eq_max_ideal] using hy_mem
obtain ⟨n, hn⟩ := (ringKrullDim_eq_one_iff_of_isLocalRing_isDomain.mp this).2 x
(fun h ↦ hx (Subtype.ext h)) hy_mem
rw [Ideal.mem_span_singleton'] at hn
obtain ⟨a, ha⟩ := hn
refine ⟨n + 1, Ideal.mem_span_singleton'.mpr ⟨⟨a * y.val, ?_⟩, Subtype.ext ?_⟩⟩
· exact ⟨0, by simp [hy_const]⟩
· simp only [Subring.coe_mul, SubmonoidClass.coe_pow, pow_succ, ← ha, mul_assoc, mul_comm x.val _]
theorem ringKrullDim_polynomial_A_eq_three : ringKrullDim (A k)[X] = 3 := by
apply le_antisymm (by simpa [ringKrullDim_A_eq_one k] using Polynomial.ringKrullDim_le (R := A k))
let φ : (A k) →+* k := by
refine ((((⊤ : Subring k).equivMapOfInjective _ RatFunc.C_injective).symm.trans
Subring.topEquiv).toRingHom.comp (Subring.inclusion ?_)).comp
(PowerSeries.constantCoeff.comp (A k).subtype).rangeRestrict
exact fun _ ⟨⟨_, ⟨u, _⟩⟩, _⟩ ↦ ⟨u, ⟨by simp, by simp_all⟩⟩
have h_phi : RatFunc.C.comp φ = PowerSeries.constantCoeff.comp (A k).subtype := RingHom.ext
fun x ↦ by simp [φ, ← Subring.coe_equivMapOfInjective_apply (hf := RatFunc.C_injective)]
let f : (A k)[X] →+* (RatFunc k)⟦X⟧ := eval₂RingHom (A k).subtype (PowerSeries.C RatFunc.X)
let Q : PrimeSpectrum (A k)[X] := ⟨RingHom.ker f, RingHom.ker_isPrime f⟩
let g : (A k)[X] →+* k[X] := mapRingHom φ
let P1 : PrimeSpectrum (A k)[X] := ⟨RingHom.ker g, RingHom.ker_isPrime g⟩
let P2 : PrimeSpectrum (A k)[X] := ⟨RingHom.ker (Polynomial.constantCoeff.comp g),
RingHom.ker_isPrime _⟩
let Y : A k := ⟨PowerSeries.X, by simp⟩
let tY : A k := ⟨PowerSeries.X * (PowerSeries.C RatFunc.X), by simp⟩
have Y_ne_zero : Y ≠ 0 := fun h ↦ by simpa [Y] using congr(Subtype.val $h)
have phi_Y_eq_zero : φ Y = 0 := RatFunc.C_injective (congr($h_phi Y).trans (by simp [Y]))
have comp_eq : (algebraMap k[X] (RatFunc k)).comp g = PowerSeries.constantCoeff.comp f :=
Polynomial.ringHom_ext (fun z ↦ by simpa [f, g] using congr($h_phi z)) (by simp [f, g])
refine Order.le_krullDim_iff.mpr ⟨⟨3, fun | 0 => ⊥ | 1 => Q | 2 => P1 | 3 => P2, fun i ↦ ?_⟩, rfl⟩
fin_cases i
· let val0 : (A k)[X] := Polynomial.C Y * Polynomial.X - Polynomial.C tY
have h1_val0 : val0 ∈ Q.asIdeal := by simp [val0, Q, f, Y, tY]
have h2_val0 : val0 ≠ 0 := support_nonempty.mp ⟨1, by simpa [val0, Y]⟩
exact ⟨OrderBot.bot_le Q, fun h ↦ h2_val0 (by simpa using h h1_val0)⟩
· let val1 : (A k)[X] := Polynomial.C Y
have h1_val1 : val1 ∈ P1.asIdeal := by simpa [P1, val1, g]
have h2_val1 : val1 ∉ Q.asIdeal := by simpa [Q, val1, f]
have : RingHom.ker f ≤ RingHom.ker g := by
rw [← RingHom.ker_comp_of_injective g (RatFunc.algebraMap_injective k), comp_eq]
exact fun x ↦ by simp_all
exact ⟨by simpa [P1, Q] using this, fun h ↦ h2_val1 (h h1_val1)⟩
· let val2 : (A k)[X] := Polynomial.X
have h1_val2 : val2 ∈ P2.asIdeal := by simp [P2, val2, g]
have h2_val2 : val2 ∉ P1.asIdeal := by simp [P1, val2, g]
exact ⟨fun x ↦ by simp_all [P1, P2], fun h ↦ h2_val2 (h h1_val2)⟩
end DimensionPolynomial
end Counterexample |
.lake/packages/mathlib/Counterexamples/Pseudoelement.lean | import Mathlib.CategoryTheory.Abelian.Pseudoelements
import Mathlib.Algebra.Category.ModuleCat.Biproducts
/-!
# Pseudoelements and pullbacks
Borceux claims in Proposition 1.9.5 that the pseudoelement constructed in
`CategoryTheory.Abelian.Pseudoelement.pseudo_pullback` is unique. We show here that this claim is
false. This means in particular that we cannot have an extensionality principle for pullbacks in
terms of pseudoelements.
## Implementation details
The construction, suggested in https://mathoverflow.net/a/419951/7845, is the following.
We work in the category of `ModuleCat ℤ` and we consider the special case of `ℚ ⊞ ℚ` (that is the
pullback over the terminal object). We consider the pseudoelements associated to `x : ℚ ⟶ ℚ ⊞ ℚ`
given by `t ↦ (t, 2 * t)` and `y : ℚ ⟶ ℚ ⊞ ℚ` given by `t ↦ (t, t)`.
## Main results
* `Counterexample.exist_ne_and_fst_eq_fst_and_snd_eq_snd` : there are two
pseudoelements `x y : ℚ ⊞ ℚ` such that `x ≠ y`, `biprod.fst x = biprod.fst y` and
`biprod.snd x = biprod.snd y`.
## References
* [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2]
-/
open CategoryTheory.Abelian CategoryTheory CategoryTheory.Limits ModuleCat LinearMap
namespace Counterexample
noncomputable section
open CategoryTheory.Abelian.Pseudoelement
/-- `x` is given by `t ↦ (t, 2 * t)`. -/
def x : Over (of ℤ ℚ ⊞ of ℤ ℚ) :=
Over.mk (biprod.lift (𝟙 _) (2 • 𝟙 _))
/-- `y` is given by `t ↦ (t, t)`. -/
def y : Over (of ℤ ℚ ⊞ of ℤ ℚ) :=
Over.mk (biprod.lift (𝟙 _) (𝟙 _))
/-- `biprod.fst ≫ x` is pseudoequal to `biprod.fst y`. -/
theorem fst_x_pseudo_eq_fst_y : PseudoEqual _ (app biprod.fst x) (app biprod.fst y) := by
refine ⟨of ℤ ℚ, 𝟙 _, 𝟙 _, inferInstance, ?_, ?_⟩
· exact (ModuleCat.epi_iff_surjective _).2 fun a => ⟨(a : ℚ), rfl⟩
· dsimp [x, y]
simp
/-- `biprod.snd ≫ x` is pseudoequal to `biprod.snd y`. -/
theorem snd_x_pseudo_eq_snd_y : PseudoEqual _ (app biprod.snd x) (app biprod.snd y) := by
refine ⟨of ℤ ℚ, 𝟙 _, 2 • 𝟙 _, inferInstance, ?_, ?_⟩
· refine (ModuleCat.epi_iff_surjective _).2 fun a => ⟨(show ℚ from a) / 2, ?_⟩
simpa only [two_smul] using add_halves (show ℚ from a)
· dsimp [x, y]
refine ConcreteCategory.hom_ext _ _ fun a => ?_
simp_rw [biprod.lift_snd]; rfl
-- Porting note: locally disable instance to avoid inferred/synthesized clash
attribute [-instance] AddCommGroup.toIntModule in
/-- `x` is not pseudoequal to `y`. -/
theorem x_not_pseudo_eq : ¬PseudoEqual _ x y := by
intro h
replace h := ModuleCat.eq_range_of_pseudoequal h
dsimp [x, y] at h
let φ := biprod.lift (𝟙 (of ℤ ℚ)) (2 • 𝟙 (of ℤ ℚ))
have mem_range := mem_range_self φ.hom (1 : ℚ)
rw [h] at mem_range
obtain ⟨a, ha⟩ := mem_range
rw [← ModuleCat.id_apply _ (φ (1 : ℚ)), ← biprod.total, ← LinearMap.comp_apply,
← ModuleCat.hom_comp, Preadditive.comp_add] at ha
let π₁ := (biprod.fst : of ℤ ℚ ⊞ of ℤ ℚ ⟶ _)
have ha₁ := congr_arg π₁ ha
rw [← ModuleCat.comp_apply, ← ModuleCat.comp_apply] at ha₁
simp only [π₁, φ, biprod.lift_fst, biprod.lift_fst_assoc, Category.id_comp,
biprod.lift_snd_assoc, Linear.smul_comp, Preadditive.add_comp, BinaryBicone.inl_fst,
BinaryBicone.inr_fst, smul_zero, add_zero] at ha₁
let π₂ := (biprod.snd : of ℤ ℚ ⊞ of ℤ ℚ ⟶ _)
have ha₂ := congr_arg π₂ ha
rw [← ModuleCat.comp_apply, ← ModuleCat.comp_apply] at ha₂
simp_all [π₂, φ]
attribute [local instance] Pseudoelement.setoid
open scoped Pseudoelement
/-- `biprod.fst ⟦x⟧ = biprod.fst ⟦y⟧`. -/
theorem fst_mk'_x_eq_fst_mk'_y :
pseudoApply biprod.fst ⟦x⟧ = pseudoApply biprod.fst ⟦y⟧ :=
Quotient.eq.2 fst_x_pseudo_eq_fst_y
/-- `biprod.snd ⟦x⟧ = biprod.snd ⟦y⟧`. -/
theorem snd_mk'_x_eq_snd_mk'_y :
pseudoApply biprod.snd ⟦x⟧ = pseudoApply biprod.snd ⟦y⟧ :=
Quotient.eq.2 snd_x_pseudo_eq_snd_y
-- Porting note: needs explicit type ascription `: Quotient <| Pseudoelement.setoid _`
-- for some reason the setoid instance isn't picked up automatically,
-- despite the local instance ~20 lines up
/-- `⟦x⟧ ≠ ⟦y⟧`. -/
theorem mk'_x_ne_mk'_y : (⟦x⟧ : Quotient <| Pseudoelement.setoid _) ≠ ⟦y⟧ :=
fun h => x_not_pseudo_eq <| Quotient.eq'.1 h
/-- There are two pseudoelements `x y : ℚ ⊞ ℚ` such that `x ≠ y`, `biprod.fst x = biprod.fst y` and
`biprod.snd x = biprod.snd y`. -/
theorem exist_ne_and_fst_eq_fst_and_snd_eq_snd :
∃ x y, -- Porting note: removed type ascription `: of ℤ ℚ ⊞ of ℤ ℚ`, it gave an error about
-- `Type` not having zero morphisms. jmc: I don't understand where the error came from
x ≠ y ∧
pseudoApply (biprod.fst : of ℤ ℚ ⊞ of ℤ ℚ ⟶ _) x = pseudoApply biprod.fst y ∧
pseudoApply biprod.snd x = pseudoApply biprod.snd y :=
⟨⟦x⟧, ⟦y⟧, mk'_x_ne_mk'_y, fst_mk'_x_eq_fst_mk'_y, snd_mk'_x_eq_snd_mk'_y⟩
end
end Counterexample |
.lake/packages/mathlib/Counterexamples/GameMultiplication.lean | import Mathlib.SetTheory.Game.Basic
import Mathlib.Tactic.FinCases
import Mathlib.Tactic.Linter.DeprecatedModule
deprecated_module
"This module is now at `CombinatorialGames.Counterexamples.Multiplication` in the CGT repo <https://github.com/vihdzp/combinatorial-games>"
(since := "2025-08-06")
/-!
# Multiplication of pre-games can't be lifted to the quotient
We show that there exist equivalent pregames `x₁ ≈ x₂` and `y` such that `x₁ * y ≉ x₂ * y`. In
particular, we cannot define the multiplication of games in general.
The specific counterexample we use is `x₁ = y = {0 | 0}` and `x₂ = {-1, 0 | 0, 1}`. The first game
is colloquially known as `star`, so we use the name `star'` for the second. We prove that
`star ≈ star'` and `star * star ≈ star`, but `star' * star ≉ star`.
-/
namespace Counterexample
namespace PGame
open SetTheory PGame
/-- The game `{-1, 0 | 0, 1}`, which is equivalent but not identical to `*`. -/
def star' : PGame := ofLists [0, -1] [0, 1]
/-- `*'` is its own negative. -/
theorem neg_star' : -star' = star' := by
simp [star']
/-- `*'` is equivalent to `*`. -/
theorem star'_equiv_star : star' ≈ star := by
have le : star' ≤ star := by
apply PGame.le_of_forall_lf
· rintro ⟨i⟩
fin_cases i
· exact zero_lf_star
· exact (neg_lt_zero_iff.2 PGame.zero_lt_one).trans_lf zero_lf_star
· exact fun _ => lf_zero_le.2 ⟨⟨0, Nat.zero_lt_two⟩, le_rfl⟩
constructor
case' right => rw [← neg_le_neg_iff, neg_star, neg_star']
assumption'
/-- The equation `** = *` is an identity, though not a relabelling. -/
theorem star_sq : star * star ≈ star := by
have le : star * star ≤ star := by
rw [le_iff_forall_lf]
constructor <;>
intro i
· apply leftMoves_mul_cases i <;>
intro _ _
case' hl => rw [mul_moveLeft_inl]
case' hr => rw [mul_moveLeft_inr]
all_goals rw [lf_iff_game_lf]; simpa using zero_lf_star
· refine lf_zero.2 ⟨toRightMovesMul (Sum.inl default), ?_⟩
rintro (j | j) <;> -- Instance can't be inferred otherwise.
exact isEmptyElim j
constructor
case' right =>
rw [← neg_le_neg_iff];
apply (neg_mul _ _).symm.equiv.1.trans;
rw [neg_star]
assumption'
/-- `*'* ⧏ *` implies `*'* ≉ *`. -/
theorem star'_mul_star_lf : star' * star ⧏ star := by
rw [lf_iff_exists_le]
refine Or.inr ⟨toRightMovesMul (Sum.inr ⟨⟨1, Nat.one_lt_two⟩, default⟩), ?_⟩
rw [mul_moveRight_inr, le_iff_game_le]
simp [star']
/-- Pre-game multiplication cannot be lifted to games. -/
theorem mul_not_lift : ∃ x₁ x₂ y : PGame, x₁ ≈ x₂ ∧ ¬ x₁ * y ≈ x₂ * y :=
⟨_, _, _, ⟨star'_equiv_star, fun h ↦ (PGame.Equiv.trans h star_sq).ge.not_gf star'_mul_star_lf⟩⟩
end PGame
end Counterexample |
.lake/packages/mathlib/Counterexamples/AharoniKorman.lean | import Mathlib.Algebra.Order.Field.Basic
import Mathlib.Algebra.Order.Field.Rat
import Mathlib.Data.Setoid.Partition
import Mathlib.Order.Filter.AtTopBot.Basic
import Mathlib.Order.Interval.Set.Infinite
import Mathlib.Order.WellFoundedSet
/-!
# Disproof of the Aharoni–Korman conjecture
The Aharoni–Korman conjecture (sometimes called the fishbone conjecture) says that every partial
order satisfies at least one of the following:
- It contains an infinite antichain
- It contains a chain C, together with a partition into antichains such that every part meets C.
In November 2024, Hollom disproved this conjecture. In this file, we construct Hollom's
counterexample P_5 and show it satisfies neither of the above, and thus disprove the conjecture.
See [hollom2025] for further details.
We show a number of key properties of P_5:
1. It is a partial order
2. It is countable
3. It has no infinite antichains
4. It is scattered (it does not contain a suborder which is order-isomorphic to ℚ)
5. It does not contain a chain C and a partition into antichains such that every part meets C
Points 1, 3, 5 are sufficient to disprove the conjecture, but we include points 2 and 4 nonetheless
as they represent other important properties of the partial order.
The final point is the most involved, so we sketch its proof here.
The proof structure is as follows:
* Begin by defining the type `Hollom` as a synonym for `ℕ³` and giving it the partial order
structure as required.
* Define the levels `level` of the partial order, corresponding to `L` in the informal proof.
* Show that this partial order has no infinite antichains (`Hollom.no_infinite_antichain`).
* Given a chain `C`, show that for infinitely many `n`, `C ∩ level n` must be finite
(`exists_finite_intersection`).
* Given a chain `C`, the existence of a partition with the desired properties is equivalent to the
existence of a "spinal map" (`exists_partition_iff_nonempty_spinalMap`). A spinal map is a
function from the partial order to `C`, which is identity on `C` and for which each fiber is an
antichain.
From this point forward, we assume `C` is a chain and that we have a spinal map to `C`, with the
aim of reaching a contradiction (as then, no such partition can exist). We may further assume that
`n ≠ 0` and `C ∩ level n` is finite.
* Define a subset `S` of `level n`, and we will aim to show a contradiction by considering
the image of `S` under the spinal map. By construction, no element of `S` can be mapped into
`level n`.
* The subset `S \ (C ∩ level n)` contains some "infinite square", i.e. a set of the form
`{(x, y, n) | a ≤ x ∧ a ≤ y}` for some `a` (`square_subset_S`).
* For two points of `C` in the same level, the intersection of `C` with the interval between
them is exactly the length of a maximal chain between them (`card_C_inter_Icc_eq`).
* For two points of `C` in the same level, and two points `(a, b, n)` and `(c, d, n)` between them,
if `a + b = c + d` then `f (a, b, n) = f (c, d, n)` (`apply_eq_of_line_eq`).
* No element of `S \ (C ∩ level n)` can be mapped into `level (n + 1)` (`not_S_hits_next`). This
step vitally uses the previous two facts.
* If all of `S \ (C ∩ level n)` is mapped into `level (n - 1)`, then we have a contradiction
(`not_S_mapsTo_previous`).
* But as `f` maps each element of `S \ (C ∩ level n)` to `level (n - 1) ∪ level n ∪ level (n + 1)`,
we have a contradiction (`no_spinalMap`), and therefore show that no spinal map exists.
-/
attribute [aesop norm 10 tactic] Lean.Elab.Tactic.Omega.omegaDefault
attribute [aesop 2 simp] Set.subset_def Finset.subset_iff
/-- A type synonym on ℕ³ on which we will construct Hollom's partial order P_5. -/
@[ext]
structure Hollom where
/--
The forward equivalence between ℕ³ and the underlying set in Hollom's partial order.
Note that this equivalence does not respect the partial order relation.
-/
toHollom ::
/--
The backward equivalence between ℕ³ and the underlying set in Hollom's partial order.
Note that this equivalence does not respect the partial order relation.
-/
ofHollom : ℕ × ℕ × ℕ
deriving DecidableEq
open Hollom
@[simp] lemma ofHollom_toHollom (x) : ofHollom (toHollom x) = x := rfl
@[simp] lemma toHollom_ofHollom (x) : toHollom (ofHollom x) = x := rfl
/-- `toHollom` and `ofHollom` as an equivalence. -/
@[simps]
def equivHollom : ℕ × ℕ × ℕ ≃ Hollom where
toFun := toHollom; invFun := ofHollom
namespace Hollom
@[simp] lemma «forall» {p : Hollom → Prop} : (∀ x, p x) ↔ ∀ x, p (toHollom x) := by aesop
@[simp] lemma «forall₂» {p : Hollom → Hollom → Prop} :
(∀ x y, p x y) ↔ ∀ x y, p (toHollom x) (toHollom y) := by aesop
@[simp] lemma «forall₃» {p : Hollom → Hollom → Hollom → Prop} :
(∀ x y z, p x y z) ↔ ∀ x y z, p (toHollom x) (toHollom y) (toHollom z) := by aesop
@[simp] lemma «exists» {p : Hollom → Prop} : (∃ x, p x) ↔ ∃ x, p (toHollom x) := by aesop
local notation3 "h(" x ", " y ", " z ")" => toHollom (x, y, z)
@[elab_as_elim, induction_eliminator, cases_eliminator]
lemma induction {p : Hollom → Prop} (h : ∀ x y z, p (h(x, y, z))) : ∀ x, p x := by simpa
/-- The Hollom partial order is countable. This is very easy to see, since it is just `ℕ³` with a
different order. -/
instance : Countable Hollom :=
.of_equiv (ℕ × ℕ × ℕ) equivHollom
/--
The ordering on ℕ³ which is used to define Hollom's example P₅
-/
@[mk_iff]
inductive HollomOrder : ℕ × ℕ × ℕ → ℕ × ℕ × ℕ → Prop
| twice {x y n u v m : ℕ} : m + 2 ≤ n → HollomOrder (x, y, n) (u, v, m)
| within {x y u v m : ℕ} : x ≤ u → y ≤ v → HollomOrder (x, y, m) (u, v, m)
| next_min {x y u v m : ℕ} : min x y + 1 ≤ min u v → HollomOrder (x, y, m + 1) (u, v, m)
| next_add {x y u v m : ℕ} : x + y ≤ 2 * (u + v) → HollomOrder (x, y, m + 1) (u, v, m)
/--
Transitivity of the hollom order. This needs to be split out from the instance otherwise it's
painfully slow to compile.
-/
lemma HollomOrder.trans :
(x y z : ℕ × ℕ × ℕ) → (h₁ : HollomOrder x y) → (h₂ : HollomOrder y z) → HollomOrder x z
| _, _, _, .twice _, .twice _ => .twice (by omega)
| _, _, _, .twice _, .within _ _ => .twice (by omega)
| _, _, _, .twice _, .next_min _ => .twice (by omega)
| _, _, _, .twice _, .next_add _ => .twice (by omega)
| _, _, _, .within _ _, .twice _ => .twice (by omega)
| _, _, _, .within _ _, .within _ _ => .within (by omega) (by omega)
| _, _, _, .within _ _, .next_min _ => .next_min (by omega)
| _, _, _, .within _ _, .next_add _ => .next_add (by omega)
| _, _, _, .next_min _, .twice _ => .twice (by omega)
| _, _, _, .next_min _, .within _ _ => .next_min (by omega)
| _, _, _, .next_min _, .next_min _ => .twice (by omega)
| _, _, _, .next_min _, .next_add _ => .twice (by omega)
| _, _, _, .next_add _, .twice _ => .twice (by omega)
| _, _, _, .next_add _, .within _ _ => .next_add (by omega)
| _, _, _, .next_add _, .next_min _ => .twice (by omega)
| _, _, _, .next_add _, .next_add _ => .twice (by omega)
instance : PartialOrder Hollom where
le x y := HollomOrder (ofHollom x) (ofHollom y)
le_refl _ := .within le_rfl le_rfl
le_trans := «forall₃».2 HollomOrder.trans
le_antisymm := «forall₂».2 fun
| _, _, .twice _, .twice _ => by omega
| _, (_, _, _), .twice _, .within _ _ => by omega -- see https://github.com/leanprover/lean4/issues/6416 about the `(_, _, _)`
| _, _, .twice _, .next_min _ => by omega
| _, _, .twice _, .next_add _ => by omega
| _, _, .within _ _, .twice _ => by omega
| _, _, .within _ _, .within _ _ => by congr 3 <;> omega
| _, _, .next_min _, .twice _ => by omega
| _, _, .next_add _, .twice _ => by omega
@[simp] lemma toHollom_le_toHollom_iff_fixed_right {a b c d n : ℕ} :
h(a, b, n) ≤ h(c, d, n) ↔ a ≤ c ∧ b ≤ d := by
refine ⟨?_, ?_⟩
· rintro (_ | _)
· omega
· omega
· rintro ⟨h₁, h₂⟩
exact .within h₁ h₂
lemma le_of_toHollom_le_toHollom {a b c d e f : ℕ} :
h(a, b, c) ≤ h(d, e, f) → f ≤ c
| .twice _ => by omega
| .within _ _ => by omega
| .next_add _ => by omega
| .next_min _ => by omega
lemma toHollom_le_toHollom {a b c d e f : ℕ} (h : (a, b) ≤ (d, e)) (hcf : f ≤ c) :
h(a, b, c) ≤ h(d, e, f) := by
simp only [Prod.mk_le_mk] at h
obtain rfl | rfl | hc : f = c ∨ f + 1 = c ∨ f + 2 ≤ c := by omega
· simpa using h
· exact .next_add (by omega)
· exact .twice hc
/--
The Hollom partial order is divided into "levels", indexed by the natural numbers. These correspond
to the third coordinate of the tuple.
This is written $L_n$ in the [hollom2025].
-/
def level (n : ℕ) : Set Hollom := {h(x, y, n) | (x : ℕ) (y : ℕ)}
lemma level_eq (n : ℕ) : level n = {x | (ofHollom x).2.2 = n} := by
simp [Set.ext_iff, level, eq_comm]
@[simp] lemma toHollom_mem_level_iff {n : ℕ} {x} : toHollom x ∈ level n ↔ x.2.2 = n := by
simp [level_eq]
@[elab_as_elim, induction_eliminator, cases_eliminator]
lemma induction_on_level {n : ℕ} {p : (x : Hollom) → x ∈ level n → Prop}
(h : ∀ x y, p h(x, y, n) (by simp)) :
∀ {x : Hollom}, (h : x ∈ level n) → p x h := by
simp +contextual only [«forall», toHollom_mem_level_iff, Prod.forall]
rintro x y _ rfl
exact h _ _
/--
For each `n`, there is an order embedding from ℕ × ℕ (which has the product order) to the Hollom
partial order.
-/
def embed (n : ℕ) : ℕ × ℕ ↪o Hollom where
toFun x := h(x.1, x.2, n)
inj' x := by aesop
map_rel_iff' := by simp
lemma embed_apply (n : ℕ) (x y : ℕ) : embed n (x, y) = h(x, y, n) := rfl
lemma embed_strictMono {n : ℕ} : StrictMono (embed n) := (embed n).strictMono
lemma level_eq_range (n : ℕ) : level n = Set.range (embed n) := by
simp [level, Set.range, embed]
lemma level_isPWO {n : ℕ} : (level n).IsPWO := by
rw [level_eq_range, ← Set.image_univ]
refine Set.IsPWO.image_of_monotone ?_ (embed n).monotone
rw [← Set.univ_prod_univ]
exact .prod (.of_linearOrder _) (.of_linearOrder _)
/--
If `A` is a subset of `level n` and is an antichain, then `A` is finite.
This is a special case of the fact that any antichain in the Hollom order is finite, but is a useful
lemma to prove that fact later: `no_infinite_antichain`.
-/
lemma no_infinite_antichain_level {n : ℕ} {A : Set Hollom} (hA : A ⊆ level n)
(hA' : IsAntichain (· ≤ ·) A) : A.Finite :=
hA'.finite_of_partiallyWellOrderedOn ((level_isPWO).mono hA)
/--
Each level is order-connected, i.e. for any `x ∈ level n` and `y ∈ level n` we have
`[x, y] ⊆ level n`.
This corresponds to 5.8 (i) in the [hollom2025].
-/
lemma ordConnected_level {n : ℕ} : (level n).OrdConnected := by
rw [Set.ordConnected_iff]
simp only [level_eq, Set.mem_setOf_eq, Set.subset_def, Set.mem_Icc, and_imp, Hollom.forall,
Prod.forall, forall_eq, toHollom_le_toHollom_iff_fixed_right]
intro a b c d ac bd e f g h1 h2
exact le_antisymm (le_of_toHollom_le_toHollom h1) (le_of_toHollom_le_toHollom h2)
/-- The map from `(x, y, n)` to `x + y`. -/
@[pp_nodot] def line (x : Hollom) : ℕ := (ofHollom x).1 + (ofHollom x).2.1
@[simp] lemma line_toHollom (x : ℕ × ℕ × ℕ) : line (toHollom x) = x.1 + x.2.1 := rfl
lemma line_injOn {C : Set Hollom} (n : ℕ) (hC : IsChain (· ≤ ·) C) (hCn : C ⊆ level n) :
C.InjOn line := by
rw [Set.InjOn]
intro x hx y hy h
induction hCn hx using induction_on_level with | h a b =>
induction hCn hy using induction_on_level with | h c d =>
have := hC.total hx hy
aesop
lemma add_lt_add_of_lt {a b c d n : ℕ} (h : h(a, b, n) < h(c, d, n)) : a + b < c + d := by
change embed n (a, b) < embed n (c, d) at h
aesop
lemma line_mapsTo {x y : Hollom} (hxy : (ofHollom x).2.2 = (ofHollom y).2.2) :
Set.MapsTo line (Set.Icc x y) (Set.Icc (line x) (line y)) := by
induction x with | h a b c =>
induction y with | h d e f =>
obtain rfl : c = f := by simpa using hxy
rw [Set.mapsTo_iff_image_subset]
intro n
simp only [Set.mem_image, Set.mem_Icc, «exists», line_toHollom, Prod.exists, exists_and_right,
forall_exists_index, and_imp]
rintro p q r h₁ h₂ rfl
obtain rfl := (le_of_toHollom_le_toHollom h₁).antisymm (le_of_toHollom_le_toHollom h₂)
simp only [toHollom_le_toHollom_iff_fixed_right] at h₁ h₂
omega
lemma embed_image_Icc {a b c d n : ℕ} :
embed n '' Set.Icc (a, b) (c, d) = Set.Icc h(a, b, n) h(c, d, n) := by
rw [OrderEmbedding.image_Icc, embed_apply, embed_apply]
rw [← level_eq_range]
exact ordConnected_level
private lemma no_strictly_decreasing {α : Type*} [Preorder α] [WellFoundedLT α] (f : ℕ → α) {n₀ : ℕ}
(hf : ∀ n ≥ n₀, f (n + 1) < f n) : False := by
let g (n : ℕ) : α := f (n₀ + n)
have : (· > ·) ↪r (· < ·) := RelEmbedding.natGT g (fun n ↦ hf _ (by simp))
exact this.not_wellFounded wellFounded_lt
private lemma no_strictAnti {α : Type*} [Preorder α] [WellFoundedLT α] (f : ℕ → α)
(hf : StrictAnti f) : False :=
no_strictly_decreasing f (n₀ := 0) fun n _ => hf (by simp)
/--
The Hollom partial order is scattered: it does not contain a suborder which is order-isomorphic
to `ℚ`. We state this as saying there is no strictly monotone function from `ℚ` to `Hollom`.
-/
theorem scattered {f : ℚ → Hollom} (hf : StrictMono f) : False := by
-- Let `g` be the function from `ℚ` to `ℕ` which is the third coordinate of `f`.
let g (q : ℚ) : ℕ := (ofHollom (f q)).2.2
have hg (q : ℚ) : f q ∈ level (g q) := by simp [g, level_eq]
-- We have that `g` is antitone, since `f` is strictly monotone.
have hg' : Antitone g := by
rw [antitone_iff_forall_lt]
intro x y hxy
have : f x < f y := hf hxy
simp only [ge_iff_le, g]
cases hx : f x with | h x₁ x₂ x₃ =>
cases hy : f y with | h y₁ y₂ y₃ =>
rw [hx, hy] at this
exact le_of_toHollom_le_toHollom this.le
-- But it cannot be injective: otherwise it is strictly antitone, and thus precomposing with
-- the obvious map `ℕ → ℚ` would give a strictly decreasing sequence in `ℕ`.
have hg'' : ¬ g.Injective := fun hg'' ↦
no_strictAnti _ ((hg'.strictAnti_of_injective hg'').comp_strictMono Nat.strictMono_cast)
-- Take `x ≠ y` with `g x = g y`
obtain ⟨x, y, hgxy, hxy'⟩ : ∃ x y, g x = g y ∧ x ≠ y := by simpa [Function.Injective] using hg''
-- and wlog `x < y`
wlog hxy : x < y generalizing x y
· simp only [not_lt] at hxy
exact this y x hgxy.symm hxy'.symm (lt_of_le_of_ne' hxy hxy')
-- Now `f '' [x, y]` is infinite, as it is the image of an infinite set of rationals,
have h₁ : (f '' Set.Icc x y).Infinite := (Set.Icc_infinite hxy).image hf.injective.injOn
-- but it is contained in `[f x, f y]` by monotonicity
have h₂ : f '' Set.Icc x y ⊆ Set.Icc (f x) (f y) := Monotone.image_Icc_subset hf.monotone
-- and this is finite, as it is a closed interval in `level (g x)`
have h₃ : (Set.Icc (f x) (f y)).Finite := by
set n := g y
obtain ⟨a, ha⟩ : f x ∈ Set.range (embed n) := by rw [← level_eq_range, ← hgxy]; exact hg _
obtain ⟨b, hb⟩ : f y ∈ Set.range (embed n) := by rw [← level_eq_range]; exact hg _
rw [← ha, ← hb, ← OrderEmbedding.image_Icc]
· exact (Set.finite_Icc a b).image (embed n)
· rw [← level_eq_range]
exact ordConnected_level
-- giving a contradiction.
exact h₁ (h₃.subset h₂)
/--
Any antichain in the Hollom partial order is finite. This corresponds to Lemma 5.9 in [hollom2025].
-/
theorem no_infinite_antichain {A : Set Hollom} (hC : IsAntichain (· ≤ ·) A) : A.Finite := by
let f (x : Hollom) : ℕ := (ofHollom x).2.2
have (n : ℕ) : A ∩ f ⁻¹' {n} ⊆ level n := fun x ↦ by induction x with | h x => simp [f]
-- We show that the antichain can only occupy finitely much of each level
-- and it can only exist in finitely many levels.
apply Set.Finite.of_finite_fibers f
case hfibers =>
intro x hx
exact no_infinite_antichain_level (this _) (hC.subset Set.inter_subset_left)
case himage =>
rw [← Set.not_infinite]
intro h
obtain ⟨n, hn⟩ := h.nonempty
suffices f '' A ⊆ Set.Iio (n + 2) from h ((Set.finite_Iio _).subset this)
intro m
simp only [Set.mem_image, «exists», Prod.exists, exists_eq_right,
Set.mem_Iio, forall_exists_index, f]
simp only [Set.mem_image, «exists», Prod.exists, exists_eq_right, f] at hn
obtain ⟨a, b, hab⟩ := hn
intro c d hcd
by_contra!
exact hC hcd hab (by simp; omega) (HollomOrder.twice this)
private lemma triangle_finite (n : ℕ) : {x : ℕ × ℕ | x.1 + x.2 ≤ n}.Finite :=
(Set.finite_Iic (n, n)).subset <| by aesop
variable {C : Set Hollom}
open Filter
/--
Show that every chain in the Hollom partial order has a finite intersection with infinitely many
levels.
This corresponds to Lemma 5.10 from [hollom2025].
-/
theorem exists_finite_intersection (hC : IsChain (· ≤ ·) C) :
∃ᶠ n in atTop, (C ∩ level n).Finite := by
-- Begin by assuming `C ∩ level n` is infinite for all `n ≥ n₀`
rw [frequently_atTop]
intro n₀
by_contra! hC'
simp only [← Set.not_infinite, not_not] at hC'
-- Define `m n` to be the smallest value of `min x y` as `(x, y, n)` ranges over `C`.
let m (n : ℕ) : ℕ := sInf {min (ofHollom x).1 (ofHollom x).2.1 | x ∈ C ∩ level n}
-- `m n` is well-defined above `n₀`, since the set in question is nonempty (it's infinite).
have nonempty_mins (n : ℕ) (hn : n₀ ≤ n) :
{min (ofHollom x).1 (ofHollom x).2.1 | x ∈ C ∩ level n}.Nonempty :=
(hC' n hn).nonempty.image _
-- We aim to show that `m n` is strictly decreasing above `n₀`, which is clearly a contradiction.
suffices ∀ n ≥ n₀, m (n + 1) < m n from no_strictly_decreasing _ this
intro n hn
-- Take `n ≥ n₀`, and take `u, v` such that `min u v = m n` (which exists by definition).
-- We aim to show `m (n + 1) < min u v`
obtain ⟨u, v, huv, hmn⟩ : ∃ u v : ℕ, h(u, v, n) ∈ C ∧ min u v = m n := by
simpa [m] using Nat.sInf_mem (nonempty_mins n hn)
rw [← hmn]
-- Consider the set of points `{(x, y, z) | x + y ≤ 2 * (u + v)}`.
let D : Set Hollom := {x | (ofHollom x).1 + (ofHollom x).2.1 ≤ 2 * (u + v)}
-- There are infinitely many points in `C ∩ level (n + 1)` that are not in `D`...
have : ((C ∩ level (n + 1)) \ D).Infinite := by
-- ...because there are finitely many points in `C ∩ level (n + 1) ∩ D`...
have : (C ∩ level (n + 1) ∩ D).Finite := by
-- (indeed, `level (n + 1) ∩ D` is finite)
refine .subset (.image (embed (n + 1)) (triangle_finite (2 * (u + v)))) ?_
simp +contextual [Set.subset_def, D, embed_apply]
-- ...and `C ∩ level (n + 1)` is infinite (by assumption).
specialize hC' (n + 1) (by omega)
rw [← (C ∩ level (n + 1)).inter_union_diff D, Set.infinite_union] at hC'
refine hC'.resolve_left ?_
simpa using this
-- In fact, we only need it to be nonempty, and find a point.
obtain ⟨x, hxy⟩ := this.nonempty
induction hxy.1.2 using induction_on_level with | h x y =>
simp only [Set.mem_diff, Set.mem_inter_iff, toHollom_mem_level_iff, and_true, Set.mem_setOf_eq,
not_le, D] at hxy
-- Take the point `(x, y, n + 1)` in `C` that avoids `D`. As `(u, v, n)` is also in the chain `C`,
-- they must be comparable.
obtain h3 | h3 := hC.total huv hxy.1
-- We cannot have `(u, v, n) ≤ (x, y, n + 1)` by definition of the order.
· simpa using le_of_toHollom_le_toHollom h3
-- Whereas if `(x, y, n + 1) ≤ (u, v, n)`, as `2 * (u + v) < x + y`, we must have
-- `min x y + 1 ≤ min u v`, which finishes the proof.
· cases h3
case twice => omega
case next_add => omega
case next_min h3 =>
rw [← Nat.add_one_le_iff]
refine h3.trans' ?_
simp only [add_le_add_iff_right]
exact Nat.sInf_le ⟨_, ⟨hxy.1, by simp⟩, by simp⟩
/-! In this section we define spinal maps, and prove important properties about them. -/
section SpinalMap
variable {α : Type*} [PartialOrder α] {C : Set α}
/--
A spinal map is a function `f : α → C` which is the identity on `C`, and for which each fiber is an
antichain.
Provided `C` is a chain, the existence of a spinal map is equivalent to the fact that `C` is a
spine.
-/
structure SpinalMap (C : Set α) where
/-- The underlying function of a spinal map. -/
toFun : α → α
mem' : ∀ x, toFun x ∈ C
eq_self_of_mem' : ∀ x ∈ C, toFun x = x
fibre_antichain' : ∀ x, IsAntichain (· ≤ ·) (toFun ⁻¹' {x})
instance : FunLike (SpinalMap C) α α where
coe := SpinalMap.toFun
coe_injective' | ⟨f, _, _, _⟩, ⟨g, _, _, _⟩, h => by simp_all only
/-! ### Basic lemmas for spinal maps -/
namespace SpinalMap
variable (f : SpinalMap C)
@[ext] lemma ext {f g : SpinalMap C} (h : ∀ x, f x = g x) : f = g := DFunLike.ext f g h
@[simp] lemma toFun_eq_coe : f.toFun = f := rfl
@[simp] lemma mem (x : α) : f x ∈ C := f.mem' x
lemma eq_self_of_mem {x : α} (hx : x ∈ C) : f x = x := f.eq_self_of_mem' x hx
lemma fibre_antichain (x : α) : IsAntichain (· ≤ ·) (f ⁻¹' {x}) := f.fibre_antichain' x
lemma range_subset : Set.range f ⊆ C := by simp [Set.subset_def]
variable {x y z : α}
@[simp] lemma idempotent (x : α) : f (f x) = f x := f.eq_self_of_mem (f.mem x)
lemma not_le_of_eq (hfxy : f x = f y) (hxy : x ≠ y) : ¬ x ≤ y :=
f.fibre_antichain (f y) hfxy rfl hxy
lemma eq_of_le (hfxy : f x = f y) (hxy : x ≤ y) : x = y := by_contra (f.not_le_of_eq hfxy · hxy)
lemma not_lt_of_eq (hfxy : f x = f y) : ¬ x < y := fun h ↦ h.ne (f.eq_of_le hfxy h.le)
lemma incomp_of_eq (hfxy : f x = f y) (hxy : x ≠ y) : ¬ (x ≤ y ∨ y ≤ x) :=
not_or.2 ⟨f.not_le_of_eq hfxy hxy, f.not_le_of_eq hfxy.symm hxy.symm⟩
lemma incomp_apply (hx : f x ≠ x) : ¬ (f x ≤ x ∨ x ≤ f x) :=
f.incomp_of_eq (f.idempotent x) hx
lemma not_apply_lt : ¬ f x < x := f.not_lt_of_eq (by simp)
lemma not_lt_apply : ¬ x < f x := f.not_lt_of_eq (by simp)
lemma le_apply_of_le (hC : IsChain (· ≤ ·) C) (hy : y ∈ C) (hx : y ≤ x) : y ≤ f x :=
hC.le_of_not_gt (f.mem x) hy fun hxy ↦ f.not_apply_lt (hxy.trans_le hx)
lemma apply_le_of_le (hC : IsChain (· ≤ ·) C) (hy : y ∈ C) (hx : x ≤ y) : f x ≤ y :=
hC.le_of_not_gt hy (f.mem x) fun hxy ↦ f.not_lt_apply (hx.trans_lt hxy)
lemma lt_apply_of_lt (hC : IsChain (· ≤ ·) C) (hy : y ∈ C) (hx : y < x) : y < f x :=
hC.lt_of_not_ge (f.mem x) hy fun hxy ↦ f.not_apply_lt (hxy.trans_lt hx)
lemma apply_lt_of_lt (hC : IsChain (· ≤ ·) C) (hy : y ∈ C) (hx : x < y) : f x < y :=
hC.lt_of_not_ge hy (f.mem x) fun hxy ↦ f.not_lt_apply (hx.trans_le hxy)
lemma apply_mem_Icc_of_mem_Icc (hC : IsChain (· ≤ ·) C) (hy : y ∈ C) (hz : z ∈ C)
(hx : x ∈ Set.Icc y z) : f x ∈ Set.Icc y z :=
⟨f.le_apply_of_le hC hy hx.1, f.apply_le_of_le hC hz hx.2⟩
lemma mapsTo_Icc_self (hC : IsChain (· ≤ ·) C) (hy : y ∈ C) (hz : z ∈ C) :
Set.MapsTo f (Set.Icc y z) (Set.Icc y z) := fun _ ↦ apply_mem_Icc_of_mem_Icc _ hC hy hz
lemma injOn_of_isChain {D : Set α} (hD : IsChain (· ≤ ·) D) : D.InjOn f := by
intro x hx y hy h
by_contra! h'
exact f.incomp_of_eq h h' (hD.total hx hy)
end SpinalMap
end SpinalMap
/--
Given a chain `C` in a partial order `α`, the existence of the following are equivalent:
* a partition of `α` into antichains, each which meets `C`
* a function `f : α → C` which is the identity on `C` and for which each fiber is an antichain
In fact, these two are in bijection, but we only need the weaker version that their existence
is equivalent.
-/
theorem exists_partition_iff_nonempty_spinalMap
{α : Type*} [PartialOrder α] {C : Set α} (hC : IsChain (· ≤ ·) C) :
(∃ S, Setoid.IsPartition S ∧ ∀ A ∈ S, IsAntichain (· ≤ ·) A ∧ (A ∩ C).Nonempty) ↔
Nonempty (SpinalMap C) := by
constructor
· rintro ⟨S, ⟨hSemp, hS⟩, hSA⟩
simp only [ExistsUnique, and_imp, and_assoc] at hS
simp only [Set.Nonempty, Set.mem_inter_iff] at hSA
choose F hFS hFmem hFuniq using hS
choose hA G hGA hGC using hSA
let f (x : α) : α := G (F x) (hFS x)
have hfCid (x : α) (hx : x ∈ C) : f x = x := inter_subsingleton_of_isChain_of_isAntichain
hC (hA (F x) (hFS _)) ⟨hGC _ _, hGA _ _⟩ ⟨hx, hFmem _⟩
have hf (x : α) : IsAntichain (· ≤ ·) (f ⁻¹' {x}) := (hA (F x) (hFS _)).subset <| by
rintro y rfl
exact hFuniq (f y) (F y) (hFS y) (hGA _ _) ▸ hFmem _
exact ⟨⟨f, fun x ↦ hGC _ _, hfCid, hf⟩⟩
· rintro ⟨f⟩
refine ⟨_, (Setoid.ker f).isPartition_classes, ?_⟩
rintro _ ⟨x, rfl⟩
exact ⟨f.fibre_antichain _, f x, by simp⟩
variable {f : SpinalMap C}
/-! ### Explicit chains
In this section we construct an explicit chain in ℕ × ℕ that will be useful later.
These comprise part of 5.8(iv) from [hollom2025]: the full strength of that observation is not
actually needed.
-/
section make_chains
open Finset
/--
An explicit contiguous chain between `(a, b)` and `(c, d)` in `ℕ × ℕ`. We implement this as the
union of two disjoint sets: the first is the chain from `(a, b)` to `(a, d)`, and the second is the
chain from `(a, d)` to `(c, d)`.
-/
def chainBetween (a b c d : ℕ) : Finset (ℕ × ℕ) :=
if a ≤ c ∧ b ≤ d
then Ico (a, b) (a, d) ∪ Icc (a, d) (c, d)
else ∅
lemma chainBetween_isChain {a b c d : ℕ} :
IsChain (· ≤ ·) (chainBetween a b c d : Set (ℕ × ℕ)) := by
rw [chainBetween]
split_ifs
· rintro ⟨v, w⟩ hvw ⟨x, y⟩ hxy
simp_all
omega
· simp
lemma image_chainBetween_isChain {a b c d n : ℕ} :
IsChain (· ≤ ·) ((chainBetween a b c d).image (embed n) : Set Hollom) := by
rw [coe_image]
apply chainBetween_isChain.image
simp
open Finset in
lemma card_chainBetween {a b c d : ℕ} (hac : a ≤ c) (hbd : b ≤ d) :
#(chainBetween a b c d) = c + d + 1 - (a + b) := by
rw [chainBetween, if_pos ⟨hac, hbd⟩, card_union_of_disjoint, Finset.card_Icc_prod]
· simp only [Icc_self, card_singleton, Nat.card_Icc]
rw [← Finset.Ico_map_sectR, card_map, Nat.card_Ico]
omega
· rw [disjoint_left]
simp
omega
lemma chainBetween_subset {a b c d : ℕ} :
chainBetween a b c d ⊆ Finset.Icc (a, b) (c, d) := by
rw [chainBetween]
aesop (add simp Finset.subset_iff)
end make_chains
open Finset in
lemma mapsTo_Icc_image (hC : IsChain (· ≤ ·) C) {a b c d n : ℕ}
(hab : h(a, b, n) ∈ C) (hcd : h(c, d, n) ∈ C) :
Set.MapsTo f
((Icc (a, b) (c, d)).image (embed n))
((Icc (a, b) (c, d)).image (embed n)) := by
simp only [coe_image, coe_Icc, embed_image_Icc]
exact f.mapsTo_Icc_self hC hab hcd
open Classical Finset in
/--
The collection of points between `(xl, yl, n)` and `(xh, yh, n)` that are also in `C` has at least
`xh + yh + 1 - (xl + yl)` elements.
In other words, this collection must be a maximal chain relative to the interval it is contained in.
Note `card_C_inter_Icc_eq` strengthens this to an equality.
-/
lemma C_inter_Icc_large (f : SpinalMap C) {n : ℕ} {xl yl xh yh : ℕ}
(hC : IsChain (· ≤ ·) C)
(hx : xl ≤ xh) (hy : yl ≤ yh)
(hlo : h(xl, yl, n) ∈ C) (hhi : h(xh, yh, n) ∈ C) :
xh + yh + 1 - (xl + yl) ≤ #{x ∈ (Icc (xl, yl) (xh, yh)).image (embed n) | x ∈ C} := by
set int : Finset Hollom := (Icc (xl, yl) (xh, yh)).image (embed n)
set I : Finset Hollom := {x ∈ int | x ∈ C}
let D : Finset Hollom := (chainBetween xl yl xh yh).image (embed n)
have hD : D ⊆ int := Finset.image_subset_image chainBetween_subset
have D_maps : Set.MapsTo f D I := by
simp only [I, Finset.coe_filter]
exact ((mapsTo_Icc_image hC hlo hhi).mono_left hD).inter (by simp [Set.MapsTo])
have f_inj : Set.InjOn f D := f.injOn_of_isChain image_chainBetween_isChain
have : #D = xh + yh + 1 - (xl + yl) := by
simp [D, Finset.card_image_of_injective, (embed n).injective, card_chainBetween hx hy]
rw [← this]
exact Finset.card_le_card_of_injOn f D_maps f_inj
open Classical Finset in
/--
The collection of points between `(xl, yl, n)` and `(xh, yh, n)` that are also in `C` has exactly
`xh + yh + 1 - (xl + yl)` elements.
In other words, this collection must be a maximal chain relative to the interval it is contained in.
Alternatively speaking, it has the same size as any maximal chain in that interval.
-/
theorem card_C_inter_Icc_eq (f : SpinalMap C) {n : ℕ} {xl yl xh yh : ℕ}
(hC : IsChain (· ≤ ·) C)
(hx : xl ≤ xh) (hy : yl ≤ yh)
(hlo : h(xl, yl, n) ∈ C) (hhi : h(xh, yh, n) ∈ C) :
#{x ∈ (Icc (xl, yl) (xh, yh)).image (embed n) | x ∈ C} = xh + yh + 1 - (xl + yl) := by
set int : Finset Hollom := (Icc (xl, yl) (xh, yh)).image (embed n)
set I : Finset Hollom := {x ∈ int | x ∈ C}
have int_eq : int = Set.Icc h(xl, yl, n) h(xh, yh, n) := by
simp only [coe_image, coe_Icc, int, embed_image_Icc]
have hI : IsChain (· ≤ ·) I := hC.mono (by simp [Set.subset_def, I])
have hIn : ↑I ⊆ level n := by simp +contextual [Set.subset_def, I, int, embed_apply]
have : Set.MapsTo line int (Icc (xl + yl) (xh + yh)) := by
rw [int_eq, coe_Icc]
exact line_mapsTo rfl
replace this : Set.MapsTo line I (Icc (xl + yl) (xh + yh)) := this.mono_left (filter_subset _ _)
refine le_antisymm ?_ (C_inter_Icc_large f hC hx hy hlo hhi)
rw [← Nat.card_Icc]
exact card_le_card_of_injOn _ this (line_injOn _ hI hIn)
open Finset in
/--
The important helper lemma to prove `apply_eq_of_line_eq`. That lemma says that given `(xl, yl, n)`
and `(xh, yh, n)` in a chain `C`, and two points `(a, b, n)` and `(c, d, n)` between them, if
`a + b = c + d` then a spinal map `f : SpinalMap C` sends them to the same place.
Here we show the special case where the two points are `(x + 1, y, n)` and `(x, y + 1, n)`, i.e.
they are beside each other.
-/
lemma apply_eq_of_line_eq_step (f : SpinalMap C) {n xl yl xh yh : ℕ}
(hC : IsChain (· ≤ ·) C)
(hlo : h(xl, yl, n) ∈ C) (hhi : h(xh, yh, n) ∈ C) (hx : xl ≤ xh) (hy : yl ≤ yh)
{x y : ℕ}
(h₁l : h(xl, yl, n) ≤ h(x + 1, y, n)) (h₂l : h(xl, yl, n) ≤ h(x, y + 1, n))
(h₁h : h(x + 1, y, n) ≤ h(xh, yh, n)) (h₂h : h(x, y + 1, n) ≤ h(xh, yh, n)) :
f h(x + 1, y, n) = f h(x, y + 1, n) := by
classical
-- Write `int` for the interval `[(xl, yl, n), (xh, yh, n)]`, as a finite set, and `I` for the
-- intersection of `C` with this interval.
set int : Finset Hollom := (Icc (xl, yl) (xh, yh)).image (embed n)
set I : Finset Hollom := {x ∈ int | x ∈ C}
-- Previous results give an exact expression for `#I`.
have cI : #I = xh + yh + 1 - (xl + yl) := card_C_inter_Icc_eq f hC hx hy hlo hhi
have int_eq : int = Set.Icc h(xl, yl, n) h(xh, yh, n) := by
simp only [coe_image, coe_Icc, int, embed_image_Icc]
-- Write `B` for the union of chains `(xl, yl, n)` to `(x, y, n)` and `(x + 1, y + 1, n)`
-- to `(xh, yh, n)`, observing that adding either of `(x + 1, y, n)` or `(x, y + 1, n)` would
-- make `B` into a maximal chain.
let B : Finset Hollom :=
(chainBetween xl yl x y ∪ chainBetween (x + 1) (y + 1) xh yh).image (embed n)
-- The map `f` sends both these points into `int`, by the properties of spinal maps,
have : f h(x + 1, y, n) ∈ int ∧ f h(x, y + 1, n) ∈ int := by
rw [← mem_coe, ← mem_coe, int_eq]
exact ⟨f.mapsTo_Icc_self hC hlo hhi ⟨h₁l, h₁h⟩, f.mapsTo_Icc_self hC hlo hhi ⟨h₂l, h₂h⟩⟩
simp only [toHollom_le_toHollom_iff_fixed_right] at h₁l h₂l h₁h h₂h
-- and we can give an exact expression for `#B`, which is exactly one less than `#I`.
have cB : #B = xh + yh - (xl + yl) := by
rw [card_image_of_injective _ (embed n).injective, card_union_of_disjoint,
card_chainBetween h₂l.1 h₁l.2, card_chainBetween h₁h.1 h₂h.2]
· omega
· simp [disjoint_left, chainBetween, *]
omega
-- It is easy to see that our chain `B` lives entirely within `int`
have hB : B ⊆ int := by
refine Finset.image_subset_image ?_
rw [Finset.union_subset_iff]
refine ⟨chainBetween_subset.trans ?_, chainBetween_subset.trans ?_⟩
· exact Finset.Icc_subset_Icc_right (by simp [*])
· exact Finset.Icc_subset_Icc_left (by simp [*])
-- and thus `f` must map it to `I`
have f_maps : Set.MapsTo f B I := by
simp only [I, Finset.coe_filter]
exact ((mapsTo_Icc_image hC hlo hhi).mono_left hB).inter (by simp [Set.MapsTo])
-- and as `B` is a chain, `f` acts injectively on it.
have f_inj : Set.InjOn f B := by
refine f.injOn_of_isChain ?_
simp only [B]
rw [coe_image]
refine IsChain.image (· ≤ ·) _ (embed n) (by simp) ?_
rw [coe_union, isChain_union]
refine ⟨chainBetween_isChain, chainBetween_isChain, ?_⟩
simp [chainBetween, *]
omega
-- Thus the image of `B` under `f` is all of `I`, except for exactly one element.
have card_eq : (I \ B.image f).card = 1 := by
rw [card_sdiff_of_subset, cI, card_image_of_injOn f_inj, cB]
· omega
· rw [← coe_subset, coe_image]
exact f_maps.image_subset
-- After applying `f`, both `(x + 1, y, n)` and `(x, y + 1, n)` are omitted from the image of `B`
-- under `f`: this follows from the fact that adding either to `B` would make it still a chain,
-- and `f` acts injectively on chains.
obtain ⟨hleft, hright⟩ : f h(x + 1, y, n) ∉ B.image f ∧ f h(x, y + 1, n) ∉ B.image f := by
constructor
all_goals
simp +contextual only [mem_image, mem_union, embed_apply, Prod.exists, «exists»,
Prod.mk.injEq, not_exists, not_and, forall_exists_index,
and_imp, or_imp, B, forall_and, Hollom.ext_iff]
constructor
· rintro _ _ c a b hab rfl rfl rfl h
have : (a, b) ≤ (x, y) := (Finset.mem_Icc.1 (chainBetween_subset hab)).2
rw [← embed_apply, ← embed_apply] at h
exact f.not_lt_of_eq congr(toHollom $h) (embed_strictMono (this.trans_lt (by simp)))
· rintro _ _ c a b hab rfl rfl rfl h
have : (x + 1, y + 1) ≤ (a, b) := (Finset.mem_Icc.1 (chainBetween_subset hab)).1
rw [← embed_apply, ← embed_apply] at h
exact f.not_lt_of_eq congr(toHollom $(h.symm)) (embed_strictMono (this.trans_lt' (by simp)))
-- Therefore the image of both points is in `I \ B.image f`,
replace hleft : f h(x + 1, y, n) ∈ I \ B.image f := by simpa [mem_sdiff, hleft, I] using this.1
replace hright : f h(x, y + 1, n) ∈ I \ B.image f := by simpa [mem_sdiff, hright, I] using this.2
-- but this set has exactly one element, so our two elements must be equal.
exact Finset.card_le_one.1 card_eq.le _ hleft _ hright
/--
A simple helper lemma to prove `apply_eq_of_line_eq`.
Here we show the special case where the two points are `(x + k, y, n)` and `(x, y + k, n)` by
induction on `k` with `apply_eq_of_line_eq_step`.
-/
lemma apply_eq_of_line_eq_aux (f : SpinalMap C) {n xl yl xh yh : ℕ}
(hC : IsChain (· ≤ ·) C)
(hlo : h(xl, yl, n) ∈ C) (hhi : h(xh, yh, n) ∈ C) (hx : xl ≤ xh) (hy : yl ≤ yh)
{x y k : ℕ}
(h₁l : h(xl, yl, n) ≤ h(x + k, y, n)) (h₂l : h(xl, yl, n) ≤ h(x, y + k, n))
(h₁h : h(x + k, y, n) ≤ h(xh, yh, n)) (h₂h : h(x, y + k, n) ≤ h(xh, yh, n)) :
f h(x + k, y, n) = f h(x, y + k, n) := by
induction k generalizing x y with
| zero => simp
| succ k ih =>
have : f h(x + (k + 1), y, n) = f h(x + k, y + 1, n) := by
simp only [← add_assoc] at h₁l h₁h ⊢
refine apply_eq_of_line_eq_step f hC hlo hhi hx hy h₁l ?_ h₁h ?_
all_goals
simp only [toHollom_le_toHollom_iff_fixed_right] at h₁l h₁h h₂l h₂h ⊢
omega
rw [this, ih, add_right_comm, add_assoc]
all_goals
simp only [toHollom_le_toHollom_iff_fixed_right] at h₁l h₁h h₂l h₂h ⊢
omega
/--
For two points of `C` in the same level, and two points `(a, b, n)` and `(c, d, n)` between them,
if `a + b = c + d` then `f (a, b, n) = f (c, d, n)`.
-/
theorem apply_eq_of_line_eq (f : SpinalMap C) {n : ℕ} (hC : IsChain (· ≤ ·) C)
{lo hi : Hollom} (hlo : lo ∈ C ∩ level n) (hhi : hi ∈ C ∩ level n) (hlohi : lo ≤ hi)
{x y : Hollom} (h : line x = line y)
(h₁l : lo ≤ x) (h₂l : lo ≤ y) (h₁h : x ≤ hi) (h₂h : y ≤ hi) :
f x = f y := by
wlog hxy : (ofHollom y).1 ≤ (ofHollom x).1 generalizing x y
· exact (this h.symm h₂l h₁l h₂h h₁h (le_of_not_ge hxy)).symm
have hx : x ∈ level n := ordConnected_level.out hlo.2 hhi.2 ⟨h₁l, h₁h⟩
have hy : y ∈ level n := ordConnected_level.out hlo.2 hhi.2 ⟨h₂l, h₂h⟩
induction hx using induction_on_level with | h x₁ y₁ =>
induction hy using induction_on_level with | h x₂ y₂ =>
simp only [] at hxy
simp only [line_toHollom] at h
obtain ⟨k, rfl⟩ := exists_add_of_le hxy
obtain rfl : y₂ = y₁ + k := by omega
induction hlo.2 using induction_on_level with | h xlo ylo =>
induction hhi.2 using induction_on_level with | h xhi yhi =>
exact apply_eq_of_line_eq_aux f hC hlo.1 hhi.1 (by simp_all) (by simp_all) h₁l h₂l h₁h h₂h
/--
Construction of the set `R`, which has the following key properties:
* It is a subset of `level n`.
* Each of its elements is comparable to all of `C ∩ level n`.
* There exists an `a` such that `{(x, y, n) | x ≥ a ∧ y ≥ a} ⊆ R`.
-/
def R (n : ℕ) (C : Set Hollom) : Set Hollom := {x ∈ level n | ∀ y ∈ C ∩ level n, x ≤ y ∨ y ≤ x}
variable {n : ℕ}
lemma R_subset_level : R n C ⊆ level n := Set.sep_subset (level n) _
/--
A helper lemma to show `square_subset_R`. In particular shows that if `C ∩ level n` is finite, the
set of points `x` such that `x` is at least as large as every element of `C ∩ level n` contains an
"infinite square", i.e. a set of the form `{(x, y, n) | x ≥ a ∧ y ≥ a}`.
The precise statement here is stronger in two ways:
* Instead of showing that some `a` works, we instead show that any sufficiently large `a` work.
This is not much of a strengthening, but is convenient to have for chaining "sufficiently large"
choices later.
* We also exclude `C ∩ level n` itself on the right.
-/
lemma square_subset_above (h : (C ∩ level n).Finite) :
∀ᶠ a in atTop, embed n '' Set.Ici (a, a) ⊆ {x | ∀ y ∈ C ∩ level n, y ≤ x} \ (C ∩ level n) := by
-- If `(C ∩ level n)` is empty, trivially we are done.
obtain h | hne := (C ∩ level n).eq_empty_or_nonempty
· simp [h]
-- Otherwise take a maximal pair `(a, b)` so that any `(c, d, n)` in `C` satisfies
-- `(c, d, n) ≤ (a, b, n)`.
obtain ⟨a, b, hab⟩ : ∃ a b, ∀ c d, h(c, d, n) ∈ C → c ≤ a ∧ d ≤ b := by
obtain ⟨⟨a, b⟩, hab⟩ := (h.image (fun t ↦ ((ofHollom t).1, (ofHollom t).2.1))).bddAbove
use a, b
intro c d hcd
simpa using hab ⟨h(_, _, _), ⟨hcd, by simp⟩, rfl⟩
-- With this pair, we can use the "base" of the square as `max a b + 1`.
rw [eventually_atTop]
refine ⟨max a b + 1, ?_⟩
simp +contextual only [ge_iff_le, sup_le_iff, embed, RelEmbedding.coe_mk,
Function.Embedding.coeFn_mk, Set.mem_inter_iff, and_imp, «forall», toHollom_mem_level_iff,
Prod.forall, Set.subset_def, Set.mem_image, Set.mem_Ici, Prod.exists, Prod.mk_le_mk,
Set.mem_setOf_eq, forall_exists_index, Prod.mk.injEq,
toHollom_le_toHollom_iff_fixed_right, Set.mem_diff, and_true, ← max_add_add_right,
Hollom.ext_iff]
-- After simplifying, direct calculations show the subset relation as required.
rintro k hak hbk _ _ _ f g hkf hkg rfl rfl rfl
constructor
· rintro c d n hcd rfl
specialize hab c d hcd
omega
· intro hfg
specialize hab _ _ hfg
omega
lemma square_subset_R (h : (C ∩ level n).Finite) :
∀ᶠ a in atTop, embed n '' Set.Ici (a, a) ⊆ R n C \ (C ∩ level n) := by
filter_upwards [square_subset_above h] with a ha
rintro _ ⟨⟨x, y⟩, hxy, rfl⟩
exact ⟨⟨by simp [embed], fun b hb ↦ .inr ((ha ⟨_, hxy, rfl⟩).1 _ hb)⟩, (ha ⟨_, hxy, rfl⟩).2⟩
lemma R_diff_infinite (h : (C ∩ level n).Finite) : (R n C \ (C ∩ level n)).Infinite := by
obtain ⟨a, ha⟩ := (square_subset_R h).exists
refine ((Set.Ici_infinite _).image ?_).mono ha
aesop (add safe unfold [Set.InjOn])
lemma not_R_hits_same {x : Hollom} (hx : x ∈ R n C) (hx' : x ∉ C ∩ level n) :
f x ∉ C ∩ level n := by
intro hfx
apply f.incomp_apply _ (hx.2 _ hfx).symm
exact ne_of_mem_of_not_mem hfx hx'
open Classical in
/--
Given a subset `C` of the Hollom partial order, and an index `n`, find the smallest element of
`C ∩ level (n + 1)`, expressed as `(x₀, y₀, n + 1)`.
This is only the global minimum provided `C` is a chain, which it is in context.
-/
noncomputable def x0y0 (n : ℕ) (C : Set Hollom) : ℕ × ℕ :=
if h : (C ∩ level (n + 1)).Nonempty
then wellFounded_lt.min {x | embed (n + 1) x ∈ C} <| by
rw [level_eq_range] at h
obtain ⟨_, h, y, rfl⟩ := h
exact ⟨y, h⟩
else 0
lemma x0y0_mem (h : (C ∩ level (n + 1)).Nonempty) :
embed (n + 1) (x0y0 n C) ∈ C := by
rw [x0y0, dif_pos h]
exact WellFounded.min_mem _ {x | embed (n + 1) x ∈ C} _
lemma x0y0_min (z : ℕ × ℕ) (hC : IsChain (· ≤ ·) C) (h : embed (n + 1) z ∈ C) :
embed (n + 1) (x0y0 n C) ≤ embed (n + 1) z := by
have : (C ∩ level (n + 1)).Nonempty := ⟨_, h, by simp [level_eq_range]⟩
refine hC.le_of_not_gt h (x0y0_mem this) ?_
rw [x0y0, dif_pos this, OrderEmbedding.lt_iff_lt]
exact wellFounded_lt.not_lt_min {x | embed (n + 1) x ∈ C} ?_ h
/--
Given a subset `C` of the Hollom partial order, and an index `n`, find the smallest element of
`C ∩ level (n + 1)`, and `x0 n C` will be the x-coordinate thereof.
-/
noncomputable def x0 (n : ℕ) (C : Set Hollom) : ℕ := (x0y0 n C).1
/--
Given a subset `C` of the Hollom partial order, and an index `n`, find the smallest element of
`C ∩ level (n + 1)`, and `y0 n C` will be the y-coordinate thereof.
-/
noncomputable def y0 (n : ℕ) (C : Set Hollom) : ℕ := (x0y0 n C).2
lemma x0_y0_mem (h : (C ∩ level (n + 1)).Nonempty) : h(x0 n C, y0 n C, n + 1) ∈ C := x0y0_mem h
lemma x0_y0_min (hC : IsChain (· ≤ ·) C) {a b : ℕ} (h : h(a, b, n + 1) ∈ C) :
h(x0 n C, y0 n C, n + 1) ≤ h(a, b, n + 1) := x0y0_min (a, b) hC h
open Classical in
/--
Construction of the set `S`, which has the following key properties:
* It is a subset of `R`.
* No element of it can be mapped to an element of `C ∩ level (n + 1)` by `f`.
* There exists an `a` such that `{(x, y, n) | x ≥ a ∧ y ≥ a} ⊆ S`.
If `C ∩ level (n + 1)` is finite, it is all elements of `R` which are comparable to
`C ∩ level (n + 1)`.
Otherwise, say `(x0, y0, n + 1)` is the smallest element of `C ∩ level (n + 1)`, and take all
elements of `R` of the form `(a, b, n)` with `max x0 y0 + 1 ≤ min a b`.
-/
noncomputable def S (n : ℕ) (C : Set Hollom) : Set Hollom :=
if (C ∩ level (n + 1)).Finite
then {x ∈ R n C | ∀ y ∈ C ∩ level (n + 1), x ≤ y ∨ y ≤ x}
else {x ∈ R n C | max (x0 n C) (y0 n C) + 1 ≤ min (ofHollom x).1 (ofHollom x).2.1}
lemma S_subset_R : S n C ⊆ R n C := by
rw [S]
split <;> exact Set.sep_subset _ _
lemma S_subset_level : S n C ⊆ level n := S_subset_R.trans R_subset_level
/--
Assuming `C ∩ level n` is finite, and `C ∩ level (n + 1)` is finite, that there exists cofinitely
many `a` such that `{(x, y, n) | x ≥ a ∧ y ≥ a} ⊆ S \ (C ∩ level n)`.
We will later show the same assuming `C ∩ level (n + 1)` is infinite.
-/
lemma square_subset_S_case_1 (h : (C ∩ level n).Finite) (h' : (C ∩ level (n + 1)).Finite) :
∀ᶠ a in atTop, embed n '' Set.Ici (a, a) ⊆ S n C \ (C ∩ level n) := by
rw [S, if_pos h']
-- Take a maximal pair `(b, c)` so that any `(d, e, n)` in `C` satisfies
-- `(d, e, n) ≤ (b, c, n)`.
obtain ⟨b, c, hab⟩ : ∃ b c, ∀ d e, h(d, e, n + 1) ∈ C → (d, e) ≤ (b, c) := by
obtain ⟨⟨b, c⟩, hbc⟩ := (h'.image (fun t ↦ ((ofHollom t).1, (ofHollom t).2.1))).bddAbove
use b, c
intro d e hde
simpa using hbc ⟨h(_, _, _), ⟨hde, by simp⟩, rfl⟩
-- Using `a ≥ max b c`, we have that all elements of `{(x, y, n) | x ≥ a ∧ y ≥ a}` are comparable
-- to all elements of `C ∩ level (n + 1)`.
have : ∀ᶠ a in atTop, embed n '' .Ici (a, a) ⊆ {x | ∀ y ∈ C ∩ level (n + 1), x ≤ y ∨ y ≤ x} := by
rw [eventually_atTop, level_eq]
refine ⟨max b c, ?_⟩
simp only [ge_iff_le, sup_le_iff, embed, RelEmbedding.coe_mk, Function.Embedding.coeFn_mk,
Set.mem_inter_iff, Set.mem_setOf_eq, and_imp, «forall», Prod.forall,
Set.subset_def, Set.mem_image, Set.mem_Ici, Prod.exists, Prod.mk_le_mk, forall_exists_index,
Prod.mk.injEq, Hollom.ext_iff]
rintro d hbd hcd _ _ _ e f hde hdf rfl rfl rfl g h _ hgh rfl
right
apply toHollom_le_toHollom _ (by simp)
have := hab _ _ hgh
simp only [Prod.mk_le_mk] at this ⊢
omega
-- Combined with the fact that sufficiently large `a` have
-- `{(x, y, n) | x ≥ a ∧ y ≥ a} ⊆ R \ (C ∩ level n)`, we can easily finish.
filter_upwards [square_subset_R h, this] with a h₁ h₂
exact fun x hx ↦ ⟨⟨(h₁ hx).1, h₂ hx⟩, (h₁ hx).2⟩
/--
Assuming `C ∩ level n` is finite, and `C ∩ level (n + 1)` is infinite, that there exists cofinitely
many `a` such that `{(x, y, n) | x ≥ a ∧ y ≥ a} ⊆ S \ (C ∩ level n)`.
We earlier showed the same assuming `C ∩ level (n + 1)` is finite.
-/
lemma square_subset_S_case_2 (h : (C ∩ level n).Finite) (h' : (C ∩ level (n + 1)).Infinite) :
∀ᶠ a in atTop, embed n '' Set.Ici (a, a) ⊆ S n C \ (C ∩ level n) := by
rw [S, if_neg h']
filter_upwards [eventually_ge_atTop (x0 n C + 1), eventually_ge_atTop (y0 n C + 1),
square_subset_R h] with a hax hay haR
aesop (add simp embed_apply)
theorem square_subset_S (h : (C ∩ level n).Finite) :
∀ᶠ a in atTop, embed n '' Set.Ici (a, a) ⊆ S n C \ (C ∩ level n) :=
(C ∩ level (n + 1)).finite_or_infinite.elim (square_subset_S_case_1 h) (square_subset_S_case_2 h)
lemma S_infinite (h : (C ∩ level n).Finite) : (S n C \ (C ∩ level n)).Infinite := by
obtain ⟨a, ha⟩ := (square_subset_S h).exists
refine ((Set.Ici_infinite _).image ?_).mono ha
aesop (add safe unfold Set.InjOn)
/--
Given `(a, b, n)` which is a lower bound on `C ∩ level n`, and assuming `C ∩ level n` is infinite,
we either have:
* for any `i`, there is an element of `C ∩ level n` greater than `(a, i, n)`
* for any `i`, there is an element of `C ∩ level n` greater than `(i, b, n)`
-/
lemma left_or_right_bias {n : ℕ} (a b : ℕ)
(hab : ∀ x y, h(x, y, n) ∈ C → h(a, b, n) ≤ h(x, y, n))
(hCn : (C ∩ level n).Infinite) :
(∀ i : ℕ, ∃ j ∈ C ∩ level n, h(a, i, n) ≤ j) ∨
(∀ i : ℕ, ∃ j ∈ C ∩ level n, h(i, b, n) ≤ j) := by
-- Suppose otherwise, and take `c` and `d` counterexamples to both alternatives
by_contra! h
obtain ⟨⟨c, hc⟩, d, hd⟩ := h
-- Observe the set of points in `C ∩ level n` below `(d, c, n)` is finite, and aim to show that
-- `C ∩ level n` is contained in this set, for a contradiction
refine hCn (((Set.finite_Iic (d, c)).image (embed n)).subset ?_)
simp only [Set.subset_def, Set.mem_inter_iff, Set.mem_image, Set.mem_Iic, Prod.exists,
Prod.mk_le_mk, and_imp, «forall», toHollom_mem_level_iff, Prod.forall]
rintro x y n hxy rfl
specialize hab x y (by simp [hxy])
specialize hc h(x, y, n) (by simp [hxy])
specialize hd h(x, y, n) (by simp [hxy])
simp_all only [toHollom_le_toHollom_iff_fixed_right, true_and, not_le, and_true]
exact ⟨_, _, ⟨hd.le, hc.le⟩, rfl⟩
/--
Given a point `x` in `S` which is not in `C ∩ level n`, its image under `f` cannot be in
`C ∩ level (n + 1)`.
-/
theorem not_S_hits_next (f : SpinalMap C) (hC : IsChain (· ≤ ·) C)
{x : Hollom} (hx : x ∈ S n C) (hx' : x ∉ C ∩ level n) :
f x ∉ C ∩ level (n + 1) := by
cases (C ∩ level (n + 1)).finite_or_infinite
-- In the case that `C ∩ level (n + 1)` is finite, this is immediate from the definition of `S`.
case inl h =>
rw [S, if_pos h, Set.mem_setOf_eq] at hx
intro hy
refine f.incomp_apply ?_ (hx.2 _ hy).symm
have := R_subset_level hx.1
simp only [level_eq, Set.mem_setOf_eq] at this
intro h
simp [level_eq, h, this] at hy
-- So suppose it is infinite
case inr h =>
-- Write `(x, y, n)` for our given point, and set `(a, b, n + 1) := f(x, y, n)`
induction S_subset_level hx using induction_on_level with | h x y =>
simp only [S, if_neg h, Set.mem_setOf_eq] at hx
intro hp
set fp := f h(x, y, n) with hfp
clear_value fp
induction hp.2 using induction_on_level with | h a b =>
clear fp
-- Certainly `x0 ≤ a` and `y0 ≤ b`
obtain ⟨ha, hb⟩ : x0 n C ≤ a ∧ y0 n C ≤ b := by simpa using x0_y0_min hC hp.1
-- Either `C ∩ level (n + 1)` stretches far left or far right: both cases are symmetric
obtain (rbias | lbias) := left_or_right_bias (x0 n C) (y0 n C) (fun x y ↦ x0_y0_min hC) h
· obtain ⟨j, hjCn, hj⟩ := rbias (a + b - x0 n C)
-- If it goes to the right, take `j ∈ C` such that `(x0, a + b - x0, n + 1) ≤ j`
-- Then we have `(a, b, n + 1) ≤ j`...
have hj' : h(a, b, n + 1) ≤ j := by
induction hjCn.2 using induction_on_level with | h c d =>
apply hC.le_of_not_gt hjCn.1 hp.1 ?_
intro h
have : c + d < a + b := add_lt_add_of_lt h
simp only [toHollom_le_toHollom_iff_fixed_right] at hj
omega
-- ...and `(x0, y0, n + 1) ≤ j`.
have h0j : h(x0 n C, y0 n C, n + 1) ≤ j := hj'.trans' (by simp [ha, hb])
have : line h(a, b, n + 1) = line h(x0 n C, a + b - x0 n C, n + 1) := by simp; omega
-- Then we have `f(a, b, n + 1) = f(x0, a + b - x0, n + 1)` since they are at the same line
have : f h(a, b, n + 1) = f h(x0 n C, a + b - x0 n C, n + 1) := apply_eq_of_line_eq f hC
⟨x0_y0_mem h.nonempty, by simp⟩ hjCn ‹_› this (x0_y0_min hC hp.1) (by simp; omega) hj' hj
-- so `f(x, y, n) = (a, b, n + 1) = f(a, b, n + 1) = f(x0, a + b - x0, n + 1)`
have : f h(x, y, n) = f h(x0 n C, a + b - x0 n C, n + 1) := by
rw [← this, ← hfp, f.eq_self_of_mem hp.1]
-- But `(x0 n C, a + b - x0 n C, n + 1) ≤ (x, y, n)` since `(x, y, n)` is in `S`, giving
-- a contradiction since they are in the same fibre.
exact f.not_le_of_eq this.symm (by simp) (.next_min (hx.2.trans' (by simp)))
· obtain ⟨j, hjCn, hj⟩ := lbias (a + b - y0 n C)
-- The left case is exactly symmetric
have hj' : h(a, b, n + 1) ≤ j := by
induction hjCn.2 using induction_on_level with | h c d =>
apply hC.le_of_not_gt hjCn.1 hp.1 ?_
intro h
have : c + d < a + b := add_lt_add_of_lt h
simp only [toHollom_le_toHollom_iff_fixed_right] at hj
omega
have h0j : h(x0 n C, y0 n C, n + 1) ≤ j := hj'.trans' (by simp [ha, hb])
have : line h(a, b, n + 1) = line h(a + b - y0 n C, y0 n C, n + 1) := by simp; omega
have := apply_eq_of_line_eq f hC ⟨x0_y0_mem h.nonempty, by simp⟩ hjCn ‹_› this
(x0_y0_min hC hp.1) (by simp; omega) hj' hj
have : f h(x, y, n) = f h(a + b - y0 n C, y0 n C, n + 1) := by
rw [← this, ← hfp, f.eq_self_of_mem hp.1]
exact f.not_le_of_eq this.symm (by simp) (.next_min (hx.2.trans' (by simp)))
/-- Every element of `S \ (C ∩ level n)` must be mapped into `C ∩ level (n - 1)`. -/
lemma S_mapsTo_previous (f : SpinalMap C) (hC : IsChain (· ≤ ·) C) (hn : n ≠ 0) :
∀ x ∈ S n C \ (C ∩ level n), f x ∈ C ∩ level (n - 1) := by
-- Clearly it must be mapped into `C`
intro x hx
refine ⟨f.mem _, ?_⟩
set p := f x with hp
clear_value p
induction S_subset_level hx.1 using induction_on_level with | h x y =>
induction p with | h a b m =>
-- Now write `(x, y, n)` for our given point, and suppose it is mapped to `(a, b, m)`.
simp only [toHollom_mem_level_iff]
-- We must have `m ≠ n`, as `(x, y, n) ∈ R` and no point of `R` can map to `C ∩ level n`
have : m ≠ n := by
rintro rfl
have : f _ ∉ _ := not_R_hits_same (S_subset_R hx.1) hx.2
simp only [Set.mem_inter_iff, SpinalMap.mem, true_and] at this
simp [← hp] at this
-- Furthermore, we must have `n + 1 ≠ m`, as `(x, y, n) ∈ S` and no point of `S` can map to
-- `C ∩ level (n + 1)`.
have : n + 1 ≠ m := by
rintro rfl
have : f _ ∉ _ := not_S_hits_next f hC hx.1 hx.2
simp only [Set.mem_inter_iff, SpinalMap.mem, true_and] at this
simp [← hp] at this
-- Next `f (a, b, m) = (a, b, m) = f (x, y, n)`
have hp' : f h(a, b, m) = f h(x, y, n) := by
rw [hp, f.idempotent]
-- But `(x, y, n) ≤ (a, b, m)` if `m + 2 ≤ n`, so this cannot hold
have : ¬ m + 2 ≤ n := by
intro h
have := f.eq_of_le hp'.symm (.twice h)
simp only [Prod.mk.injEq, Hollom.ext_iff] at this
omega
-- and `(a, b, m) ≤ (x, y, n)` if `n + 2 ≤ m`, so this cannot hold either
have : ¬ n + 2 ≤ m := by
intro h
have := f.eq_of_le hp' (.twice h)
simp only [Prod.mk.injEq, Hollom.ext_iff] at this
omega
-- So the only remaining option is that `m = n - 1`.
omega
open Finset in
/--
Supposing that all of `S \ (C ∩ level n)` is sent to `C ∩ level (n - 1)`, we deduce a contradiction.
-/
theorem not_S_mapsTo_previous (hC : IsChain (· ≤ ·) C)
(hCn : (C ∩ level n).Finite) (hn : n ≠ 0)
(h : ∀ x ∈ S n C \ (C ∩ level n), f x ∈ C ∩ level (n - 1)) :
False := by
-- Take `a` such that `{(x, y, n) | x ≥ a ∧ y ≥ a} ⊆ S \ (C ∩ level n)`...
obtain ⟨a, ha⟩ := (square_subset_S hCn).exists
-- ...then let `F` be the chain from `(a, a)` to `(3 * a, a)`...
let F : Finset Hollom := (chainBetween a a (3 * a) a).image (embed n)
-- ...observing that by definition of `a`, we know `F` is entirely within `S \ (C ∩ level n)`...
have F_subs : ↑F ⊆ S n C \ (C ∩ level n) := calc
F = embed n '' chainBetween a a (3 * a) a := Finset.coe_image
_ ⊆ embed n '' Finset.Icc (a, a) (3 * a, a) := Set.image_mono chainBetween_subset
_ = embed n '' Set.Icc (a, a) (3 * a, a) := by simp
_ ⊆ embed n '' Set.Ici (a, a) := Set.image_mono Set.Icc_subset_Ici_self
_ ⊆ S n C \ (C ∩ level n) := ha
-- ...and it has length `2a+1`.
have card_F : #F = 2 * a + 1 := by
rw [Finset.card_image_of_injective _ (embed n).injective,
card_chainBetween (by omega) (by simp)]
omega
let T := {x ∈ C ∩ level (n - 1) | line x < 2 * a}
-- Therefore, the image of `F` is within `C ∩ level (n - 1)`, and each of its points must be
-- within `{(x, y, n - 1) | x + y < 2 * a}`. That is, the image of `F` under `f` is within `T`.
have F_mapsTo : Set.MapsTo f F T := by
intro x hx
refine ⟨h _ (F_subs hx), ?_⟩
set c := f x with hc
have hc' : c ∈ C ∩ level (n - 1) := h _ (F_subs hx)
clear_value c
rw [coe_image, chainBetween, Ico_self, if_pos (by omega), empty_union, ← Icc_map_sectL] at hx
simp only [embed_apply, coe_map, Function.Embedding.sectL_apply, coe_Icc,
Set.mem_image, Set.mem_Icc, exists_exists_and_eq_and] at hx
obtain ⟨b, ⟨hab, hba⟩, rfl⟩ := hx
induction hc'.2 using induction_on_level with | h u v =>
simp only [line_toHollom]
by_contra!
have le : h(b, a, n) ≤ h(u, v, n - 1) := by
match n, hn with
| n + 1, _ =>
simp only [add_tsub_cancel_right]
apply HollomOrder.next_add (by omega)
have : f h(u, v, n - 1) = f h(b, a, n) := by rw [f.eq_self_of_mem hc'.1, hc]
have := le_of_toHollom_le_toHollom (f.eq_of_le this.symm le).ge
omega
-- And `f` acts injectively on `F`, as it is a chain.
have F_inj : Set.InjOn f F := f.injOn_of_isChain image_chainBetween_isChain
-- By definition of `T`, the `line` map sends it to the interval `[0, 2a)`
have line_mapsTo : Set.MapsTo line T (range (2 * a)) := by
rintro x ⟨_, hx⟩
simpa using hx
-- and it does so injectively, as `T` is a chain.
have line_inj : Set.InjOn line T :=
line_injOn (n - 1)
(hC.mono (by simp +contextual [Set.subset_def, T]))
(by simp +contextual [Set.subset_def, T])
-- Therefore `line ∘ f` sends `F` to `[0, 2a)` injectively
have line_F_mapsTo : Set.MapsTo (line ∘ f) F (range (2 * a)) := line_mapsTo.comp F_mapsTo
-- which is a contradiction by cardinality arguments.
have := card_le_card_of_injOn _ line_F_mapsTo (line_inj.comp F_inj F_mapsTo)
simp only [Finset.card_range] at this
omega
/-- The Hollom partial order has no spinal maps. -/
theorem no_spinalMap (hC : IsChain (· ≤ ·) C) (f : SpinalMap C) : False := by
obtain ⟨n, hn, hn'⟩ : ∃ n, n ≠ 0 ∧ (C ∩ Hollom.level n).Finite := by
obtain ⟨n, hn, hn'⟩ := Filter.frequently_atTop.1 (Hollom.exists_finite_intersection hC) 1
exact ⟨n, by omega, hn'⟩
exact Hollom.not_S_mapsTo_previous hC hn' hn (Hollom.S_mapsTo_previous f hC hn)
end Hollom
-- To conclude, we repeat the important properties of the Hollom partial order.
-- It is a partial order:
example : PartialOrder Hollom := inferInstance
-- It is countable:
example : Countable Hollom := inferInstance
-- It has no infinite antichains:
example (A : Set Hollom) (hA : IsAntichain (· ≤ ·) A) : A.Finite := Hollom.no_infinite_antichain hA
-- It is scattered (any function from ℚ to it cannot be strictly monotonic):
example {f : ℚ → Hollom} : ¬ StrictMono f := Hollom.scattered
-- and finally, it disproves the Aharoni–Korman conjecture:
/--
The Aharoni–Korman conjecture (sometimes called the fishbone conjecture) says that every partial
order satisfies one of the following:
- It contains an infinite antichain
- It contains a chain C, and has a partition into antichains such that every part meets C.
In November 2024, Hollom disproved this conjecture.
This statement says that it is not the case that every partially ordered set satisfies one of the
above conditions.
-/
theorem aharoni_korman_false :
¬ ∀ (α : Type) (_ : PartialOrder α),
(∃ A : Set α, IsAntichain (· ≤ ·) A ∧ A.Infinite) ∨
(∃ C : Set α, IsChain (· ≤ ·) C ∧
∃ S : Set (Set α), Setoid.IsPartition S ∧
∀ A ∈ S, IsAntichain (· ≤ ·) A ∧ (A ∩ C).Nonempty) := by
simp only [not_forall, not_or, not_exists]
refine ⟨Hollom, inferInstance, ?_, ?_⟩
· intro A ⟨hA, hA'⟩
exact hA' (Hollom.no_infinite_antichain hA)
· rintro C ⟨hC, h⟩
rw [Hollom.exists_partition_iff_nonempty_spinalMap hC] at h
obtain ⟨f⟩ := h
exact Hollom.no_spinalMap hC f |
.lake/packages/mathlib/Counterexamples/PolynomialIsDomain.lean | import Mathlib.Algebra.GroupWithZero.TransferInstance
import Mathlib.Algebra.Order.Ring.Nat
import Mathlib.Algebra.Ring.Equiv
import Mathlib.RingTheory.Polynomial.Opposites
/-!
# A commutative semiring that is a domain whose polynomial semiring is not a domain
`NatMaxAdd` is the natural numbers equipped with the usual multiplication but with maximum as
addition. Under these operations it is a commutative semiring that is a domain, but
`1 + 1 = 1 + 0 = 1` in this semiring so addition is not cancellative.
As a consequence, the polynomial semiring `NatMaxAdd[X]` is not a domain,
even though it has no zero-divisors other than 0.
-/
/-- A type synonym for ℕ equipped with maximum as addition. -/
def NatMaxAdd := ℕ
open scoped Polynomial
namespace NatMaxAdd
/-- Identification of `NatMaxAdd` with `ℕ`. -/
protected abbrev mk : ℕ ≃ NatMaxAdd := Equiv.refl _
attribute [irreducible] NatMaxAdd
open NatMaxAdd (mk)
instance : AddCommSemigroup NatMaxAdd where
add a b := mk (mk.symm a ⊔ mk.symm b)
add_assoc _ _ _ := mk.symm.injective (sup_assoc ..)
add_comm _ _ := mk.symm.injective (sup_comm ..)
instance : AddZeroClass NatMaxAdd where
zero := mk 0
zero_add _ := mk.symm.injective (bot_sup_eq _)
add_zero _ := mk.symm.injective (sup_bot_eq _)
instance : CommMonoidWithZero NatMaxAdd := mk.symm.commMonoidWithZero
/-- `NatMaxAdd` is isomorphic to `ℕ` multiplicatively. -/
protected def mulEquiv : NatMaxAdd ≃* ℕ where
__ := mk.symm
map_mul' _ _ := rfl
instance : CommSemiring NatMaxAdd where
nsmul := nsmulRec
left_distrib _ _ _ := mk.symm.injective (Nat.mul_max_mul_left ..).symm
right_distrib _ _ _ := mk.symm.injective (Nat.mul_max_mul_right ..).symm
instance : IsDomain NatMaxAdd := NatMaxAdd.mulEquiv.isDomain
theorem natCast_eq_one (n : ℕ) : ∀ [NeZero n], (n : NatMaxAdd) = 1 := by
induction n with
| zero => intro; exact (NeZero.ne 0 rfl).elim
| succ n ih =>
obtain _ | n := n
· intro; rfl
· rw [Nat.cast_succ, ih]; intro; rfl
theorem not_isCancelAdd : ¬ IsCancelAdd NatMaxAdd := fun h ↦ by cases @h.1.1 1 0 1 rfl
theorem not_isDomain_polynomial : ¬ IsDomain NatMaxAdd[X] :=
Polynomial.isDomain_iff.not.mpr fun h ↦ not_isCancelAdd h.2
theorem noZeroDivisors_polynomial : NoZeroDivisors NatMaxAdd[X] := inferInstance
end NatMaxAdd
theorem not_isDomain_commSemiring_imp_isDomain_polynomial :
¬ ∀ (R : Type) [CommSemiring R] [IsDomain R], IsDomain R[X] :=
fun h ↦ NatMaxAdd.not_isDomain_polynomial (h _) |
.lake/packages/mathlib/Counterexamples/ZeroDivisorsInAddMonoidAlgebras.lean | import Mathlib.Algebra.Group.UniqueProds.Basic
import Mathlib.Algebra.MonoidAlgebra.Defs
import Mathlib.Algebra.Ring.GeomSum
import Mathlib.Data.Finsupp.Lex
import Mathlib.Data.ZMod.Basic
/-!
# Examples of zero-divisors in `AddMonoidAlgebra`s
This file contains an easy source of zero-divisors in an `AddMonoidAlgebra`.
If `k` is a field and `G` is an additive group containing a non-zero torsion element, then
`k[G]` contains non-zero zero-divisors: this is lemma `zero_divisors_of_torsion`.
There is also a version for periodic elements of an additive monoid: `zero_divisors_of_periodic`.
The converse of this statement is
[Kaplansky's zero divisor conjecture](https://en.wikipedia.org/wiki/Kaplansky%27s_conjectures).
The formalized example generalizes in trivial ways the assumptions: the field `k` can be any
nontrivial ring `R` and the additive group `G` with a torsion element can be any additive monoid
`A` with a non-zero periodic element.
Besides this example, we also address a comment in `Data.Finsupp.Lex` to the effect that the proof
that addition is monotone on `α →₀ N` uses that it is *strictly* monotone on `N`.
The specific statement is about `Finsupp.Lex.addLeftStrictMono` and its analogue
`Finsupp.Lex.addRightStrictMono`. We do not need two separate counterexamples, since the
operation is commutative.
The example is very simple. Let `F = {0, 1}` with order determined by `0 < 1` and absorbing
addition (which is the same as `max` in this case). We denote a function `f : F → F` (which is
automatically finitely supported!) by `[f 0, f 1]`, listing its values. Recall that the order on
finitely supported function is lexicographic, matching the list notation. The inequality
`[0, 1] ≤ [1, 0]` holds. However, adding `[1, 0]` to both sides yields the *reversed* inequality
`[1, 1] > [1, 0]`.
-/
open Finsupp hiding single
open AddMonoidAlgebra
namespace Counterexample
/-- This is a simple example showing that if `R` is a non-trivial ring and `A` is an additive
monoid with an element `a` satisfying `n • a = a` and `(n - 1) • a ≠ a`, for some `2 ≤ n`,
then `R[A]` contains non-zero zero-divisors. The elements are easy to write down:
`[a]` and `[a] ^ (n - 1) - 1` are non-zero elements of `R[A]` whose product
is zero.
Observe that such an element `a` *cannot* be invertible. In particular, this lemma never applies
if `A` is a group. -/
theorem zero_divisors_of_periodic {R A} [Nontrivial R] [Ring R] [AddMonoid A] {n : ℕ} (a : A)
(n2 : 2 ≤ n) (na : n • a = a) (na1 : (n - 1) • a ≠ 0) :
∃ f g : R[A], f ≠ 0 ∧ g ≠ 0 ∧ f * g = 0 := by
refine ⟨single a 1, single ((n - 1) • a) 1 - single 0 1, by simp, ?_, ?_⟩
· exact sub_ne_zero.mpr (by simpa [single, AddMonoidAlgebra, single_eq_single_iff])
· rw [mul_sub, AddMonoidAlgebra.single_mul_single, AddMonoidAlgebra.single_mul_single,
sub_eq_zero, add_zero, ← succ_nsmul', Nat.sub_add_cancel (one_le_two.trans n2), na]
theorem single_zero_one {R A} [Semiring R] [Zero A] :
single (0 : A) (1 : R) = (1 : R[A]) :=
rfl
/-- This is a simple example showing that if `R` is a non-trivial ring and `A` is an additive
monoid with a non-zero element `a` of finite order `oa`, then `R[A]` contains
non-zero zero-divisors. The elements are easy to write down:
`∑ i ∈ Finset.range oa, [a] ^ i` and `[a] - 1` are non-zero elements of `R[A]`
whose product is zero.
In particular, this applies whenever the additive monoid `A` is an additive group with a non-zero
torsion element. -/
theorem zero_divisors_of_torsion {R A} [Nontrivial R] [Ring R] [AddMonoid A] (a : A)
(o2 : 2 ≤ addOrderOf a) : ∃ f g : R[A], f ≠ 0 ∧ g ≠ 0 ∧ f * g = 0 := by
refine
⟨(Finset.range (addOrderOf a)).sum fun i : ℕ => single a 1 ^ i, single a 1 - single 0 1, ?_, ?_,
?_⟩
· apply_fun fun x : R[A] => x 0
refine ne_of_eq_of_ne (?_ : (_ : R) = 1) one_ne_zero
dsimp only; rw [Finset.sum_apply']
refine (Finset.sum_eq_single 0 ?_ ?_).trans ?_
· intro b hb b0
rw [single_pow, one_pow, single_eq_of_ne']
exact nsmul_ne_zero_of_lt_addOrderOf b0 (Finset.mem_range.mp hb)
· grind
· rw [single_pow, one_pow, zero_smul, single_eq_same]
· apply_fun fun x : R[A] => x 0
refine sub_ne_zero.mpr (ne_of_eq_of_ne (?_ : (_ : R) = 0) ?_)
· have a0 : a ≠ 0 :=
ne_of_eq_of_ne (one_nsmul a).symm
(nsmul_ne_zero_of_lt_addOrderOf one_ne_zero (Nat.succ_le_iff.mp o2))
simp only [a0, single_eq_of_ne', Ne, not_false_iff]
· simpa only [single_eq_same] using zero_ne_one
· convert Commute.geom_sum₂_mul (R := AddMonoidAlgebra R A) _ (addOrderOf a) using 3
· rw [single_zero_one, one_pow, mul_one]
· rw [single_pow, one_pow, addOrderOf_nsmul_eq_zero, single_zero_one, one_pow, sub_self]
· simp only [single_zero_one, Commute.one_right]
example {R} [Ring R] [Nontrivial R] (n : ℕ) (n0 : 2 ≤ n) :
∃ f g : AddMonoidAlgebra R (ZMod n), f ≠ 0 ∧ g ≠ 0 ∧ f * g = 0 :=
zero_divisors_of_torsion (1 : ZMod n) (n0.trans_eq (ZMod.addOrderOf_one _).symm)
/-- `F` is the type with two elements `zero` and `one`. We define the "obvious" linear order and
absorbing addition on it to generate our counterexample. -/
inductive F
| zero
| one
deriving DecidableEq, Inhabited
/-- The same as `List.getRest`, except that we take the "rest" from the first match, rather than
from the beginning, returning `[]` if there is no match. For instance,
```lean
#eval dropUntil [1,2] [3,1,2,4,1,2] -- [4, 1, 2]
```
-/
def List.dropUntil {α} [DecidableEq α] : List α → List α → List α
| _, [] => []
| l, a :: as => ((a::as).getRest l).getD (dropUntil l as)
open Lean Elab Command in
/-- `guard_decl na mod` makes sure that the declaration with name `na` is in the module `mod`.
```lean
guard_decl Nat.nontrivial Mathlib.Algebra.Ring.Nat -- does nothing
guard_decl Nat.nontrivial Not.In.Here
-- the module Not.In.Here is not imported!
```
This test makes sure that the comment referring to this example is in the file claimed in the
doc-module to this counterexample. -/
elab "guard_decl" na:ident mod:ident : command => do
let dcl ← liftCoreM <| realizeGlobalConstNoOverloadWithInfo na
let mdn := mod.getId
let env ← getEnv
let some dcli := env.getModuleIdxFor? dcl | unreachable!
let some mdni := env.getModuleIdx? mdn | throwError "the module {mod} is not imported!"
unless dcli = mdni do throwError "instance {na} is no longer in {mod}."
guard_decl Finsupp.Lex.addLeftMono Mathlib.Data.Finsupp.Lex
guard_decl Finsupp.Lex.addRightMono Mathlib.Data.Finsupp.Lex
namespace F
instance : Zero F :=
⟨F.zero⟩
/-- `1` is not really needed, but it is nice to use the notation. -/
instance : One F :=
⟨F.one⟩
/-- A tactic to prove trivial goals by enumeration. -/
macro "boom" : tactic => `(tactic| (repeat' rintro ⟨⟩) <;> decide)
/-- `val` maps `0 1 : F` to their counterparts in `ℕ`.
We use it to lift the linear order on `ℕ`. -/
def val : F → ℕ
| 0 => 0
| 1 => 1
instance : LinearOrder F :=
LinearOrder.lift' val (by boom)
@[simp]
theorem z01 : (0 : F) < 1 := by decide
instance : Add F where
add := max
/-- `F` would be a `CommSemiring`, using `min` as multiplication. Again, we do not need this. -/
instance : AddCommMonoid F where
add_assoc := by boom
zero_add := by boom
add_zero := by boom
add_comm := by boom
nsmul := nsmulRec
/-- The `AddLeftMono`es asserting monotonicity of addition hold for `F`. -/
instance addLeftMono : AddLeftMono F :=
⟨by boom⟩
example : AddRightMono F := by infer_instance
/-- The following examples show that `F` has all the typeclasses used by
`Finsupp.Lex.addLeftStrictMono`... -/
example : LinearOrder F := by infer_instance
example : AddMonoid F := by infer_instance
/-- ... except for the strict monotonicity of addition, the crux of the matter. -/
example : ¬AddLeftStrictMono F := fun h =>
lt_irrefl 1 <| (h.elim : Covariant F F (· + ·) (· < ·)) 1 z01
/-- A few `simp`-lemmas to take care of trivialities in the proof of the example below. -/
@[simp]
theorem f1 : ∀ a : F, 1 + a = 1 := by boom
@[simp]
theorem f011 : ofLex (Finsupp.single (0 : F) (1 : F)) 1 = 0 :=
single_apply_eq_zero.mpr fun h => h
@[simp]
theorem f010 : ofLex (Finsupp.single (0 : F) (1 : F)) 0 = 1 :=
single_eq_same
@[simp]
theorem f111 : ofLex (Finsupp.single (1 : F) (1 : F)) 1 = 1 :=
single_eq_same
@[simp]
theorem f110 : ofLex (Finsupp.single (1 : F) (1 : F)) 0 = 0 :=
single_apply_eq_zero.mpr fun h => h.symm
/-- Here we see that (not-necessarily strict) monotonicity of addition on `Lex (F →₀ F)` is not
a consequence of monotonicity of addition on `F`. Strict monotonicity of addition on `F` is
enough and is the content of `Finsupp.Lex.addLeftStrictMono`. -/
example : ¬AddLeftMono (Lex (F →₀ F)) := by
rintro ⟨h⟩
refine (not_lt (α := Lex (F →₀ F))).mpr (@h (Finsupp.single (0 : F) (1 : F))
(Finsupp.single 1 1) (Finsupp.single 0 1) ?_) ⟨1, ?_⟩
· exact Or.inr ⟨0, by simp [(by boom : ∀ j : F, j < 0 ↔ False)]⟩
· simp [(by boom : ∀ j : F, j < 1 ↔ j = 0), ofLex_add, f010, f1, f110, f011, f111]
example {α} [Ring α] [Nontrivial α] : ∃ f g : AddMonoidAlgebra α F, f ≠ 0 ∧ g ≠ 0 ∧ f * g = 0 :=
zero_divisors_of_periodic (1 : F) le_rfl (by simp [two_smul]) z01.ne'
example {α} [Zero α] :
2 • (Finsupp.single 0 1 : α →₀ F) = (Finsupp.single 0 1 : α →₀ F)
∧ (Finsupp.single 0 1 : α →₀ F) ≠ 0 :=
⟨Finsupp.smul_single _ _ _, by simp [Ne, Finsupp.single_eq_zero]⟩
end F
/-- A Type that does not have `UniqueProds`. -/
example : ¬UniqueProds ℕ := by
rintro ⟨h⟩
refine not_not.mpr (h (Finset.singleton_nonempty 0) (Finset.insert_nonempty 0 {1})) ?_
simp [UniqueMul, not_or]
/-- Some Types that do not have `UniqueSums`. -/
example (n : ℕ) (n2 : 2 ≤ n) : ¬UniqueSums (ZMod n) := by
haveI : Fintype (ZMod n) := @ZMod.fintype n ⟨(zero_lt_two.trans_le n2).ne'⟩
haveI : Nontrivial (ZMod n) := CharP.nontrivial_of_char_ne_one (one_lt_two.trans_le n2).ne'
rintro ⟨h⟩
refine not_not.mpr (h Finset.univ_nonempty Finset.univ_nonempty) ?_
suffices ∀ x y : ZMod n, ∃ x' y' : ZMod n, x' + y' = x + y ∧ (x' = x → ¬y' = y) by
simpa [UniqueAdd]
exact fun x y => ⟨x - 1, y + 1, sub_add_add_cancel _ _ _, by simp⟩
end Counterexample |
.lake/packages/mathlib/Counterexamples/Phillips.lean | import Mathlib.Analysis.Normed.Module.HahnBanach
import Mathlib.MeasureTheory.Integral.Bochner.Set
import Mathlib.MeasureTheory.Measure.Lebesgue.Basic
import Mathlib.Topology.ContinuousMap.Bounded.Star
/-!
# A counterexample on Pettis integrability
There are several theories of integration for functions taking values in Banach spaces. Bochner
integration, requiring approximation by simple functions, is the analogue of the one-dimensional
theory. It is very well behaved, but only works for functions with second-countable range.
For functions `f` taking values in a larger Banach space `B`, one can define the Dunford integral
as follows. Assume that, for all continuous linear functional `φ`, the function `φ ∘ f` is
measurable (we say that `f` is weakly measurable, or scalarly measurable) and integrable.
Then `φ ↦ ∫ φ ∘ f` is continuous (by the closed graph theorem), and therefore defines an element
of the bidual `B**`. This is the Dunford integral of `f`.
This Dunford integral is not usable in practice as it does not belong to the right space. Let us
say that a function is Pettis integrable if its Dunford integral belongs to the canonical image of
`B` in `B**`. In this case, we define the Pettis integral as the Dunford integral inside `B`.
This integral is very general, but not really usable to do analysis. This file illustrates this,
by giving an example of a function with nice properties but which is *not* Pettis-integrable.
This function:
- is defined from `[0, 1]` to a complete Banach space;
- is weakly measurable;
- has norm everywhere bounded by `1` (in particular, its norm is integrable);
- and yet it is not Pettis-integrable with respect to Lebesgue measure.
This construction is due to [Ralph S. Phillips, *Integration in a convex linear
topological space*][phillips1940], in Example 10.8. It requires the continuum hypothesis. The
example is the following.
Under the continuum hypothesis, one can find a subset of `ℝ²` which,
along each vertical line, only misses a countable set of points, while it is countable along each
horizontal line. This is due to Sierpinski, and formalized in `sierpinski_pathological_family`.
(In fact, Sierpinski proves that the existence of such a set is equivalent to the continuum
hypothesis).
Let `B` be the set of all bounded functions on `ℝ` (we are really talking about everywhere defined
functions here). Define `f : ℝ → B` by taking `f x` to be the characteristic function of the
vertical slice at position `x` of Sierpinski's set. It is our counterexample.
To show that it is weakly measurable, we should consider `φ ∘ f` where `φ` is an arbitrary
continuous linear form on `B`. There is no reasonable classification of such linear forms (they can
be very wild). But if one restricts such a linear form to characteristic functions, one gets a
finitely additive signed "measure". Such a "measure" can be decomposed into a discrete part
(supported on a countable set) and a continuous part (giving zero mass to countable sets).
For all but countably many points, `f x` will not intersect the discrete support of `φ` thanks to
the definition of the Sierpinski set. This implies that `φ ∘ f` is constant outside of a countable
set, and equal to the total mass of the continuous part of `φ` there. In particular, it is
measurable (and its integral is the total mass of the continuous part of `φ`).
Assume that `f` has a Pettis integral `g`. For all continuous linear form `φ`, then `φ g` should
be the total mass of the continuous part of `φ`. Taking for `φ` the evaluation at the point `x`
(which has no continuous part), one gets `g x = 0`. Take then for `φ` the Lebesgue integral on
`[0, 1]` (or rather an arbitrary extension of Lebesgue integration to all bounded functions,
thanks to Hahn-Banach). Then `φ g` should be the total mass of the continuous part of `φ`,
which is `1`. This contradicts the fact that `g = 0`, and concludes the proof that `f` has no
Pettis integral.
## Implementation notes
The space of all bounded functions is defined as the space of all bounded continuous functions
on a discrete copy of the original type, as mathlib only contains the space of all bounded
continuous functions (which is the useful one).
-/
namespace Counterexample
universe u
variable {α : Type u}
open Set BoundedContinuousFunction MeasureTheory
open Cardinal (aleph)
open scoped Cardinal BoundedContinuousFunction
noncomputable section
/-- A copy of a type, endowed with the discrete topology -/
def DiscreteCopy (α : Type u) : Type u :=
α
instance : TopologicalSpace (DiscreteCopy α) :=
⊥
instance : DiscreteTopology (DiscreteCopy α) :=
⟨rfl⟩
instance [Inhabited α] : Inhabited (DiscreteCopy α) :=
⟨show α from default⟩
namespace Phillips1940
/-!
### Extending the integral
Thanks to Hahn-Banach, one can define a (non-canonical) continuous linear functional on the space
of all bounded functions, coinciding with the integral on the integrable ones.
-/
/-- The subspace of integrable functions in the space of all bounded functions on a type.
This is a technical device, used to apply Hahn-Banach theorem to construct an extension of the
integral to all bounded functions. -/
def boundedIntegrableFunctions [MeasurableSpace α] (μ : Measure α) :
Subspace ℝ (DiscreteCopy α →ᵇ ℝ) where
carrier := {f | Integrable f μ}
zero_mem' := integrable_zero _ _ _
add_mem' hf hg := Integrable.add hf hg
smul_mem' c _ hf := Integrable.smul c hf
/-- The integral, as a continuous linear map on the subspace of integrable functions in the space
of all bounded functions on a type. This is a technical device, that we will extend through
Hahn-Banach. -/
def boundedIntegrableFunctionsIntegralCLM [MeasurableSpace α] (μ : Measure α) [IsFiniteMeasure μ] :
boundedIntegrableFunctions μ →L[ℝ] ℝ :=
LinearMap.mkContinuous (E := ↥(boundedIntegrableFunctions μ))
{ toFun := fun f => ∫ x, f.1 x ∂μ
map_add' := fun f g => integral_add f.2 g.2
map_smul' := fun c f => integral_smul c f.1 } (μ.real univ)
(by
intro f
rw [mul_comm]
apply norm_integral_le_of_norm_le_const
apply Filter.Eventually.of_forall
intro x
exact BoundedContinuousFunction.norm_coe_le_norm f.1 x)
/-- Given a measure, there exists a continuous linear form on the space of all bounded functions
(not necessarily measurable) that coincides with the integral on bounded measurable functions. -/
theorem exists_linear_extension_to_boundedFunctions [MeasurableSpace α] (μ : Measure α)
[IsFiniteMeasure μ] :
∃ φ : (DiscreteCopy α →ᵇ ℝ) →L[ℝ] ℝ,
∀ f : DiscreteCopy α →ᵇ ℝ, Integrable f μ → φ f = ∫ x, f x ∂μ := by
rcases exists_extension_norm_eq _ (boundedIntegrableFunctionsIntegralCLM μ) with ⟨φ, hφ⟩
exact ⟨φ, fun f hf => hφ.1 ⟨f, hf⟩⟩
/-- An arbitrary extension of the integral to all bounded functions, as a continuous linear map.
It is not at all canonical, and constructed using Hahn-Banach. -/
def _root_.MeasureTheory.Measure.extensionToBoundedFunctions [MeasurableSpace α] (μ : Measure α)
[IsFiniteMeasure μ] : (DiscreteCopy α →ᵇ ℝ) →L[ℝ] ℝ :=
(exists_linear_extension_to_boundedFunctions μ).choose
theorem extensionToBoundedFunctions_apply [MeasurableSpace α] (μ : Measure α) [IsFiniteMeasure μ]
(f : DiscreteCopy α →ᵇ ℝ) (hf : Integrable f μ) :
μ.extensionToBoundedFunctions f = ∫ x, f x ∂μ :=
(exists_linear_extension_to_boundedFunctions μ).choose_spec f hf
/-!
### Additive measures on the space of all sets
We define bounded finitely additive signed measures on the space of all subsets of a type `α`,
and show that such an object can be split into a discrete part and a continuous part.
-/
/-- A bounded signed finitely additive measure defined on *all* subsets of a type. -/
structure BoundedAdditiveMeasure (α : Type u) where
toFun : Set α → ℝ
additive' : ∀ s t, Disjoint s t → toFun (s ∪ t) = toFun s + toFun t
exists_bound : ∃ C : ℝ, ∀ s, |toFun s| ≤ C
attribute [coe] BoundedAdditiveMeasure.toFun
instance : Inhabited (BoundedAdditiveMeasure α) :=
⟨{ toFun := fun _ => 0
additive' := fun s t _ => by simp
exists_bound := ⟨0, fun _ => by simp⟩ }⟩
instance : CoeFun (BoundedAdditiveMeasure α) fun _ => Set α → ℝ :=
⟨fun f => f.toFun⟩
namespace BoundedAdditiveMeasure
/-- A constant bounding the mass of any set for `f`. -/
def C (f : BoundedAdditiveMeasure α) :=
f.exists_bound.choose
theorem additive (f : BoundedAdditiveMeasure α) (s t : Set α) (h : Disjoint s t) :
f (s ∪ t) = f s + f t :=
f.additive' s t h
theorem abs_le_bound (f : BoundedAdditiveMeasure α) (s : Set α) : |f s| ≤ f.C :=
f.exists_bound.choose_spec s
theorem le_bound (f : BoundedAdditiveMeasure α) (s : Set α) : f s ≤ f.C :=
le_trans (le_abs_self _) (f.abs_le_bound s)
@[simp]
theorem empty (f : BoundedAdditiveMeasure α) : f ∅ = 0 := by
have : (∅ : Set α) = ∅ ∪ ∅ := by simp only [empty_union]
apply_fun f at this
rwa [f.additive _ _ (empty_disjoint _), right_eq_add] at this
instance : Neg (BoundedAdditiveMeasure α) :=
⟨fun f =>
{ toFun := fun s => -f s
additive' := fun s t hst => by simp only [f.additive s t hst, add_comm, neg_add_rev]
exists_bound := ⟨f.C, fun s => by simp [f.abs_le_bound]⟩ }⟩
@[simp]
theorem neg_apply (f : BoundedAdditiveMeasure α) (s : Set α) : (-f) s = -f s :=
rfl
/-- Restricting a bounded additive measure to a subset still gives a bounded additive measure. -/
def restrict (f : BoundedAdditiveMeasure α) (t : Set α) : BoundedAdditiveMeasure α where
toFun s := f (t ∩ s)
additive' s s' h := by
rw [← f.additive (t ∩ s) (t ∩ s'), inter_union_distrib_left]
exact h.mono inter_subset_right inter_subset_right
exists_bound := ⟨f.C, fun s => f.abs_le_bound _⟩
@[simp]
theorem restrict_apply (f : BoundedAdditiveMeasure α) (s t : Set α) : f.restrict s t = f (s ∩ t) :=
rfl
/-- There is a maximal countable set of positive measure, in the sense that any countable set
not intersecting it has nonpositive measure. Auxiliary lemma to prove `exists_discrete_support`. -/
theorem exists_discrete_support_nonpos (f : BoundedAdditiveMeasure α) :
∃ s : Set α, s.Countable ∧ ∀ t : Set α, t.Countable → f (t \ s) ≤ 0 := by
/- The idea of the proof is to construct the desired set inductively, adding at each step a
countable set with close to maximal measure among those points that have not already been
chosen. Doing this countably many steps will be enough. Indeed, otherwise, a remaining set would
have positive measure `ε`. This means that at each step the set we have added also had a large
measure, say at least `ε / 2`. After `n` steps, the set we have constructed has therefore
measure at least `n * ε / 2`. This is a contradiction since the measures have to remain
uniformly bounded.
We argue from the start by contradiction, as this means that our inductive construction will
never be stuck, so we won't have to consider this case separately.
In this proof, we use explicit coercions `↑s` for `s : A` as otherwise the system tries to find
a `CoeFun` instance on `↥A`, which is too costly.
-/
by_contra! h
-- We will formulate things in terms of the type of countable subsets of `α`, as this is more
-- convenient to formalize the inductive construction.
let A : Set (Set α) := {t | t.Countable}
let empty : A := ⟨∅, countable_empty⟩
haveI : Nonempty A := ⟨empty⟩
-- given a countable set `s`, one can find a set `t` in its complement with measure close to
-- maximal.
have : ∀ s : A, ∃ t : A, ∀ u : A, f (↑u \ ↑s) ≤ 2 * f (↑t \ ↑s) := by
intro s
have B : BddAbove (range fun u : A => f (↑u \ ↑s)) := by
refine ⟨f.C, fun x hx => ?_⟩
rcases hx with ⟨u, hu⟩
rw [← hu]
exact f.le_bound _
let S := iSup fun t : A => f (↑t \ ↑s)
have S_pos : 0 < S := by
rcases h s.1 s.2 with ⟨t, t_count, ht⟩
apply ht.trans_le
let t' : A := ⟨t, t_count⟩
change f (↑t' \ ↑s) ≤ S
exact le_ciSup B t'
rcases exists_lt_of_lt_ciSup (half_lt_self S_pos) with ⟨t, ht⟩
refine ⟨t, fun u => ?_⟩
calc
f (↑u \ ↑s) ≤ S := le_ciSup B _
_ ≤ 2 * f (↑t \ ↑s) := (div_le_iff₀' two_pos).1 ht.le
choose! F hF using this
-- iterate the above construction, by adding at each step a set with measure close to maximal in
-- the complement of already chosen points. This is the set `s n` at step `n`.
let G : A → A := fun u => ⟨(↑u : Set α) ∪ ↑(F u), u.2.union (F u).2⟩
let s : ℕ → A := fun n => G^[n] empty
-- We will get a contradiction from the fact that there is a countable set `u` with positive
-- measure in the complement of `⋃ n, s n`.
rcases h (⋃ n, ↑(s n)) (countable_iUnion fun n => (s n).2) with ⟨t, t_count, ht⟩
let u : A := ⟨t \ ⋃ n, ↑(s n), t_count.mono diff_subset⟩
set ε := f ↑u with hε
have ε_pos : 0 < ε := ht
have I1 : ∀ n, ε / 2 ≤ f (↑(s (n + 1)) \ ↑(s n)) := by
intro n
rw [div_le_iff₀' (show (0 : ℝ) < 2 by simp), hε]
convert hF (s n) u using 2
· dsimp
ext x
simp only [u, not_exists, mem_iUnion, mem_diff]
tauto
· congr 1
simp only [G, s, Function.iterate_succ', Subtype.coe_mk, union_diff_left, Function.comp]
have I2 : ∀ n : ℕ, (n : ℝ) * (ε / 2) ≤ f ↑(s n) := by
intro n
induction n with
| zero =>
simp only [s, empty, BoundedAdditiveMeasure.empty, id, Nat.cast_zero, zero_mul,
Function.iterate_zero, Subtype.coe_mk, le_rfl]
| succ n IH =>
have : (s (n + 1)).1 = (s (n + 1)).1 \ (s n).1 ∪ (s n).1 := by
simpa only [s, Function.iterate_succ', union_diff_self]
using (diff_union_of_subset subset_union_left).symm
rw [this, f.additive]
swap; · exact disjoint_sdiff_self_left
calc
((n + 1 : ℕ) : ℝ) * (ε / 2) = ε / 2 + n * (ε / 2) := by simp only [Nat.cast_succ]; ring
_ ≤ f (↑(s (n + 1 : ℕ)) \ ↑(s n)) + f ↑(s n) := add_le_add (I1 n) IH
rcases exists_nat_gt (f.C / (ε / 2)) with ⟨n, hn⟩
have : (n : ℝ) ≤ f.C / (ε / 2) := by
rw [le_div_iff₀ (half_pos ε_pos)]; exact (I2 n).trans (f.le_bound _)
exact lt_irrefl _ (this.trans_lt hn)
theorem exists_discrete_support (f : BoundedAdditiveMeasure α) :
∃ s : Set α, s.Countable ∧ ∀ t : Set α, t.Countable → f (t \ s) = 0 := by
rcases f.exists_discrete_support_nonpos with ⟨s₁, s₁_count, h₁⟩
rcases (-f).exists_discrete_support_nonpos with ⟨s₂, s₂_count, h₂⟩
refine ⟨s₁ ∪ s₂, s₁_count.union s₂_count, fun t ht => le_antisymm ?_ ?_⟩
· have : t \ (s₁ ∪ s₂) = (t \ (s₁ ∪ s₂)) \ s₁ := by
rw [diff_diff, union_comm, union_assoc, union_self]
rw [this]
exact h₁ _ (ht.mono diff_subset)
· have : t \ (s₁ ∪ s₂) = (t \ (s₁ ∪ s₂)) \ s₂ := by rw [diff_diff, union_assoc, union_self]
rw [this]
simp only [neg_nonpos, neg_apply] at h₂
exact h₂ _ (ht.mono diff_subset)
/-- A countable set outside of which the measure gives zero mass to countable sets. We are not
claiming this set is unique, but we make an arbitrary choice of such a set. -/
def discreteSupport (f : BoundedAdditiveMeasure α) : Set α :=
(exists_discrete_support f).choose
theorem countable_discreteSupport (f : BoundedAdditiveMeasure α) : f.discreteSupport.Countable :=
(exists_discrete_support f).choose_spec.1
theorem apply_countable (f : BoundedAdditiveMeasure α) (t : Set α) (ht : t.Countable) :
f (t \ f.discreteSupport) = 0 :=
(exists_discrete_support f).choose_spec.2 t ht
/-- The discrete part of a bounded additive measure, obtained by restricting the measure to its
countable support. -/
def discretePart (f : BoundedAdditiveMeasure α) : BoundedAdditiveMeasure α :=
f.restrict f.discreteSupport
/-- The continuous part of a bounded additive measure, giving zero measure to every countable
set. -/
def continuousPart (f : BoundedAdditiveMeasure α) : BoundedAdditiveMeasure α :=
f.restrict (univ \ f.discreteSupport)
theorem eq_add_parts (f : BoundedAdditiveMeasure α) (s : Set α) :
f s = f.discretePart s + f.continuousPart s := by
simp only [discretePart, continuousPart, restrict_apply]
rw [← f.additive, ← union_inter_distrib_right]
· simp only [union_univ, union_diff_self, univ_inter]
· have : Disjoint f.discreteSupport (univ \ f.discreteSupport) := disjoint_sdiff_self_right
exact this.mono inter_subset_left inter_subset_left
theorem discretePart_apply (f : BoundedAdditiveMeasure α) (s : Set α) :
f.discretePart s = f (f.discreteSupport ∩ s) :=
rfl
theorem continuousPart_apply_eq_zero_of_countable (f : BoundedAdditiveMeasure α) (s : Set α)
(hs : s.Countable) : f.continuousPart s = 0 := by
simp only [continuousPart, restrict_apply]
convert f.apply_countable s hs using 2
ext x
simp [and_comm]
theorem continuousPart_apply_diff (f : BoundedAdditiveMeasure α) (s t : Set α) (hs : s.Countable) :
f.continuousPart (t \ s) = f.continuousPart t := by
conv_rhs => rw [← diff_union_inter t s]
rw [additive, left_eq_add]
· exact continuousPart_apply_eq_zero_of_countable _ _ (hs.mono inter_subset_right)
· exact Disjoint.mono_right inter_subset_right disjoint_sdiff_self_left
end BoundedAdditiveMeasure
open BoundedAdditiveMeasure
section
/-!
### Relationship between continuous functionals and finitely additive measures.
-/
theorem norm_indicator_le_one (s : Set α) (x : α) : ‖(indicator s (1 : α → ℝ)) x‖ ≤ 1 := by
simp only [Set.indicator, Pi.one_apply]; split_ifs <;> norm_num
/-- A functional in the dual space of bounded functions gives rise to a bounded additive measure,
by applying the functional to the indicator functions. -/
def _root_.ContinuousLinearMap.toBoundedAdditiveMeasure [TopologicalSpace α] [DiscreteTopology α]
(f : (α →ᵇ ℝ) →L[ℝ] ℝ) : BoundedAdditiveMeasure α where
toFun s := f (ofNormedAddCommGroupDiscrete (indicator s 1) 1 (norm_indicator_le_one s))
additive' s t hst := by
have :
ofNormedAddCommGroupDiscrete (indicator (s ∪ t) 1) 1 (norm_indicator_le_one _) =
ofNormedAddCommGroupDiscrete (indicator s 1) 1 (norm_indicator_le_one s) +
ofNormedAddCommGroupDiscrete (indicator t 1) 1 (norm_indicator_le_one t) := by
ext x; simp [indicator_union_of_disjoint hst]
grind
exists_bound :=
⟨‖f‖, fun s => by
have I :
‖ofNormedAddCommGroupDiscrete (indicator s 1) 1 (norm_indicator_le_one s)‖ ≤ 1 := by
apply norm_ofNormedAddCommGroup_le _ zero_le_one
apply le_trans (f.le_opNorm _)
simpa using mul_le_mul_of_nonneg_left I (norm_nonneg f)⟩
@[simp]
theorem continuousPart_evalCLM_eq_zero [TopologicalSpace α] [DiscreteTopology α] (s : Set α)
(x : α) : (evalCLM ℝ x).toBoundedAdditiveMeasure.continuousPart s = 0 :=
let f := (evalCLM ℝ x).toBoundedAdditiveMeasure
calc
f.continuousPart s = f.continuousPart (s \ {x}) :=
(continuousPart_apply_diff _ _ _ (countable_singleton x)).symm
_ = f (univ \ f.discreteSupport ∩ (s \ {x})) := by simp [continuousPart]
_ = indicator (univ \ f.discreteSupport ∩ (s \ {x})) 1 x := rfl
_ = 0 := by simp
theorem toFunctions_toMeasure [MeasurableSpace α] (μ : Measure α) [IsFiniteMeasure μ] (s : Set α)
(hs : MeasurableSet s) :
μ.extensionToBoundedFunctions.toBoundedAdditiveMeasure s = μ.real s := by
simp only [ContinuousLinearMap.toBoundedAdditiveMeasure]
rw [extensionToBoundedFunctions_apply]
· simp [integral_indicator hs]
· simp only [coe_ofNormedAddCommGroupDiscrete]
have : Integrable (fun _ => (1 : ℝ)) μ := integrable_const (1 : ℝ)
apply
this.mono' (Measurable.indicator (@measurable_const _ _ _ _ (1 : ℝ)) hs).aestronglyMeasurable
apply Filter.Eventually.of_forall
exact norm_indicator_le_one _
theorem toFunctions_toMeasure_continuousPart [MeasurableSpace α] [MeasurableSingletonClass α]
(μ : Measure α) [IsFiniteMeasure μ] [NoAtoms μ] (s : Set α) (hs : MeasurableSet s) :
μ.extensionToBoundedFunctions.toBoundedAdditiveMeasure.continuousPart s = μ.real s := by
let f := μ.extensionToBoundedFunctions.toBoundedAdditiveMeasure
change f (univ \ f.discreteSupport ∩ s) = μ.real s
rw [toFunctions_toMeasure]; swap
· exact
MeasurableSet.inter
(MeasurableSet.univ.diff (Countable.measurableSet f.countable_discreteSupport)) hs
simp only [measureReal_def]
congr 1
rw [inter_comm, ← inter_diff_assoc, inter_univ]
exact measure_diff_null (f.countable_discreteSupport.measure_zero _)
end
/-!
### A set in `ℝ²` large along verticals, small along horizontals
We construct a subset of `ℝ²`, given as a family of sets, which is large along verticals (i.e.,
it only misses a countable set along each vertical) but small along horizontals (it is countable
along horizontals). Such a set cannot be measurable as it would contradict Fubini theorem.
We need the continuum hypothesis to construct it.
-/
theorem sierpinski_pathological_family (Hcont : #ℝ = ℵ₁) :
∃ f : ℝ → Set ℝ, (∀ x, (univ \ f x).Countable) ∧ ∀ y, {x : ℝ | y ∈ f x}.Countable := by
rcases Cardinal.ord_eq ℝ with ⟨r, hr, H⟩
refine ⟨fun x => {y | r x y}, fun x => ?_, fun y => ?_⟩
· have : univ \ {y | r x y} = {y | r y x} ∪ {x} := by
ext y
simp only [true_and, mem_univ, mem_setOf_eq, mem_insert_iff, union_singleton, mem_diff]
rcases trichotomous_of r x y with (h | rfl | h)
· simp only [h, not_or, false_iff, not_true]
constructor
· rintro rfl; exact irrefl_of r y h
· exact asymm h
· simp only [true_or, iff_true]; exact irrefl x
· simp only [h, iff_true, or_true]; exact asymm h
rw [this]
apply Countable.union _ (countable_singleton _)
rw [Cardinal.countable_iff_lt_aleph_one, ← Hcont]
exact Cardinal.card_typein_lt r x H
· rw [Cardinal.countable_iff_lt_aleph_one, ← Hcont]
exact Cardinal.card_typein_lt r y H
/-- A family of sets in `ℝ` which only miss countably many points, but such that any point is
contained in only countably many of them. -/
def spf (Hcont : #ℝ = ℵ₁) (x : ℝ) : Set ℝ :=
(sierpinski_pathological_family Hcont).choose x
theorem countable_compl_spf (Hcont : #ℝ = ℵ₁) (x : ℝ) : (univ \ spf Hcont x).Countable :=
(sierpinski_pathological_family Hcont).choose_spec.1 x
theorem countable_spf_mem (Hcont : #ℝ = ℵ₁) (y : ℝ) : {x | y ∈ spf Hcont x}.Countable :=
(sierpinski_pathological_family Hcont).choose_spec.2 y
/-!
### A counterexample for the Pettis integral
We construct a function `f` from `[0,1]` to a complete Banach space `B`, which is weakly measurable
(i.e., for any continuous linear form `φ` on `B` the function `φ ∘ f` is measurable), bounded in
norm (i.e., for all `x`, one has `‖f x‖ ≤ 1`), and still `f` has no Pettis integral.
This construction, due to Phillips, requires the continuum hypothesis. We will take for `B` the
space of all bounded functions on `ℝ`, with the supremum norm (no measure here, we are really
talking of everywhere defined functions). And `f x` will be the characteristic function of a set
which is large (it has countable complement), as in the Sierpinski pathological family.
-/
/-- A family of bounded functions `f_x` from `ℝ` (seen with the discrete topology) to `ℝ` (in fact
taking values in `{0, 1}`), indexed by a real parameter `x`, corresponding to the characteristic
functions of the different fibers of the Sierpinski pathological family -/
def f (Hcont : #ℝ = ℵ₁) (x : ℝ) : DiscreteCopy ℝ →ᵇ ℝ :=
ofNormedAddCommGroupDiscrete (indicator (spf Hcont x) 1) 1 (norm_indicator_le_one _)
theorem apply_f_eq_continuousPart (Hcont : #ℝ = ℵ₁) (φ : (DiscreteCopy ℝ →ᵇ ℝ) →L[ℝ] ℝ)
(x : ℝ) (hx : φ.toBoundedAdditiveMeasure.discreteSupport ∩ spf Hcont x = ∅) :
φ (f Hcont x) = φ.toBoundedAdditiveMeasure.continuousPart univ := by
set ψ := φ.toBoundedAdditiveMeasure
have : φ (f Hcont x) = ψ (spf Hcont x) := rfl
have U : univ = spf Hcont x ∪ univ \ spf Hcont x := by simp only [union_univ, union_diff_self]
rw [this, eq_add_parts, discretePart_apply, hx, ψ.empty, zero_add, U,
ψ.continuousPart.additive _ _ disjoint_sdiff_self_right,
ψ.continuousPart_apply_eq_zero_of_countable _ (countable_compl_spf Hcont x), add_zero]
theorem countable_ne (Hcont : #ℝ = ℵ₁) (φ : (DiscreteCopy ℝ →ᵇ ℝ) →L[ℝ] ℝ) :
{x | φ.toBoundedAdditiveMeasure.continuousPart univ ≠ φ (f Hcont x)}.Countable := by
have A :
{x | φ.toBoundedAdditiveMeasure.continuousPart univ ≠ φ (f Hcont x)} ⊆
{x | φ.toBoundedAdditiveMeasure.discreteSupport ∩ spf Hcont x ≠ ∅} := by
intro x hx
simp only [mem_setOf] at *
contrapose! hx
exact apply_f_eq_continuousPart Hcont φ x hx |>.symm
have B :
{x | φ.toBoundedAdditiveMeasure.discreteSupport ∩ spf Hcont x ≠ ∅} ⊆
⋃ y ∈ φ.toBoundedAdditiveMeasure.discreteSupport, {x | y ∈ spf Hcont x} := by
intro x hx
dsimp at hx
rw [← Ne, ← nonempty_iff_ne_empty] at hx
simp only [exists_prop, mem_iUnion, mem_setOf_eq]
exact hx
apply Countable.mono (Subset.trans A B)
exact Countable.biUnion (countable_discreteSupport _) fun a _ => countable_spf_mem Hcont a
theorem comp_ae_eq_const (Hcont : #ℝ = ℵ₁) (φ : (DiscreteCopy ℝ →ᵇ ℝ) →L[ℝ] ℝ) :
∀ᵐ x ∂volume.restrict (Icc (0 : ℝ) 1),
φ.toBoundedAdditiveMeasure.continuousPart univ = φ (f Hcont x) := by
apply ae_restrict_of_ae
refine measure_mono_null ?_ ((countable_ne Hcont φ).measure_zero _)
intro x
simp only [imp_self, mem_setOf_eq, mem_compl_iff]
theorem integrable_comp (Hcont : #ℝ = ℵ₁) (φ : (DiscreteCopy ℝ →ᵇ ℝ) →L[ℝ] ℝ) :
IntegrableOn (fun x => φ (f Hcont x)) (Icc 0 1) := by
have : IntegrableOn (fun _ => φ.toBoundedAdditiveMeasure.continuousPart univ) (Icc (0 : ℝ) 1)
volume := by simp
exact Integrable.congr this (comp_ae_eq_const Hcont φ)
theorem integral_comp (Hcont : #ℝ = ℵ₁) (φ : (DiscreteCopy ℝ →ᵇ ℝ) →L[ℝ] ℝ) :
∫ x in Icc 0 1, φ (f Hcont x) = φ.toBoundedAdditiveMeasure.continuousPart univ := by
rw [← integral_congr_ae (comp_ae_eq_const Hcont φ)]
simp
/-!
The next few statements show that the function `f Hcont : ℝ → (DiscreteCopy ℝ →ᵇ ℝ)` takes its
values in a complete space, is scalarly measurable, is everywhere bounded by `1`, and still has
no Pettis integral.
-/
example : CompleteSpace (DiscreteCopy ℝ →ᵇ ℝ) := by infer_instance
/-- The function `f Hcont : ℝ → (DiscreteCopy ℝ →ᵇ ℝ)` is scalarly measurable. -/
theorem measurable_comp (Hcont : #ℝ = ℵ₁) (φ : (DiscreteCopy ℝ →ᵇ ℝ) →L[ℝ] ℝ) :
Measurable fun x => φ (f Hcont x) := by
have : Measurable fun _ : ℝ => φ.toBoundedAdditiveMeasure.continuousPart univ := measurable_const
refine this.measurable_of_countable_ne ?_
exact countable_ne Hcont φ
/-- The function `f Hcont : ℝ → (DiscreteCopy ℝ →ᵇ ℝ)` is uniformly bounded by `1` in norm. -/
theorem norm_bound (Hcont : #ℝ = ℵ₁) (x : ℝ) : ‖f Hcont x‖ ≤ 1 :=
norm_ofNormedAddCommGroup_le _ zero_le_one (norm_indicator_le_one _)
/-- The function `f Hcont : ℝ → (DiscreteCopy ℝ →ᵇ ℝ)` has no Pettis integral. -/
theorem no_pettis_integral (Hcont : #ℝ = ℵ₁) :
¬∃ g : DiscreteCopy ℝ →ᵇ ℝ,
∀ φ : (DiscreteCopy ℝ →ᵇ ℝ) →L[ℝ] ℝ, ∫ x in Icc 0 1, φ (f Hcont x) = φ g := by
rintro ⟨g, h⟩
simp only [integral_comp] at h
have : g = 0 := by
ext x
have : g x = evalCLM ℝ x g := rfl
rw [this, ← h]
simp
simp only [this, ContinuousLinearMap.map_zero] at h
specialize h (volume.restrict (Icc (0 : ℝ) 1)).extensionToBoundedFunctions
simp_rw [toFunctions_toMeasure_continuousPart _ _ MeasurableSet.univ] at h
simp at h
end Phillips1940
end
end Counterexample |
.lake/packages/mathlib/Counterexamples/DirectSumIsInternal.lean | import Mathlib.Algebra.DirectSum.Module
import Mathlib.Algebra.Group.ConjFinite
import Mathlib.Data.Fintype.Lattice
import Mathlib.Tactic.FinCases
/-!
# Not all complementary decompositions of a module over a semiring make up a direct sum
This shows that while `ℤ≤0` and `ℤ≥0` are complementary `ℕ`-submodules of `ℤ`, which in turn
implies as a collection they are `iSupIndep` and that they span all of `ℤ`, they
do not form a decomposition into a direct sum.
This file demonstrates why `DirectSum.isInternal_submodule_of_iSupIndep_of_iSup_eq_top` must
take `Ring R` and not `Semiring R`.
-/
namespace Counterexample
theorem UnitsInt.one_ne_neg_one : (1 : ℤˣ) ≠ -1 := by decide
/-- Submodules of positive and negative integers, keyed by sign. -/
def withSign (i : ℤˣ) : Submodule ℕ ℤ :=
AddSubmonoid.toNatSubmodule <|
show AddSubmonoid ℤ from
{ carrier := {z | 0 ≤ i • z}
zero_mem' := show 0 ≤ i • (0 : ℤ) from (smul_zero _).ge
add_mem' := fun {x y} (hx : 0 ≤ i • x) (hy : 0 ≤ i • y) =>
show 0 ≤ i • (x + y) by
rw [smul_add]
exact add_nonneg hx hy }
local notation "ℤ≥0" => withSign 1
local notation "ℤ≤0" => withSign (-1)
theorem mem_withSign_one {x : ℤ} : x ∈ ℤ≥0 ↔ 0 ≤ x :=
show _ ≤ (_ : ℤˣ) • x ↔ _ by rw [one_smul]
theorem mem_withSign_neg_one {x : ℤ} : x ∈ ℤ≤0 ↔ x ≤ 0 :=
show _ ≤ (_ : ℤˣ) • x ↔ _ by rw [Units.neg_smul, le_neg, one_smul, neg_zero]
/-- The two submodules are complements. -/
theorem withSign.isCompl : IsCompl ℤ≥0 ℤ≤0 := by
constructor
· apply Submodule.disjoint_def.2
intro x hx hx'
exact le_antisymm (mem_withSign_neg_one.mp hx') (mem_withSign_one.mp hx)
· rw [codisjoint_iff_le_sup]
intro x _hx
obtain hp | hn := (le_refl (0 : ℤ)).ge_or_le x
· exact Submodule.mem_sup_left (mem_withSign_one.mpr hp)
· exact Submodule.mem_sup_right (mem_withSign_neg_one.mpr hn)
def withSign.independent : iSupIndep withSign := by
apply
(iSupIndep_pair UnitsInt.one_ne_neg_one _).mpr withSign.isCompl.disjoint
intro i
fin_cases i <;> simp
theorem withSign.iSup : iSup withSign = ⊤ := by
rw [← Finset.sup_univ_eq_iSup, UnitsInt.univ, Finset.sup_insert, Finset.sup_singleton]
exact withSign.isCompl.sup_eq_top
/-- But there is no embedding into `ℤ` from the direct sum. -/
theorem withSign.not_injective :
¬Function.Injective (DirectSum.toModule ℕ ℤˣ ℤ fun i => (withSign i).subtype) := by
intro hinj
let p1 : ℤ≥0 := ⟨1, mem_withSign_one.2 zero_le_one⟩
let n1 : ℤ≤0 := ⟨-1, mem_withSign_neg_one.2 <| neg_nonpos.2 zero_le_one⟩
let z :=
DirectSum.lof ℕ _ (fun i => withSign i) 1 p1 + DirectSum.lof ℕ _ (fun i => withSign i) (-1) n1
have : z ≠ 0 := by
intro h
replace h := DFunLike.congr_fun h 1
-- This used to be `rw`, but we need `erw` after https://github.com/leanprover/lean4/pull/2644
erw [DFinsupp.zero_apply, DFinsupp.add_apply, DFinsupp.single_eq_same,
DFinsupp.single_eq_of_ne UnitsInt.one_ne_neg_one, add_zero, Subtype.ext_iff,
Submodule.coe_zero] at h
apply zero_ne_one h.symm
apply hinj.ne this
rw [LinearMap.map_zero, LinearMap.map_add, DirectSum.toModule_lof, DirectSum.toModule_lof]
simp [p1, n1]
/-- And so they do not represent an internal direct sum. -/
theorem withSign.not_internal : ¬DirectSum.IsInternal withSign :=
withSign.not_injective ∘ And.left
end Counterexample |
.lake/packages/mathlib/Counterexamples/Motzkin.lean | import Mathlib.Tactic.LinearCombination
import Mathlib.Tactic.Positivity
/-!
# The Motzkin polynomial
The Motzkin polynomial is a well-known counterexample: it is nonnegative everywhere, but not
expressible as a polynomial sum of squares.
This file contains a proof of the first property (nonnegativity).
TODO: prove the second property.
-/
variable {K : Type*} [CommRing K] [LinearOrder K] [IsStrictOrderedRing K]
/-- The **Motzkin polynomial** is nonnegative.
This bivariate polynomial cannot be written as a sum of squares. -/
lemma motzkin_polynomial_nonneg (x y : K) :
0 ≤ x ^ 4 * y ^ 2 + x ^ 2 * y ^ 4 - 3 * x ^ 2 * y ^ 2 + 1 := by
by_cases hx : x = 0
· simp [hx]
have h : 0 < (x ^ 2 + y ^ 2) ^ 2 := by positivity
refine nonneg_of_mul_nonneg_left ?_ h
have H : 0 ≤ (x ^ 3 * y + x * y ^ 3 - 2 * x * y) ^ 2 * (1 + x ^ 2 + y ^ 2)
+ (x ^ 2 - y ^ 2) ^ 2 := by positivity
linear_combination H |
.lake/packages/mathlib/Counterexamples/EulerSumOfPowers.lean | import Mathlib.NumberTheory.FLT.Three
/-!
# Euler's sum of powers conjecture
Euler's sum of powers conjecture says that at least n nth powers of positive integers
are required to sum to an nth power of a positive integer.
This was an attempt to generalize Fermat's Last Theorem,
which is the special case of summing 2 nth powers.
We demonstrate the connection with FLT, prove that it's true for `n ≤ 3`,
and provide counterexamples for `n = 4` and `n = 5`.
The status of the conjecture for `n ≥ 6` is unknown.
https://en.wikipedia.org/wiki/Euler%27s_sum_of_powers_conjecture
http://euler.free.fr/
## TODO
* Formalize Elkies's construction of infinitely many coprime counterexamples for `n = 4`
https://www.ams.org/journals/mcom/1988-51-184/S0025-5718-1988-0930224-9/S0025-5718-1988-0930224-9.pdf
-/
namespace Counterexample
/-- Euler's sum of powers conjecture over a given semiring with a specific exponent. -/
abbrev SumOfPowersConjectureWith (R : Type*) [Semiring R] (n : ℕ) : Prop :=
∀ (a : List R) (b : R), 2 ≤ a.length → 0 ∉ a → b ≠ 0 →
(a.map (· ^ n)).sum = b ^ n → n ≤ a.length
/-- Euler's sum of powers conjecture over the naturals for a given exponent. -/
abbrev SumOfPowersConjectureFor (n : ℕ) : Prop := SumOfPowersConjectureWith ℕ n
/-- Euler's sum of powers conjecture over the naturals. -/
abbrev SumOfPowersConjecture : Prop := ∀ n, SumOfPowersConjectureFor n
/-- Euler's sum of powers conjecture over a given semiring with a specific exponent implies FLT. -/
theorem fermatLastTheoremWith_of_sumOfPowersConjectureWith (R : Type*) [Semiring R] :
∀ n ≥ 3, SumOfPowersConjectureWith R n → FermatLastTheoremWith R n := by
intro n hn conj a b c ha hb hc hsum
have : n ≤ 2 := conj [a, b] c (by simp) (by simp [ha.symm, hb.symm]) hc (by simpa)
cutsat
/-- Euler's sum of powers conjecture over the naturals implies FLT. -/
theorem fermatLastTheorem_of_sumOfPowersConjecture : SumOfPowersConjecture → FermatLastTheorem :=
fun conj n hn ↦ fermatLastTheoremWith_of_sumOfPowersConjectureWith ℕ n hn <| conj n
/-- For `n = 3`, Euler's sum of powers conjecture over a given semiring is equivalent to FLT. -/
theorem sumOfPowersConjectureWith_three_iff_fermatLastTheoremWith_three (R : Type*) [Semiring R] :
SumOfPowersConjectureWith R 3 ↔ FermatLastTheoremWith R 3 := by
refine ⟨fermatLastTheoremWith_of_sumOfPowersConjectureWith R 3 (by rfl), ?_⟩
intro FLT a b ha ha₀ hb₀ hsum
contrapose! hsum
have ⟨x, y, hxy⟩ := a.length_eq_two.mp <| by cutsat
simp [hxy, FLT x y b (by grind) (by grind) hb₀]
/-- Euler's sum of powers conjecture over the naturals is true for `n ≤ 3`. -/
theorem sumOfPowersConjectureFor_le_three : ∀ n ≤ 3, SumOfPowersConjectureFor n := by
intro n hn
by_cases h3 : n = 3
· exact h3 ▸ (sumOfPowersConjectureWith_three_iff_fermatLastTheoremWith_three _).mpr
fermatLastTheoremThree
cutsat
/-- Given a ring homomorphism from `R` to `S` with no nontrivial zeros,
the conjecture over `S` implies the conjecture over `R`. -/
lemma sumOfPowersConjecture_of_ringHom {R S : Type*} [Semiring R] [Semiring S] {f : R →+* S}
(hf : ∀ x, f x = 0 → x = 0) {n : ℕ} (conj : SumOfPowersConjectureWith S n) :
SumOfPowersConjectureWith R n := by
intro a b ha ha₀ hb hsum
have h : (· ^ n) ∘ f = f ∘ (· ^ n) := by ext; simp
convert conj (a.map f) (f b) ?_ ?_ ?_ (by simp [h, hsum, List.sum_map_hom]) <;> grind
/-- Given an injective ring homomorphism from `R` to `S`,
the conjecture over `S` implies the conjecture over `R`. -/
lemma sumOfPowersConjecture_of_injective {R S : Type*} [Semiring R] [Semiring S] {f : R →+* S}
(hf : Function.Injective f) {n : ℕ} (h : SumOfPowersConjectureWith S n) :
SumOfPowersConjectureWith R n :=
sumOfPowersConjecture_of_ringHom (fun _ _ ↦ hf <| by rwa [map_zero]) h
/--
The first counterexample was found by Leon J. Lander and Thomas R. Parkin in 1966
through a computer search, disproving the conjecture.
https://www.ams.org/journals/bull/1966-72-06/S0002-9904-1966-11654-3/S0002-9904-1966-11654-3.pdf
This is also the smallest counterexample for `n = 5`.
-/
theorem sumOfPowersConjectureFor_five_false : ¬SumOfPowersConjectureFor 5 := by
intro conj
let a := [27, 84, 110, 133]
let b := 144
have : 5 ≤ 4 := conj a b (by simp [a]) (by simp [a]) (by simp) (by decide)
cutsat
/--
The first counterexample for `n = 4` was found by Noam D. Elkies in October 1988:
`a := [2_682_440, 15_365_639, 18_796_760]`, `b := 20_615_673`
https://www.ams.org/journals/mcom/1988-51-184/S0025-5718-1988-0930224-9/S0025-5718-1988-0930224-9.pdf
In this paper, Elkies constructs infinitely many solutions to `a^4 + b^4 + c^4 = d^4` for coprime
`a, b, c, d`, which provide infinitely many coprime counterexamples for the case `n = 4`.
Here we use the smallest counterexample for `n = 4`, which was found a month later by Roger E. Frye
https://ieeexplore.ieee.org/document/74138
-/
theorem sumOfPowersConjectureFor_four_false : ¬SumOfPowersConjectureFor 4 := by
intro conj
let a := [95_800, 217_519, 414_560]
let b := 422_481
have : 4 ≤ 3 := conj a b (by simp [a]) (by simp [a]) (by simp) (by decide)
cutsat
/--
For all `(k, m, n)` we define the Diophantine equation `∑ x_i ^ k = ∑ y_i ^ k`
where `x` and `y` are disjoint with length `m` and `n` respectively.
This is a generalization of the diophantine equation of Euler's sum of powers conjecture.
-/
abbrev ExistsEqualSumsOfLikePowersFor (R : Type*) [Semiring R] (k m n : ℕ) : Prop :=
∃ (x y : List R), (x.length = m) ∧ (y.length = n) ∧ (0 ∉ x) ∧ (0 ∉ y) ∧ (List.Disjoint x y) ∧
(x.map (· ^ k)).sum = (y.map (· ^ k)).sum
/-- Euler's sum of powers conjecture for `k` restricts solutions for `(k, m, 1)`. -/
theorem existsEqualSumsOfLikePowersFor_of_sumOfPowersConjectureWith (R : Type*) [Semiring R]
(k m : ℕ) (hm : 2 ≤ m) :
SumOfPowersConjectureWith R k → ExistsEqualSumsOfLikePowersFor R k m 1 → k ≤ m := by
intro conj ⟨x, y, hx, hy, hx₀, hy₀, hdisj, hsum⟩
simp only [List.map_cons, List.map_nil, List.sum_cons, List.sum_nil, add_zero,
List.eq_cons_of_length_one hy] at hsum
exact hx ▸ conj x (y.get ⟨0, _⟩) (by cutsat) hx₀ (by grind) hsum
/--
After the first counterexample was found, Leon J. Lander, Thomas R. Parkin, and John Selfridge
made a similar conjecture that is not amenable to the counterexamples found so far.
The status of this conjecture is unknown.
https://en.wikipedia.org/wiki/Lander,_Parkin,_and_Selfridge_conjecture
https://www.ams.org/journals/mcom/1967-21-099/S0025-5718-1967-0222008-0/S0025-5718-1967-0222008-0.pdf
-/
abbrev LanderParkinSelfridgeConjecture (R : Type*) [Semiring R] (k m n : ℕ) : Prop :=
ExistsEqualSumsOfLikePowersFor R k m n → k ≤ m + n
/-- Euler's sum of powers conjecture for `k` implies the Lander, Parkin, and Selfridge conjecture
for `(k, m, 1)`. -/
theorem LanderParkinSelfridgeConjecture_of_sumOfPowersConjectureWith (R : Type*) [Semiring R]
(k m : ℕ) (hm : 2 ≤ m) :
SumOfPowersConjectureWith R k → LanderParkinSelfridgeConjecture R k m 1 := by
intro conj hsum
have := existsEqualSumsOfLikePowersFor_of_sumOfPowersConjectureWith R k m hm conj hsum
cutsat
end Counterexample |
.lake/packages/mathlib/Counterexamples/DiscreteTopologyNonDiscreteUniformity.lean | import Mathlib.Analysis.SpecificLimits.Basic
/-!
# Discrete uniformities and discrete topology
Exactly as different metrics can induce equivalent topologies on a space, it is possible that
different uniform structures (a notion that generalises that of a metric structure) induce the same
topology on a space. In this file we are concerned in particular with the *discrete topology*,
formalised using the class `DiscreteTopology`, and the *discrete uniformity*, that is the bottom
element of the lattice of uniformities on a type (see `bot_uniformity`).
The theorem `discreteTopology_of_discrete_uniformity` shows that the topology induced by the
discrete uniformity is the discrete one, but it is well-known that the converse might not hold in
general, along the lines of the above discussion. We explicitly produce a metric and a uniform
structure on a space (on `ℕ`, actually) that are not discrete, yet induce the discrete topology.
To check that a certain uniformity is not discrete, recall that once a type `α` is endowed with a
uniformity, it is possible to speak about `Cauchy` filters on `a` and it is quite easy to see that
if the uniformity on `a` is the discrete one, a filter is Cauchy if and only if it coincides with
the principal filter `𝓟 {x}` (see `Filter.principal`) for some `x : α`. This is the
declaration `UniformSpace.DiscreteUnif.eq_const_of_cauchy` in Mathlib.
A special case of this result is the intuitive observation that a sequence `a : ℕ → ℕ` can be a
Cauchy sequence if and only if it is eventually constant: when claiming this equivalence, one is
implicitly endowing `ℕ` with the metric inherited from `ℝ`, that induces the discrete uniformity
on `ℕ`. Hence, the intuition suggesting that a Cauchy sequence, whose
terms are "closer and closer to each other", valued in `ℕ` must be eventually constant for
*topological* reasons, namely the fact that `ℕ` is a discrete topological space, is *wrong* in the
sense that the reason is intrinsically "metric". In particular, if a non-constant sequence (like
the identity `id : ℕ → ℕ` is Cauchy, then the uniformity is certainly *not discrete*.
## The counterexamples
We produce two counterexamples: in the first section `Metric` we construct a metric and in the
second section `SetPointUniformity` we construct a uniformity, explicitly as a filter on `ℕ × ℕ`.
They basically coincide, and the difference of the examples lies in their flavours.
### The metric
We begin by defining a metric on `ℕ` (see `dist_def`) that
1. Induces the discrete topology, as proven in `TopIsDiscrete`;
2. Is not the discrete metric, in particular because the identity is a Cauchy sequence, as proven
in `idIsCauchy`
The definition is simply `dist m n = |2 ^ (- n : ℤ) - 2 ^ (- m : ℤ)|`, and I am grateful to
Anatole Dedecker for his suggestion.
### The point-set-theoretic uniformity
A uniformity on `ℕ` is a filter on `ℕ × ℕ` satisfying some properties: we define a sequence of
subsets `fundamentalEntourage n : (Set ℕ × ℕ)` (indexed by `n : ℕ`) and we observe it satisfies the
condition needed to be a basis of a filter: moreover, the filter generated by this basis satisfies
the condition for being a uniformity, and this is the uniformity we put on `ℕ`.
For each `n`, the set `fundamentalEntourage n : Set (ℕ × ℕ)` consists of the `n+1` points
`{(0,0),(1,1)...(n,n)}` on the diagonal; together with the half plane `{(x,y) | n ≤ x ∧ n ≤ y}`
That this collection can be used as a filter basis is proven in the definition `counterBasis` and
that the filter `counterBasis.filterBasis` is a uniformity is proven in the definition
`counterCoreUniformity`.
This induces the discrete topology, as proven in `TopIsDiscrete` and the `atTop` filter is Cauchy
(see `atTopIsCauchy`): that this specializes to the statement that the identity sequence
`id : ℕ → ℕ` is Cauchy is proven in `idIsCauchy`.
## Implementation details
Since most of the statements evolve around membership of explicit natural numbers (framed by some
inequality) to explicit subsets, many proofs are easily closed by `aesop` or `omega` or `linarith`.
### References
* [N. Bourbaki, *General Topology*, Chapter II][bourbaki1966]
-/
open Set Function Filter Metric
/- We remove the "usual" instances of (discrete) topological space and of (discrete) uniform space
from `ℕ`. -/
attribute [-instance] instTopologicalSpaceNat instUniformSpaceNat Nat.instDist
section Metric
noncomputable local instance : PseudoMetricSpace ℕ where
dist := fun n m ↦ |2 ^ (- n : ℤ) - 2 ^ (- m : ℤ)|
dist_self := by simp only [zpow_neg, zpow_natCast, sub_self, abs_zero, implies_true]
dist_comm := fun _ _ ↦ abs_sub_comm ..
dist_triangle := fun _ _ _ ↦ abs_sub_le ..
@[simp]
lemma dist_def {n m : ℕ} : dist n m = |2 ^ (-n : ℤ) - 2 ^ (-m : ℤ)| := rfl
lemma Int.eq_of_pow_sub_le {d : ℕ} {m n : ℤ} (hd1 : 1 < d)
(h : |(d : ℝ) ^ (-m) - d ^ (-n)| < d ^ (-n - 1)) : m = n := by
have hd0 : 0 < d := one_pos.trans hd1
replace h : |(1 : ℝ) - d ^ (n - m)| < (d : ℝ)⁻¹ := by
rw [← mul_lt_mul_iff_of_pos_left (a := (d : ℝ) ^ (-n)) (zpow_pos _ _),
← abs_of_nonneg (a := (d : ℝ) ^ (-n)) (le_of_lt <| zpow_pos _ _), ← abs_mul, mul_sub, mul_one,
← zpow_add₀ <| Nat.cast_ne_zero.mpr (ne_of_gt hd0), sub_eq_add_neg (b := m),
neg_add_cancel_left, ← abs_neg, neg_sub,
abs_of_nonneg (a := (d : ℝ) ^ (-n)) (le_of_lt <| zpow_pos _ _), ← zpow_neg_one,
← zpow_add₀ <| Nat.cast_ne_zero.mpr (ne_of_gt hd0), ← sub_eq_add_neg]
· exact h
all_goals exact Nat.cast_pos'.mpr hd0
by_cases H : (m : ℤ) ≤ n
· obtain ⟨a, ha⟩ := Int.eq_ofNat_of_zero_le (sub_nonneg.mpr H)
rw [ha, ← mul_lt_mul_iff_of_pos_left (a := (d : ℝ)) <| Nat.cast_pos'.mpr hd0,
mul_inv_cancel₀ <| Nat.cast_ne_zero.mpr (ne_of_gt hd0),
← abs_of_nonneg (a := (d : ℝ)) <| Nat.cast_nonneg' d, ← abs_mul,
show |(d : ℝ) * (1 - |(d : ℝ)| ^ (a : ℤ))| = |(d : ℤ) * (1 - |(d : ℤ)| ^ a)| by norm_cast,
← Int.cast_one (R := ℝ), Int.cast_lt, Int.abs_lt_one_iff, Int.mul_eq_zero,
sub_eq_zero, eq_comm (a := 1), pow_eq_one_iff_cases] at h
simp only [Nat.cast_eq_zero, ne_of_gt hd0, Nat.abs_cast, Nat.cast_eq_one, ne_of_gt hd1,
Int.reduceNeg, reduceCtorEq, false_and, or_self, or_false, false_or] at h
rwa [h, Nat.cast_zero, sub_eq_zero, eq_comm] at ha
· have h1 : (d : ℝ) ^ (n - m) ≤ 1 - (d : ℝ)⁻¹ := calc
(d : ℝ) ^ (n - m) ≤ (d : ℝ)⁻¹ := by
rw [← zpow_neg_one]
apply zpow_right_mono₀ <| Nat.one_le_cast.mpr hd0
linarith
_ ≤ 1 - (d : ℝ)⁻¹ := by
rw [inv_eq_one_div, one_sub_div <| Nat.cast_ne_zero.mpr (ne_of_gt hd0),
div_le_div_iff_of_pos_right <| Nat.cast_pos'.mpr hd0, le_sub_iff_add_le]
norm_cast
linarith [sub_lt_of_abs_sub_lt_right (a := (1 : ℝ)) (b := d ^ (n - m)) (c := d⁻¹) h]
lemma ball_eq_singleton {n : ℕ} : Metric.ball n ((2 : ℝ) ^ (-n - 1 : ℤ)) = {n} := by
ext m
constructor
· zify [zpow_natCast, mem_ball, dist_def, mem_singleton_iff]
apply Int.eq_of_pow_sub_le one_lt_two
· intro H
rw [H, mem_ball, dist_self]
apply zpow_pos two_pos
theorem TopIsDiscrete : DiscreteTopology ℕ := by
apply discreteTopology_iff_isOpen_singleton.mpr
intro
simpa only [← ball_eq_singleton] using isOpen_ball
lemma idIsCauchy : CauchySeq (id : ℕ → ℕ) := by
rw [Metric.cauchySeq_iff]
refine fun ε ↦ Metric.cauchySeq_iff.mp
(@cauchySeq_of_le_geometric_two ℝ _ 1 (fun n ↦ 2 ^(-n : ℤ)) fun n ↦ le_of_eq ?_) ε
simp only [Nat.cast_add, Nat.cast_one, neg_add_rev, Int.reduceNeg, one_div]
rw [Real.dist_eq, zpow_add' <| Or.intro_left _ two_ne_zero]
calc
|2 ^ (- n : ℤ) - 2 ^ (-1 : ℤ) * 2 ^ (- n : ℤ)|
_ = |(1 - (2 : ℝ)⁻¹) * 2 ^ (- n : ℤ)| := by rw [← one_sub_mul, zpow_neg_one]
_ = |2⁻¹ * 2 ^ (-(n : ℤ))| := by congr; rw [inv_eq_one_div 2, sub_half 1]
_ = 2⁻¹ / 2 ^ n := by rw [zpow_neg, abs_mul, abs_inv, abs_inv, inv_eq_one_div,
Nat.abs_ofNat, one_div, zpow_natCast, abs_pow, ← div_eq_mul_inv, Nat.abs_ofNat]
end Metric
section SetPointUniformity
/- As the `instance PseudoMetricSpace ℕ` declared in the previous section was local, `ℕ` has no
topology at this point. We are going to define a non-discrete uniform structure (just using the
filter-based definition), that will endow it with a topology that we will eventually show to be
discrete. -/
/-- The fundamental entourages (index by `n : ℕ`) used to construct a basis of the uniformity: for
each `n`, the set `fundamentalEntourage n : Set (ℕ × ℕ)` consists of the `n+1` points
`{(0,0),(1,1)...(n,n)}` on the diagonal; together with the half plane `{(x,y) | n ≤ x ∧ n ≤ y}`. -/
def fundamentalEntourage (n : ℕ) : Set (ℕ × ℕ) :=
(⋃ i : Icc 0 n, {((i : ℕ), (i : ℕ))}) ∪ Set.Ici (n , n)
@[simp]
lemma fundamentalEntourage_ext (t : ℕ) (T : Set (ℕ × ℕ)) : fundamentalEntourage t = T ↔
T = (⋃ i : Icc 0 t, {((i : ℕ), (i : ℕ))}) ∪ Set.Ici (t , t) := by
simpa only [fundamentalEntourage] using eq_comm
lemma mem_range_fundamentalEntourage (S : Set (ℕ × ℕ)) :
S ∈ (range fundamentalEntourage) ↔ ∃ n, fundamentalEntourage n = S := by
simp only [Set.mem_range, Eq.symm]
lemma mem_fundamentalEntourage (n : ℕ) (P : ℕ × ℕ) : P ∈ fundamentalEntourage n ↔
(n ≤ P.1 ∧ n ≤ P.2) ∨ (P.1 = P.2) := by
refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩
· simp only [fundamentalEntourage, iUnion_singleton_eq_range, mem_union, mem_range,
Subtype.exists, mem_Icc, zero_le, true_and, exists_prop', nonempty_prop, mem_Ici] at h
rcases h with h | h
· apply Or.inr
rw [((h.choose_spec).2).symm]
· exact Or.inl h
· simp only [iUnion_singleton_eq_range, mem_union, mem_range, Subtype.exists, mem_Icc, zero_le,
true_and, exists_prop', nonempty_prop, mem_Ici, fundamentalEntourage]
rcases h with h | h
· exact Or.inr h
· cases le_total n P.1 with
| inl h_le => exact Or.inr ⟨h_le, h ▸ h_le⟩
| inr h_le => exact Or.inl ⟨P.1, ⟨h_le, congrArg _ h⟩⟩
/-- The collection `fundamentalEntourage` satisfies the axioms to be a basis for a filter on
`ℕ × ℕ` and gives rise to a term in the relevant type. -/
def counterBasis : FilterBasis (ℕ × ℕ) where
sets := range fundamentalEntourage
nonempty := range_nonempty _
inter_sets := by
intro S T hS hT
obtain ⟨s, hs⟩ := hS
obtain ⟨t, ht⟩ := hT
simp only [mem_range, subset_inter_iff, exists_exists_eq_and, fundamentalEntourage]
use max t s
refine ⟨fun ⟨P1, P2⟩ hP ↦ ?_, fun ⟨P1, P2⟩ hP ↦ ?_⟩ <;> rcases hP with h | h
· simp only [iUnion_singleton_eq_range, mem_range, Prod.mk.injEq, Subtype.exists,
exists_and_left, exists_eq_left] at h
simpa only [← hs, mem_fundamentalEntourage] using Or.inr h.2
· simpa only [← hs, mem_fundamentalEntourage] using Or.inl
⟨le_trans (by omega) h.1, le_trans (by omega) h.2⟩
· simp only [iUnion_singleton_eq_range, mem_range, Prod.mk.injEq, Subtype.exists,
exists_and_left, exists_eq_left] at h
simpa only [← ht, mem_fundamentalEntourage] using Or.inr h.2
· simp only [mem_Ici, Prod.mk_le_mk] at h
simpa only [← ht, mem_fundamentalEntourage] using Or.inl ⟨le_trans
(by omega) h.1, le_trans (by omega) h.2⟩
@[simp]
lemma mem_counterBasis_iff (S : Set (ℕ × ℕ)) :
S ∈ counterBasis ↔ S ∈ range fundamentalEntourage := by
dsimp [counterBasis]
rfl
/-- The "crude" uniform structure, without topology, simply as a the filter generated by `Basis`
and satisfying the axioms for being a uniformity. We later extract the topology `counterTopology`
generated by it and bundle `counterCoreUniformity` and `counterTopology` in a uniform structure
on `ℕ`, proving in passing that `counterTopology = ⊥`. -/
def counterCoreUniformity : UniformSpace.Core ℕ := by
apply UniformSpace.Core.mkOfBasis counterBasis <;>
intro S hS
· obtain ⟨n, hn⟩ := hS
simp only [fundamentalEntourage_ext, iUnion_singleton_eq_range] at hn
simp only [hn, mem_union, mem_range, Prod.mk.injEq, and_self, Subtype.exists, mem_Icc, zero_le,
true_and, exists_prop', nonempty_prop, exists_eq_right, mem_Ici, Prod.mk_le_mk]
omega
· refine ⟨S, hS, ?_⟩
obtain ⟨n, hn⟩ := hS
simp only [fundamentalEntourage_ext, iUnion_singleton_eq_range] at hn
simp only [hn, preimage_union, union_subset_iff]
constructor
· apply subset_union_of_subset_left (subset_of_eq _)
aesop
· apply subset_union_of_subset_right (subset_of_eq _)
aesop
· refine ⟨S, hS, ?_⟩
obtain ⟨n, hn⟩ := hS
simp only [fundamentalEntourage_ext, iUnion_singleton_eq_range] at hn
simp only [hn]
rintro ⟨P1, P2⟩ ⟨m, h1, h2⟩
simp only [mem_union, mem_range, Prod.mk.injEq, Subtype.exists, mem_Icc, zero_le, true_and,
exists_and_left, exists_prop', nonempty_prop, exists_eq_left, mem_Ici, Prod.mk_le_mk] at h1 h2
aesop
/-- The topology on `ℕ` induced by the "crude" uniformity -/
instance counterTopology : TopologicalSpace ℕ := counterCoreUniformity.toTopologicalSpace
/-- The uniform structure on `ℕ` bundling together the "crude" uniformity and the topology -/
instance counterUniformity : UniformSpace ℕ := UniformSpace.ofCore counterCoreUniformity
lemma HasBasis_counterUniformity :
(uniformity ℕ).HasBasis (fun _ ↦ True) fundamentalEntourage := by
change counterCoreUniformity.uniformity.HasBasis (fun _ ↦ True) fundamentalEntourage
simp only [Filter.hasBasis_iff, true_and]
intro T
refine ⟨fun ⟨s, ⟨⟨r, hr⟩, hs⟩⟩ ↦ ⟨r, subset_of_eq_of_subset hr hs⟩ , fun ⟨n, hn⟩ ↦ ?_⟩
exact (@FilterBasis.mem_filter_iff _ counterBasis T).mpr ⟨fundamentalEntourage n, by simp, hn⟩
/-- A proof that the topology on `ℕ` induced by the "crude" uniformity `counterCoreUniformity`
(or by `counterUniformity` tout-court, since they are `defeq`) is discrete -/
theorem TopIsDiscrete' : DiscreteTopology ℕ := by
rw [discreteTopology_iff_nhds]
intro n
rw [nhds_eq_comap_uniformity']
apply Filter.ext
intro S
simp only [Filter.mem_comap, Filter.mem_pure]
have := @Filter.HasBasis.mem_uniformity_iff _ _ _ _ _ HasBasis_counterUniformity
refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩
· simp_rw [this] at h
obtain ⟨T, ⟨⟨i, ⟨-, h1⟩⟩, h2⟩⟩ := h
apply h2 (h1 _ _ _)
rw [mem_fundamentalEntourage]
aesop
· refine ⟨fundamentalEntourage (n + 1), ?_, ?_⟩
· change fundamentalEntourage (n + 1) ∈ counterCoreUniformity.uniformity
exact @Filter.HasBasis.mem_of_mem (ℕ × ℕ) ℕ counterCoreUniformity.uniformity (fun _ ↦ True)
fundamentalEntourage (n + 1) HasBasis_counterUniformity trivial
· simp only [preimage_subset_iff, mem_fundamentalEntourage, add_le_iff_nonpos_right,
nonpos_iff_eq_zero, one_ne_zero, and_false, false_or]
exact fun _ a ↦ mem_of_eq_of_mem a h
/- With respect to the above uniformity, the `atTop` filter is Cauchy; in particular, it is not of
the form `𝓟 {x}` for any `x`, although the topology is discrete. This implies in passing that this
uniformity is not discrete. -/
lemma atTopIsCauchy : Cauchy (atTop : Filter ℕ) := by
rw [HasBasis_counterUniformity.cauchy_iff]
refine ⟨atTop_neBot, fun i _ ↦ ?_⟩
simp_rw [mem_fundamentalEntourage, mem_atTop_sets, ge_iff_le]
exact ⟨Ici i, ⟨⟨i, fun _ hb ↦ hb⟩, fun _ hx _ hy ↦ Or.inl ⟨hx, hy⟩⟩⟩
/-- We find the same result about the identity map found in `idIsCauchy`, without using any metric
structure. -/
lemma idIsCauchy' : CauchySeq (id : ℕ → _) := ⟨map_neBot, cauchy_iff_le.mp atTopIsCauchy⟩
end SetPointUniformity |
.lake/packages/mathlib/Counterexamples/CanonicallyOrderedCommSemiringTwoMul.lean | import Mathlib.Algebra.Ring.Subsemiring.Order
import Mathlib.Data.ZMod.Basic
/-!
A canonically ordered commutative semiring with two different elements `a` and `b` such that
`a ≠ b` and `2 * a = 2 * b`. Thus, multiplication by a fixed non-zero element of a canonically
ordered semiring need not be injective. In particular, multiplying by a strictly positive element
need not be strictly monotone.
Recall that a canonically ordered commutative semiring is a commutative semiring with a partial
ordering that is "canonical" in the sense that the inequality `a ≤ b` holds if and only if there is
a `c` such that `a + c = b`. There are several compatibility conditions among
addition/multiplication and the order relation. The point of the counterexample is to show that
monotonicity of multiplication cannot be strengthened to **strict** monotonicity.
Reference:
https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/canonically_ordered.20pathology
-/
namespace Counterexample
theorem mem_zmod_2 (a : ZMod 2) : a = 0 ∨ a = 1 := by
rcases a with ⟨_ | _, _ | _ | _ | _⟩
· exact Or.inl rfl
· exact Or.inr rfl
theorem add_self_zmod_2 (a : ZMod 2) : a + a = 0 := by rcases mem_zmod_2 a with (rfl | rfl) <;> rfl
namespace Nxzmod2
variable {a b : ℕ × ZMod 2}
/-- The preorder relation on `ℕ × ℤ/2ℤ` where we only compare the first coordinate,
except that we leave incomparable each pair of elements with the same first component.
For instance, `∀ α, β ∈ ℤ/2ℤ`, the inequality `(1,α) ≤ (2,β)` holds,
whereas, `∀ n ∈ ℤ`, the elements `(n,0)` and `(n,1)` are incomparable. -/
instance preN2 : PartialOrder (ℕ × ZMod 2) where
le x y := x = y ∨ x.1 < y.1
le_refl a := Or.inl rfl
le_trans x y z xy yz := by
rcases xy with (rfl | xy)
· exact yz
· rcases yz with (rfl | yz)
· exact Or.inr xy
· exact Or.inr (xy.trans yz)
le_antisymm := by
intro a b ab ba
obtain ab | ab := ab
· exact ab
· obtain ba | ba := ba
· exact ba.symm
· exact (Nat.lt_asymm ab ba).elim
instance csrN2 : CommSemiring (ℕ × ZMod 2) := by infer_instance
instance csrN21 : AddCancelCommMonoid (ℕ × ZMod 2) :=
{ Nxzmod2.csrN2 with add_left_cancel := fun a _ _ h => (add_right_inj a).mp h }
/-- A strict inequality forces the first components to be different. -/
@[simp]
theorem lt_def : a < b ↔ a.1 < b.1 := by
refine ⟨fun h => ?_, fun h => ?_⟩
· rcases h with ⟨rfl | a1, h1⟩
· exact (not_or.mp h1).1.elim rfl
· exact a1
refine ⟨Or.inr h, not_or.mpr ⟨fun k => ?_, not_lt.mpr h.le⟩⟩
rw [k] at h
exact Nat.lt_asymm h h
instance : ZeroLEOneClass (ℕ × ZMod 2) :=
⟨by dsimp only [LE.le]; decide⟩
instance : PosMulStrictMono (ℕ × ZMod 2) where
mul_lt_mul_of_pos_left a ha b c hbc := by rw [lt_def] at *; exact mul_lt_mul_of_pos_left hbc ha
instance : MulPosStrictMono (ℕ × ZMod 2) where
mul_lt_mul_of_pos_right a ha b c hbc := by rw [lt_def] at *; exact mul_lt_mul_of_pos_right hbc ha
instance isStrictOrderedRing_N2 : IsStrictOrderedRing (ℕ × ZMod 2) where
add_le_add_left := by
rintro a b (rfl | ab) c
· rfl
· exact .inr (by simpa)
le_of_add_le_add_left := by
rintro a b c (hbc | hbc)
· exact (add_right_injective _ hbc).le
· exact .inr (by simpa using hbc)
end Nxzmod2
namespace ExL
open Nxzmod2 Subtype
/-- Initially, `L` was defined as the subsemiring closure of `(1,0)`. -/
def L : Type :=
{ l : ℕ × ZMod 2 // l ≠ (0, 1) }
theorem add_L {a b : ℕ × ZMod 2} (ha : a ≠ (0, 1)) (hb : b ≠ (0, 1)) : a + b ≠ (0, 1) := by
rcases a with ⟨a, a2⟩
rcases b with ⟨b, b2⟩
match b with
| 0 =>
rcases mem_zmod_2 b2 with (rfl | rfl)
· simp [ha, -Prod.mk.injEq]
· cases hb rfl
| b + 1 =>
simp
theorem mul_L {a b : ℕ × ZMod 2} (ha : a ≠ (0, 1)) (hb : b ≠ (0, 1)) : a * b ≠ (0, 1) := by
rcases a with ⟨a, a2⟩
rcases b with ⟨b, b2⟩
cases b
· rcases mem_zmod_2 b2 with (rfl | rfl) <;> rcases mem_zmod_2 a2 with (rfl | rfl) <;>
simp only [Prod.mk_mul_mk, mul_zero, mul_one, ne_eq, Prod.mk.injEq, zero_ne_one, and_false,
not_false_eq_true, not_true_eq_false]
exact hb rfl
cases a
· rcases mem_zmod_2 b2 with (rfl | rfl) <;> rcases mem_zmod_2 a2 with (rfl | rfl) <;>
simp only [Prod.mk_mul_mk, mul_zero, zero_mul, mul_one, ne_eq, Prod.mk.injEq, zero_ne_one,
and_false, not_false_eq_true, not_true_eq_false]
exact ha rfl
· simp [mul_ne_zero _ _, Nat.succ_ne_zero _]
/-- The subsemiring corresponding to the elements of `L`, used to transfer instances. -/
def lSubsemiring : Subsemiring (ℕ × ZMod 2) where
carrier := {l | l ≠ (0, 1)}
zero_mem' := by decide
one_mem' := by decide
add_mem' := add_L
mul_mem' := mul_L
instance : CommSemiring L :=
lSubsemiring.toCommSemiring
instance : PartialOrder L :=
Subtype.partialOrder _
instance : IsOrderedRing L :=
lSubsemiring.toIsOrderedRing
instance inhabited : Inhabited L :=
⟨1⟩
theorem bot_le : ∀ a : L, 0 ≤ a := by
rintro ⟨⟨an, a2⟩, ha⟩
cases an
· rcases mem_zmod_2 a2 with (rfl | rfl)
· rfl
· exact (ha rfl).elim
· refine Or.inr ?_
exact Nat.succ_pos _
instance orderBot : OrderBot L where
bot := 0
bot_le := bot_le
theorem exists_add_of_le : ∀ a b : L, a ≤ b → ∃ c, b = a + c := by
rintro a ⟨b, _⟩ (⟨rfl, rfl⟩ | h)
· exact ⟨0, (add_zero _).symm⟩
· exact
⟨⟨b - a.1, fun H => (tsub_pos_of_lt h).ne' (Prod.mk_inj.1 H).1⟩,
Subtype.ext <| Prod.ext (add_tsub_cancel_of_le h.le).symm (add_sub_cancel _ _).symm⟩
theorem le_self_add : ∀ a b : L, a ≤ a + b := by
rintro a ⟨⟨bn, b2⟩, hb⟩
obtain rfl | h := Nat.eq_zero_or_pos bn
· obtain rfl | rfl := mem_zmod_2 b2
· exact Or.inl (Prod.ext (add_zero _).symm (add_zero _).symm)
· exact (hb rfl).elim
· exact Or.inr ((lt_add_iff_pos_right _).mpr h)
theorem eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : L, a * b = 0 → a = 0 ∨ b = 0 := by
rintro ⟨⟨a, a2⟩, ha⟩ ⟨⟨b, b2⟩, hb⟩ ab1
injection ab1 with ab
injection ab with abn ab2
rw [mul_eq_zero] at abn
rcases abn with (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩)
· refine Or.inl ?_
rcases mem_zmod_2 a2 with (rfl | rfl)
· rfl
· exact (ha rfl).elim
· refine Or.inr ?_
rcases mem_zmod_2 b2 with (rfl | rfl)
· rfl
· exact (hb rfl).elim
instance : CommSemiring L := inferInstance
instance : PartialOrder L := inferInstance
instance : IsOrderedRing L := inferInstance
instance : CanonicallyOrderedAdd L where
exists_add_of_le := exists_add_of_le _ _
le_add_self a b := by rw [add_comm]; exact le_self_add a b
le_self_add := le_self_add
instance : NoZeroDivisors L where
eq_zero_or_eq_zero_of_mul_eq_zero := @(eq_zero_or_eq_zero_of_mul_eq_zero)
/-- The elements `(1,0)` and `(1,1)` of `L` are different, but their doubles coincide.
-/
example : ∃ a b : L, a ≠ b ∧ 2 * a = 2 * b := by
refine ⟨⟨(1, 0), by simp⟩, 1, fun h : (⟨(1, 0), _⟩ : L) = ⟨⟨1, 1⟩, _⟩ => ?_, rfl⟩
obtain F : (0 : ZMod 2) = 1 := congr_arg (fun j : L => j.1.2) h
cases F
end ExL
end Counterexample |
.lake/packages/mathlib/Counterexamples/OrderedCancelAddCommMonoidWithBounds.lean | import Mathlib.Algebra.Order.Monoid.Defs
import Mathlib.Order.BoundedOrder.Lattice
/-!
# Do not combine OrderedCancelAddCommMonoid with BoundedOrder
This file shows that combining `OrderedCancelAddCommMonoid` with `BoundedOrder` is not a good idea,
as such a structure must be trivial (`⊥ = x = ⊤` for all `x`).
The same applies to any superclasses, e.g. combining `StrictOrderedSemiring` with `CompleteLattice`.
-/
example {α : Type*} [AddCommMonoid α] [PartialOrder α] [IsOrderedCancelAddMonoid α]
[BoundedOrder α] [Nontrivial α] : False :=
have top_pos := pos_of_lt_add_right (bot_le.trans_lt (add_lt_add_left bot_lt_top (⊥ : α)))
have top_add_top_lt_self := lt_add_of_le_of_pos (@le_top _ _ _ (⊤ + ⊤)) top_pos
top_add_top_lt_self.false |
.lake/packages/mathlib/Counterexamples/HomogeneousPrimeNotPrime.lean | import Mathlib.Algebra.Divisibility.Finite
import Mathlib.Algebra.Divisibility.Prod
import Mathlib.Data.Fintype.Units
import Mathlib.RingTheory.GradedAlgebra.Homogeneous.Ideal
/-!
# A homogeneous ideal that is homogeneously prime but not prime
In `Ideal.IsHomogeneous.isPrime_of_homogeneous_mem_or_mem`, we assumed that the underlying grading
is indexed by a `LinearOrderedCancelAddCommMonoid` to prove that a homogeneous ideal is prime
if and only if it is homogeneously prime. This file shows that even if this assumption isn't
strictly necessary, the assumption of "being cancellative" is. We construct a counterexample where
the underlying indexing set is a `LinearOrderedAddCommMonoid` but is not cancellative and the
statement is false.
We achieve this by considering the ring `R=ℤ/4ℤ`. We first give the two element set `ι = {0, 1}` a
structure of linear ordered additive commutative monoid by setting `0 + 0 = 0` and `_ + _ = 1` and
`0 < 1`. Then we use `ι` to grade `R²` by setting `{(a, a) | a ∈ R}` to have grade `0`; and
`{(0, b) | b ∈ R}` to have grade 1. Then the ideal `I = span {(2, 2)} ⊆ ℤ/4ℤ × ℤ/4ℤ` is homogeneous
and not prime. But it is homogeneously prime, i.e. if `(a, b), (c, d)` are two homogeneous elements
then `(a, b) * (c, d) ∈ I` implies either `(a, b) ∈ I` or `(c, d) ∈ I`.
## Tags
homogeneous, prime
-/
namespace Counterexample
namespace CounterexampleNotPrimeButHomogeneousPrime
open DirectSum
abbrev Two :=
WithZero Unit
instance : Fintype Two :=
inferInstanceAs (Fintype (Option Unit))
instance : IsOrderedAddMonoid Two :=
{ add_le_add_left := by decide }
section
variable (R : Type*) [CommRing R]
/-- The grade 0 part of `R²` is `{(a, a) | a ∈ R}`. -/
def submoduleZ : Submodule R (R × R) where
carrier := {zz | zz.1 = zz.2}
zero_mem' := rfl
add_mem' := @fun _ _ ha hb => congr_arg₂ (· + ·) ha hb
smul_mem' a _ hb := congr_arg (a * ·) hb
instance [Fintype R] [DecidableEq R] : Fintype (submoduleZ R) :=
inferInstanceAs (Fintype {zz : R × R // zz.1 = zz.2})
/-- The grade 1 part of `R²` is `{(0, b) | b ∈ R}`. -/
def submoduleO : Submodule R (R × R) :=
LinearMap.ker (LinearMap.fst R R R)
instance [Fintype R] [DecidableEq R] : Fintype (submoduleO R) :=
inferInstanceAs (Fintype {zz : R × R // zz.1 = 0})
/-- Given the above grading (see `submoduleZ` and `submoduleO`),
we turn `R²` into a graded ring. -/
def grading : Two → Submodule R (R × R)
| 0 => submoduleZ R
| 1 => submoduleO R
instance [Fintype R] [DecidableEq R] : ∀ (i : Two), Fintype (grading R i)
| 0 => inferInstanceAs (Fintype (submoduleZ R))
| 1 => inferInstanceAs (Fintype (submoduleO R))
theorem grading.one_mem : (1 : R × R) ∈ grading R 0 :=
Eq.refl (1, 1).fst
theorem grading.mul_mem :
∀ ⦃i j : Two⦄ {a b : R × R} (_ : a ∈ grading R i) (_ : b ∈ grading R j),
a * b ∈ grading R (i + j)
| 0, 0, a, b, (ha : a.1 = a.2), (hb : b.1 = b.2) => show a.1 * b.1 = a.2 * b.2 by rw [ha, hb]
| 0, 1, a, b, (_ : a.1 = a.2), (hb : b.1 = 0) =>
show a.1 * b.1 = 0 by rw [hb, mul_zero]
| 1, 0, a, b, (ha : a.1 = 0), _ => show a.1 * b.1 = 0 by rw [ha, zero_mul]
| 1, 1, a, b, (ha : a.1 = 0), _ => show a.1 * b.1 = 0 by rw [ha, zero_mul]
end
local notation "R" => ZMod 4
/-- `R² ≅ {(a, a) | a ∈ R} ⨁ {(0, b) | b ∈ R}` by `(x, y) ↦ (x, x) + (0, y - x)`. -/
def grading.decompose : R × R →+ DirectSum Two fun i => grading R i where
toFun zz :=
of (grading R ·) 0 ⟨(zz.1, zz.1), rfl⟩ +
of (grading R ·) 1 ⟨(0, zz.2 - zz.1), rfl⟩
map_zero' := by decide
map_add' := by
rintro ⟨a1, b1⟩ ⟨a2, b2⟩
rw [add_add_add_comm, ← map_add, ← map_add]
dsimp only [Prod.mk_add_mk]
simp_rw [add_sub_add_comm]
rfl
theorem grading.right_inv : Function.RightInverse (coeLinearMap (grading R)) grading.decompose := by
intro zz
induction zz using DirectSum.induction_on with
| zero => decide
| of => decide +revert
| add d1 d2 ih1 ih2 => simp only [map_add, ih1, ih2]
instance : GradedAlgebra (grading R) where
one_mem := grading.one_mem R
mul_mem := grading.mul_mem R
decompose' := grading.decompose
left_inv := by decide
right_inv := grading.right_inv
/-- The counterexample is the ideal `I = span {(2, 2)}`. -/
def I : Ideal (R × R) :=
Ideal.span {((2, 2) : R × R)}
theorem I_not_prime : ¬I.IsPrime := by
rintro ⟨-, h⟩
simp only [I, Ideal.mem_span_singleton] at h
revert h
decide +revert +kernel
theorem I_isHomogeneous : Ideal.IsHomogeneous (grading R) I := by
rw [Ideal.IsHomogeneous.iff_exists]
refine ⟨{⟨(2, 2), ⟨0, rfl⟩⟩}, ?_⟩
rw [Set.image_singleton]
rfl
theorem homogeneous_mem_or_mem : ∀ {x y : R × R},
SetLike.IsHomogeneousElem (grading R) x → SetLike.IsHomogeneousElem (grading R) y →
x * y ∈ I → x ∈ I ∨ y ∈ I := by
have h2 : Prime (2:R) := by
unfold Prime
decide +kernel
simp only [I, Ideal.mem_span_singleton]
rintro ⟨x1, x2⟩ ⟨y1, y2⟩ ⟨_ | ⟨⟨⟩⟩, rfl : x1 = _⟩ ⟨_ | ⟨⟨⟩⟩, rfl : y1 = _⟩ h <;>
decide +revert
end CounterexampleNotPrimeButHomogeneousPrime
end Counterexample |
.lake/packages/mathlib/Counterexamples/SeminormLatticeNotDistrib.lean | import Mathlib.Analysis.Seminorm
/-!
# The lattice of seminorms is not distributive
We provide an example of three seminorms over the ℝ-vector space ℝ×ℝ which don't satisfy the lattice
distributivity property `(p ⊔ q1) ⊓ (p ⊔ q2) ≤ p ⊔ (q1 ⊓ q2)`.
This proves the lattice `Seminorm ℝ (ℝ × ℝ)` is not distributive.
## References
* https://en.wikipedia.org/wiki/Seminorm#Examples
-/
open Seminorm
open scoped NNReal
namespace Counterexample
namespace SeminormNotDistrib
@[simps!]
noncomputable def p : Seminorm ℝ (ℝ × ℝ) :=
(normSeminorm ℝ ℝ).comp (LinearMap.fst _ _ _) ⊔ (normSeminorm ℝ ℝ).comp (LinearMap.snd _ _ _)
@[simps!]
noncomputable def q1 : Seminorm ℝ (ℝ × ℝ) :=
(4 : ℝ≥0) • (normSeminorm ℝ ℝ).comp (LinearMap.fst _ _ _)
@[simps!]
noncomputable def q2 : Seminorm ℝ (ℝ × ℝ) :=
(4 : ℝ≥0) • (normSeminorm ℝ ℝ).comp (LinearMap.snd _ _ _)
theorem eq_one : (p ⊔ q1 ⊓ q2) (1, 1) = 1 := by
suffices ⨅ x : ℝ × ℝ, q1 x + q2 (1 - x) ≤ 1 by simpa
apply ciInf_le_of_le bddBelow_range_add ((0, 1) : ℝ × ℝ); dsimp [q1, q2]
simp only [abs_zero, smul_zero, sub_self, add_zero, zero_le_one]
/-- This is a counterexample to the distributivity of the lattice `Seminorm ℝ (ℝ × ℝ)`. -/
theorem not_distrib : ¬(p ⊔ q1) ⊓ (p ⊔ q2) ≤ p ⊔ q1 ⊓ q2 := by
intro le_sup_inf
have c : ¬4 / 3 ≤ (1 : ℝ) := by norm_num
apply c; nth_rw 1 [← eq_one]
apply le_trans _ (le_sup_inf _)
apply le_ciInf; intro x
rcases le_or_gt x.fst (1 / 3) with h1 | h1
· rcases le_or_gt x.snd (2 / 3) with h2 | h2
· calc
4 / 3 = 4 * (1 - 2 / 3) := by norm_num
_ ≤ 4 * (1 - x.snd) := by gcongr
_ ≤ 4 * |1 - x.snd| := by gcongr; apply le_abs_self
_ = q2 ((1, 1) - x) := rfl
_ ≤ (p ⊔ q2) ((1, 1) - x) := le_sup_right
_ ≤ (p ⊔ q1) x + (p ⊔ q2) ((1, 1) - x) := le_add_of_nonneg_left (apply_nonneg _ _)
· calc
4 / 3 = 2 / 3 + (1 - 1 / 3) := by norm_num
_ ≤ x.snd + (1 - x.fst) := by gcongr
_ ≤ |x.snd| + |1 - x.fst| := add_le_add (le_abs_self _) (le_abs_self _)
_ ≤ p x + p ((1, 1) - x) := add_le_add le_sup_right le_sup_left
_ ≤ (p ⊔ q1) x + (p ⊔ q2) ((1, 1) - x) := add_le_add le_sup_left le_sup_left
· calc
4 / 3 = 4 * (1 / 3) := by norm_num
_ ≤ 4 * x.fst := by gcongr
_ ≤ 4 * |x.fst| := by gcongr; apply le_abs_self
_ = q1 x := rfl
_ ≤ (p ⊔ q1) x := le_sup_right
_ ≤ (p ⊔ q1) x + (p ⊔ q2) ((1, 1) - x) := le_add_of_nonneg_right (apply_nonneg _ _)
end SeminormNotDistrib
end Counterexample |
.lake/packages/mathlib/Counterexamples/Cyclotomic105.lean | import Mathlib.RingTheory.Polynomial.Cyclotomic.Basic
import Mathlib.Tactic.NormNum.Prime
/-!
# Not all coefficients of cyclotomic polynomials are -1, 0, or 1
We show that not all coefficients of cyclotomic polynomials are equal to `0`, `-1` or `1`, in the
theorem `not_forall_coeff_cyclotomic_neg_one_zero_one`. We prove this with the counterexample
`coeff_cyclotomic_105 : coeff (cyclotomic 105 ℤ) 7 = -2`.
-/
open Nat (properDivisors)
open Finset
namespace Counterexample
section Computation
instance Nat.fact_prime_five : Fact (Nat.Prime 5) :=
⟨by norm_num⟩
instance Nat.fact_prime_seven : Fact (Nat.Prime 7) :=
⟨by norm_num⟩
theorem properDivisors_15 : Nat.properDivisors 15 = {1, 3, 5} :=
rfl
theorem properDivisors_21 : Nat.properDivisors 21 = {1, 3, 7} :=
rfl
theorem properDivisors_35 : Nat.properDivisors 35 = {1, 5, 7} :=
rfl
theorem properDivisors_105 : Nat.properDivisors 105 = {1, 3, 5, 7, 15, 21, 35} :=
rfl
end Computation
open Polynomial
theorem cyclotomic_3 : cyclotomic 3 ℤ = 1 + X + X ^ 2 := by
simp only [cyclotomic_prime, sum_range_succ, range_one, sum_singleton, pow_zero, pow_one]
theorem cyclotomic_5 : cyclotomic 5 ℤ = 1 + X + X ^ 2 + X ^ 3 + X ^ 4 := by
simp only [cyclotomic_prime, sum_range_succ, range_one, sum_singleton, pow_zero, pow_one]
theorem cyclotomic_7 : cyclotomic 7 ℤ = 1 + X + X ^ 2 + X ^ 3 + X ^ 4 + X ^ 5 + X ^ 6 := by
simp only [cyclotomic_prime, sum_range_succ, range_one, sum_singleton, pow_zero, pow_one]
theorem cyclotomic_15 : cyclotomic 15 ℤ = 1 - X + X ^ 3 - X ^ 4 + X ^ 5 - X ^ 7 + X ^ 8 := by
refine ((eq_cyclotomic_iff (by simp) _).2 ?_).symm
rw [properDivisors_15, Finset.prod_insert _, Finset.prod_insert _, Finset.prod_singleton,
cyclotomic_one, cyclotomic_3, cyclotomic_5]
· ring
repeat' norm_num
theorem cyclotomic_21 :
cyclotomic 21 ℤ = 1 - X + X ^ 3 - X ^ 4 + X ^ 6 - X ^ 8 + X ^ 9 - X ^ 11 + X ^ 12 := by
refine ((eq_cyclotomic_iff (by simp) _).2 ?_).symm
rw [properDivisors_21, Finset.prod_insert _, Finset.prod_insert _, Finset.prod_singleton,
cyclotomic_one, cyclotomic_3, cyclotomic_7]
· ring
repeat' norm_num
theorem cyclotomic_35 :
cyclotomic 35 ℤ =
1 - X + X ^ 5 - X ^ 6 + X ^ 7 - X ^ 8 + X ^ 10 - X ^ 11 + X ^ 12 - X ^ 13 + X ^ 14 - X ^ 16 +
X ^ 17 - X ^ 18 + X ^ 19 - X ^ 23 + X ^ 24 := by
refine ((eq_cyclotomic_iff (by simp) _).2 ?_).symm
rw [properDivisors_35, Finset.prod_insert _, Finset.prod_insert _, Finset.prod_singleton,
cyclotomic_one, cyclotomic_5, cyclotomic_7]
· ring
repeat' norm_num
theorem cyclotomic_105 :
cyclotomic 105 ℤ =
1 + X + X ^ 2 - X ^ 5 - X ^ 6 - 2 * X ^ 7 - X ^ 8 - X ^ 9 + X ^ 12 + X ^ 13 + X ^ 14 +
X ^ 15 + X ^ 16 + X ^ 17 - X ^ 20 - X ^ 22 - X ^ 24 - X ^ 26 - X ^ 28 + X ^ 31 + X ^ 32 +
X ^ 33 + X ^ 34 + X ^ 35 + X ^ 36 - X ^ 39 - X ^ 40 - 2 * X ^ 41 - X ^ 42 - X ^ 43 +
X ^ 46 + X ^ 47 + X ^ 48 := by
refine ((eq_cyclotomic_iff (by simp) _).2 ?_).symm
rw [properDivisors_105]
repeat rw [Finset.prod_insert]
· rw [Finset.prod_singleton, cyclotomic_one, cyclotomic_3, cyclotomic_5, cyclotomic_7,
cyclotomic_15, cyclotomic_21, cyclotomic_35]
ring
repeat' norm_num
theorem coeff_cyclotomic_105 : coeff (cyclotomic 105 ℤ) 7 = -2 := by
simp [cyclotomic_105, coeff_X_of_ne_one, coeff_one]
theorem not_forall_coeff_cyclotomic_neg_one_zero_one :
¬∀ n i, coeff (cyclotomic n ℤ) i ∈ ({-1, 0, 1} : Set ℤ) := by
intro h
specialize h 105 7
rw [coeff_cyclotomic_105] at h
norm_num at h
end Counterexample |
.lake/packages/mathlib/Counterexamples/MapFloor.lean | import Mathlib.Algebra.Order.Round
import Mathlib.Algebra.Order.Group.PiLex
import Mathlib.Algebra.Order.Hom.Ring
import Mathlib.Algebra.Polynomial.Reverse
/-!
# Floors and ceils aren't preserved under ordered ring homomorphisms
Intuitively, if `f : α → β` is an ordered ring homomorphism, then floors and ceils should be
preserved by `f` because:
* `f` preserves the naturals/integers in `α` and `β` because it's a ring hom.
* `f` preserves what's between `n` and `n + 1` because it's monotone.
However, there is a catch. Potentially something whose floor was `n` could
get mapped to `n + 1`, and this has floor `n + 1`, not `n`. Note that this is at most an off by one
error.
This pathology disappears if you require `f` to be strictly monotone or `α` to be archimedean.
## The counterexample
Consider `ℤ[ε]` (`IntWithEpsilon`), the integers with infinitesimals adjoined. This is a linearly
ordered commutative floor ring (`IntWithEpsilon.linearOrderedCommRing`,
`IntWithEpsilon.floorRing`).
The map `f : ℤ[ε] → ℤ` that forgets about the epsilons (`IntWithEpsilon.forgetEpsilons`) is an
ordered ring homomorphism.
But it does not preserve floors (nor ceils) as `⌊-ε⌋ = -1` while `⌊f (-ε)⌋ = ⌊0⌋ = 0`
(`IntWithEpsilon.forgetEpsilons_floor_lt`, `IntWithEpsilon.lt_forgetEpsilons_ceil`).
-/
namespace Counterexample
noncomputable section
open Function Int Polynomial
open scoped Polynomial
/-- The integers with infinitesimals adjoined. -/
def IntWithEpsilon :=
ℤ[X] deriving Nontrivial, CommRing, Inhabited
local notation "ℤ[ε]" => IntWithEpsilon
local notation "ε" => (X : ℤ[ε])
namespace IntWithEpsilon
instance linearOrder : LinearOrder ℤ[ε] :=
LinearOrder.lift' (toLex ∘ coeff) coeff_injective
instance isOrderedAddMonoid : IsOrderedAddMonoid ℤ[ε] :=
Function.Injective.isOrderedAddMonoid
(toLex ∘ coeff) (fun _ _ => funext fun _ => coeff_add _ _ _) .rfl
theorem pos_iff {p : ℤ[ε]} : 0 < p ↔ 0 < p.trailingCoeff := by
rw [trailingCoeff]
refine
⟨?_, fun h =>
⟨p.natTrailingDegree, fun m hm => (coeff_eq_zero_of_lt_natTrailingDegree hm).symm, h⟩⟩
rintro ⟨n, hn⟩
convert hn.2
exact (natTrailingDegree_le_of_ne_zero hn.2.ne').antisymm
(le_natTrailingDegree (by rintro rfl; cases hn.2.false) fun m hm => (hn.1 _ hm).symm)
instance : ZeroLEOneClass ℤ[ε] :=
{ zero_le_one := Or.inr ⟨0, by simp⟩ }
instance : IsStrictOrderedRing ℤ[ε] :=
.of_mul_pos fun p q => by simp_rw [pos_iff]; rw [trailingCoeff_mul]; exact mul_pos
instance : FloorRing ℤ[ε] :=
FloorRing.ofFloor _ (fun p => if (p.coeff 0 : ℤ[ε]) ≤ p then p.coeff 0 else p.coeff 0 - 1)
fun p q => by
simp_rw [← not_lt, not_iff_not]
constructor
· split_ifs with h
· rintro ⟨_ | n, hn⟩
· apply (sub_one_lt _).trans _
simp at hn
rwa [intCast_coeff_zero] at hn
· dsimp at hn
simp [hn.1 _ n.zero_lt_succ]
rw [intCast_coeff_zero]; simp
· exact fun h' => cast_lt.1 ((not_lt.1 h).trans_lt h')
· split_ifs with h
· exact fun h' => h.trans_le (cast_le.2 <| sub_one_lt_iff.1 h')
· exact fun h' => ⟨0, by simp; rwa [intCast_coeff_zero]⟩
/-- The ordered ring homomorphisms from `ℤ[ε]` to `ℤ` that "forgets" the `ε`s. -/
def forgetEpsilons : ℤ[ε] →+*o ℤ where
toFun p := coeff p 0
map_zero' := coeff_zero _
map_one' := coeff_one_zero
map_add' _ _ := coeff_add _ _ _
map_mul' := mul_coeff_zero
monotone' := monotone_iff_forall_lt.2 (by
rintro p q ⟨n, hn⟩
rcases n with - | n
· exact hn.2.le
· exact (hn.1 _ n.zero_lt_succ).le)
@[simp]
theorem forgetEpsilons_apply (p : ℤ[ε]) : forgetEpsilons p = coeff p 0 :=
rfl
/-- The floor of `n - ε` is `n - 1` but its image under `forgetEpsilons` is `n`, whose floor is
itself. -/
theorem forgetEpsilons_floor_lt (n : ℤ) :
forgetEpsilons ⌊(n - ↑ε : ℤ[ε])⌋ < ⌊forgetEpsilons (n - ↑ε)⌋ := by
suffices ⌊(n - ↑ε : ℤ[ε])⌋ = n - 1 by simp [map_sub, this]
have : (0 : ℤ[ε]) < ε := ⟨1, by simp⟩
exact (if_neg <| by rw [coeff_sub, intCast_coeff_zero]; simp [this]).trans (by
rw [coeff_sub, intCast_coeff_zero]; simp)
/-- The ceil of `n + ε` is `n + 1` but its image under `forgetEpsilons` is `n`, whose ceil is
itself. -/
theorem lt_forgetEpsilons_ceil (n : ℤ) :
⌈forgetEpsilons (n + ↑ε)⌉ < forgetEpsilons ⌈(n + ↑ε : ℤ[ε])⌉ := by
rw [← neg_lt_neg_iff, ← map_neg, ← cast_neg, ← floor_neg, ← floor_neg, ← map_neg, neg_add', ←
cast_neg]
exact forgetEpsilons_floor_lt _
end IntWithEpsilon
end
end Counterexample |
.lake/packages/mathlib/Counterexamples/MonicNonRegular.lean | import Mathlib.Algebra.Polynomial.Monic
/-!
# `Monic` does not necessarily imply `IsRegular` in a `Semiring` with no opposites
This counterexample shows that the hypothesis `Ring R` cannot be changed to `Semiring R` in
`Polynomial.Monic.isRegular`.
The example is very simple.
The coefficient Semiring is the Semiring `N₃` of the natural numbers `{0, 1, 2, 3}` where the
standard addition and standard multiplication are truncated at `3`.
The products `(X + 2) * (X + 2)` and `(X + 2) * (X + 3)` are equal to
`X ^ 2 + 4 * X + 4` and `X ^ 2 + 5 * X + 6` respectively.
By truncation, `4, 5, 6` all mean `3` in `N`.
It follows that multiplication by `(X + 2)` is not injective.
-/
open Polynomial
namespace Counterexample.NonRegular
/-- `N₃` is going to be a `CommSemiring` where addition and multiplication are truncated at `3`. -/
inductive N₃
| zero
| one
| two
| more
namespace N₃
instance : Zero N₃ := ⟨zero⟩
instance : One N₃ := ⟨one⟩
/-- Truncated addition on `N₃`. -/
instance : Add N₃ where
add
| 0, x => x
| x, 0 => x
| 1, 1 => two
| _, _ => more
/-- Truncated multiplication on `N₃`. -/
instance : Mul N₃ where
mul
| 1, x => x
| x, 1 => x
| 0, _ => 0
| _, 0 => 0
| _, _ => more
instance : CommMonoid N₃ where
mul_assoc := by rintro ⟨⟩ ⟨⟩ ⟨⟩ <;> rfl
one_mul := by rintro ⟨⟩ <;> rfl
mul_one := by rintro ⟨⟩ <;> rfl
mul_comm := by rintro ⟨⟩ ⟨⟩ <;> rfl
instance : CommSemiring N₃ :=
{ (inferInstance : CommMonoid N₃) with
add_assoc := by rintro ⟨⟩ ⟨⟩ ⟨⟩ <;> rfl
zero_add := by rintro ⟨⟩ <;> rfl
add_zero := by rintro ⟨⟩ <;> rfl
add_comm := by rintro ⟨⟩ ⟨⟩ <;> rfl
left_distrib := by rintro ⟨⟩ ⟨⟩ ⟨⟩ <;> rfl
right_distrib := by rintro ⟨⟩ ⟨⟩ ⟨⟩ <;> rfl
zero_mul := by rintro ⟨⟩ <;> rfl
mul_zero := by rintro ⟨⟩ <;> rfl
nsmul := nsmulRec }
theorem X_add_two_mul_X_add_two : (X + C 2 : N₃[X]) * (X + C 2) = (X + C 2) * (X + C 3) := by
simp only [mul_add, add_mul, X_mul, add_assoc]
apply congr_arg
rw [← add_assoc, ← add_mul, ← C_add, ← C_mul, ← C_mul]
rw [← add_assoc, ← add_mul, ← C_add]
rfl
/-! The main example: multiplication by the polynomial `X + 2` is not injective,
yet the polynomial is monic. -/
theorem monic_X_add_two : Monic (X + C 2 : N₃[X]) := by
unfold Monic leadingCoeff
nontriviality
rw [natDegree_X_add_C 2]
simp only [coeff_C, coeff_add, coeff_X_one, ite_false, add_zero, reduceCtorEq]
theorem not_isLeftRegular_X_add_two : ¬ IsLeftRegular (X + C 2 : N₃[X]) := by
intro h
have H := h X_add_two_mul_X_add_two
apply_fun (coeff · 0) at H
simp only [coeff_add, coeff_X_zero, zero_add, coeff_C, ite_true] at H
cases H
/-- The statement of the counterexample: not all monic polynomials over semirings are regular. -/
theorem not_monic_implies_isLeftRegular :
¬∀ {R : Type} [Semiring R] (p : R[X]), Monic p → IsLeftRegular p :=
fun h => not_isLeftRegular_X_add_two (h _ monic_X_add_two)
end N₃
end Counterexample.NonRegular |
.lake/packages/mathlib/Counterexamples/SeparableNotSecondCountable.lean | import Mathlib.Analysis.Real.Cardinality
/-!
# Example of a linear order which is a separable space but is not a second countable topology
In this file we provide an example of a linear order
such that the order topology is a separable space but is not a second countable topology.
The example is `ℝ ×ₗ Bool` which is the real line with each point duplicated
so that the duplicate is greater than the original point
and points with different real values are compared by these values.
-/
open Set TopologicalSpace
namespace RealProdLexBool
instance instTopologicalSpace : TopologicalSpace (ℝ ×ₗ Bool) := Preorder.topology _
instance instOrderTopology : OrderTopology (ℝ ×ₗ Bool) := ⟨rfl⟩
noncomputable instance instLinearOrder : LinearOrder (ℝ ×ₗ Bool) := inferInstance
instance instSeparableSpace : SeparableSpace (ℝ ×ₗ Bool) := by
refine ⟨⟨range fun q : ℚ ↦ toLex (q, false), countable_range _, ?_⟩⟩
simp only [dense_iff_inter_open, Set.Nonempty, toLex.surjective.exists]
rintro U hUo ⟨⟨x, _ | _⟩, hx⟩
· rcases exists_Ioc_subset_of_mem_nhds (hUo.mem_nhds hx) (exists_lt _) with ⟨y, hyx, hyU⟩
rcases toLex.surjective y with ⟨y, rfl⟩
have : y.1 < x := by simpa [Prod.Lex.toLex_lt_toLex, y.2.false_le.not_gt] using hyx
rcases exists_rat_btwn this with ⟨q, hyq, hqx⟩
refine ⟨(q, false), hyU ?_, mem_range_self _⟩
simp [Prod.Lex.toLex_le_toLex, Prod.Lex.toLex_lt_toLex, hyq, hqx]
· rcases exists_Ico_subset_of_mem_nhds (hUo.mem_nhds hx) (exists_gt _) with ⟨y, hyx, hyU⟩
rcases toLex.surjective y with ⟨y, rfl⟩
have : x < y.1 := by simpa [Prod.Lex.toLex_lt_toLex, y.2.le_true.not_gt] using hyx
rcases exists_rat_btwn this with ⟨q, hyq, hqx⟩
refine ⟨(q, false), hyU ?_, mem_range_self _⟩
simp [Prod.Lex.toLex_le_toLex, Prod.Lex.toLex_lt_toLex, hyq, hqx]
theorem not_secondCountableTopology : ¬SecondCountableTopology (ℝ ×ₗ Bool) := by
intro h
have : {x : ℝ ×ₗ Bool | (ofLex x).2}.Countable := by
simpa [Prod.Lex.covBy_iff, Bool.covBy_iff, exists_or, not_covBy, (Bool.le_true _).not_gt,
(Bool.false_le _).lt_iff_ne] using countable_setOf_covBy_left (α := ℝ ×ₗ Bool)
refine not_countable_univ <| (this.image fun x ↦ (ofLex x).1).mono fun x _ ↦ ?_
exact ⟨toLex (x, true), rfl, rfl⟩
end RealProdLexBool |
.lake/packages/mathlib/widget/src/penrose/README.md | This directory contains source files for [Penrose diagrams](https://penrose.cs.cmu.edu/):
* Domain files (`.dsl`) describe the objects available in a given domain.
* Style files (`.sty`) specify how diagrams involving the objects from a given domain should be
drawn.
* Substance files (`.sub`) describe specific diagrams.
Penrose diagrams are displayed in the infoview using
[ProofWidgets4](https://github.com/EdAyers/ProofWidgets4). |
.lake/packages/mathlib/Cache/IO.lean | import Std.Data.TreeSet
import Cache.Lean
variable {α : Type}
open Lean
namespace Cache.IO
open System (FilePath)
/-- Target directory for build files -/
def LIBDIR : FilePath :=
".lake" / "build" / "lib" / "lean"
/-- Target directory for IR files -/
def IRDIR : FilePath :=
".lake" / "build" / "ir"
/-- Determine if the package `mod` is part of the mathlib cache.
TODO: write a better predicate. -/
def isPartOfMathlibCache (mod : Name) : Bool := #[
`Mathlib,
`Batteries,
`Aesop,
`Cli,
`ImportGraph,
`LeanSearchClient,
`Plausible,
`Qq,
`ProofWidgets,
`Archive,
`Counterexamples,
`MathlibTest,
-- Allow PRs to upload oleans for Reap for testing.
`Requests,
`OpenAIClient,
`Reap,
-- Allow PRs to upload oleans for Canonical for testing.
`Canonical,
-- Allow PRs to upload oleans for LeanHammer for testing.
`Duper,
`Auto,
`PremiseSelection,
`Hammer].contains mod.getRoot
/-- Target directory for caching -/
initialize CACHEDIR : FilePath ← do
match ← IO.getEnv "MATHLIB_CACHE_DIR" with
| some path => return path
| none =>
match ← IO.getEnv "XDG_CACHE_HOME" with
| some path => return path / "mathlib"
| none =>
let home ← if System.Platform.isWindows then
let drive ← IO.getEnv "HOMEDRIVE"
let path ← IO.getEnv "HOMEPATH"
pure <| return (← drive) ++ (← path)
else IO.getEnv "HOME"
match home with
| some path => return path / ".cache" / "mathlib"
| none => pure ⟨".cache"⟩
/-- Target file path for `curl` configurations -/
def CURLCFG :=
IO.CACHEDIR / "curl.cfg"
/-- curl version at https://github.com/leanprover-community/static-curl -/
def CURLVERSION :=
"7.88.1"
def CURLBIN :=
-- change file name if we ever need a more recent version to trigger re-download
IO.CACHEDIR / s!"curl-{CURLVERSION}"
/-- leantar version at https://github.com/digama0/leangz -/
def LEANTARVERSION :=
"0.1.16"
def EXE := if System.Platform.isWindows then ".exe" else ""
def LEANTARBIN :=
-- change file name if we ever need a more recent version to trigger re-download
IO.CACHEDIR / s!"leantar-{LEANTARVERSION}{EXE}"
def LAKEPACKAGESDIR : FilePath :=
".lake" / "packages"
def getCurl : IO String := do
return if (← CURLBIN.pathExists) then CURLBIN.toString else "curl"
def getLeanTar : IO String := do
return if (← LEANTARBIN.pathExists) then LEANTARBIN.toString else "leantar"
/-- Bump this number to invalidate the cache, in case the existing hashing inputs are insufficient.
It is not a global counter, and can be reset to 0 as long as the lean githash or lake manifest has
changed since the last time this counter was touched. -/
def rootHashGeneration : UInt64 := 4
/--
`CacheM` stores the following information:
* the source directory where `Mathlib.lean` lies
* the Lean search path. This contains
paths to the source directory of each imported package, i.e. where the `.lean` files
can be found.
(Note: in a standard setup these might also be the paths where the correpsponding `.lake`
folders are located. However, `lake` has multiple options to customise these paths, like
setting `srcDir` in a `lean_lib`. See `mkBuildPaths` below which currently assumes
that no such options are set in any mathlib dependency)
* the build directory for proofwidgets
-/
structure CacheM.Context where
/-- source directory for mathlib files -/
mathlibDepPath : FilePath
/-- the Lean source search path -/
srcSearchPath : SearchPath
/-- build directory for proofwidgets -/
proofWidgetsBuildDir : FilePath
@[inherit_doc CacheM.Context]
abbrev CacheM := ReaderT CacheM.Context IO
/-- Whether this is running on Mathlib repo or not -/
def isMathlibRoot : IO Bool :=
FilePath.mk "Mathlib" |>.pathExists
section
/-- Find path to `Mathlib` source directory -/
private def CacheM.mathlibDepPath (sp : SearchPath) : IO FilePath := do
let mathlibSourceFile ← Lean.findLean sp `Mathlib
let some mathlibSource ← pure mathlibSourceFile.parent
| throw <| IO.userError s!"Mathlib not found in dependencies"
return mathlibSource
def _root_.Lean.SearchPath.relativize (sp : SearchPath) : IO SearchPath := do
let pwd ← IO.FS.realPath "."
let pwd' := pwd.toString ++ System.FilePath.pathSeparator.toString
return sp.map fun x => ⟨if x = pwd then "." else x.toString.stripPrefix pwd'⟩
private def CacheM.getContext : IO CacheM.Context := do
let sp ← (← getSrcSearchPath).relativize
let mathlibSource ← CacheM.mathlibDepPath sp
return {
mathlibDepPath := mathlibSource,
srcSearchPath := sp,
proofWidgetsBuildDir := LAKEPACKAGESDIR / "proofwidgets" / ".lake" / "build"}
/-- Run a `CacheM` in `IO` by loading the context from `LEAN_SRC_PATH`. -/
def CacheM.run (f : CacheM α) : IO α := do ReaderT.run f (← getContext)
end
/--
`mod` is assumed to be the module name like `Mathlib.Init`.
Find the source directory for `mod`.
This corresponds to the folder where the `.lean` files are located, i.e. for `Mathlib.Init`,
the file should be located at `(← getSrcDir _) / "Mathlib" / "Init.lean`.
Usually it is either `.` or something like `./.lake/packages/mathlib/`
-/
def getSrcDir (sp : SearchPath) (mod : Name) : IO FilePath := do
let some srcDir ← sp.findWithExtBase "lean" mod |
throw <| IO.userError s!"Unknown package directory for {mod}\nsearch paths: {sp}"
return srcDir
/-- Runs a terminal command and retrieves its output, passing the lines to `processLine` -/
partial def runCurlStreaming (args : Array String) (init : α)
(processLine : α → String → IO α) : IO α := do
let child ← IO.Process.spawn { cmd := ← getCurl, args, stdout := .piped, stderr := .piped }
loop child.stdout init
where
loop (h : IO.FS.Handle) (a : α) : IO α := do
let line ← h.getLine
if line.isEmpty then
return a
else
loop h (← processLine a line)
/-- Runs a terminal command and retrieves its output -/
def runCmd (cmd : String) (args : Array String) (throwFailure stderrAsErr := true) : IO String := do
let out ← IO.Process.output { cmd := cmd, args := args }
if (out.exitCode != 0 || stderrAsErr && !out.stderr.isEmpty) && throwFailure then
throw <| IO.userError s!"failure in {cmd} {args}:\n{out.stderr}"
else if !out.stderr.isEmpty then
IO.eprintln out.stderr
return out.stdout
def runCurl (args : Array String) (throwFailure stderrAsErr := true) : IO String := do
runCmd (← getCurl) (#["--no-progress-meter"] ++ args) throwFailure stderrAsErr
def validateCurl : IO Bool := do
if (← CURLBIN.pathExists) then return true
match (← runCmd "curl" #["--version"]).splitOn " " with
| "curl" :: v :: _ => match v.splitOn "." with
| maj :: min :: _ =>
let version := (maj.toNat!, min.toNat!)
let _ := @lexOrd
let _ := @leOfOrd
if version >= (7, 81) then return true
-- TODO: support more platforms if the need arises
let arch ← (·.trim) <$> runCmd "uname" #["-m"] false
let kernel ← (·.trim) <$> runCmd "uname" #["-s"] false
if kernel == "Linux" && arch ∈ ["x86_64", "aarch64"] then
IO.println s!"curl is too old; downloading more recent version"
IO.FS.createDirAll IO.CACHEDIR
let _ ← runCmd "curl" (stderrAsErr := false) #[
s!"https://github.com/leanprover-community/static-curl/releases/download/v{CURLVERSION}/curl-{arch}-linux-static",
"-L", "-o", CURLBIN.toString]
let _ ← runCmd "chmod" #["u+x", CURLBIN.toString]
return true
if version >= (7, 70) then
IO.println s!"Warning: recommended `curl` version ≥7.81. Found {v}"
return true
else
IO.println s!"Warning: recommended `curl` version ≥7.70. Found {v}. Can't use `--parallel`."
return false
| _ => throw <| IO.userError "Invalidly formatted version of `curl`"
| _ => throw <| IO.userError "Invalidly formatted response from `curl --version`"
def Version := Nat × Nat × Nat
deriving Inhabited, DecidableEq
instance : Ord Version := let _ := @lexOrd; lexOrd
instance : LE Version := leOfOrd
def parseVersion (s : String) : Option Version := do
let [maj, min, patch] := s.splitOn "." | none
some (maj.toNat!, min.toNat!, patch.toNat!)
def validateLeanTar : IO Unit := do
if (← LEANTARBIN.pathExists) then return
if let some version ← some <$> runCmd "leantar" #["--version"] <|> pure none then
let "leantar" :: v :: _ := version.splitOn " "
| throw <| IO.userError "Invalidly formatted response from `leantar --version`"
let some v := parseVersion v | throw <| IO.userError "Invalidly formatted version of `leantar`"
-- currently we need exactly one version of leantar, change this to reflect compatibility
if v = (parseVersion LEANTARVERSION).get! then return
let win := System.Platform.getIsWindows ()
let target ← if win then
pure "x86_64-pc-windows-msvc"
else
let mut arch ← (·.trim) <$> runCmd "uname" #["-m"] false
if arch = "arm64" then arch := "aarch64"
unless arch ∈ ["x86_64", "aarch64"] do
throw <| IO.userError s!"unsupported architecture {arch}"
pure <|
if System.Platform.getIsOSX () then s!"{arch}-apple-darwin"
else s!"{arch}-unknown-linux-musl"
IO.println s!"installing leantar {LEANTARVERSION}"
IO.FS.createDirAll IO.CACHEDIR
let ext := if win then "zip" else "tar.gz"
let _ ← runCmd "curl" (stderrAsErr := false) #[
s!"https://github.com/digama0/leangz/releases/download/v{LEANTARVERSION}/leantar-v{LEANTARVERSION}-{target}.{ext}",
"-L", "-o", s!"{LEANTARBIN}.{ext}"]
let _ ← runCmd "tar" #["-xf", s!"{LEANTARBIN}.{ext}",
"-C", IO.CACHEDIR.toString, "--strip-components=1"]
IO.FS.rename (IO.CACHEDIR / s!"leantar{EXE}").toString LEANTARBIN.toString
/-- Recursively gets all files from a directory with a certain extension -/
partial def getFilesWithExtension
(fp : FilePath) (extension : String) (acc : Array FilePath := #[]) :
IO <| Array FilePath := do
if ← fp.isDir then
(← fp.readDir).foldlM (fun acc dir => getFilesWithExtension dir.path extension acc) acc
else return if fp.extension == some extension then acc.push fp else acc
/--
The Hash map of the cache.
-/
abbrev ModuleHashMap := Std.HashMap Name UInt64
namespace ModuleHashMap
/-- Filter the hashmap by whether the entries exist as files in the cache directory.
If `keep` is true, the result will contain the entries that do exist;
if `keep` is false, the result will contain the entries that do not exist.
-/
def filterExists (hashMap : ModuleHashMap) (keep : Bool) : IO ModuleHashMap :=
hashMap.foldM (init := ∅) fun acc mod hash => do
let exist ← (CACHEDIR / hash.asLTar).pathExists
let add := if keep then exist else !exist
if add then return acc.insert mod hash else return acc
def hashes (hashMap : ModuleHashMap) : Std.TreeSet UInt64 compare :=
hashMap.fold (init := ∅) fun acc _ hash => acc.insert hash
end ModuleHashMap
/--
Given a module name, concatenates the paths to its build files.
Each build file also has a `Bool` indicating whether that file is required for caching to proceed.
-/
def mkBuildPaths (mod : Name) : CacheM <| List (FilePath × Bool) := do
/-
TODO: if `srcDir` or other custom lake layout options are set in the `lean_lib`,
`packageSrcDir / LIBDIR` might be the wrong path!
See [Lake documentation](https://github.com/leanprover/lean4/tree/master/src/lake#layout)
for available options.
If a dependency is added to mathlib which uses such a custom layout, `mkBuildPaths`
needs to be adjusted!
-/
let sp := (← read).srcSearchPath
let packageDir ← getSrcDir sp mod
let path := (System.mkFilePath <| mod.components.map toString)
if !(← (packageDir / ".lake").isDir) then
IO.eprintln <| s!"Warning: {packageDir / ".lake"} seems not to exist, most likely `cache` \
will not work as expected!"
return [
-- Note that `packCache` below requires that the `.trace` file is first in this list.
(packageDir / LIBDIR / path.withExtension "trace", true),
-- Note: the `.olean`, `.olean.server`, `.olean.private` files must be consecutive,
-- and in this order. The corresponding `.hash` files can come afterwards, in any order.
(packageDir / LIBDIR / path.withExtension "olean", true),
(packageDir / LIBDIR / path.withExtension "olean.server", false),
(packageDir / LIBDIR / path.withExtension "olean.private", false),
(packageDir / LIBDIR / path.withExtension "olean.hash", true),
(packageDir / LIBDIR / path.withExtension "olean.server.hash", false),
(packageDir / LIBDIR / path.withExtension "olean.private.hash", false),
(packageDir / LIBDIR / path.withExtension "ilean", true),
(packageDir / LIBDIR / path.withExtension "ilean.hash", true),
(packageDir / LIBDIR / path.withExtension "ir", false),
(packageDir / LIBDIR / path.withExtension "ir.hash", false),
(packageDir / IRDIR / path.withExtension "c", true),
(packageDir / IRDIR / path.withExtension "c.hash", true),
(packageDir / LIBDIR / path.withExtension "extra", false)]
/-- Check that all required build files exist. -/
def allExist (paths : List (FilePath × Bool)) : IO Bool := do
for (path, required) in paths do
if required then if !(← path.pathExists) then return false
pure true
private structure PackTask where
sourceFile : FilePath
zip : String
task? : Option (Task (Except IO.Error Unit))
/-- Compresses build files into the local cache and returns an array with the compressed files -/
def packCache (hashMap : ModuleHashMap) (overwrite verbose unpackedOnly : Bool)
(comment : Option String := none) :
CacheM <| Array String := do
IO.FS.createDirAll CACHEDIR
IO.println "Compressing cache"
let sp := (← read).srcSearchPath
let mut acc : Array PackTask := #[]
for (mod, hash) in hashMap.toList do
let sourceFile ← Lean.findLean sp mod
let zip := hash.asLTar
let zipPath := CACHEDIR / zip
let buildPaths ← mkBuildPaths mod
if ← allExist buildPaths then
if overwrite || !(← zipPath.pathExists) then
let task ← IO.asTask do
-- Note here we require that the `.trace` file is first
-- in the list generated by `mkBuildPaths`.
let trace :: args := (← buildPaths.filterM (·.1.pathExists)) |>.map (·.1.toString)
| unreachable!
discard <| runCmd (← getLeanTar) <| #[zipPath.toString, trace] ++
(if let some c := comment then #["-c", s!"git=mathlib4@{c}"] else #[]) ++ args
acc := acc.push {sourceFile, zip, task? := some task}
else if !unpackedOnly then
acc := acc.push {sourceFile, zip, task? := none}
acc := acc.qsort (·.sourceFile.toString < ·.sourceFile.toString)
acc.mapM fun {sourceFile, zip, task?} => do
if let some task := task? then
if verbose then
IO.println s!"packing {sourceFile} as {zip}"
IO.ofExcept task.get
return zip
/-- Gets the set of all cached files -/
def getLocalCacheSet : IO <| Std.TreeSet String compare := do
let paths ← getFilesWithExtension CACHEDIR "ltar"
return .ofList (paths.toList.map (·.withoutParent CACHEDIR |>.toString)) _
def isFromMathlib (mod : Name) : Bool :=
mod.getRoot == `Mathlib
/-- Decompresses build files into their respective folders -/
def unpackCache (hashMap : ModuleHashMap) (force : Bool) : CacheM Unit := do
let hashMap ← hashMap.filterExists true
let size := hashMap.size
if size > 0 then
let now ← IO.monoMsNow
IO.println s!"Decompressing {size} file(s)"
let args := (if force then #["-f"] else #[]) ++ #["-x", "--delete-corrupted", "-j", "-"]
let child ← IO.Process.spawn { cmd := ← getLeanTar, args, stdin := .piped }
let (stdin, child) ← child.takeStdin
/-
TODO: The case distinction below could be avoided by making use of the `leantar` option `-C`
(rsp the `"base"` field in JSON format, see below) here and in `packCache`.
See also https://github.com/leanprover-community/mathlib4/pull/8767#discussion_r1422077498
Doing this, one could avoid that the package directory path (for dependencies) appears
inside the leantar files, but unless `cache` is upstreamed to work on upstream packages
themselves (without `Mathlib`), this might not be too useful to change.
NOTE: making changes to the generated .ltar files invalidates them while it *DOES NOT* change
the file hash! This means any such change needs to be accompanied by a change
to the root hash affecting *ALL* files
(e.g. any modification to lakefile, lean-toolchain or manifest)
-/
let isMathlibRoot ← isMathlibRoot
let mathlibDepPath := (← read).mathlibDepPath.toString
let config : Array Lean.Json := hashMap.fold (init := #[]) fun config mod hash =>
let pathStr := s!"{CACHEDIR / hash.asLTar}"
if isMathlibRoot || !isFromMathlib mod then
config.push <| .str pathStr
else
-- only mathlib files, when not in the mathlib4 repo, need to be redirected
config.push <| .mkObj [("file", pathStr), ("base", mathlibDepPath)]
stdin.putStr <| Lean.Json.compress <| .arr config
let exitCode ← child.wait
if exitCode != 0 then throw <| IO.userError s!"leantar failed with error code {exitCode}"
IO.println s!"Unpacked in {(← IO.monoMsNow) - now} ms"
IO.println "Completed successfully!"
else IO.println "No cache files to decompress"
instance : Ord FilePath where
compare x y := compare x.toString y.toString
/-- Removes all cache files except for what's in the `keep` set -/
def cleanCache (keep : Std.TreeSet FilePath compare := ∅) : IO Unit := do
for path in ← getFilesWithExtension CACHEDIR "ltar" do
if !keep.contains path then IO.FS.removeFile path
/-- Prints the LTAR file and embedded comments (in particular, the mathlib commit that built the
file) regarding the specified modules. -/
def lookup (hashMap : ModuleHashMap) (modules : List Name) : IO Unit := do
let mut err := false
for mod in modules do
let some hash := hashMap[mod]? | err := true
let ltar := CACHEDIR / hash.asLTar
IO.println s!"{mod}: {ltar}"
for line in (← runCmd (← getLeanTar) #["-k", ltar.toString]).splitOn "\n" |>.dropLast do
println! " comment: {line}"
if err then IO.Process.exit 1
/--
Parse a string as either a path or a Lean module name.
TODO: If the argument describes a folder, use `walkDir` to find all `.lean` files within.
Return tuples of the form ("module name", "path to .lean file").
The input string `arg` takes one of the following forms:
1. `Mathlib.Algebra.Fields.Basic`: there exists such a Lean file
2. `Mathlib.Algebra.Fields`: no Lean file exists but a folder (TODO)
3. `Mathlib/Algebra/Fields/Basic.lean`: the file exists (note potentially `\` on Windows)
4. `Mathlib/Algebra/Fields/`: the folder exists (TODO)
Not supported yet:
5. `Aesop/Builder.lean`: the file does not exist, it's actually somewhere in `.lake`.
Note: An argument like `Archive` is treated as module, not a path.
-/
def leanModulesFromSpec (sp : SearchPath) (argₛ : String) :
IO <| Except String <| Array (Name × FilePath) := do
-- TODO: This could be just `FilePath.normalize` if the TODO there was addressed
let arg : FilePath := System.mkFilePath <|
(argₛ : FilePath).normalize.components.filter (· != "")
if arg.components.length > 1 || arg.extension == "lean" then
-- provided file name of a Lean file
let mod : Name := arg.withExtension "" |>.components.foldl .str .anonymous
if !(← arg.pathExists) then
-- TODO: (5.) We could use `getSrcDir` to allow arguments like `Aesop/Builder.lean` which
-- refer to a file located under `.lake/packages/...`
return .error s!"Invalid argument: non-existing path {arg}"
if arg.extension == "lean" then
-- (3.) provided existing `.lean` file
return .ok #[(mod, arg)]
else
-- (4.) provided existing directory: walk it
return .error "Searching lean files in a folder is not supported yet!"
else
-- provided a module
let mod := argₛ.toName
let sourceFile ← Lean.findLean sp mod
if ← sourceFile.pathExists then
-- (1.) provided valid module
return .ok #[(mod, sourceFile)]
else
-- provided "pseudo-module" (like `Mathlib.Data`) which
-- does not correspond to a Lean file, but to an existing folder
-- `Mathlib/Data/`
let folder := sourceFile.withExtension ""
IO.println s!"Searching directory {folder} for .lean files"
if ← folder.pathExists then
-- (2.) provided "module name" of an existing folder: walk dir
-- TODO: will be implemented in https://github.com/leanprover-community/mathlib4/issues/21838
return .error "Entering a part of a module name \
(i.e. `Mathlib.Data` when only the folder `Mathlib/Data/` but no \
file `Mathlib/Data.lean` exists) is not supported yet!"
else
return .error s!"Invalid argument: non-existing module {mod}"
/--
Parse command line arguments.
Position `0` (i.e. the command `get`, `clean`, etc.) is ignored.
The remaining arguments are parsed as either module name or file path, see `leanModulesFromSpec`.
-/
def parseArgs (args : List String) : CacheM <| Std.HashMap Name FilePath := do
match args with
| [] => pure ∅
| _ :: args₀ => args₀.foldlM (init := ∅) fun acc (arg : String) => do
let sp := (← read).srcSearchPath
match (← leanModulesFromSpec sp arg) with
| .ok mods =>
pure <| acc.insertMany mods
| .error msg =>
IO.eprintln msg
IO.Process.exit 1
end Cache.IO |
.lake/packages/mathlib/Cache/Requests.lean | import Batteries.Data.String.Matcher
import Cache.Hashing
namespace Cache.Requests
open System (FilePath)
-- FRO cache may be flaky: https://leanprover.zulipchat.com/#narrow/channel/113488-general/topic/The.20cache.20doesn't.20work/near/411058849
initialize useFROCache : Bool ← do
let froCache ← IO.getEnv "USE_FRO_CACHE"
return froCache == some "1" || froCache == some "true"
/--
Structure to hold repository information with priority ordering
-/
structure RepoInfo where
repo : String
useFirst : Bool
deriving Repr
/--
Helper function to extract repository name from a git remote URL
-/
def extractRepoFromUrl (url : String) : Option String := do
let url := url.stripSuffix ".git"
let pos ← url.revFind (· == '/')
let pos ← url.revFindAux (fun c => c == '/' || c == ':') pos
return (String.Pos.Raw.extract url) (String.Pos.Raw.next url pos) url.endPos
/-- Spot check if a URL is valid for a git remote -/
def isRemoteURL (url : String) : Bool :=
"https://".isPrefixOf url || "http://".isPrefixOf url || "git@github.com:".isPrefixOf url
/--
Helper function to get repository from a remote name
-/
def getRepoFromRemote (mathlibDepPath : FilePath) (remoteName : String) (errorContext : String) : IO String := do
-- If the remote is already a valid URL, attempt to extract the repo from it. This happens with `gh pr checkout`
if isRemoteURL remoteName then
repoFromURL remoteName
else
-- If not, we use `git remote get-url` to find the URL of the remote. This assumes the remote has a
-- standard name like `origin` or `upstream` or it errors out.
let out ← IO.Process.output
{cmd := "git", args := #["remote", "get-url", remoteName], cwd := mathlibDepPath}
-- If `git remote get-url` fails then bail out with an error to help debug
let output := out.stdout.trim
unless out.exitCode == 0 do
throw <| IO.userError s!"\
Failed to run Git to determine Mathlib's repository from {remoteName} remote (exit code: {out.exitCode}).\n\
{errorContext}\n\
Stdout:\n{output}\nStderr:\n{out.stderr.trim}\n"
-- Finally attempt to extract the repository from the remote URL returned by `git remote get-url`
repoFromURL output
where repoFromURL (url : String) : IO String := do
if let some repo := extractRepoFromUrl url then
return repo
else
throw <| IO.userError s!"\
Failed to extract repository from remote URL: {url}.\n\
{errorContext}\n\
Please ensure the remote URL is valid and points to a GitHub repository."
/--
Finds the remote name that points to `leanprover-community/mathlib4` repository.
Returns the remote name and prints warnings if the setup doesn't follow conventions.
-/
def findMathlibRemote (mathlibDepPath : FilePath) : IO String := do
let remotesInfo ← IO.Process.output
{cmd := "git", args := #["remote", "-v"], cwd := mathlibDepPath}
unless remotesInfo.exitCode == 0 do
throw <| IO.userError s!"\
Failed to run Git to list remotes (exit code: {remotesInfo.exitCode}).\n\
Ensure Git is installed.\n\
Stdout:\n{remotesInfo.stdout.trim}\nStderr:\n{remotesInfo.stderr.trim}\n"
let remoteLines := remotesInfo.stdout.splitToList (· == '\n')
let mut mathlibRemote : Option String := none
let mut originPointsToMathlib : Bool := false
for line in remoteLines do
let parts := line.trim.splitToList (· == '\t')
if parts.length >= 2 then
let remoteName := parts[0]!
let remoteUrl := parts[1]!.takeWhile (· != ' ') -- Remove (fetch) or (push) suffix
-- Check if this remote points to leanprover-community/mathlib4
let isMathlibRepo := remoteUrl.containsSubstr "leanprover-community/mathlib4"
if isMathlibRepo then
if remoteName == "origin" then
originPointsToMathlib := true
mathlibRemote := some remoteName
match mathlibRemote with
| none =>
throw <| IO.userError "Could not find a remote pointing to leanprover-community/mathlib4"
| some remoteName =>
if remoteName != "upstream" then
let mut warning := s!"Some Mathlib ecosystem tools assume that the git remote for `leanprover-community/mathlib4` is named `upstream`. You have named it `{remoteName}` instead. We recommend changing the name to `upstream`."
if originPointsToMathlib then
warning := warning ++ " Moreover, `origin` should point to your own fork of the mathlib4 repository."
warning := warning ++ " You can set this up with `git remote add upstream https://github.com/leanprover-community/mathlib4.git`."
IO.println s!"Warning: {warning}"
return remoteName
/--
Extracts PR number from a git ref like "refs/remotes/upstream/pr/1234"
-/
def extractPRNumber (ref : String) : Option Nat := do
let parts := ref.splitToList (· == '/')
if parts.length >= 2 && parts[parts.length - 2]! == "pr" then
let prStr := parts[parts.length - 1]!
prStr.toNat?
else
none
/-- Check if we're in a detached HEAD state at a nightly-testing tag -/
def isDetachedAtNightlyTesting (mathlibDepPath : FilePath) : IO Bool := do
-- Get the current commit hash and check if it's a nightly-testing tag
let currentCommit ← IO.Process.output
{cmd := "git", args := #["rev-parse", "HEAD"], cwd := mathlibDepPath}
if currentCommit.exitCode == 0 then
let commitHash := currentCommit.stdout.trim
let tagInfo ← IO.Process.output
{cmd := "git", args := #["name-rev", "--tags", commitHash], cwd := mathlibDepPath}
if tagInfo.exitCode == 0 then
let parts := tagInfo.stdout.trim.splitOn " "
-- git name-rev returns "commit_hash tags/tag_name" or just "commit_hash undefined" if no tag
if parts.length >= 2 && parts[1]!.startsWith "tags/" then
let tagName := parts[1]!.drop 5 -- Remove "tags/" prefix
return tagName.startsWith "nightly-testing-"
else
return false
else
return false
else
return false
/--
Attempts to determine the GitHub repository of a version of Mathlib from its Git remote.
If the current commit coincides with a PR ref, it will determine the source fork
of that PR rather than just using the origin remote.
-/
def getRemoteRepo (mathlibDepPath : FilePath) : IO RepoInfo := do
-- Since currently we need to push a PR to `leanprover-community/mathlib` build a user cache,
-- we check if we are a special branch or a branch with PR. This leaves out non-PRed fork
-- branches. These should be covered if we ever change how the cache is uploaded from forks
-- to obviate the need for a PR.
let currentBranch ← IO.Process.output
{cmd := "git", args := #["rev-parse", "--abbrev-ref", "HEAD"], cwd := mathlibDepPath}
if currentBranch.exitCode == 0 then
let branchName := currentBranch.stdout.trim.stripPrefix "heads/"
IO.println s!"Current branch: {branchName}"
-- Check if we're in a detached HEAD state at a nightly-testing tag
let isDetachedAtNightlyTesting ← if branchName == "HEAD" then
isDetachedAtNightlyTesting mathlibDepPath
else
pure false
-- Check if we're on a branch that should use nightly-testing remote
let shouldUseNightlyTesting := branchName == "nightly-testing" ||
branchName.startsWith "lean-pr-testing-" ||
branchName.startsWith "batteries-pr-testing-" ||
branchName.startsWith "bump/" ||
isDetachedAtNightlyTesting
if shouldUseNightlyTesting then
let repo := "leanprover-community/mathlib4-nightly-testing"
let cacheService := if useFROCache then "Cloudflare" else "Azure"
IO.println s!"Using cache ({cacheService}) from nightly-testing remote: {repo}"
return {repo := repo, useFirst := true}
-- Only search for PR refs if we're not on a regular branch like master, bump/*, or nightly-testing*
-- let isSpecialBranch := branchName == "master" || branchName.startsWith "bump/" ||
-- branchName.startsWith "nightly-testing"
-- TODO: this code is currently broken in two ways: 1. you need to write `%(refname)` in quotes and
-- 2. it is looking in the wrong place when in detached HEAD state.
-- We comment it out for now, but we should fix it later.
-- Check if the current commit coincides with any PR ref
-- if !isSpecialBranch then
-- let mathlibRemoteName ← findMathlibRemote mathlibDepPath
-- let currentCommit ← IO.Process.output
-- {cmd := "git", args := #["rev-parse", "HEAD"], cwd := mathlibDepPath}
--
-- if currentCommit.exitCode == 0 then
-- let commit := currentCommit.stdout.trim
-- -- Get all PR refs that contain this commit
-- let prRefPattern := s!"refs/remotes/{mathlibRemoteName}/pr/*"
-- let refsInfo ← IO.Process.output
-- {cmd := "git", args := #["for-each-ref", "--contains", commit, prRefPattern, "--format=%(refname)"], cwd := mathlibDepPath}
-- -- The code below is for debugging purposes currently
-- IO.println s!"`git for-each-ref --contains {commit} {prRefPattern} --format=%(refname)` returned:
-- {refsInfo.stdout.trim} with exit code {refsInfo.exitCode} and stderr: {refsInfo.stderr.trim}."
-- let refsInfo' ← IO.Process.output
-- {cmd := "git", args := #["for-each-ref", "--contains", commit, prRefPattern, "--format=\"%(refname)\""], cwd := mathlibDepPath}
-- IO.println s!"`git for-each-ref --contains {commit} {prRefPattern} --format=\"%(refname)\"` returned:
-- {refsInfo'.stdout.trim} with exit code {refsInfo'.exitCode} and stderr: {refsInfo'.stderr.trim}."
--
-- if refsInfo.exitCode == 0 && !refsInfo.stdout.trim.isEmpty then
-- let prRefs := refsInfo.stdout.trim.split (· == '\n')
-- -- Extract PR numbers from refs like "refs/remotes/upstream/pr/1234"
-- for prRef in prRefs do
-- if let some prNumber := extractPRNumber prRef then
-- -- Get PR details using gh
-- let prInfo ← IO.Process.output
-- {cmd := "gh", args := #["pr", "view", toString prNumber, "--json", "headRefName,headRepositoryOwner,number"], cwd := mathlibDepPath}
-- if prInfo.exitCode == 0 then
-- if let .ok json := Lean.Json.parse prInfo.stdout.trim then
-- if let .ok owner := json.getObjValAs? Lean.Json "headRepositoryOwner" then
-- if let .ok login := owner.getObjValAs? String "login" then
-- if let .ok repoName := json.getObjValAs? String "headRefName" then
-- if let .ok prNum := json.getObjValAs? Nat "number" then
-- let repo := s!"{login}/mathlib4"
-- IO.println s!"Using cache from PR #{prNum} source: {login}/{repoName} (commit {commit.take 8} found in PR ref)"
-- let useFirst := if login != "leanprover-community" then true else false
-- return {repo := repo, useFirst := useFirst}
-- Fall back to using the remote that the current branch is tracking
let trackingRemote ← IO.Process.output
{cmd := "git", args := #["config", "--get", s!"branch.{currentBranch.stdout.trim}.remote"], cwd := mathlibDepPath}
let remoteName := if trackingRemote.exitCode == 0 then
trackingRemote.stdout.trim
else
-- If no tracking remote is configured, fall back to origin
"origin"
let repo ← getRepoFromRemote mathlibDepPath remoteName
s!"Ensure Git is installed and the '{remoteName}' remote points to its GitHub repository."
let cacheService := if useFROCache then "Cloudflare" else "Azure"
IO.println s!"Using cache ({cacheService}) from {remoteName}: {repo}"
return {repo := repo, useFirst := false}
/-- Public URL for mathlib cache -/
def URL : String :=
if useFROCache then
"https://mathlib4.lean-cache.cloud"
else
"https://lakecache.blob.core.windows.net/mathlib4"
/-- Retrieves the azure token from the environment -/
def getToken : IO String := do
let envVar := if useFROCache then "MATHLIB_CACHE_S3_TOKEN" else "MATHLIB_CACHE_SAS"
let some token ← IO.getEnv envVar
| throw <| IO.userError s!"environment variable {envVar} must be set to upload caches"
return token
/-- The full name of the main Mathlib GitHub repository. -/
def MATHLIBREPO := "leanprover-community/mathlib4"
/--
Given a file name like `"1234.tar.gz"`, makes the URL to that file on the server.
The `f/` prefix means that it's a common file for caching.
-/
def mkFileURL (repo URL fileName : String) : String :=
let pre := if !useFROCache && repo == MATHLIBREPO then "" else s!"{repo}/"
s!"{URL}/f/{pre}{fileName}"
section Get
/-- Formats the config file for `curl`, containing the list of files to be downloaded -/
def mkGetConfigContent (repo : String) (hashMap : IO.ModuleHashMap) : IO String := do
hashMap.toArray.foldlM (init := "") fun acc ⟨_, hash⟩ => do
let fileName := hash.asLTar
-- Below we use `String.quote`, which is intended for quoting for use in Lean code
-- this does not exactly match the requirements for quoting for curl:
-- ```
-- If the parameter contains whitespace (or starts with : or =),
-- the parameter must be enclosed within quotes.
-- Within double quotes, the following escape sequences are available:
-- \, ", \t, \n, \r and \v.
-- A backslash preceding any other letter is ignored.
-- ```
-- If this becomes an issue we can implement the curl spec.
-- Note we append a '.part' to the filenames here,
-- which `downloadFiles` then removes when the download is successful.
pure <| acc ++ s!"url = {mkFileURL repo URL fileName}\n\
-o {(IO.CACHEDIR / (fileName ++ ".part")).toString.quote}\n"
/-- Calls `curl` to download a single file from the server to `CACHEDIR` (`.cache`) -/
def downloadFile (repo : String) (hash : UInt64) : IO Bool := do
let fileName := hash.asLTar
let url := mkFileURL repo URL fileName
let path := IO.CACHEDIR / fileName
let partFileName := fileName ++ ".part"
let partPath := IO.CACHEDIR / partFileName
let out ← IO.Process.output
{ cmd := (← IO.getCurl), args := #[url, "--fail", "--silent", "-o", partPath.toString] }
if out.exitCode = 0 then
IO.FS.rename partPath path
pure true
else
IO.FS.removeFile partPath
pure false
private structure TransferState where
last : Nat
success : Nat
failed : Nat
done : Nat
speed : Nat
def monitorCurl (args : Array String) (size : Nat)
(caption : String) (speedVar : String) (removeOnError := false) : IO TransferState := do
let mkStatus success failed done speed := Id.run do
let speed :=
if speed != 0 then
s!", {speed / 1000} KB/s"
else ""
let mut msg := s!"\r{caption}: {success} file(s) [attempted {done}/{size} = {100*done/size}%{speed}]"
if failed != 0 then
msg := msg ++ s!", {failed} failed"
return msg
let init : TransferState := ⟨← IO.monoMsNow, 0, 0, 0, 0⟩
let s@{success, failed, done, speed, ..} ← IO.runCurlStreaming args init fun a line => do
let mut {last, success, failed, done, speed} := a
-- output errors other than 404 and remove corresponding partial downloads
let line := line.trim
if !line.isEmpty then
match Lean.Json.parse line with
| .ok result =>
match result.getObjValAs? Nat "http_code" with
| .ok 200 =>
if let .ok fn := result.getObjValAs? String "filename_effective" then
if (← System.FilePath.pathExists fn) && fn.endsWith ".part" then
IO.FS.rename fn (fn.dropRight 5)
success := success + 1
| .ok 404 => pure ()
| code? =>
failed := failed + 1
let mkFailureMsg code? fn? msg? : String := Id.run do
let mut msg := "Transfer failed"
if let .ok fn := fn? then
msg := s!"{fn}: {msg}"
if let .ok code := code? then
msg := s!"{msg} (error code: {code})"
if let .ok errMsg := msg? then
msg := s!"{msg}: {errMsg}"
return msg
let msg? := result.getObjValAs? String "errormsg"
let fn? := result.getObjValAs? String "filename_effective"
IO.println (mkFailureMsg code? fn? msg?)
if let .ok fn := fn? then
if removeOnError then
-- `curl --remove-on-error` can already do this, but only from 7.83 onwards
if (← System.FilePath.pathExists fn) then
IO.FS.removeFile fn
done := done + 1
let now ← IO.monoMsNow
if now - last ≥ 100 then -- max 10/s update rate
speed := match result.getObjValAs? Nat speedVar with
| .ok speed => speed | .error _ => speed
IO.eprint (mkStatus success failed done speed)
last := now
| .error e =>
IO.println s!"Non-JSON output from curl:\n {line}\n{e}"
pure {last, success, failed, done, speed}
if done > 0 then
-- to avoid confusingly moving on without finishing the count
IO.eprintln (mkStatus success failed done speed)
return s
/-- Call `curl` to download files from the server to `CACHEDIR` (`.cache`).
Exit the process with exit code 1 if any files failed to download. -/
def downloadFiles
(repo : String) (hashMap : IO.ModuleHashMap)
(forceDownload : Bool) (parallel : Bool) (warnOnMissing : Bool): IO Unit := do
let hashMap ← if forceDownload then pure hashMap else hashMap.filterExists false
let size := hashMap.size
if size > 0 then
IO.FS.createDirAll IO.CACHEDIR
IO.println s!"Attempting to download {size} file(s) from {repo} cache"
let failed ← if parallel then
IO.FS.writeFile IO.CURLCFG (← mkGetConfigContent repo hashMap)
let args := #["--request", "GET", "--parallel",
-- commented as this creates a big slowdown on curl 8.13.0: "--fail",
"--silent",
"--retry", "5", -- there seem to be some intermittent failures
"--write-out", "%{json}\n", "--config", IO.CURLCFG.toString]
let {success, failed, done, ..} ←
monitorCurl args size "Downloaded" "speed_download" (removeOnError := true)
IO.FS.removeFile IO.CURLCFG
if warnOnMissing && success + failed < done then
IO.eprintln "Warning: some files were not found in the cache."
IO.eprintln "This usually means that your local checkout of mathlib4 has diverged from upstream."
IO.eprintln "If you push your commits to a branch of the mathlib4 repository, CI will build the oleans and they will be available later."
IO.eprintln "Alternatively, if you already have pushed your commits to a branch, this may mean the CI build has failed part-way through building."
pure failed
else
let r ← hashMap.foldM (init := []) fun acc _ hash => do
pure <| (← IO.asTask do downloadFile repo hash) :: acc
pure <| r.foldl (init := 0) fun f t => if let .ok true := t.get then f else f + 1
if failed > 0 then
IO.println s!"{failed} download(s) failed"
IO.Process.exit 1
else IO.println "No files to download"
/-- Check if the project's `lean-toolchain` file matches mathlib's.
Print and error and exit the process with error code 1 otherwise. -/
def checkForToolchainMismatch : IO.CacheM Unit := do
let mathlibToolchainFile := (← read).mathlibDepPath / "lean-toolchain"
let downstreamToolchain ← IO.FS.readFile "lean-toolchain"
let mathlibToolchain ← IO.FS.readFile mathlibToolchainFile
if !(mathlibToolchain.trim = downstreamToolchain.trim) then
IO.println "Dependency Mathlib uses a different lean-toolchain"
IO.println s!" Project uses {downstreamToolchain.trim}"
IO.println s!" Mathlib uses {mathlibToolchain.trim}"
IO.println "\nThe cache will not work unless your project's toolchain matches Mathlib's toolchain"
IO.println s!"This can be achieved by copying the contents of the file `{mathlibToolchainFile}`
into the `lean-toolchain` file at the root directory of your project"
if !System.Platform.isWindows then
IO.println s!"You can use `cp {mathlibToolchainFile} ./lean-toolchain`"
else
IO.println s!"On powershell you can use `cp {mathlibToolchainFile} ./lean-toolchain`"
IO.println s!"On Windows CMD you can use `copy {mathlibToolchainFile} lean-toolchain`"
IO.Process.exit 1
return ()
/-- Fetches the ProofWidgets cloud release and prunes non-JS files. -/
def getProofWidgets (buildDir : FilePath) : IO Unit := do
if (← buildDir.pathExists) then
-- Check if the ProofWidgets build is out-of-date via `lake`.
-- This is done through Lake as cache has no simple heuristic
-- to determine whether the ProofWidgets JS is out-of-date.
let out ← IO.Process.output
{cmd := "lake", args := #["-v", "build", "--no-build", "proofwidgets:release"]}
if out.exitCode == 0 then -- up-to-date
return
else if out.exitCode == 3 then -- needs fetch (`--no-build` triggered)
pure ()
else
printLakeOutput out
throw <| IO.userError s!"Failed to validate ProofWidgets cloud release: \
lake failed with error code {out.exitCode}"
-- Download and unpack the ProofWidgets cloud release (for its `.js` files)
IO.print "Fetching ProofWidgets cloud release..."
let out ← IO.Process.output
{cmd := "lake", args := #["-v", "build", "proofwidgets:release"]}
if out.exitCode == 0 then
IO.println " done!"
else
IO.print "\n"
printLakeOutput out
throw <| IO.userError s!"Failed to fetch ProofWidgets cloud release: \
lake failed with error code {out.exitCode}"
-- Prune non-JS ProofWidgets files (e.g., `olean`, `.c`)
try
IO.FS.removeDirAll (buildDir / "lib")
IO.FS.removeDirAll (buildDir / "ir")
catch e =>
throw <| IO.userError s!"Failed to prune ProofWidgets cloud release: {e}"
where
printLakeOutput out := do
unless out.stdout.isEmpty do
IO.eprintln "lake stdout:"
IO.eprint out.stderr
unless out.stderr.isEmpty do
IO.eprintln "lake stderr:"
IO.eprint out.stderr
/-- Downloads missing files, and unpacks files. -/
def getFiles
(repo? : Option String) (hashMap : IO.ModuleHashMap)
(forceDownload forceUnpack parallel decompress : Bool)
: IO.CacheM Unit := do
let isMathlibRoot ← IO.isMathlibRoot
unless isMathlibRoot do checkForToolchainMismatch
getProofWidgets (← read).proofWidgetsBuildDir
if let some repo := repo? then
downloadFiles repo hashMap forceDownload parallel (warnOnMissing := true)
else
let repoInfo ← getRemoteRepo (← read).mathlibDepPath
-- Build list of repositories to download from in order
let repos : List String :=
if repoInfo.repo == MATHLIBREPO then
[repoInfo.repo]
else if repoInfo.useFirst then
[repoInfo.repo, MATHLIBREPO]
else
[MATHLIBREPO, repoInfo.repo]
for h : i in [0:repos.length] do
downloadFiles repos[i] hashMap forceDownload parallel (warnOnMissing := i = repos.length - 1)
if decompress then
IO.unpackCache hashMap forceUnpack
else
IO.println "Downloaded all files successfully!"
end Get
section Put
/-- FRO cache S3 URL -/
def UPLOAD_URL : String :=
if useFROCache then
"https://a09a7664adc082e00f294ac190827820.r2.cloudflarestorage.com/mathlib4"
else
URL
/-- Formats the config file for `curl`, containing the list of files to be uploaded -/
def mkPutConfigContent (repo : String) (fileNames : Array String) (token : String) : IO String := do
let token := if useFROCache then "" else s!"?{token}" -- the FRO cache doesn't pass the token here
let l ← fileNames.toList.mapM fun fileName : String => do
pure s!"-T {(IO.CACHEDIR / fileName).toString}\nurl = {mkFileURL repo UPLOAD_URL fileName}{token}"
return "\n".intercalate l
/-- Calls `curl` to send a set of cached files to the server -/
def putFiles
(repo : String) (fileNames : Array String)
(overwrite : Bool) (token : String) : IO Unit := do
-- TODO: reimplement using HEAD requests?
let _ := overwrite
let size := fileNames.size
if size > 0 then
IO.FS.writeFile IO.CURLCFG (← mkPutConfigContent repo fileNames token)
IO.println s!"Attempting to upload {size} file(s) to {repo} cache"
let args := if useFROCache then
-- TODO: reimplement using HEAD requests?
let _ := overwrite
#["--aws-sigv4", "aws:amz:auto:s3", "--user", token]
else if overwrite then
#["-H", "x-ms-blob-type: BlockBlob"]
else
#["-H", "x-ms-blob-type: BlockBlob", "-H", "If-None-Match: *"]
let args := args ++ #[
"-X", "PUT", "--parallel",
"--retry", "5", -- there seem to be some intermittent failures
"--write-out", "%{json}\n", "--config", IO.CURLCFG.toString]
discard <| monitorCurl args size "Uploaded" "speed_upload"
IO.FS.removeFile IO.CURLCFG
else IO.println "No files to upload"
end Put
section Commit
def isGitStatusClean : IO Bool :=
return (← IO.runCmd "git" #["status", "--porcelain"]).isEmpty
def getGitCommitHash : IO String := return (← IO.runCmd "git" #["rev-parse", "HEAD"]).trimRight
/--
Sends a commit file to the server, containing the hashes of the respective committed files.
The file name is the current Git hash and the `c/` prefix means that it's a commit file.
-/
def commit (hashMap : IO.ModuleHashMap) (overwrite : Bool) (token : String) : IO Unit := do
let hash ← getGitCommitHash
let path := IO.CACHEDIR / hash
IO.FS.createDirAll IO.CACHEDIR
IO.FS.writeFile path <| ("\n".intercalate <| hashMap.hashes.toList.map toString) ++ "\n"
if useFROCache then
-- TODO: reimplement using HEAD requests?
let _ := overwrite
discard <| IO.runCurl #["-T", path.toString,
"--aws-sigv4", "aws:amz:auto:s3", "--user", token, s!"{UPLOAD_URL}/c/{hash}"]
else
let params := if overwrite
then #["-X", "PUT", "-H", "x-ms-blob-type: BlockBlob"]
else #["-X", "PUT", "-H", "x-ms-blob-type: BlockBlob", "-H", "If-None-Match: *"]
discard <| IO.runCurl <| params ++ #["-T", path.toString, s!"{URL}/c/{hash}?{token}"]
IO.FS.removeFile path
end Commit
section Collect
inductive QueryType
| files | commits | all
def QueryType.prefix : QueryType → String
| files => "&prefix=f/"
| commits => "&prefix=c/"
| all => ""
def formatError {α : Type} : IO α :=
throw <| IO.userError "Invalid format for curl return"
def QueryType.desc : QueryType → String
| files => "hosted files"
| commits => "hosted commits"
| all => "everything"
/--
Retrieves metadata about hosted files: their names and the timestamps of last modification.
Example: `["f/39476538726384726.tar.gz", "Sat, 24 Dec 2022 17:33:01 GMT"]`
-/
def getFilesInfo (q : QueryType) : IO <| List (String × String) := do
if useFROCache then
throw <| .userError "FIXME: getFilesInfo is not adapted to FRO cache yet"
IO.println s!"Downloading info list of {q.desc}"
let ret ← IO.runCurl #["-X", "GET", s!"{URL}?comp=list&restype=container{q.prefix}"]
match ret.splitOn "<Name>" with
| [] => formatError
| [_] => return []
| _ :: parts =>
parts.mapM fun part => match part.splitOn "</Name>" with
| [name, rest] => match rest.splitOn "<Last-Modified>" with
| [_, rest] => match rest.splitOn "</Last-Modified>" with
| [date, _] => pure (name, date)
| _ => formatError
| _ => formatError
| _ => formatError
end Collect
end Cache.Requests |
.lake/packages/mathlib/Cache/Lean.lean | import Lean.Data.Json
import Lean.Util.Path
/-!
# Helper Functions
This file contains helper functions that could potentially be upstreamed to Lean
or replaced by an appropriate function from Lean.
Some functions here are duplicates from the folder `Mathlib/Lean/`.
-/
/-- Format as hex digit string. Used by `Cache` to format hashes. -/
def Nat.toHexDigits (n : Nat) : Nat → (res : String := "") → String
| 0, s => s
| len + 1, s =>
let b := UInt8.ofNat (n >>> (len * 8))
Nat.toHexDigits n len <|
s.push (Nat.digitChar (b >>> 4).toNat) |>.push (Nat.digitChar (b &&& 15).toNat)
/-- Format hash as hex digit with extension `.ltar` -/
def UInt64.asLTar (n : UInt64) : String :=
s!"{Nat.toHexDigits n.toNat 8}.ltar"
-- copied from Mathlib
/-- Create a `Name` from a list of components. -/
def Lean.Name.fromComponents : List Name → Name := go .anonymous where
go : Name → List Name → Name
| n, [] => n
| n, s :: rest => go (s.updatePrefix n) rest
namespace Lean.SearchPath
open System in
/--
Find the source directory for a module. This could be `.`
(or in fact also something uncleaned like `./././.`) if the
module is part of the current package, or something like `.lake/packages/mathlib` if the
module is from a dependency.
This is an exact copy of the first part of `Lean.SearchPath.findWithExt` which, in turn,
is used by `Lean.findLean sp mod`. In the future, `findWithExt` could be refactored to
expose this base path.
-/
def findWithExtBase (sp : SearchPath) (ext : String) (mod : Name) : IO (Option FilePath) := do
let pkg := mod.getRoot.toString (escape := false)
sp.findM? fun p =>
(p / pkg).isDir <||> ((p / pkg).addExtension ext).pathExists
end Lean.SearchPath
namespace System.FilePath
/-- Removes a parent path from the beginning of a path -/
def withoutParent (path parent : FilePath) : FilePath :=
mkFilePath <| go path.components parent.components
where
go : List String → List String → List String
| path@(x :: xs), y :: ys => if x == y then go xs ys else path
| [], _ => []
| path, [] => path
end System.FilePath |
.lake/packages/mathlib/Cache/Hashing.lean | import Cache.IO
import Lean.Elab.ParseImportsFast
namespace Cache.Hashing
open Lean IO
open System hiding SearchPath
/--
The `HashMemo` contains all information `Cache` needs about the modules:
* the name
* its imports
* the file's hash (in `hashMap` and `cache`)
additionally, it contains the `rootHash` which reflects changes to Mathlib's
Lake project settings.
-/
structure HashMemo where
/-- Hash of mathlib's lake project settings. -/
rootHash : UInt64
/-- Maps the `.lean` file of a module to the `.lean` files of its imports. -/
depsMap : Std.HashMap Name (Array Name) := ∅
/--
For files with a valid hash (usually Mathlib and upstream),
this contains the same information as `hashMap`.
Other files have `none` here and do not appear in `hashMap`
(e.g. `.lean` source could not be found, imports a file without valid hash).
-/
cache : Std.HashMap Name (Option UInt64) := ∅
/-- Stores the hash of the module's content for modules in Mathlib or upstream. -/
hashMap : ModuleHashMap := ∅
deriving Inhabited
partial def insertDeps (hashMap : ModuleHashMap) (mod : Name) (hashMemo : HashMemo) :
ModuleHashMap :=
if hashMap.contains mod then hashMap else
match (hashMemo.depsMap[mod]?, hashMemo.hashMap[mod]?) with
| (some deps, some hash) => deps.foldl (insertDeps · · hashMemo) (hashMap.insert mod hash)
| _ => hashMap
/--
Filters the `hashMap` of a `HashMemo` so that it only contains key/value pairs such that every key:
* Belongs to the given list of module names or
* Corresponds to a module that's imported (transitively or not) by
some module in the list module names
-/
def HashMemo.filterByRootModules (hashMemo : HashMemo) (modules : List Name) :
IO ModuleHashMap := do
let mut hashMap := ∅
for mod in modules do
if hashMemo.hashMap.contains mod then
hashMap := insertDeps hashMap mod hashMemo
else IO.println s!"{mod} is not covered by the olean cache."
return hashMap
/-- We cache the hash of each file and their dependencies for later lookup -/
abbrev HashM := StateT HashMemo CacheM
/--
Read the imports from the raw file `content` and return an array of tuples
`(module name, source file)`, one per import.
Note: `fileName` is a string which is purely used for displaying an error message if
parsing imports from `content` should fail. It is intended to be the file's name.
-/
def getFileImports (content : String) (fileName : String := "") :
CacheM <| Array (Name × FilePath) := do
let sp := (← read).srcSearchPath
let res ← Lean.parseImports' content fileName
res.imports
|>.filter (isPartOfMathlibCache ·.module)
|>.mapM fun imp => do
let impSourceFile ← Lean.findLean sp imp.module
pure (imp.module, impSourceFile)
/-- Computes a canonical hash of a file's contents. -/
def hashFileContents (contents : String) : UInt64 :=
-- revert potential file transformation by git's `autocrlf`
hash contents.crlfToLf
/--
Computes the root hash, which mixes the hashes of the content of:
* `lakefile.lean`
* `lean-toolchain`
* `lake-manifest.json`
and the hash of `Lean.githash`.
-/
def getRootHash : CacheM UInt64 := do
let mathlibDepPath := (← read).mathlibDepPath
let rootFiles : List FilePath := [
mathlibDepPath / "lakefile.lean",
mathlibDepPath / "lean-toolchain",
mathlibDepPath / "lake-manifest.json"]
let hashes ← rootFiles.mapM fun path =>
hashFileContents <$> IO.FS.readFile path
return hash (rootHashGeneration :: hashes)
/--
Computes the hash of a file, which mixes:
* The root hash
* The hash of its relative path (inside its package directory)
* The hash of its content
* The hashes of the imported files that are part of `Mathlib`
Note: we pass `sourceFile` along to avoid searching for it twice
-/
partial def getHash (mod : Name) (sourceFile : FilePath) (visited : Std.HashSet Name := ∅) :
HashM <| Option UInt64 := do
if visited.contains mod then
throw <| IO.userError s!"dependency loop found involving {mod}!"
let visitedₙ := visited.insert mod
match (← get).cache[mod]? with
| some hash? => return hash?
| none =>
if !(← sourceFile.pathExists) then
IO.println s!"Warning: {sourceFile} not found. Skipping all files that depend on it."
modify fun stt => { stt with cache := stt.cache.insert mod none }
return none
let content ← IO.FS.readFile sourceFile
let fileImports ← getFileImports content mod.toString
let mut importHashes := #[]
for importHash? in
← fileImports.mapM (fun (modₙ, sourceFileₙ) => getHash modₙ sourceFileₙ visitedₙ) do
match importHash? with
| some importHash => importHashes := importHashes.push importHash
| none =>
-- one import did not have a hash: invalidate hash of this module
modify fun stt => { stt with cache := stt.cache.insert mod none }
return none
/-
TODO: Currently, the cache uses the hash of the unresolved file name
(e.g. `Mathlib/Init.lean`) which is reconstructed from the module name
(e.g. `Mathlib.Init`) in `path`. It could, however, directly use `hash mod` instead.
We can change this at any time causing a one-time cache invalidation, just as
a toolchain-bump would.
-/
let filePath := mkFilePath (mod.components.map toString) |>.withExtension "lean"
let rootHash := (← get).rootHash
let pathHash := hash filePath.components -- TODO: change to `hash mod`
let fileHash := hash <| rootHash :: pathHash :: hashFileContents content :: importHashes.toList
modifyGet fun stt =>
(some fileHash, { stt with
hashMap := stt.hashMap.insert mod fileHash
cache := stt.cache.insert mod (some fileHash)
depsMap := stt.depsMap.insert mod (fileImports.map (·.1)) })
/-- Files to start hashing from. -/
def roots : CacheM <| Array <| Name × FilePath := do
let mathlibDepPath := (← read).mathlibDepPath
return #[(`Mathlib, (mathlibDepPath / "Mathlib.lean"))]
/-- Main API to retrieve the hashes of the Lean files -/
def getHashMemo (extraRoots : Std.HashMap Name FilePath) : CacheM HashMemo :=
-- TODO: `Std.HashMap.mapM` seems not to exist yet, so we go via `.toArray`.
return (← StateT.run ((extraRoots.insertMany (← roots)).toArray.mapM fun
⟨key, val⟩ => getHash key val) { rootHash := ← getRootHash }).2
end Cache.Hashing |
.lake/packages/mathlib/Cache/Main.lean | import Cache.Requests
def help : String := "Mathlib4 caching CLI
Usage: cache [COMMAND]
Commands:
# No privilege required
get [ARGS] Download linked files missing on the local cache and decompress
get! [ARGS] Download all linked files and decompress
get- [ARGS] Download linked files missing to the local cache, but do not decompress
pack Compress non-compressed build files into the local cache
pack! Compress build files into the local cache (no skipping)
unpack Decompress linked already downloaded files
unpack! Decompress linked already downloaded files (no skipping)
clean Delete non-linked files
clean! Delete everything on the local cache
lookup [ARGS] Show information about cache files for the given lean files
# Privilege required
put Run 'mk' then upload linked files missing on the server
put! Run 'mk' then upload all linked files
put-unpacked 'put' only files not already 'pack'ed; intended for CI use
commit Write a commit on the server
commit! Overwrite a commit on the server
collect TODO
* Linked files refer to local cache files with corresponding Lean sources
* Commands ending with '!' should be used manually, when hot-fixes are needed
# The arguments for 'get', 'get!', 'get-' and 'lookup'
'get', 'get!', 'get-' and 'lookup' can process a list of module names or file names.
'get [ARGS]' will only get the cache for the specified Lean files and all files imported by one.
Valid arguments are:
* Module names like 'Mathlib.Init'
* File names like 'Mathlib/Init.lean'
* Folder names like 'Mathlib/Data/' (find all Lean files inside `Mathlib/Data/`)
* With bash's automatic glob expansion one can also write things like
'Mathlib/**/Order/*.lean'.
"
/-- Commands which (potentially) call `curl` for downloading files -/
def curlArgs : List String :=
["get", "get!", "get-", "put", "put!", "put-unpacked", "commit", "commit!"]
/-- Commands which (potentially) call `leantar` for compressing or decompressing files -/
def leanTarArgs : List String :=
["get", "get!", "put", "put!", "put-unpacked", "pack", "pack!", "unpack", "lookup"]
/-- Parses an optional `--repo` option. -/
def parseRepo (args : List String) : IO (Option String × List String) := do
if let arg :: args := args then
if arg.startsWith "--" then
if let some repo := arg.dropPrefix? "--repo=" then
return (some repo.toString, args)
else
throw <| IO.userError s!"unknown option: {arg}"
return (none, args)
open Cache IO Hashing Requests System in
def main (args : List String) : IO Unit := do
if args.isEmpty then
println help
Process.exit 0
CacheM.run do
let (repo?, args) ← parseRepo args
let mut roots : Std.HashMap Lean.Name FilePath ← parseArgs args
if roots.isEmpty then do
-- No arguments means to start from `Mathlib.lean`
-- TODO: could change this to the default-target of a downstream project
let mod := `Mathlib
let sp := (← read).srcSearchPath
let sourceFile ← Lean.findLean sp mod
roots := roots.insert mod sourceFile
let hashMemo ← getHashMemo roots
let hashMap := hashMemo.hashMap
let goodCurl ← pure !curlArgs.contains (args.headD "") <||> validateCurl
if leanTarArgs.contains (args.headD "") then validateLeanTar
let get (args : List String) (force := false) (decompress := true) := do
let hashMap ← if args.isEmpty then pure hashMap else hashMemo.filterByRootModules roots.keys
getFiles repo? hashMap force force goodCurl decompress
let pack (overwrite verbose unpackedOnly := false) := do
packCache hashMap overwrite verbose unpackedOnly (← getGitCommitHash)
let put (overwrite unpackedOnly := false) := do
let repo := repo?.getD MATHLIBREPO
putFiles repo (← pack overwrite (verbose := true) unpackedOnly) overwrite (← getToken)
match args with
| "get" :: args => get args
| "get!" :: args => get args (force := true)
| "get-" :: args => get args (decompress := false)
| ["pack"] => discard <| pack
| ["pack!"] => discard <| pack (overwrite := true)
| ["unpack"] => unpackCache hashMap false
| ["unpack!"] => unpackCache hashMap true
| ["clean"] =>
cleanCache <| hashMap.fold (fun acc _ hash => acc.insert <| CACHEDIR / hash.asLTar) .empty
| ["clean!"] => cleanCache
-- We allow arguments for `put*` so they can be added to the `roots`.
| "put" :: _ => put
| "put!" :: _ => put (overwrite := true)
| "put-unpacked" :: _ => put (unpackedOnly := true)
| ["commit"] =>
if !(← isGitStatusClean) then IO.println "Please commit your changes first" return else
commit hashMap false (← getToken)
| ["commit!"] =>
if !(← isGitStatusClean) then IO.println "Please commit your changes first" return else
commit hashMap true (← getToken)
| ["collect"] => IO.println "TODO"
| "lookup" :: _ => lookup hashMap roots.keys
| _ => println help |
.lake/packages/mathlib/Archive/Sensitivity.lean | import Mathlib.Analysis.Normed.Module.Basic
import Mathlib.Data.Real.Sqrt
import Mathlib.LinearAlgebra.Dual.Lemmas
import Mathlib.LinearAlgebra.FiniteDimensional.Lemmas
import Mathlib.Tactic.ApplyFun
import Mathlib.Tactic.FinCases
/-!
# Huang's sensitivity theorem
A formalization of Hao Huang's sensitivity theorem: in the hypercube of
dimension n ≥ 1, if one colors more than half the vertices then at least one
vertex has at least √n colored neighbors.
A fun summer collaboration by
Reid Barton, Johan Commelin, Jesse Michael Han, Chris Hughes, Robert Y. Lewis, and Patrick Massot,
based on Don Knuth's account of the story
(https://www.cs.stanford.edu/~knuth/papers/huang.pdf),
using the Lean theorem prover (https://leanprover.github.io/),
by Leonardo de Moura at Microsoft Research, and his collaborators
(https://leanprover.github.io/people/),
and using Lean's user maintained mathematics library
(https://github.com/leanprover-community/mathlib).
The project was developed at https://github.com/leanprover-community/lean-sensitivity and is now
archived at https://github.com/leanprover-community/mathlib/blob/master/archive/sensitivity.lean
-/
namespace Sensitivity
/-! The next two lines assert we do not want to give a constructive proof,
but rather use classical logic. -/
noncomputable section
local notation "√" => Real.sqrt
open Bool Finset Fintype Function LinearMap Module Module.DualBases
/-!
### The hypercube
Notations:
- `ℕ` denotes natural numbers (including zero).
- `Fin n` = {0, ⋯ , n - 1}.
- `Bool` = {`true`, `false`}.
-/
/-- The hypercube in dimension `n`. -/
def Q (n : ℕ) :=
Fin n → Bool
instance (n) : Inhabited (Q n) := inferInstanceAs (Inhabited (Fin n → Bool))
instance (n) : Fintype (Q n) := inferInstanceAs (Fintype (Fin n → Bool))
/-- The projection from `Q n.succ` to `Q n` forgetting the first value
(i.e. the image of zero). -/
def π {n : ℕ} : Q n.succ → Q n := fun p => p ∘ Fin.succ
namespace Q
@[ext]
theorem ext {n} {f g : Q n} (h : ∀ x, f x = g x) : f = g := funext h
/-! `n` will always denote a natural number. -/
variable (n : ℕ)
/-- `Q 0` has a unique element. -/
instance : Unique (Q 0) :=
⟨⟨fun _ => true⟩, by intro; ext x; fin_cases x⟩
/-- `Q n` has 2^n elements. -/
theorem card : card (Q n) = 2 ^ n := by simp [Q]
/-! Until the end of this namespace, `n` will be an implicit argument (still
a natural number). -/
variable {n}
theorem succ_n_eq (p q : Q n.succ) : p = q ↔ p 0 = q 0 ∧ π p = π q := by
constructor
· rintro rfl; exact ⟨rfl, rfl⟩
· rintro ⟨h₀, h⟩
ext x
by_cases hx : x = 0
· rwa [hx]
· rw [← Fin.succ_pred x hx]
convert congr_fun h (Fin.pred x hx)
/-- The adjacency relation defining the graph structure on `Q n`:
`p.adjacent q` if there is an edge from `p` to `q` in `Q n`. -/
def adjacent {n : ℕ} (p : Q n) : Set (Q n) := { q | ∃! i, p i ≠ q i }
/-- In `Q 0`, no two vertices are adjacent. -/
theorem not_adjacent_zero (p q : Q 0) : q ∉ p.adjacent := by rintro ⟨v, _⟩; apply finZeroElim v
/-- If `p` and `q` in `Q n.succ` have different values at zero then they are adjacent
iff their projections to `Q n` are equal. -/
theorem adj_iff_proj_eq {p q : Q n.succ} (h₀ : p 0 ≠ q 0) : q ∈ p.adjacent ↔ π p = π q := by
constructor
· rintro ⟨i, _, h_uni⟩
ext x; by_contra hx
apply Fin.succ_ne_zero x
rw [h_uni _ hx, h_uni _ h₀]
· intro heq
use 0, h₀
intro y hy
contrapose! hy
rw [← Fin.succ_pred _ hy]
apply congr_fun heq
/-- If `p` and `q` in `Q n.succ` have the same value at zero then they are adjacent
iff their projections to `Q n` are adjacent. -/
theorem adj_iff_proj_adj {p q : Q n.succ} (h₀ : p 0 = q 0) :
q ∈ p.adjacent ↔ π q ∈ (π p).adjacent := by
constructor
· rintro ⟨i, h_eq, h_uni⟩
have h_i : i ≠ 0 := fun h_i => absurd h₀ (by rwa [h_i] at h_eq)
use i.pred h_i,
show p (Fin.succ (Fin.pred i _)) ≠ q (Fin.succ (Fin.pred i _)) by rwa [Fin.succ_pred]
intro y hy
simp [Eq.symm (h_uni _ hy)]
· rintro ⟨i, h_eq, h_uni⟩
use i.succ, h_eq
intro y hy
rw [← Fin.pred_inj (ha := (?ha : y ≠ 0)) (hb := (?hb : i.succ ≠ 0)),
Fin.pred_succ]
case ha =>
contrapose! hy
rw [hy, h₀]
case hb =>
apply Fin.succ_ne_zero
apply h_uni
simp [π, hy]
@[symm]
theorem adjacent.symm {p q : Q n} : q ∈ p.adjacent ↔ p ∈ q.adjacent := by
simp only [adjacent, ne_comm, Set.mem_setOf_eq]
end Q
/-! ### The vector space -/
/-- The free vector space on vertices of a hypercube, defined inductively. -/
def V : ℕ → Type
| 0 => ℝ
| n + 1 => V n × V n
@[simp]
theorem V_zero : V 0 = ℝ := rfl
@[simp]
theorem V_succ {n : ℕ} : V (n + 1) = (V n × V n) := rfl
namespace V
@[ext]
theorem ext {n : ℕ} {p q : V n.succ} (h₁ : p.1 = q.1) (h₂ : p.2 = q.2) : p = q := Prod.ext h₁ h₂
variable (n : ℕ)
/-! `V n` is a real vector space whose equality relation is computable. -/
instance : DecidableEq (V n) := by induction n <;> · dsimp only [V]; infer_instance
instance : AddCommGroup (V n) := by induction n <;> · dsimp only [V]; infer_instance
instance : Module ℝ (V n) := by induction n <;> · dsimp only [V]; infer_instance
end V
/-- The basis of `V` indexed by the hypercube, defined inductively. -/
noncomputable def e : ∀ {n}, Q n → V n
| 0 => fun _ => (1 : ℝ)
| Nat.succ _ => fun x => cond (x 0) (e (π x), 0) (0, e (π x))
@[simp]
theorem e_zero_apply (x : Q 0) : e x = (1 : ℝ) :=
rfl
/-- The dual basis to `e`, defined inductively. -/
noncomputable def ε : ∀ {n : ℕ}, Q n → V n →ₗ[ℝ] ℝ
| 0, _ => LinearMap.id
| Nat.succ _, p =>
cond (p 0) ((ε <| π p).comp <| LinearMap.fst _ _ _) ((ε <| π p).comp <| LinearMap.snd _ _ _)
variable {n : ℕ}
open Classical in
theorem duality (p q : Q n) : ε p (e q) = if p = q then 1 else 0 := by
induction n with
| zero => simp [Subsingleton.elim (α := Q 0) p q, ε, e]
| succ n IH =>
dsimp [ε, e]
cases hp : p 0 <;> cases hq : q 0
all_goals
simp only [Bool.cond_true, Bool.cond_false, LinearMap.fst_apply, LinearMap.snd_apply,
LinearMap.comp_apply, IH]
congr 1; rw [Q.succ_n_eq]; simp [hp, hq]
/-- Any vector in `V n` annihilated by all `ε p`'s is zero. -/
theorem epsilon_total {v : V n} (h : ∀ p : Q n, (ε p) v = 0) : v = 0 := by
induction n with
| zero => dsimp [ε] at h; exact h fun _ => true
| succ n ih =>
obtain ⟨v₁, v₂⟩ := v
ext <;> change _ = (0 : V n) <;> simp only <;> apply ih <;> intro p <;>
[let q : Q n.succ := fun i => if h : i = 0 then true else p (i.pred h);
let q : Q n.succ := fun i => if h : i = 0 then false else p (i.pred h)]
all_goals
specialize h q
first
| rw [ε, show q 0 = true from rfl, Bool.cond_true] at h
| rw [ε, show q 0 = false from rfl, Bool.cond_false] at h
rwa [show p = π q by ext; simp [q, Fin.succ_ne_zero, π]]
open Module
open Classical in
/-- `e` and `ε` are dual families of vectors. It implies that `e` is indeed a basis
and `ε` computes coefficients of decompositions of vectors on that basis. -/
theorem dualBases_e_ε (n : ℕ) : DualBases (@e n) (@ε n) where
eval_same := by simp [duality]
eval_of_ne _ _ h := by simp [duality, h]
total h := sub_eq_zero.mp <| epsilon_total fun i ↦ by
simpa only [map_sub, sub_eq_zero] using h i
/-! We will now derive the dimension of `V`, first as a cardinal in `dim_V` and,
since this cardinal is finite, as a natural number in `finrank_V` -/
theorem dim_V : Module.rank ℝ (V n) = 2 ^ n := by
have : Module.rank ℝ (V n) = (2 ^ n : ℕ) := by
classical
rw [rank_eq_card_basis (dualBases_e_ε _).basis, Q.card]
assumption_mod_cast
open Classical in
instance : FiniteDimensional ℝ (V n) :=
(dualBases_e_ε _).basis.finiteDimensional_of_finite
theorem finrank_V : finrank ℝ (V n) = 2 ^ n := by
have := @dim_V n
rw [← finrank_eq_rank] at this; assumption_mod_cast
/-! ### The linear map -/
/-- The linear operator $f_n$ corresponding to Huang's matrix $A_n$,
defined inductively as a ℝ-linear map from `V n` to `V n`. -/
noncomputable def f : ∀ n, V n →ₗ[ℝ] V n
| 0 => 0
| n + 1 =>
LinearMap.prod (LinearMap.coprod (f n) LinearMap.id) (LinearMap.coprod LinearMap.id (-f n))
/-! The preceding definition uses linear map constructions to automatically
get that `f` is linear, but its values are somewhat buried as a side-effect.
The next two lemmas unbury them. -/
@[simp]
theorem f_zero : f 0 = 0 :=
rfl
theorem f_succ_apply (v : V n.succ) : f n.succ v = (f n v.1 + v.2, v.1 - f n v.2) := by
cases v
rw [f]
simp only [sub_eq_add_neg]
exact rfl
/-! In the next statement, the explicit conversion `(n : ℝ)` of `n` to a real number
is necessary since otherwise `n • v` refers to the multiplication defined
using only the addition of `V`. -/
theorem f_squared (v : V n) : (f n) (f n v) = (n : ℝ) • v := by
induction n with
| zero => simp only [Nat.cast_zero, zero_smul, f_zero, zero_apply]
| succ n IH =>
cases v; rw [f_succ_apply, f_succ_apply]; simp [IH, add_smul (n : ℝ) 1, add_assoc]; abel
/-! We now compute the matrix of `f` in the `e` basis (`p` is the line index,
`q` the column index). -/
open Classical in
theorem f_matrix (p q : Q n) : |ε q (f n (e p))| = if p ∈ q.adjacent then 1 else 0 := by
induction n with
| zero =>
dsimp [f]
simp [Q.not_adjacent_zero]
rfl
| succ n IH =>
have ite_nonneg : ite (π q = π p) (1 : ℝ) 0 ≥ 0 := by split_ifs <;> norm_num
dsimp only [e, ε, f, V]; rw [LinearMap.prod_apply]; dsimp; cases hp : p 0 <;> cases hq : q 0
all_goals
repeat rw [Bool.cond_true]
repeat rw [Bool.cond_false]
simp [hp, hq, IH, duality, abs_of_nonneg ite_nonneg, Q.adj_iff_proj_eq,
Q.adj_iff_proj_adj]
/-- The linear operator $g_m$ corresponding to Knuth's matrix $B_m$. -/
noncomputable def g (m : ℕ) : V m →ₗ[ℝ] V m.succ :=
LinearMap.prod (f m + √ (m + 1) • LinearMap.id) LinearMap.id
/-! In the following lemmas, `m` will denote a natural number. -/
variable {m : ℕ}
/-! Again we unpack what are the values of `g`. -/
theorem g_apply : ∀ v, g m v = (f m v + √ (m + 1) • v, v) := by
delta g; intro v; simp
theorem g_injective : Injective (g m) := by
rw [g]
intro x₁ x₂ h
simp only [V, LinearMap.prod_apply, LinearMap.id_apply, Prod.mk_inj, Pi.prod] at h
exact h.right
theorem f_image_g (w : V m.succ) (hv : ∃ v, g m v = w) : f m.succ w = √ (m + 1) • w := by
rcases hv with ⟨v, rfl⟩
have : √ (m + 1) * √ (m + 1) = m + 1 := Real.mul_self_sqrt (mod_cast zero_le _)
rw [f_succ_apply, g_apply]
simp [this, f_squared, smul_add, add_smul, smul_smul]
abel
/-!
### The main proof
In this section, in order to enforce that `n` is positive, we write it as
`m + 1` for some natural number `m`. -/
/-! `dim X` will denote the dimension of a subspace `X` as a cardinal. -/
local notation "dim " X:70 => Module.rank ℝ { x // x ∈ X }
/-! `fdim X` will denote the (finite) dimension of a subspace `X` as a natural number. -/
local notation "fdim" => finrank ℝ
/-! `Span S` will denote the ℝ-subspace spanned by `S`. -/
local notation "Span" => Submodule.span ℝ
/-! `Card X` will denote the cardinal of a subset of a finite type, as a
natural number. -/
local notation "Card " X:70 => #(Set.toFinset X)
/-! In the following, `⊓` and `⊔` will denote intersection and sums of ℝ-subspaces,
equipped with their subspace structures. The notations come from the general
theory of lattices, with inf and sup (also known as meet and join). -/
open Classical in
/-- If a subset `H` of `Q (m+1)` has cardinal at least `2^m + 1` then the
subspace of `V (m+1)` spanned by the corresponding basis vectors non-trivially
intersects the range of `g m`. -/
theorem exists_eigenvalue (H : Set (Q m.succ)) (hH : Card H ≥ 2 ^ m + 1) :
∃ y ∈ Span (e '' H) ⊓ range (g m), y ≠ 0 := by
let W := Span (e '' H)
let img := range (g m)
suffices 0 < dim (W ⊓ img) by
exact mod_cast exists_mem_ne_zero_of_rank_pos this
have dim_le : dim (W ⊔ img) ≤ 2 ^ (m + 1 : Cardinal) := by
convert ← Submodule.rank_le (W ⊔ img)
rw [← Nat.cast_succ]
apply dim_V
have dim_add : dim (W ⊔ img) + dim (W ⊓ img) = dim W + 2 ^ m := by
convert ← Submodule.rank_sup_add_rank_inf_eq W img
rw [rank_range_of_injective (g m) g_injective]
apply dim_V
have dimW : dim W = card H := by
have li : LinearIndependent ℝ (H.restrict e) := by
convert (dualBases_e_ε m.succ).basis.linearIndependent.comp _ Subtype.val_injective
rw [(dualBases_e_ε _).coe_basis]
rfl
have hdW := rank_span li
rw [Set.range_restrict] at hdW
convert hdW
rw [← (dualBases_e_ε _).coe_basis, Cardinal.mk_image_eq (dualBases_e_ε _).basis.injective,
Cardinal.mk_fintype]
rw [← finrank_eq_rank ℝ] at dim_le dim_add dimW ⊢
rw [← finrank_eq_rank ℝ, ← finrank_eq_rank ℝ] at dim_add
norm_cast at dim_le dim_add dimW ⊢
rw [pow_succ'] at dim_le
rw [Set.toFinset_card] at hH
linarith
open Classical in
/-- **Huang sensitivity theorem** also known as the **Huang degree theorem** -/
theorem huang_degree_theorem (H : Set (Q m.succ)) (hH : Card H ≥ 2 ^ m + 1) :
∃ q, q ∈ H ∧ √ (m + 1) ≤ Card H ∩ q.adjacent := by
rcases exists_eigenvalue H hH with ⟨y, ⟨⟨y_mem_H, y_mem_g⟩, y_ne⟩⟩
have coeffs_support : ((dualBases_e_ε m.succ).coeffs y).support ⊆ H.toFinset := by
intro p p_in
rw [Finsupp.mem_support_iff] at p_in
rw [Set.mem_toFinset]
exact (dualBases_e_ε _).mem_of_mem_span y_mem_H p p_in
obtain ⟨q, H_max⟩ : ∃ q : Q m.succ, ∀ q' : Q m.succ, |(ε q' :) y| ≤ |ε q y| :=
Finite.exists_max _
have H_q_pos : 0 < |ε q y| := by
contrapose! y_ne
exact epsilon_total fun p => abs_nonpos_iff.mp (le_trans (H_max p) y_ne)
refine ⟨q, (dualBases_e_ε _).mem_of_mem_span y_mem_H q (abs_pos.mp H_q_pos), ?_⟩
let s := √ (m + 1)
suffices s * |ε q y| ≤ _ * |ε q y| from (mul_le_mul_iff_left₀ H_q_pos).mp ‹_›
let coeffs := (dualBases_e_ε m.succ).coeffs
calc
s * |ε q y| = |ε q (s • y)| := by
rw [map_smul, smul_eq_mul, abs_mul, abs_of_nonneg (Real.sqrt_nonneg _)]
_ = |ε q (f m.succ y)| := by rw [← f_image_g y (by simpa using y_mem_g)]
_ = |ε q (f m.succ (lc _ (coeffs y)))| := by rw [(dualBases_e_ε _).lc_coeffs y]
_ =
|(coeffs y).sum fun (i : Q m.succ) (a : ℝ) =>
a • (ε q ∘ f m.succ ∘ fun i : Q m.succ => e i) i| := by
rw [lc_def, (f m.succ).map_finsupp_linearCombination, (ε q).map_finsupp_linearCombination,
Finsupp.linearCombination_apply]
_ ≤ ∑ p ∈ (coeffs y).support, |coeffs y p * (ε q <| f m.succ <| e p)| :=
(norm_sum_le _ fun p => coeffs y p * _)
_ = ∑ p ∈ (coeffs y).support, |coeffs y p| * ite (p ∈ q.adjacent) 1 0 := by
simp only [abs_mul, f_matrix]
_ = ∑ p ∈ (coeffs y).support with q.adjacent p, |coeffs y p| := by
simp [sum_filter]; rfl
_ ≤ ∑ p ∈ (coeffs y).support with q.adjacent p, |coeffs y q| := sum_le_sum fun p _ ↦ H_max p
_ = #{p ∈ (coeffs y).support | q.adjacent p} * |coeffs y q| := by
rw [sum_const, nsmul_eq_mul]
_ = #((coeffs y).support ∩ q.adjacent.toFinset) * |coeffs y q| := by
congr with x; simp; rfl
_ ≤ #(H ∩ q.adjacent).toFinset * |ε q y| := by
refine (mul_le_mul_iff_left₀ H_q_pos).2 ?_
norm_cast
apply card_le_card
rw [Set.toFinset_inter]
convert inter_subset_inter_right coeffs_support
end
end Sensitivity |
.lake/packages/mathlib/Archive/ZagierTwoSquares.lean | import Mathlib.GroupTheory.Perm.Cycle.Type
import Mathlib.Tactic.Linarith
/-!
# Zagier's "one-sentence proof" of Fermat's theorem on sums of two squares
"The involution on the finite set `S = {(x, y, z) : ℕ × ℕ × ℕ | x ^ 2 + 4 * y * z = p}` defined by
```
(x, y, z) ↦ (x + 2 * z, z, y - x - z) if x < y - z
(2 * y - x, y, x - y + z) if y - z < x < 2 * y
(x - 2 * y, x - y + z, y) if x > 2 * y
```
has exactly one fixed point, so `|S|` is odd and the involution defined by
`(x, y, z) ↦ (x, z, y)` also has a fixed point." — [Don Zagier](Zagier1990)
This elementary proof (`Nat.Prime.sq_add_sq'`) is independent of `Nat.Prime.sq_add_sq` in
`Mathlib/NumberTheory/SumTwoSquares.lean`, which uses the unique factorisation of `ℤ[i]`.
For a geometric interpretation of the piecewise involution (`Zagier.complexInvo`)
see [Moritz Firsching's MathOverflow answer](https://mathoverflow.net/a/299696).
-/
namespace Zagier
section Sets
open Set
variable (k : ℕ) [hk : Fact (4 * k + 1).Prime]
/-- The set of all triples of natural numbers `(x, y, z)` satisfying
`x * x + 4 * y * z = 4 * k + 1`. -/
def zagierSet : Set (ℕ × ℕ × ℕ) := {t | t.1 * t.1 + 4 * t.2.1 * t.2.2 = 4 * k + 1}
lemma zagierSet_lower_bound {x y z : ℕ} (h : (x, y, z) ∈ zagierSet k) : 0 < x ∧ 0 < y ∧ 0 < z := by
rw [zagierSet, mem_setOf_eq] at h
refine ⟨?_, ?_, ?_⟩
all_goals
by_contra q
rw [not_lt, nonpos_iff_eq_zero] at q
simp only [q, mul_zero, zero_mul, zero_add, add_zero] at h
· apply_fun (· % 4) at h
simp [mul_assoc, Nat.add_mod] at h
all_goals
rcases (Nat.dvd_prime hk.out).1 (dvd_of_mul_left_eq _ h) with e | e
all_goals
simp only [e, right_eq_add, ne_eq, add_eq_zero, and_false, not_false_eq_true,
mul_eq_left₀, reduceCtorEq] at h
simp only [h, zero_add] at hk
exact Nat.not_prime_one hk.out
lemma zagierSet_upper_bound {x y z : ℕ} (h : (x, y, z) ∈ zagierSet k) :
x ≤ k + 1 ∧ y ≤ k ∧ z ≤ k := by
obtain ⟨_, _, _⟩ := zagierSet_lower_bound k h
rw [zagierSet, mem_setOf_eq] at h
refine ⟨?_, ?_, ?_⟩ <;> nlinarith
lemma zagierSet_subset : zagierSet k ⊆ Ioc 0 (k + 1) ×ˢ Ioc 0 k ×ˢ Ioc 0 k := by
intro x h
have lb := zagierSet_lower_bound k h
have ub := zagierSet_upper_bound k h
exact ⟨⟨lb.1, ub.1⟩, ⟨lb.2.1, ub.2.1⟩, ⟨lb.2.2, ub.2.2⟩⟩
noncomputable instance : Fintype (zagierSet k) :=
(((finite_Ioc 0 (k + 1)).prod ((finite_Ioc 0 k).prod (finite_Ioc 0 k))).subset
(zagierSet_subset k)).fintype
end Sets
section Involutions
open Function
variable (k : ℕ)
/-- The obvious involution `(x, y, z) ↦ (x, z, y)`. -/
def obvInvo : Function.End (zagierSet k) := fun ⟨⟨x, y, z⟩, h⟩ => ⟨⟨x, z, y⟩, by
simp only [zagierSet, Set.mem_setOf_eq] at h ⊢
linarith [h]⟩
theorem obvInvo_sq : obvInvo k ^ 2 = 1 := rfl
/-- If `obvInvo k` has a fixed point, a representation of `4 * k + 1` as a sum of two squares
can be extracted from it. -/
theorem sq_add_sq_of_nonempty_fixedPoints (hn : (fixedPoints (obvInvo k)).Nonempty) :
∃ a b : ℕ, a ^ 2 + b ^ 2 = 4 * k + 1 := by
simp only [sq]
obtain ⟨⟨⟨x, y, z⟩, he⟩, hf⟩ := hn
have := mem_fixedPoints_iff.mp hf
simp only [obvInvo, Subtype.mk.injEq, Prod.mk.injEq, true_and] at this
simp only [zagierSet, Set.mem_setOf_eq] at he
use x, (2 * y)
rw [show 2 * y * (2 * y) = 4 * y * y by linarith, ← he, this.1]
/-- The complicated involution, defined piecewise according to how `x` compares with
`y - z` and `2 * y`. -/
def complexInvo : Function.End (zagierSet k) := fun ⟨⟨x, y, z⟩, h⟩ =>
⟨if x + z < y then ⟨x + 2 * z, z, y - x - z⟩ else
if 2 * y < x then ⟨x - 2 * y, x + z - y, y⟩ else
⟨2 * y - x, y, x + z - y⟩, by
split_ifs with less more <;> simp only [zagierSet, Set.mem_setOf_eq] at h ⊢
· -- less: `x + z < y` (`x < y - z` as stated by Zagier)
rw [Nat.sub_sub]; zify [less.le] at h ⊢; linarith [h]
· -- more: `2 * y < x`
push_neg at less; zify [less, more.le] at h ⊢; linarith [h]
· -- middle: `x` is neither less than `y - z` or more than `2 * y`
push_neg at less more; zify [less, more] at h ⊢; linarith [h]⟩
variable [hk : Fact (4 * k + 1).Prime]
/-- `complexInvo k` is indeed an involution. -/
theorem complexInvo_sq : complexInvo k ^ 2 = 1 := by
change complexInvo k ∘ complexInvo k = id
funext ⟨⟨x, y, z⟩, h⟩
rw [comp_apply]
obtain ⟨xb, _, _⟩ := zagierSet_lower_bound k h
conv_lhs => arg 2; simp only [complexInvo]
split_ifs with less more <;> rw [complexInvo, Subtype.mk.injEq, id_eq]
· -- less
simp only [show ¬(x + 2 * z + (y - x - z) < z) by linarith [less], ite_false,
lt_add_iff_pos_left, xb, add_tsub_cancel_right, ite_true]
rw [Nat.sub_sub, two_mul, ← tsub_add_eq_add_tsub (by linarith), ← add_assoc,
Nat.add_sub_cancel, add_comm (x + z), Nat.sub_add_cancel less.le]
· -- more
push_neg at less
simp only [show x - 2 * y + y < x + z - y by zify [less, more.le]; linarith, ite_true]
rw [Nat.sub_add_cancel more.le, Nat.sub_right_comm, Nat.sub_sub _ _ y, ← two_mul, add_comm,
Nat.add_sub_assoc more.le, Nat.add_sub_cancel]
· -- middle
push_neg at less more
simp only [show ¬(2 * y - x + (x + z - y) < y) by zify [less, more]; linarith,
show ¬(2 * y < 2 * y - x) by zify [more]; linarith, ite_false]
rw [tsub_tsub_assoc (2 * y).le_refl more, tsub_self, zero_add,
← Nat.add_sub_assoc less, ← add_assoc, Nat.sub_add_cancel more, Nat.sub_sub _ _ y,
← two_mul, add_comm, Nat.add_sub_cancel]
/-- Any fixed point of `complexInvo k` must be `(1, 1, k)`. -/
theorem eq_of_mem_fixedPoints {t : zagierSet k} (mem : t ∈ fixedPoints (complexInvo k)) :
t.val = (1, 1, k) := by
obtain ⟨⟨x, y, z⟩, h⟩ := t
obtain ⟨_, _, _⟩ := zagierSet_lower_bound k h
rw [mem_fixedPoints_iff, complexInvo, Subtype.mk.injEq] at mem
split_ifs at mem with less more <;>
-- less (completely handled by the pre-applied `simp_all only`)
simp_all only [not_lt, Prod.mk.injEq, add_eq_left, mul_eq_zero, false_or,
lt_self_iff_false, reduceCtorEq]
· -- more
obtain ⟨_, _, _⟩ := mem; simp_all
· -- middle (the one fixed point falls under this case)
simp only [zagierSet, Set.mem_setOf_eq] at h
replace mem := mem.1
rw [tsub_eq_iff_eq_add_of_le more, ← two_mul] at mem
replace mem := (mul_left_cancel₀ two_ne_zero mem).symm
subst mem
rw [show x * x + 4 * x * z = x * (x + 4 * z) by linarith] at h
rcases (Nat.dvd_prime hk.out).1 (dvd_of_mul_left_eq _ h) with e | e
· rw [e, mul_one] at h
simp_all [show z = 0 by linarith [e]]
· simp only [e, mul_left_eq_self₀, add_eq_zero, and_false, or_false, reduceCtorEq] at h
simp only [h, true_and]
linarith [e]
/-- The singleton containing `(1, 1, k)`. -/
def singletonFixedPoint : Finset (zagierSet k) :=
{⟨(1, 1, k), (by simp only [zagierSet, Set.mem_setOf_eq]; linarith)⟩}
/-- `complexInvo k` has exactly one fixed point. -/
theorem card_fixedPoints_eq_one : Fintype.card (fixedPoints (complexInvo k)) = 1 := by
rw [show 1 = Finset.card (singletonFixedPoint k) by rfl, ← Set.toFinset_card]
congr
rw [singletonFixedPoint, Finset.eq_singleton_iff_unique_mem]
constructor
· simp [IsFixedPt, complexInvo]
· intro _ mem
simp only [Set.mem_toFinset] at mem
replace mem := eq_of_mem_fixedPoints k mem
congr!
end Involutions
end Zagier
open Zagier
/-- **Fermat's theorem on sums of two squares** (Wiedijk #20).
Every prime congruent to 1 mod 4 is the sum of two squares, proved using Zagier's involutions. -/
theorem Nat.Prime.sq_add_sq' {p : ℕ} [h : Fact p.Prime] (hp : p % 4 = 1) :
∃ a b : ℕ, a ^ 2 + b ^ 2 = p := by
rw [← div_add_mod p 4, hp] at h ⊢
let k := p / 4
apply sq_add_sq_of_nonempty_fixedPoints
have key := (Equiv.Perm.card_fixedPoints_modEq (p := 2) (n := 1) (obvInvo_sq k)).symm.trans
(Equiv.Perm.card_fixedPoints_modEq (p := 2) (n := 1) (complexInvo_sq k))
contrapose key
rw [Set.not_nonempty_iff_eq_empty] at key
simp_rw [k, key, Fintype.card_eq_zero, card_fixedPoints_eq_one]
decide |
.lake/packages/mathlib/Archive/Kuratowski.lean | import Mathlib.Data.Set.Card
import Mathlib.Topology.Closure
/-!
# The Kuratowski closure-complement theorem
This file proves Kuratowski's closure-complement theorem, which says that if one repeatedly
applies the closure and complement operators to a set in a topological space, at most 14
distinct sets can be obtained.
In another file it will be shown that the maximum can be realized in the real numbers.
(A set realizing the maximum is called a 14-set.)
## Main definitions
* `Topology.ClosureCompl.IsObtainable` is the binary inductive predicate saying that a set can be
obtained from another using the closure and complement operations.
* `Topology.ClosureCompl.theFourteen` is an explicit multiset of fourteen sets obtained from a
given set using the closure and complement operations.
## Main results
* `Topology.ClosureCompl.mem_theFourteen_iff_isObtainable`:
a set `t` is obtainable by from `s` if and only if they are in the Multiset `theFourteen s`.
* `Topology.ClosureCompl.ncard_isObtainable_le_fourteen`:
for an arbitrary set `s`, there are at most 14 distinct sets that can be obtained from `s` using
the closure and complement operations (the **Kuratowski closure-complement theorem**).
## Notation
* `k`: the closure of a set.
* `i`: the interior of a set.
* `c`: the complement of a set in docstrings; `ᶜ` is used in the code.
## References
* https://en.wikipedia.org/wiki/Kuratowski%27s_closure-complement_problem
* https://web.archive.org/web/20220212062843/http://nzjm.math.auckland.ac.nz/images/6/63/The_Kuratowski_Closure-Complement_Theorem.pdf
-/
namespace Topology.ClosureCompl
variable {X : Type*} [TopologicalSpace X]
/-- `IsObtainable s t` means that `t` can be obtained from `s` by taking closures and complements.
-/
inductive IsObtainable (s : Set X) : Set X → Prop
| base : IsObtainable s s
| protected closure ⦃t : Set X⦄ : IsObtainable s t → IsObtainable s (closure t)
| complement ⦃t : Set X⦄ : IsObtainable s t → IsObtainable s tᶜ
scoped notation "k" => closure
scoped notation "i" => interior
/-- The function `kckc` is idempotent: `kckckckc s = kckc s` for any set `s`.
This is because `ckc = i` and `ki` is idempotent. -/
theorem kckc_idem (s : Set X) : k (k (k (k sᶜ)ᶜ)ᶜ)ᶜ = k (k sᶜ)ᶜ := by simp
/-- Cancelling the first applied complement we obtain `kckckck s = kck s` for any set `s`. -/
theorem kckckck_eq_kck (s : Set X) : k (k (k (k s)ᶜ)ᶜ)ᶜ = k (k s)ᶜ := by simp
/-- The at most fourteen sets that are obtainable from `s` are given by applying
`id, c, k, ck, kc, ckc, kck, ckck, kckc, ckckc, kckck, ckckck, kckckc, ckckckc` to `s`. -/
def theFourteen (s : Set X) : Multiset (Set X) :=
{s, sᶜ, k s, (k s)ᶜ, k sᶜ, (k sᶜ)ᶜ, k (k s)ᶜ, (k (k s)ᶜ)ᶜ,
k (k sᶜ)ᶜ, (k (k sᶜ)ᶜ)ᶜ, k (k (k s)ᶜ)ᶜ, (k (k (k s)ᶜ)ᶜ)ᶜ,
k (k (k sᶜ)ᶜ)ᶜ, (k (k (k sᶜ)ᶜ)ᶜ)ᶜ}
/-- `theFourteen` has exactly 14 sets (possibly with repetition) in it. -/
theorem card_theFourteen (s : Set X) : (theFourteen s).card = 14 := rfl
/-- If `t` is obtainable from `s` by the closure and complement operations,
then it is in the multiset `theFourteen s`. -/
theorem IsObtainable.mem_theFourteen {s t : Set X} (h : IsObtainable s t) : t ∈ theFourteen s := by
induction h with | base => exact .head _ | closure _ mem => ?_ | complement _ mem => ?_
all_goals repeat obtain _ | ⟨_, mem⟩ := mem; rotate_left
all_goals simp [theFourteen]
/-- A set `t` is obtainable by from `s` if and only if they are in the Multiset `theFourteen s`. -/
theorem mem_theFourteen_iff_isObtainable {s t : Set X} :
t ∈ theFourteen s ↔ IsObtainable s t where
mp h := by
repeat
obtain _ | ⟨_, h⟩ := h
rotate_left
all_goals
repeat
first
| apply IsObtainable.complement
| apply IsObtainable.closure
exact IsObtainable.base
mpr := (·.mem_theFourteen)
/-- **Kuratowski's closure-complement theorem**: the number of obtainable sets via closure and
complement operations from a single set `s` is at most 14. -/
theorem ncard_isObtainable_le_fourteen (s : Set X) : {t | IsObtainable s t}.ncard ≤ 14 := by
classical
convert Set.ncard_coe_finset _ ▸ (theFourteen s).toFinset_card_le
simp [Set.ext_iff, mem_theFourteen_iff_isObtainable]
end Topology.ClosureCompl |
.lake/packages/mathlib/Archive/Hairer.lean | import Mathlib.Algebra.MvPolynomial.Funext
import Mathlib.Analysis.Analytic.Polynomial
import Mathlib.Analysis.Analytic.Uniqueness
import Mathlib.Analysis.Distribution.AEEqOfIntegralContDiff
import Mathlib.LinearAlgebra.Dual.Lemmas
import Mathlib.RingTheory.MvPolynomial.Basic
import Mathlib.Topology.Algebra.MvPolynomial
/-!
# Smooth functions whose integral calculates the values of polynomials
In any space `ℝᵈ` and given any `N`, we construct a smooth function supported in the unit ball
whose integral against a multivariate polynomial `P` of total degree at most `N` is `P 0`.
This is a test of the state of the library suggested by Martin Hairer.
-/
noncomputable section
open Metric Set MeasureTheory PiLp
open MvPolynomial hiding support
open Function hiding eval
open scoped ContDiff
variable {ι : Type*} [Fintype ι]
section normed
variable {𝕜 E F : Type*} [NontriviallyNormedField 𝕜]
variable [NormedAddCommGroup E] [NormedSpace 𝕜 E] [NormedAddCommGroup F] [NormedSpace 𝕜 F]
variable (𝕜 E F) in
/-- The set of `C^n` functions supported in a set `s`, as a submodule of the space of functions. -/
def ContDiffSupportedOn (n : ℕ∞) (s : Set E) : Submodule 𝕜 (E → F) where
carrier := { f : E → F | tsupport f ⊆ s ∧ ContDiff 𝕜 n f }
add_mem' hf hg := ⟨tsupport_add.trans <| union_subset hf.1 hg.1, hf.2.add hg.2⟩
zero_mem' :=
⟨(tsupport_eq_empty_iff.mpr rfl).subset.trans (empty_subset _), contDiff_const (c := 0)⟩
smul_mem' r f hf :=
⟨(closure_mono <| support_const_smul_subset r f).trans hf.1, contDiff_const.smul hf.2⟩
namespace ContDiffSupportedOn
variable {n : ℕ∞} {s : Set E}
instance : FunLike (ContDiffSupportedOn 𝕜 E F n s) E F where
coe := Subtype.val
coe_injective' := Subtype.coe_injective
@[simp]
lemma coe_mk (f : E → F) (h) : (⟨f, h⟩ : ContDiffSupportedOn 𝕜 E F n s) = f := rfl
lemma tsupport_subset (f : ContDiffSupportedOn 𝕜 E F n s) : tsupport f ⊆ s := f.2.1
lemma support_subset (f : ContDiffSupportedOn 𝕜 E F n s) :
support f ⊆ s := subset_tsupport _ |>.trans (tsupport_subset f)
lemma contDiff (f : ContDiffSupportedOn 𝕜 E F n s) :
ContDiff 𝕜 n f := f.2.2
theorem continuous (f : ContDiffSupportedOn 𝕜 E F n s) : Continuous f :=
(ContDiffSupportedOn.contDiff _).continuous
lemma hasCompactSupport [ProperSpace E] (f : ContDiffSupportedOn 𝕜 E F n (closedBall 0 1)) :
HasCompactSupport f :=
HasCompactSupport.of_support_subset_isCompact (isCompact_closedBall 0 1) (support_subset f)
theorem integrable_eval_mul (p : MvPolynomial ι ℝ)
(f : ContDiffSupportedOn ℝ (EuclideanSpace ℝ ι) ℝ ⊤ (closedBall 0 1)) :
Integrable fun (x : EuclideanSpace ℝ ι) ↦ eval x p * f x :=
(p.continuous_eval.comp (continuous_ofLp 2 _)).mul
(ContDiffSupportedOn.contDiff f).continuous
|>.integrable_of_hasCompactSupport (hasCompactSupport f).mul_left
end ContDiffSupportedOn
end normed
open ContDiffSupportedOn
variable (ι)
/-- Interpreting a multivariate polynomial as an element of the dual of smooth functions supported
in the unit ball, via integration against Lebesgue measure. -/
def L : MvPolynomial ι ℝ →ₗ[ℝ]
Module.Dual ℝ (ContDiffSupportedOn ℝ (EuclideanSpace ℝ ι) ℝ ⊤ (closedBall 0 1)) :=
have int := ContDiffSupportedOn.integrable_eval_mul (ι := ι)
.mk₂ ℝ (fun p f ↦ ∫ x : EuclideanSpace ℝ ι, eval x p • f x)
(fun p₁ p₂ f ↦ by simp [add_mul, integral_add (int p₁ f) (int p₂ f)])
(fun r p f ↦ by simp [mul_assoc, integral_const_mul])
(fun p f₁ f₂ ↦ by simp_rw [smul_eq_mul, ← integral_add (int p _) (int p _), ← mul_add]; rfl)
fun r p f ↦ by simp_rw [← integral_smul, smul_comm r]; rfl
lemma inj_L : Injective (L ι) :=
(injective_iff_map_eq_zero _).mpr fun p hp ↦ by
have H : ∀ᵐ x : EuclideanSpace ℝ ι, x ∈ ball 0 1 → eval x p = 0 :=
isOpen_ball.ae_eq_zero_of_integral_contDiff_smul_eq_zero
(p.continuous_eval.comp (continuous_ofLp 2 _)
|>.locallyIntegrable.locallyIntegrableOn _)
fun g hg _h2g g_supp ↦ by
simpa [mul_comm (g _), L] using congr($hp ⟨g, g_supp.trans ball_subset_closedBall, hg⟩)
simp_rw [MvPolynomial.funext_iff, map_zero]
refine fun x ↦ AnalyticOnNhd.eval_linearMap (EuclideanSpace.equiv ι ℝ).toLinearMap p
|>.eqOn_zero_of_preconnected_of_eventuallyEq_zero
(preconnectedSpace_iff_univ.mp inferInstance) (z₀ := 0) trivial
(Filter.mem_of_superset (Metric.ball_mem_nhds 0 zero_lt_one) ?_) trivial
rw [← ae_restrict_iff'₀ measurableSet_ball.nullMeasurableSet] at H
apply Measure.eqOn_of_ae_eq H
(p.continuous_eval.comp (continuous_ofLp 2 _)).continuousOn continuousOn_const
rw [isOpen_ball.interior_eq]
apply subset_closure
lemma hairer (N : ℕ) (ι : Type*) [Fintype ι] :
∃ (ρ : EuclideanSpace ℝ ι → ℝ), tsupport ρ ⊆ closedBall 0 1 ∧ ContDiff ℝ ∞ ρ ∧
∀ (p : MvPolynomial ι ℝ), p.totalDegree ≤ N →
∫ x : EuclideanSpace ℝ ι, eval x p • ρ x = eval 0 p := by
have := (inj_L ι).comp (restrictTotalDegree ι ℝ N).injective_subtype
rw [← LinearMap.coe_comp] at this
obtain ⟨⟨φ, supφ, difφ⟩, hφ⟩ :=
LinearMap.flip_surjective_iff₁.2 this ((aeval 0).toLinearMap.comp <| Submodule.subtype _)
exact ⟨φ, supφ, difφ, fun P hP ↦ congr($hφ ⟨P, (mem_restrictTotalDegree ι N P).mpr hP⟩)⟩ |
.lake/packages/mathlib/Archive/README.md | # Archive
This is an archive for formalizations which don't have a good place in mathlib, probably because there is (almost) no math depending on these results.
We keep these formalizations here so that when mathlib changes, we can keep these formalizations up to date.
## Contributing
If you have done a formalization which you want to add here, just make a pull request to mathlib.
When you make a pull request, do make sure that you put all lemmas which are generally useful in right place in mathlib (in the `Mathlib/` directory).
Try to adhere to the guidelines for mathlib. They will be much less strictly enforced for the archive, but we still want you to adhere to all the conventions that make maintenance easier. This ensures that when mathlib is changing, the mathlib maintainers can fix these contributions without much effort. Here are the guidelines:
- The [style guide](https://leanprover-community.github.io/contribute/style.html) for contributors.
- The [git commit conventions](https://github.com/leanprover/lean4/blob/master/doc/dev/commit_convention.md).
- You don't have to follow the [naming conventions](https://leanprover-community.github.io/contribute/naming.html). |
.lake/packages/mathlib/Archive/Arithcc.lean | import Mathlib.Data.Nat.Basic
import Mathlib.Order.Basic
import Mathlib.Tactic.Common
/-!
# A compiler for arithmetic expressions
A formalization of the correctness of a compiler from arithmetic expressions to machine language
described by McCarthy and Painter, which is considered the first proof of compiler correctness.
## Main definitions
* `Expr` : the syntax of the source language.
* `value` : the semantics of the source language.
* `Instruction`: the syntax of the target language.
* `step` : the semantics of the target language.
* `compile` : the compiler.
## Main results
* `compiler_correctness`: the compiler correctness theorem.
## Notation
* `≃[t]/ac`: partial equality of two machine states excluding registers x ≥ t and the accumulator.
* `≃[t]` : partial equality of two machine states excluding registers x ≥ t.
## References
* John McCarthy and James Painter. Correctness of a compiler for arithmetic expressions.
In Mathematical Aspects of Computer Science, volume 19 of Proceedings of Symposia in
Applied Mathematics. American Mathematical Society, 1967.
<http://jmc.stanford.edu/articles/mcpain/mcpain.pdf>
## Tags
compiler
-/
namespace Arithcc
section Types
/-! ### Types -/
/-- Value type shared by both source and target languages. -/
abbrev Word :=
ℕ
/-- Variable identifier type in the source language. -/
abbrev Identifier :=
String
/-- Register name type in the target language. -/
abbrev Register :=
ℕ
theorem Register.lt_succ_self : ∀ r : Register, r < r + 1 :=
Nat.lt_succ_self
theorem Register.le_of_lt_succ {r₁ r₂ : Register} : r₁ < r₂ + 1 → r₁ ≤ r₂ :=
Nat.le_of_succ_le_succ
end Types
section Source
/-! ### Source language -/
/-- An expression in the source language is formed by constants, variables, and sums. -/
inductive Expr
| const (v : Word) : Expr
| var (x : Identifier) : Expr
| sum (s₁ s₂ : Expr) : Expr
deriving Inhabited
/-- The semantics of the source language (2.1). -/
@[simp]
def value : Expr → (Identifier → Word) → Word
| Expr.const v, _ => v
| Expr.var x, ξ => ξ x
| Expr.sum s₁ s₂, ξ => value s₁ ξ + value s₂ ξ
end Source
section Target
/-! ### Target language -/
/-- Instructions of the target machine language (3.1--3.7). -/
inductive Instruction
| li : Word → Instruction
| load : Register → Instruction
| sto : Register → Instruction
| add : Register → Instruction
deriving Inhabited
/-- Machine state consists of the accumulator and a vector of registers.
The paper uses two functions `c` and `a` for accessing both the accumulator and registers.
For clarity, we make accessing the accumulator explicit and use `read`/`write` for registers.
-/
structure State where mk ::
ac : Word
rs : Register → Word
instance : Inhabited State :=
⟨{ ac := 0
rs := fun _ => 0 }⟩
/-- This is similar to the `c` function (3.8), but for registers only. -/
@[simp]
def read (r : Register) (η : State) : Word :=
η.rs r
/-- This is similar to the `a` function (3.9), but for registers only. -/
@[simp]
def write (r : Register) (v : Word) (η : State) : State :=
{ η with rs := fun x => if x = r then v else η.rs x }
/-- The semantics of the target language (3.11). -/
def step : Instruction → State → State
| Instruction.li v, η => { η with ac := v }
| Instruction.load r, η => { η with ac := read r η }
| Instruction.sto r, η => write r η.ac η
| Instruction.add r, η => { η with ac := read r η + η.ac }
/-- The resulting machine state of running a target program from a given machine state (3.12). -/
@[simp]
def outcome : List Instruction → State → State
| [], η => η
| i :: is, η => outcome is (step i η)
/-- A lemma on the concatenation of two programs (3.13). -/
@[simp]
theorem outcome_append (p₁ p₂ : List Instruction) (η : State) :
outcome (p₁ ++ p₂) η = outcome p₂ (outcome p₁ η) := by
induction p₁ generalizing η with
| nil => simp
| cons _ _ p₁_ih => simp [p₁_ih]
end Target
section Compiler
open Instruction
/-! ### Compiler -/
/-- Map a variable in the source expression to a machine register. -/
@[simp]
def loc (ν : Identifier) (map : Identifier → Register) : Register :=
map ν
/-- The implementation of the compiler (4.2).
This definition explicitly takes a map from variables to registers.
-/
@[simp↓]
def compile (map : Identifier → Register) : Expr → Register → List Instruction
| Expr.const v, _ => [li v]
| Expr.var x, _ => [load (loc x map)]
| Expr.sum s₁ s₂, t => compile map s₁ t ++ [sto t] ++ compile map s₂ (t + 1) ++ [add t]
end Compiler
section Correctness
/-! ### Correctness -/
/-- Machine states ζ₁ and ζ₂ are equal except for the accumulator and registers {x | x ≥ t}. -/
def StateEqRs (t : Register) (ζ₁ ζ₂ : State) : Prop :=
∀ r : Register, r < t → ζ₁.rs r = ζ₂.rs r
notation:50 ζ₁ " ≃[" t "]/ac " ζ₂:50 => StateEqRs t ζ₁ ζ₂
@[refl]
protected theorem StateEqRs.refl (t : Register) (ζ : State) : ζ ≃[t]/ac ζ := by simp [StateEqRs]
@[symm]
protected theorem StateEqRs.symm {t : Register} (ζ₁ ζ₂ : State) :
ζ₁ ≃[t]/ac ζ₂ → ζ₂ ≃[t]/ac ζ₁ := by
simp_all [StateEqRs]
@[trans]
protected theorem StateEqRs.trans {t : Register} (ζ₁ ζ₂ ζ₃ : State) :
ζ₁ ≃[t]/ac ζ₂ → ζ₂ ≃[t]/ac ζ₃ → ζ₁ ≃[t]/ac ζ₃ := by
simp_all [StateEqRs]
/-- Machine states ζ₁ and ζ₂ are equal except for registers {x | x ≥ t}. -/
def StateEq (t : Register) (ζ₁ ζ₂ : State) : Prop :=
ζ₁.ac = ζ₂.ac ∧ StateEqRs t ζ₁ ζ₂
notation:50 ζ₁ " ≃[" t "] " ζ₂:50 => StateEq t ζ₁ ζ₂
@[refl]
protected theorem StateEq.refl (t : Register) (ζ : State) : ζ ≃[t] ζ := by simp [StateEq]; rfl
@[symm]
protected theorem StateEq.symm {t : Register} (ζ₁ ζ₂ : State) : ζ₁ ≃[t] ζ₂ → ζ₂ ≃[t] ζ₁ := by
simp only [StateEq, and_imp]; intros
constructor <;> (symm; assumption)
@[trans]
protected theorem StateEq.trans {t : Register} (ζ₁ ζ₂ ζ₃ : State) :
ζ₁ ≃[t] ζ₂ → ζ₂ ≃[t] ζ₃ → ζ₁ ≃[t] ζ₃ := by
simp only [StateEq, and_imp]; intros
constructor
· simp_all only
· trans ζ₂ <;> assumption
instance (t : Register) : Trans (StateEq (t + 1)) (StateEq (t + 1)) (StateEq (t + 1)) :=
⟨@StateEq.trans _⟩
/-- Transitivity of chaining `≃[t]` and `≃[t]/ac`. -/
@[trans]
protected theorem StateEqStateEqRs.trans (t : Register) (ζ₁ ζ₂ ζ₃ : State) :
ζ₁ ≃[t] ζ₂ → ζ₂ ≃[t]/ac ζ₃ → ζ₁ ≃[t]/ac ζ₃ := by
simp only [StateEq, and_imp]; intros
trans ζ₂ <;> assumption
instance (t : Register) : Trans (StateEq (t + 1)) (StateEqRs (t + 1)) (StateEqRs (t + 1)) :=
⟨@StateEqStateEqRs.trans _⟩
/-- Writing the same value to register `t` gives `≃[t + 1]` from `≃[t]`. -/
theorem stateEq_implies_write_eq {t : Register} {ζ₁ ζ₂ : State} (h : ζ₁ ≃[t] ζ₂) (v : Word) :
write t v ζ₁ ≃[t + 1] write t v ζ₂ := by
simp only [StateEq, StateEqRs, write] at *
constructor; · exact h.1
intro r hr
have hr : r ≤ t := Register.le_of_lt_succ hr
rcases lt_or_eq_of_le hr with hr | hr
· obtain ⟨_, h⟩ := h
specialize h r hr
simp_all
· simp_all
/-- Writing the same value to any register preserves `≃[t]/ac`. -/
theorem stateEqRs_implies_write_eq_rs {t : Register} {ζ₁ ζ₂ : State} (h : ζ₁ ≃[t]/ac ζ₂)
(r : Register) (v : Word) : write r v ζ₁ ≃[t]/ac write r v ζ₂ := by
simp only [StateEqRs, write] at *
intro r' hr'
specialize h r' hr'
congr
/-- `≃[t + 1]` with writing to register `t` implies `≃[t]`. -/
theorem write_eq_implies_stateEq {t : Register} {v : Word} {ζ₁ ζ₂ : State}
(h : ζ₁ ≃[t + 1] write t v ζ₂) : ζ₁ ≃[t] ζ₂ := by
simp only [StateEq, write, StateEqRs] at *
constructor; · exact h.1
intro r hr
obtain ⟨_, h⟩ := h
specialize h r (lt_trans hr (Register.lt_succ_self _))
rwa [if_neg (ne_of_lt hr)] at h
/-- The main **compiler correctness theorem**.
Unlike Theorem 1 in the paper, both `map` and the assumption on `t` are explicit.
-/
theorem compiler_correctness
(map : Identifier → Register) (e : Expr) (ξ : Identifier → Word) (η : State) (t : Register)
(hmap : ∀ x, read (loc x map) η = ξ x) (ht : ∀ x, loc x map < t) :
outcome (compile map e t) η ≃[t] { η with ac := value e ξ } := by
induction e generalizing η t with
-- 5.I
| const => simp [StateEq, step]; rfl
-- 5.II
| var =>
simp_all [StateEq, StateEqRs, step]
-- 5.III
| sum =>
rename_i e_s₁ e_s₂ e_ih_s₁ e_ih_s₂
simp only [compile, List.append_assoc, List.cons_append, outcome_append, outcome, value]
generalize value e_s₁ ξ = ν₁ at e_ih_s₁ ⊢
generalize value e_s₂ ξ = ν₂ at e_ih_s₂ ⊢
generalize dν : ν₁ + ν₂ = ν
generalize dζ₁ : outcome (compile _ e_s₁ t) η = ζ₁
generalize dζ₂ : step (Instruction.sto t) ζ₁ = ζ₂
generalize dζ₃ : outcome (compile _ e_s₂ (t + 1)) ζ₂ = ζ₃
generalize dζ₄ : step (Instruction.add t) ζ₃ = ζ₄
have hζ₁ : ζ₁ ≃[t] { η with ac := ν₁ } := calc
ζ₁ = outcome (compile map e_s₁ t) η := by simp_all
_ ≃[t] { η with ac := ν₁ } := by apply e_ih_s₁ <;> assumption
have hζ₁_ν₁ : ζ₁.ac = ν₁ := by simp_all [StateEq]
have hζ₂ : ζ₂ ≃[t + 1]/ac write t ν₁ η := calc
ζ₂ = step (Instruction.sto t) ζ₁ := by simp_all
_ = write t ζ₁.ac ζ₁ := by simp [step]
_ = write t ν₁ ζ₁ := by simp_all
_ ≃[t + 1] write t ν₁ { η with ac := ν₁ } := by apply stateEq_implies_write_eq hζ₁
_ ≃[t + 1]/ac write t ν₁ η := by
apply stateEqRs_implies_write_eq_rs
simp [StateEqRs]
have ht' : ∀ x, loc x map < t + 1 := by
intros
apply lt_trans (ht _) (Register.lt_succ_self _)
have hmap' : ∀ x, read (loc x map) ζ₂ = ξ x := by
intro x
calc
read (loc x map) ζ₂ = read (loc x map) (write t ν₁ η) := hζ₂ _ (ht' _)
_ = read (loc x map) η := by simp only [loc] at ht; simp [(ht _).ne]
_ = ξ x := hmap x
have hζ₃ : ζ₃ ≃[t + 1] { write t ν₁ η with ac := ν₂ } := calc
ζ₃ = outcome (compile map e_s₂ (t + 1)) ζ₂ := by simp_all
_ ≃[t + 1] { ζ₂ with ac := ν₂ } := by apply e_ih_s₂ <;> assumption
_ ≃[t + 1] { write t ν₁ η with ac := ν₂ } := by simpa [StateEq]
have hζ₃_ν₂ : ζ₃.ac = ν₂ := by simp_all [StateEq]
have hζ₃_ν₁ : read t ζ₃ = ν₁ := by
simp only [StateEq, StateEqRs, write, read] at hζ₃ ⊢
obtain ⟨_, hζ₃⟩ := hζ₃
specialize hζ₃ t (Register.lt_succ_self _)
simp_all
have hζ₄ : ζ₄ ≃[t + 1] { write t ν₁ η with ac := ν } := calc
ζ₄ = step (Instruction.add t) ζ₃ := by simp_all
_ = { ζ₃ with ac := read t ζ₃ + ζ₃.ac } := by simp [step]
_ = { ζ₃ with ac := ν } := by simp_all
_ ≃[t + 1] { { write t ν₁ η with ac := ν₂ } with ac := ν } := by
simp [StateEq] at hζ₃ ⊢; cases hζ₃; assumption
_ ≃[t + 1] { write t ν₁ η with ac := ν } := by simp_all; rfl
apply write_eq_implies_stateEq <;> assumption
end Correctness
section Test
open Instruction
/-- The example in the paper for compiling (x + 3) + (x + (y + 2)). -/
example (x y t : Register) :
let map v := if v = "x" then x else if v = "y" then y else 0
let p :=
Expr.sum (Expr.sum (Expr.var "x") (Expr.const 3))
(Expr.sum (Expr.var "x") (Expr.sum (Expr.var "y") (Expr.const 2)))
compile map p t =
[load x, sto t, li 3, add t, sto t, load x, sto (t + 1), load y, sto (t + 2), li 2,
add (t + 2), add (t + 1), add t] :=
rfl
end Test
end Arithcc |
.lake/packages/mathlib/Archive/MiuLanguage/DecisionSuf.lean | import Archive.MiuLanguage.DecisionNec
import Mathlib.Tactic.Linarith
/-!
# Decision procedure - sufficient condition and decidability
We give a sufficient condition for a string to be derivable in the MIU language. Together with the
necessary condition, we use this to prove that `Derivable` is an instance of `DecidablePred`.
Let `count I st` and `count U st` denote the number of `I`s (respectively `U`s) in `st : Miustr`.
We'll show that `st` is derivable if it has the form `M::x` where `x` is a string of `I`s and `U`s
for which `count I x` is congruent to 1 or 2 modulo 3.
To prove this, it suffices to show `Derivable M::y` where `y` is any `Miustr` consisting only of
`I`s such that the number of `I`s in `y` is `a+3b`, where `a = count I x` and `b = count U x`.
This suffices because Rule 3 permits us to change any string of three consecutive `I`s into a `U`.
As `count I y = (count I x) + 3*(count U x) ≡ (count I x) [MOD 3]`, it suffices to show
`Derivable M::z` where `z` is an `Miustr` of `I`s such that `count I z` is congruent to
1 or 2 modulo 3.
Let `z` be such an `Miustr` and let `c` denote `count I z`, so `c ≡ 1 or 2 [MOD 3]`.
To derive such an `Miustr`, it suffices to derive an `Miustr` `M::w`, where again `w` is an
`Miustr` of only `I`s with the additional conditions that `count I w` is a power of 2, that
`count I w ≥ c` and that `count I w ≡ c [MOD 3]`.
To see that this suffices, note that we can remove triples of `I`s from the end of `M::w`,
creating `U`s as we go along. Once the number of `I`s equals `m`, we remove `U`s two at a time
until we have no `U`s. The only issue is that we may begin the removal process with an odd number
of `U`s.
Writing `d = count I w`, we see that this happens if and only if `(d-c)/3` is odd.
In this case, we must apply Rule 1 to `z`, prior to removing triples of `I`s. We thereby
introduce an additional `U` and ensure that the final number of `U`s will be even.
## Tags
miu, decision procedure, decidability, decidable_pred, decidable
-/
namespace Miu
open MiuAtom List Nat
/-- We start by showing that an `Miustr` `M::w` can be derived, where `w` consists only of `I`s and
where `count I w` is a power of 2.
-/
private theorem der_cons_replicate (n : ℕ) : Derivable (M :: replicate (2 ^ n) I) := by
induction n with
| zero => constructor
| succ k hk =>
rw [pow_add, pow_one 2, mul_two, replicate_add]
exact Derivable.r2 hk
/-!
## Converting `I`s to `U`s
For any given natural number `c ≡ 1 or 2 [MOD 3]`, we need to show that can derive an `Miustr`
`M::w` where `w` consists only of `I`s, where `d = count I w` is a power of 2, where `d ≥ c` and
where `d ≡ c [MOD 3]`.
Given the above lemmas, the desired result reduces to an arithmetic result, given in the file
`arithmetic.lean`.
We'll use this result to show we can derive an `Miustr` of the form `M::z` where `z` is a string
consisting only of `I`s such that `count I z ≡ 1 or 2 [MOD 3]`.
As an intermediate step, we show that derive `z` from `zt`, where `t` is an `Miustr` consisting of
an even number of `U`s and `z` is any `Miustr`.
-/
/--
Any number of successive occurrences of `"UU"` can be removed from the end of a `Derivable` `Miustr`
to produce another `Derivable` `Miustr`.
-/
theorem der_of_der_append_replicate_U_even {z : Miustr} {m : ℕ}
(h : Derivable (z ++ ↑(replicate (m * 2) U))) : Derivable z := by
induction m with
| zero =>
revert h
rw [replicate, append_nil]; exact id
| succ k hk =>
apply hk
simp only [succ_mul, replicate_add] at h
rw [← append_nil ↑(z ++ ↑(replicate (k * 2) U))]
apply Derivable.r4
rwa [append_nil, append_assoc]
/-!
In fine-tuning my application of `simp`, I issued the following command to determine which lemmas
`simp` uses.
`set_option trace.simplify.rewrite true`
-/
/-- We may replace several consecutive occurrences of `"III"` with the same number of `"U"`s.
In application of the following lemma, `xs` will either be `[]` or `[U]`.
-/
theorem der_cons_replicate_I_replicate_U_append_of_der_cons_replicate_I_append (c k : ℕ)
(_ : c % 3 = 1 ∨ c % 3 = 2) (xs : Miustr)
(hder : Derivable (↑(M :: replicate (c + 3 * k) I) ++ xs)) :
Derivable (↑(M :: (replicate c I ++ replicate k U)) ++ xs) := by
induction k generalizing xs with
| zero =>
simpa only [replicate, mul_zero, add_zero, append_nil, forall_true_iff, imp_self]
| succ a ha =>
specialize ha (U :: xs)
-- We massage the goal into a form amenable to the application of `ha`.
rw [replicate_add, ← append_assoc, ← cons_append, replicate_one, append_assoc,
singleton_append]
apply ha
apply Derivable.r3
change Derivable (↑(M :: replicate (c + 3 * a) I) ++ ↑(replicate 3 I) ++ xs)
rwa [cons_append, ← replicate_add, add_assoc]
/-!
### Arithmetic
We collect purely arithmetic lemmas: `add_mod2` is used to ensure we have an even number of `U`s
while `le_pow2_and_pow2_eq_mod3` treats the congruence condition modulo 3.
-/
section Arithmetic
/-- For every `a`, the number `a + a % 2` is even.
-/
theorem add_mod2 (a : ℕ) : ∃ t, a + a % 2 = t * 2 := by
simp only [mul_comm _ 2] -- write `t*2` as `2*t`
apply dvd_of_mod_eq_zero -- it suffices to prove `(a + a % 2) % 2 = 0`
rw [add_mod, mod_mod, ← two_mul, mul_mod_right]
private theorem le_pow2_and_pow2_eq_mod3' (c : ℕ) (x : ℕ) (h : c = 1 ∨ c = 2) :
∃ m : ℕ, c + 3 * x ≤ 2 ^ m ∧ 2 ^ m % 3 = c % 3 := by
induction x with
| zero =>
use c + 1
rcases h with hc | hc <;> · rw [hc]; norm_num
| succ k hk =>
rcases hk with ⟨g, hkg, hgmod⟩
by_cases hp : c + 3 * (k + 1) ≤ 2 ^ g
· use g, hp, hgmod
refine ⟨g + 2, ?_, ?_⟩
· rw [mul_succ, ← add_assoc, pow_add]
change c + 3 * k + 3 ≤ 2 ^ g * (1 + 3); rw [mul_add (2 ^ g) 1 3, mul_one]
linarith [hkg, @Nat.one_le_two_pow g]
· rw [pow_add, ← mul_one c]
exact ModEq.mul hgmod rfl
/-- If `a` is 1 or 2 modulo 3, then exists `k` a power of 2 for which `a ≤ k` and `a ≡ k [MOD 3]`.
-/
theorem le_pow2_and_pow2_eq_mod3 (a : ℕ) (h : a % 3 = 1 ∨ a % 3 = 2) :
∃ m : ℕ, a ≤ 2 ^ m ∧ 2 ^ m % 3 = a % 3 := by
obtain ⟨m, hm⟩ := le_pow2_and_pow2_eq_mod3' (a % 3) (a / 3) h
use m
constructor
· convert hm.1; exact (mod_add_div a 3).symm
· rw [hm.2, mod_mod _ 3]
end Arithmetic
theorem replicate_pow_minus_append {m : ℕ} :
M :: replicate (2 ^ m - 1) I ++ [I] = M :: replicate (2 ^ m) I := by
change M :: replicate (2 ^ m - 1) I ++ replicate 1 I = M :: replicate (2 ^ m) I
rw [cons_append, ← replicate_add, tsub_add_cancel_of_le (one_le_pow' m 1)]
/--
`der_replicate_I_of_mod3` states that `M::y` is `Derivable` if `y` is any `Miustr` consisiting just
of `I`s, where `count I y` is 1 or 2 modulo 3.
-/
theorem der_replicate_I_of_mod3 (c : ℕ) (h : c % 3 = 1 ∨ c % 3 = 2) :
Derivable (M :: replicate c I) := by
-- From `der_cons_replicate`, we can derive the `Miustr` `M::w` described in the introduction.
obtain ⟨m, hm⟩ := le_pow2_and_pow2_eq_mod3 c h -- `2^m` will be the number of `I`s in `M::w`
have hw₂ : Derivable (M :: replicate (2 ^ m) I ++ replicate ((2 ^ m - c) / 3 % 2) U) := by
rcases mod_two_eq_zero_or_one ((2 ^ m - c) / 3) with h_zero | h_one
· -- `(2^m - c)/3 ≡ 0 [MOD 2]`
simp only [der_cons_replicate m, append_nil, List.replicate, h_zero]
· -- case `(2^m - c)/3 ≡ 1 [MOD 2]`
rw [h_one, ← replicate_pow_minus_append, append_assoc]
apply Derivable.r1
rw [replicate_pow_minus_append]
exact der_cons_replicate m
have hw₃ : Derivable (M :: replicate c I ++
replicate ((2 ^ m - c) / 3) U ++ replicate ((2 ^ m - c) / 3 % 2) U) := by
apply
der_cons_replicate_I_replicate_U_append_of_der_cons_replicate_I_append c ((2 ^ m - c) / 3) h
convert hw₂ using 4
-- now we must show `c + 3 * ((2 ^ m - c) / 3) = 2 ^ m`
rw [Nat.mul_div_cancel']
· exact add_tsub_cancel_of_le hm.1
· exact (modEq_iff_dvd' hm.1).mp hm.2.symm
rw [append_assoc, ← replicate_add _ _] at hw₃
obtain ⟨t, ht⟩ := add_mod2 ((2 ^ m - c) / 3)
rw [ht] at hw₃
exact der_of_der_append_replicate_U_even hw₃
example (c : ℕ) (h : c % 3 = 1 ∨ c % 3 = 2) : Derivable (M :: replicate c I) := by
-- From `der_cons_replicate`, we can derive the `Miustr` `M::w` described in the introduction.
obtain ⟨m, hm⟩ := le_pow2_and_pow2_eq_mod3 c h -- `2^m` will be the number of `I`s in `M::w`
have hw₂ : Derivable (M :: replicate (2 ^ m) I ++ replicate ((2 ^ m - c) / 3 % 2) U) := by
rcases mod_two_eq_zero_or_one ((2 ^ m - c) / 3) with h_zero | h_one
· -- `(2^m - c)/3 ≡ 0 [MOD 2]`
simp only [der_cons_replicate m, append_nil, List.replicate, h_zero]
· -- case `(2^m - c)/3 ≡ 1 [MOD 2]`
rw [h_one, ← replicate_pow_minus_append, append_assoc]
apply Derivable.r1
rw [replicate_pow_minus_append]
exact der_cons_replicate m
have hw₃ : Derivable (M :: replicate c I ++
replicate ((2 ^ m - c) / 3) U ++ replicate ((2 ^ m - c) / 3 % 2) U) := by
apply
der_cons_replicate_I_replicate_U_append_of_der_cons_replicate_I_append c ((2 ^ m - c) / 3) h
convert hw₂ using 4
-- now we must show `c + 3 * ((2 ^ m - c) / 3) = 2 ^ m`
rw [Nat.mul_div_cancel']
· exact add_tsub_cancel_of_le hm.1
· exact (modEq_iff_dvd' hm.1).mp hm.2.symm
rw [append_assoc, ← replicate_add _ _] at hw₃
obtain ⟨t, ht⟩ := add_mod2 ((2 ^ m - c) / 3)
rw [ht] at hw₃
exact der_of_der_append_replicate_U_even hw₃
/-!
### `Decstr` is a sufficient condition
The remainder of this file sets up the proof that `Decstr en` is sufficient to ensure
`Derivable en`. Decidability of `Derivable en` is an easy consequence.
The proof proceeds by induction on the `count U` of `en`.
We tackle first the base case of the induction. This requires auxiliary results giving
conditions under which `count I ys = length ys`.
-/
/-- If an `Miustr` has a zero `count U` and contains no `M`, then its `count I` is its length.
-/
theorem count_I_eq_length_of_count_U_zero_and_neg_mem {ys : Miustr} (hu : count U ys = 0)
(hm : M ∉ ys) : count I ys = length ys := by
induction ys with
| nil => rfl
| cons x xs hxs =>
cases x
· -- case `x = M` gives a contradiction.
exfalso; exact hm mem_cons_self
· -- case `x = I`
rw [count_cons, beq_self_eq_true, if_pos rfl, length, succ_inj]
apply hxs
· simpa only [count]
· rw [mem_cons, not_or] at hm; exact hm.2
· -- case `x = U` gives a contradiction.
simp_all
/-- `base_case_suf` is the base case of the sufficiency result.
-/
theorem base_case_suf (en : Miustr) (h : Decstr en) (hu : count U en = 0) : Derivable en := by
rcases h with ⟨⟨mhead, nmtail⟩, hi⟩
have : en ≠ nil := by
intro k
simp only [k, count, countP, countP.go, zero_mod, zero_ne_one, false_or,
reduceCtorEq] at hi
rcases exists_cons_of_ne_nil this with ⟨y, ys, rfl⟩
rcases mhead
rsuffices ⟨c, rfl, hc⟩ : ∃ c, replicate c I = ys ∧ (c % 3 = 1 ∨ c % 3 = 2)
· exact der_replicate_I_of_mod3 c hc
· use count I ys
refine And.intro ?_ hi
apply replicate_count_eq_of_count_eq_length
exact count_I_eq_length_of_count_U_zero_and_neg_mem hu nmtail
/-!
Before continuing to the proof of the induction step, we need other auxiliary results that
relate to `count U`.
-/
theorem mem_of_count_U_eq_succ {xs : Miustr} {k : ℕ} (h : count U xs = succ k) : U ∈ xs := by
induction xs with
| nil => exfalso; rw [count] at h; contradiction
| cons z zs hzs =>
rw [mem_cons]
cases z <;> try exact Or.inl rfl
all_goals right; simp only [count_cons] at h; exact hzs h
theorem eq_append_cons_U_of_count_U_pos {k : ℕ} {zs : Miustr} (h : count U zs = succ k) :
∃ as bs : Miustr, zs = as ++ ↑(U :: bs) :=
append_of_mem (mem_of_count_U_eq_succ h)
/-- `ind_hyp_suf` is the inductive step of the sufficiency result.
-/
theorem ind_hyp_suf (k : ℕ) (ys : Miustr) (hu : count U ys = succ k) (hdec : Decstr ys) :
∃ as bs : Miustr,
ys = M :: as ++ U :: bs ∧
count U (↑(M :: as) ++ ↑[I, I, I] ++ bs : Miustr) = k ∧
Decstr (↑(M :: as) ++ ↑[I, I, I] ++ bs) := by
rcases hdec with ⟨⟨mhead, nmtail⟩, hic⟩
have : ys ≠ nil := by rintro rfl; contradiction
rcases exists_cons_of_ne_nil this with ⟨z, zs, rfl⟩
rcases mhead
simp only [count_cons] at hu
rcases eq_append_cons_U_of_count_U_pos hu with ⟨as, bs, rfl⟩
use as, bs
refine ⟨rfl, ?_, ?_, ?_⟩
· simp_rw [count_append, count_cons, beq_self_eq_true, if_true, add_succ, beq_iff_eq,
reduceCtorEq, reduceIte, add_zero, succ_inj] at hu
rwa [count_append, count_append]
· apply And.intro rfl
rw [cons_append, cons_append]
dsimp [tail] at nmtail ⊢
rw [mem_append] at nmtail
simpa only [append_assoc, cons_append, nil_append, mem_append, mem_cons, reduceCtorEq,
false_or] using nmtail
· rw [count_append, count_append]; rw [← cons_append, count_append] at hic
simp only [count_cons_self, count_nil, count_cons] at hic ⊢
rw [add_right_comm, add_mod_right]; exact hic
/-- `der_of_decstr` states that `Derivable en` follows from `Decstr en`.
-/
theorem der_of_decstr {en : Miustr} (h : Decstr en) : Derivable en := by
/- The next three lines have the effect of introducing `count U en` as a variable that can be used
for induction -/
have hu : ∃ n, count U en = n := exists_eq'
obtain ⟨n, hu⟩ := hu
induction n generalizing en with
| zero => exact base_case_suf _ h hu
| succ k hk =>
rcases ind_hyp_suf k en hu h with ⟨as, bs, hyab, habuc, hdecab⟩
have h₂ : Derivable (↑(M :: as) ++ ↑[I, I, I] ++ bs) := hk hdecab habuc
rw [hyab]
exact Derivable.r3 h₂
/-!
### Decidability of `Derivable`
-/
/-- Finally, we have the main result, namely that `Derivable` is a decidable predicate.
-/
instance : DecidablePred Derivable := fun _ => decidable_of_iff _ ⟨der_of_decstr, decstr_of_der⟩
/-!
By decidability, we can automatically determine whether any given `Miustr` is `Derivable`.
-/
example : ¬Derivable "MU" := by decide
example : Derivable "MUIUIUIIIIIUUUIUII" := by decide
end Miu |
.lake/packages/mathlib/Archive/MiuLanguage/Basic.lean | import Mathlib.Tactic.Linarith
/-!
# An MIU Decision Procedure in Lean
The [MIU formal system](https://en.wikipedia.org/wiki/MU_puzzle) was introduced by Douglas
Hofstadter in the first chapter of his 1979 book,
[Gödel, Escher, Bach](https://en.wikipedia.org/wiki/G%C3%B6del,_Escher,_Bach).
The system is defined by four rules of inference, one axiom, and an alphabet of three symbols:
`M`, `I`, and `U`.
Hofstadter's central question is: can the string `"MU"` be derived?
It transpires that there is a simple decision procedure for this system. A string is derivable if
and only if it starts with `M`, contains no other `M`s, and the number of `I`s in the string is
congruent to 1 or 2 modulo 3.
The principal aim of this project is to give a Lean proof that the derivability of a string is a
decidable predicate.
## The MIU System
In Hofstadter's description, an _atom_ is any one of `M`, `I` or `U`. A _string_ is a finite
sequence of zero or more symbols. To simplify notation, we write a sequence `[I,U,U,M]`,
for example, as `IUUM`.
The four rules of inference are:
1. xI → xIU,
2. Mx → Mxx,
3. xIIIy → xUy,
4. xUUy → xy,
where the notation α → β is to be interpreted as 'if α is derivable, then β is derivable'.
Additionally, he has an axiom:
* `MI` is derivable.
In Lean, it is natural to treat the rules of inference and the axiom on an equal footing via an
inductive data type `Derivable` designed so that `Derivable x` represents the notion that the string
`x` can be derived from the axiom by the rules of inference. The axiom is represented as a
nonrecursive constructor for `Derivable`. This mirrors the translation of Peano's axiom '0 is a
natural number' into the nonrecursive constructor `zero` of the inductive type `Nat`.
## References
* [Jeremy Avigad, Leonardo de Moura and Soonho Kong, _Theorem Proving in Lean_]
[avigad_moura_kong-2017]
* [Douglas R Hofstadter, _Gödel, Escher, Bach_][Hofstadter-1979]
## Tags
miu, derivable strings
-/
namespace Miu
/-!
### Declarations and instance derivations for `MiuAtom` and `Miustr`
-/
/-- The atoms of MIU can be represented as an enumerated type in Lean.
-/
inductive MiuAtom : Type
| M : MiuAtom
| I : MiuAtom
| U : MiuAtom
deriving DecidableEq
/-!
The annotation `deriving DecidableEq` above indicates that Lean will automatically derive that
`MiuAtom` is an instance of `DecidableEq`. The use of `deriving` is crucial in this project and will
lead to the automatic derivation of decidability.
-/
open MiuAtom
/--
We show that the type `MiuAtom` is inhabited, giving `M` (for no particular reason) as the default
element.
-/
instance miuAtomInhabited : Inhabited MiuAtom :=
Inhabited.mk M
/-- `MiuAtom.repr` is the 'natural' function from `MiuAtom` to `String`.
-/
def MiuAtom.repr : MiuAtom → String
| M => "M"
| I => "I"
| U => "U"
/-- Using `MiuAtom.repr`, we prove that `MiuAtom` is an instance of `Repr`.
-/
instance : Repr MiuAtom :=
⟨fun u _ => u.repr⟩
/-- For simplicity, an `Miustr` is just a list of elements of type `MiuAtom`.
-/
abbrev Miustr := List MiuAtom
instance : Membership MiuAtom Miustr := by unfold Miustr; infer_instance
/-- For display purposes, an `Miustr` can be represented as a `String`.
-/
def Miustr.mrepr : Miustr → String
| [] => ""
| c :: cs => c.repr ++ Miustr.mrepr cs
instance miurepr : Repr Miustr :=
⟨fun u _ => u.mrepr⟩
/-- In the other direction, we set up a coercion from `String` to `Miustr`.
-/
def lcharToMiustr : List Char → Miustr
| [] => []
| c :: cs =>
let ms := lcharToMiustr cs
match c with
| 'M' => M :: ms
| 'I' => I :: ms
| 'U' => U :: ms
| _ => []
instance stringCoeMiustr : Coe String Miustr :=
⟨fun st => lcharToMiustr st.data⟩
/-!
### Derivability
-/
/--
The inductive type `Derivable` has five constructors. The nonrecursive constructor `mk` corresponds
to Hofstadter's axiom that `"MI"` is derivable. Each of the constructors `r1`, `r2`, `r3`, `r4`
corresponds to the one of Hofstadter's rules of inference.
-/
inductive Derivable : Miustr → Prop
| mk : Derivable "MI"
| r1 {x} : Derivable (x ++ [I]) → Derivable (x ++ [I, U])
| r2 {x} : Derivable (M :: x) → Derivable (M :: x ++ x)
| r3 {x y} : Derivable (x ++ [I, I, I] ++ y) → Derivable (x ++ (U :: y))
| r4 {x y} : Derivable (x ++ [U, U] ++ y) → Derivable (x ++ y)
/-!
### Rule usage examples
-/
example (h : Derivable "UMI") : Derivable "UMIU" := by
change Derivable ([U, M] ++ [I, U])
exact Derivable.r1 h -- Rule 1
example (h : Derivable "MIIU") : Derivable "MIIUIIU" := by
change Derivable (M :: [I, I, U] ++ [I, I, U])
exact Derivable.r2 h -- Rule 2
example (h : Derivable "UIUMIIIMMM") : Derivable "UIUMUMMM" := by
change Derivable ([U, I, U, M] ++ U :: [M, M, M])
exact Derivable.r3 h -- Rule 3
example (h : Derivable "MIMIMUUIIM") : Derivable "MIMIMIIM" := by
change Derivable ([M, I, M, I, M] ++ [I, I, M])
exact Derivable.r4 h -- Rule 4
/-!
### Derivability examples
-/
private theorem MIU_der : Derivable "MIU" := by
change Derivable ([M] ++ [I, U])
apply Derivable.r1 -- reduce to deriving `"MI"`,
constructor -- which is the base of the inductive construction.
example : Derivable "MIUIU" := by
change Derivable (M :: [I, U] ++ [I, U])
exact Derivable.r2 MIU_der -- `"MIUIU"` can be derived as `"MIU"` can.
example : Derivable "MUI" := by
have h₂ : Derivable "MII" := by
change Derivable (M :: [I] ++ [I])
exact Derivable.r2 Derivable.mk
have h₃ : Derivable "MIIII" := by
change Derivable (M :: [I, I] ++ [I, I])
exact Derivable.r2 h₂
change Derivable ([M] ++ U :: [I])
exact Derivable.r3 h₃ -- We prove our main goal using rule 3
end Miu |
.lake/packages/mathlib/Archive/MiuLanguage/DecisionNec.lean | import Archive.MiuLanguage.Basic
import Mathlib.Data.List.Basic
import Mathlib.Data.Nat.ModEq
/-!
# Decision procedure: necessary condition
We introduce a condition `Decstr` and show that if a string `en` is `Derivable`, then `Decstr en`
holds.
Using this, we give a negative answer to the question: is `"MU"` derivable?
## Tags
miu, decision procedure
-/
namespace Miu
open MiuAtom Nat List
/-!
### Numerical condition on the `I` count
Suppose `st : Miustr`. Then `count I st` is the number of `I`s in `st`. We'll show, if
`Derivable st`, then `count I st` must be 1 or 2 modulo 3. To do this, it suffices to show that if
the `en : Miustr` is derived from `st`, then `count I en` moudulo 3 is either equal to or is twice
`count I st`, modulo 3.
-/
/-- Given `st en : Miustr`, the relation `CountEquivOrEquivTwoMulMod3 st en` holds if `st` and
`en` either have equal `count I`, modulo 3, or `count I en` is twice `count I st`, modulo 3.
-/
def CountEquivOrEquivTwoMulMod3 (st en : Miustr) : Prop :=
let a := count I st
let b := count I en
b ≡ a [MOD 3] ∨ b ≡ 2 * a [MOD 3]
example : CountEquivOrEquivTwoMulMod3 "II" "MIUI" :=
Or.inl rfl
example : CountEquivOrEquivTwoMulMod3 "IUIM" "MI" :=
Or.inr rfl
/-- If `a` is 1 or 2 mod 3 and if `b` is `a` or twice `a` mod 3, then `b` is 1 or 2 mod 3.
-/
theorem mod3_eq_1_or_mod3_eq_2 {a b : ℕ} (h1 : a % 3 = 1 ∨ a % 3 = 2)
(h2 : b % 3 = a % 3 ∨ b % 3 = 2 * a % 3) : b % 3 = 1 ∨ b % 3 = 2 := by
rcases h2 with h2 | h2
· rw [h2]; exact h1
· rcases h1 with h1 | h1
· right; simp [h2, mul_mod, h1]
· left; simp only [h2, mul_mod, h1, mod_mod]
/-- `count_equiv_one_or_two_mod3_of_derivable` shows any derivable string must have a `count I` that
is 1 or 2 modulo 3.
-/
theorem count_equiv_one_or_two_mod3_of_derivable (en : Miustr) :
Derivable en → count I en % 3 = 1 ∨ count I en % 3 = 2 := by
intro h
induction h with
| mk => left; rfl
| r1 _ h_ih =>
apply mod3_eq_1_or_mod3_eq_2 h_ih; left
rw [count_append, count_append]; rfl
| r2 _ h_ih =>
apply mod3_eq_1_or_mod3_eq_2 h_ih; right
simp_rw [count_append, count_cons, beq_iff_eq, reduceCtorEq, ite_false, add_zero, two_mul]
| r3 _ h_ih =>
apply mod3_eq_1_or_mod3_eq_2 h_ih; left
rw [count_append, count_append, count_append]
simp_rw [count_cons_self, count_nil, count_cons, beq_iff_eq, reduceCtorEq, ite_false,
add_right_comm, add_mod_right]
simp
| r4 _ h_ih =>
apply mod3_eq_1_or_mod3_eq_2 h_ih; left
rw [count_append, count_append, count_append]
simp only [ne_eq, not_false_eq_true, count_cons_of_ne, count_nil, add_zero, reduceCtorEq]
/-- Using the above theorem, we solve the MU puzzle, showing that `"MU"` is not derivable.
Once we have proved that `Derivable` is an instance of `DecidablePred`, this will follow
immediately from `dec_trivial`.
-/
theorem not_derivable_mu : ¬Derivable "MU" := by
intro h
cases count_equiv_one_or_two_mod3_of_derivable _ h <;> contradiction
/-!
### Condition on `M`
That solves the MU puzzle, but we'll proceed by demonstrating the other necessary condition for a
string to be derivable, namely that the string must start with an M and contain no M in its tail.
-/
/-- `Goodm xs` holds if `xs : Miustr` begins with `M` and has no `M` in its tail.
-/
def Goodm (xs : Miustr) : Prop :=
List.headI xs = M ∧ M ∉ List.tail xs
instance : DecidablePred Goodm := by unfold Goodm; infer_instance
/-- Demonstration that `"MI"` starts with `M` and has no `M` in its tail.
-/
theorem goodmi : Goodm [M, I] := by
constructor
· rfl
· rw [tail, mem_singleton]; trivial
/-!
We'll show, for each `i` from 1 to 4, that if `en` follows by Rule `i` from `st` and if
`Goodm st` holds, then so does `Goodm en`.
-/
theorem goodm_of_rule1 (xs : Miustr) (h₁ : Derivable (xs ++ [I])) (h₂ : Goodm (xs ++ [I])) :
Goodm (xs ++ [I, U]) := by
obtain ⟨mhead, nmtail⟩ := h₂
constructor
· cases xs <;> simp_all
· change M ∉ tail (xs ++ ([I] ++ [U]))
rw [← append_assoc, tail_append_singleton_of_ne_nil]
· simp_rw [mem_append, mem_singleton, reduceCtorEq, or_false]; exact nmtail
· simp
theorem goodm_of_rule2 (xs : Miustr) (_ : Derivable (M :: xs)) (h₂ : Goodm (M :: xs)) :
Goodm ((M :: xs) ++ xs) := by
constructor
· rfl
· obtain ⟨mhead, mtail⟩ := h₂
contrapose! mtail
rw [cons_append] at mtail
exact or_self_iff.mp (mem_append.mp mtail)
theorem goodm_of_rule3 (as bs : Miustr) (h₁ : Derivable (as ++ [I, I, I] ++ bs))
(h₂ : Goodm (as ++ [I, I, I] ++ bs)) : Goodm (as ++ (U :: bs)) := by
obtain ⟨mhead, nmtail⟩ := h₂
have k : as ≠ nil := by rintro rfl; contradiction
constructor
· cases as
· contradiction
exact mhead
· contrapose! nmtail
rcases exists_cons_of_ne_nil k with ⟨x, xs, rfl⟩
simp_rw [cons_append] at nmtail ⊢
simpa using nmtail
/-!
The proof of the next lemma is identical, on the tactic level, to the previous proof.
-/
theorem goodm_of_rule4 (as bs : Miustr) (h₁ : Derivable (as ++ [U, U] ++ bs))
(h₂ : Goodm (as ++ [U, U] ++ bs)) : Goodm (as ++ bs) := by
obtain ⟨mhead, nmtail⟩ := h₂
have k : as ≠ nil := by rintro rfl; contradiction
constructor
· cases as
· contradiction
exact mhead
· contrapose! nmtail
rcases exists_cons_of_ne_nil k with ⟨x, xs, rfl⟩
simp_rw [cons_append] at nmtail ⊢
simpa using nmtail
/-- Any derivable string must begin with `M` and have no `M` in its tail.
-/
theorem goodm_of_derivable (en : Miustr) : Derivable en → Goodm en := by
intro h
induction h
· exact goodmi
· apply goodm_of_rule1 <;> assumption
· apply goodm_of_rule2 <;> assumption
· apply goodm_of_rule3 <;> assumption
· apply goodm_of_rule4 <;> assumption
/-!
We put together our two conditions to give one necessary condition `Decstr` for an `Miustr` to be
derivable.
-/
/--
`Decstr en` is the condition that `count I en` is 1 or 2 modulo 3, that `en` starts with `M`, and
that `en` has no `M` in its tail. We automatically derive that this is a decidable predicate.
-/
def Decstr (en : Miustr) :=
Goodm en ∧ (count I en % 3 = 1 ∨ count I en % 3 = 2)
instance : DecidablePred Decstr := by unfold Decstr; infer_instance
/-- Suppose `en : Miustr`. If `en` is `Derivable`, then the condition `Decstr en` holds.
-/
theorem decstr_of_der {en : Miustr} : Derivable en → Decstr en := by
intro h
constructor
· exact goodm_of_derivable en h
· exact count_equiv_one_or_two_mod3_of_derivable en h
end Miu |
.lake/packages/mathlib/Archive/Wiedijk100Theorems/AscendingDescendingSequences.lean | import Mathlib.Algebra.Order.Group.Nat
import Mathlib.Data.Finset.Max
import Mathlib.Data.Fintype.Powerset
import Mathlib.Data.Set.Monotone
import Mathlib.Order.Interval.Finset.Nat
/-!
# Erdős–Szekeres theorem
This file proves Theorem 73 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/), also
known as the Erdős–Szekeres theorem: given a sequence of more than `r * s` distinct
values, there is an increasing sequence of length longer than `r` or a decreasing sequence of length
longer than `s`.
We use the proof outlined at
https://en.wikipedia.org/wiki/Erdos-Szekeres_theorem#Pigeonhole_principle.
## Tags
sequences, increasing, decreasing, Ramsey, Erdos-Szekeres, Erdős–Szekeres, Erdős-Szekeres
-/
open Function Finset
namespace Theorems100
variable {α β : Type*} [Fintype α] [LinearOrder α] [LinearOrder β] {f : α → β} {i : α}
/-- The possible lengths of an increasing sequence which ends at `i`. -/
private noncomputable def incSequencesTo (f : α → β) (i : α) : Finset ℕ :=
open Classical in
image card {t : Finset α | IsGreatest t i ∧ StrictMonoOn f t}
/-- The possible lengths of a decreasing sequence which ends at `i`. -/
private noncomputable def decSequencesTo (f : α → β) (i : α) : Finset ℕ :=
open Classical in
image card {t : Finset α | IsGreatest t i ∧ StrictAntiOn f t}
/-- The singleton sequence is increasing, so 1 is a possible length. -/
private lemma one_mem_incSequencesTo : 1 ∈ incSequencesTo f i := mem_image.2 ⟨{i}, by simp⟩
/-- The singleton sequence is decreasing, so 1 is a possible length. -/
private lemma one_mem_decSequencesTo : 1 ∈ decSequencesTo f i := one_mem_incSequencesTo (β := βᵒᵈ)
/-- The singleton sequence is increasing, so the set of lengths is nonempty. -/
private lemma incSequencesTo_nonempty : (incSequencesTo f i).Nonempty := ⟨1, one_mem_incSequencesTo⟩
/-- The singleton sequence is decreasing, so the set of lengths is nonempty. -/
private lemma decSequencesTo_nonempty : (decSequencesTo f i).Nonempty := ⟨1, one_mem_decSequencesTo⟩
/-- The maximum length of an increasing sequence which ends at `i`. -/
private noncomputable def maxIncSequencesTo (f : α → β) (i : α) : ℕ :=
max' (incSequencesTo f i) incSequencesTo_nonempty
/-- The maximum length of a decreasing sequence which ends at `i`. -/
private noncomputable def maxDecSequencesTo (f : α → β) (i : α) : ℕ :=
max' (decSequencesTo f i) decSequencesTo_nonempty
private lemma one_le_maxIncSequencesTo : 1 ≤ maxIncSequencesTo f i :=
le_max' _ _ one_mem_incSequencesTo
private lemma one_le_maxDecSequencesTo : 1 ≤ maxDecSequencesTo f i :=
le_max' _ _ one_mem_decSequencesTo
private lemma maxIncSequencesTo_mem : maxIncSequencesTo f i ∈ incSequencesTo f i :=
max'_mem _ incSequencesTo_nonempty
private lemma maxDecSequencesTo_mem : maxDecSequencesTo f i ∈ decSequencesTo f i :=
max'_mem _ decSequencesTo_nonempty
/--
We will want to show that if `i ≠ j`, then the pairs
`(maxIncSequencesTo f i, maxDecSequencesTo f i)` and
`(maxIncSequencesTo f j, maxDecSequencesTo f j)` are different.
To this end, we will assume wlog that `i < j`, and show that if `f i < f j`,
then `maxIncSequencesTo f i < maxIncSequencesTo f j`, and later dualise to prove that if `f j < f i`
then `maxDecSequencesTo f i < maxDecSequencesTo f j`.
-/
private lemma maxIncSequencesTo_lt {i j : α} (hij : i < j) (hfij : f i < f j) :
maxIncSequencesTo f i < maxIncSequencesTo f j := by
classical
rw [Nat.lt_iff_add_one_le]
refine le_max' _ _ ?_
have : maxIncSequencesTo f i ∈ incSequencesTo f i := max'_mem _ incSequencesTo_nonempty
simp only [incSequencesTo, mem_image, mem_filter, mem_univ, true_and, and_assoc] at this
obtain ⟨t, hti, ht₁, ht₂⟩ := this
simp only [incSequencesTo, mem_image, mem_filter, mem_univ, true_and, and_assoc]
have : ∀ x ∈ t, x < j := by
intro x hx
exact (hti.2 hx).trans_lt hij
refine ⟨insert j t, ?_, ?_, ?_⟩
next =>
convert hti.insert j using 1
next => simp
next => rw [max_eq_left hij.le]
next =>
simp only [coe_insert]
rw [strictMonoOn_insert_iff_of_forall_le]
· refine ⟨?_, ht₁⟩
intro x hx hxj
exact (ht₁.monotoneOn hx hti.1 (hti.2 hx)).trans_lt hfij
· exact fun x hx ↦ (this x hx).le
have : j ∉ t := fun hj ↦ lt_irrefl _ (this _ hj)
simp [this, ht₂]
private lemma maxDecSequencesTo_gt {i j : α} (hij : i < j) (hfij : f j < f i) :
maxDecSequencesTo f i < maxDecSequencesTo f j :=
maxIncSequencesTo_lt (β := βᵒᵈ) hij hfij
/--
For each entry, we form a pair of labels consisting of the maximum lengths of increasing and
decreasing sequences ending there.
-/
private noncomputable def paired (f : α → β) (i : α) : ℕ × ℕ :=
(maxIncSequencesTo f i, maxDecSequencesTo f i)
/--
By combining the previous two lemmas, we see that since `f` is injective, the pairs of labels
must also be unique.
-/
private lemma paired_injective (hf : Injective f) : Injective (paired f) := by
apply injective_of_lt_imp_ne
intro i j hij q
cases lt_or_gt_of_ne (hf.ne hij.ne)
case inl h => exact (maxIncSequencesTo_lt hij h).ne congr($q.1)
case inr h => exact (maxDecSequencesTo_gt hij h).ne congr($q.2)
/-- **Erdős–Szekeres Theorem**: Given a sequence of more than `r * s` distinct values, there is an
increasing sequence of length longer than `r` or a decreasing sequence of length longer than `s`.
Proof idea:
We label each value in the sequence with two numbers specifying the longest increasing
subsequence ending there, and the longest decreasing subsequence ending there.
We then show the pair of labels must be unique. Now if there is no increasing sequence longer than
`r` and no decreasing sequence longer than `s`, then there are at most `r * s` possible labels,
which is a contradiction if there are more than `r * s` elements.
-/
theorem erdos_szekeres {r s : ℕ} {f : α → β} (hn : r * s < Fintype.card α) (hf : Injective f) :
(∃ t : Finset α, r < #t ∧ StrictMonoOn f t) ∨
∃ t : Finset α, s < #t ∧ StrictAntiOn f t := by
classical
-- It suffices to prove that there is some `i` where one of the max lengths is bigger than
-- `r` or `s`, as this corresponds to a monotone sequence of the required length.
rsuffices ⟨i, hi⟩ : ∃ i, r < maxIncSequencesTo f i ∨ s < maxDecSequencesTo f i
· refine Or.imp ?_ ?_ hi
on_goal 1 =>
have : maxIncSequencesTo f i ∈ image card _ := maxIncSequencesTo_mem
on_goal 2 =>
have : maxDecSequencesTo f i ∈ image card _ := maxDecSequencesTo_mem
all_goals
intro hi
obtain ⟨t, ht₁, ht₂⟩ := mem_image.1 this
refine ⟨t, by rwa [ht₂], ?_⟩
rw [mem_filter] at ht₁
exact ht₁.2.2
-- If such an `i` does not exist, then our pairs of labels lie in a small set, which is a
-- contradiction since the pairs are unique.
by_contra! q
have : Set.MapsTo (paired f) (univ : Finset α) (Icc 1 r ×ˢ Icc 1 s : Finset _) := by
simp [paired, one_le_maxIncSequencesTo, one_le_maxDecSequencesTo, Set.MapsTo, *]
refine hn.not_ge ?_
simpa using card_le_card_of_injOn (paired f) this (paired_injective hf).injOn
end Theorems100 |
.lake/packages/mathlib/Archive/Wiedijk100Theorems/SolutionOfCubicQuartic.lean | import Mathlib.Tactic.LinearCombination
import Mathlib.RingTheory.Polynomial.Cyclotomic.Roots
/-!
# The roots of cubic and quartic polynomials
This file proves Theorem 37 and 46 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/).
We give the solutions to the cubic equation `a * x^3 + b * x^2 + c * x + d = 0` over a field `K`
that has characteristic neither 2 nor 3, that has a third primitive root of
unity, and in which certain other quantities admit square and cube roots. This is based on the
[Cardano's Formula](https://en.wikipedia.org/wiki/Cubic_equation#Cardano's_formula).
We also give solutions to the quartic equation `a * x^4 + b * x^3 + c * x^2 + d * x + e = 0` over
a field `K` that is not characteristic 2, and in which certain quantities admit square roots, in
terms of a quantity that is a root of a particular cubic equation.
## Main statements
- `cubic_eq_zero_iff`: gives the roots of the cubic equation
where the discriminant `p = 3 * a * c - b^2` is nonzero.
- `cubic_eq_zero_iff_of_p_eq_zero`: gives the roots of the cubic equation
where the discriminant equals zero.
- `quartic_eq_zero_iff`: gives the roots of the quartic equation
where the quantity `b^3 - 4 * a * b * c + 8 * a^2 * d` is nonzero, in terms of a root `u`
to a cubic resolvent.
- `quartic_eq_zero_iff_of_q_eq_zero`: gives the roots of the quartic equation
where the quantity `b^3 - 4 * a * b * c + 8 * a^2 * d` equals zero.
## Proof outline
Proofs of the cubic and quartic formulas are similar in outline.
For a cubic:
1. Given cubic $ax^3 + bx^2 + cx + d = 0$, we show it is equivalent to some "depressed cubic"
$y^3 + 3py - 2q = 0$ where $y = x + b / (3a)$, $p = (3ac - b^2) / (9a^2)$, and
$q = (9abc - 2b^3 - 27a^2d) / (54a^3)$ (`h₁` in `cubic_eq_zero_iff`).
2. When $p$ is zero, this is easily solved (`cubic_eq_zero_iff_of_p_eq_zero`).
3. Otherwise one can directly derive a factorization of the depressed cubic, in terms of some
primitive cube root of unity $\omega^3 = 1$ (`cubic_depressed_eq_zero_iff`).
Similarly, for a quartic:
1. Given quartic $ax^4 + bx^3 + cx^2 + dx + e = 0$, it is equivalent to some "depressed quartic"
$y^4 + py^2 + qy + r = 0$ where $y = x + b / (4a)$, $p = (8ac - 3b^2) / (8a^2))$,
$q = b^3 - 4abc + 8a^2d) / (8a^3))$, and $r = (16ab^2c + 256a^3e - 3b^4 - 64a^2bd) / (256a^4)$
(`h₁` in `quartic_eq_zero_iff`).
2. When $q$ is zero, this is easily solved as a quadratic in $y^2$
(`quartic_eq_zero_iff_of_q_eq_zero`).
3. Otherwise one can directly derive a factorization of the depressed quartic into two quadratics,
in terms of some root of the *cubic resolvent* $u^3 - pu^2 - 4ru + 4pr - q^2 = 0$
(`quartic_depressed_eq_zero_iff`).
## References
The cubic formula was originally ported from Isabelle/HOL. The
[original file](https://isabelle.in.tum.de/dist/library/HOL/HOL-ex/Cubic_Quartic.html) was written by Amine Chaieb.
The proof of the quartic formula is similar in structure to the cubic, and uses the formulation in
[Zwillinger, *CRC Standard Mathematical Tables and Formulae*](zwillinger2003).
## Tags
polynomial, cubic, quartic, root
-/
namespace Theorems100
section Field
open Polynomial
variable {K : Type*} [Field K] (a b c d e : K) {ω p q r s t u v w x y : K}
section Cubic
theorem cube_root_of_unity_sum (hω : IsPrimitiveRoot ω 3) : 1 + ω + ω ^ 2 = 0 := by
simpa [cyclotomic_prime, Finset.sum_range_succ] using hω.isRoot_cyclotomic (by decide)
/-- The roots of a monic cubic whose quadratic term is zero and whose linear term is nonzero. -/
theorem cubic_depressed_eq_zero_iff (hω : IsPrimitiveRoot ω 3) (hp_nonzero : p ≠ 0)
(hr : r ^ 2 = q ^ 2 + p ^ 3) (hs3 : s ^ 3 = q + r) (ht : t * s = p) (x : K) :
x ^ 3 + 3 * p * x - 2 * q = 0 ↔ x = s - t ∨ x = s * ω - t * ω ^ 2 ∨ x = s * ω ^ 2 - t * ω := by
have h₁ : ∀ x a₁ a₂ a₃ : K, x = a₁ ∨ x = a₂ ∨ x = a₃ ↔ (x - a₁) * (x - a₂) * (x - a₃) = 0 := by
intros; simp only [mul_eq_zero, sub_eq_zero, or_assoc]
rw [h₁]
apply Eq.congr_left
have hs_nonzero : s ≠ 0 := by
contrapose! hp_nonzero with hs_nonzero
linear_combination -1 * ht + t * hs_nonzero
rw [← mul_left_inj' (pow_ne_zero 3 hs_nonzero)]
have H := cube_root_of_unity_sum hω
linear_combination
hr + (-q + r + s ^ 3) * hs3 - (3 * x * s ^ 3 + (t * s) ^ 2 + t * s * p + p ^ 2) * ht +
(x ^ 2 * (s - t) + x * (-ω * (s ^ 2 + t ^ 2) + s * t * (3 + ω ^ 2 - ω)) -
(-(s ^ 3 - t ^ 3) * (ω - 1) + s ^ 2 * t * ω ^ 2 - s * t ^ 2 * ω ^ 2)) * s ^ 3 * H
variable [Invertible (2 : K)] [Invertible (3 : K)]
/-- **The Solution of Cubic**.
The roots of a cubic polynomial whose discriminant is nonzero. -/
theorem cubic_eq_zero_iff (ha : a ≠ 0) (hω : IsPrimitiveRoot ω 3)
(hp : p = (3 * a * c - b ^ 2) / (9 * a ^ 2)) (hp_nonzero : p ≠ 0)
(hq : q = (9 * a * b * c - 2 * b ^ 3 - 27 * a ^ 2 * d) / (54 * a ^ 3))
(hr : r ^ 2 = q ^ 2 + p ^ 3) (hs3 : s ^ 3 = q + r) (ht : t * s = p) (x : K) :
a * x ^ 3 + b * x ^ 2 + c * x + d = 0 ↔
x = s - t - b / (3 * a) ∨
x = s * ω - t * ω ^ 2 - b / (3 * a) ∨ x = s * ω ^ 2 - t * ω - b / (3 * a) := by
let y := x + b / (3 * a)
have h9 : (9 : K) = 3 ^ 2 := by norm_num
have h54 : (54 : K) = 2 * 3 ^ 3 := by norm_num
have h₁ : a * x ^ 3 + b * x ^ 2 + c * x + d = a * (y ^ 3 + 3 * p * y - 2 * q) := by
simp only [hp, h9, hq, h54, y]; field
have h₂ : ∀ x, a * x = 0 ↔ x = 0 := by intro x; simp [ha]
rw [h₁, h₂, cubic_depressed_eq_zero_iff hω hp_nonzero hr hs3 ht]
simp_rw [y, eq_sub_iff_add_eq]
/-- The solution of the cubic equation when p equals zero. -/
theorem cubic_eq_zero_iff_of_p_eq_zero (ha : a ≠ 0) (hω : IsPrimitiveRoot ω 3)
(hpz : 3 * a * c - b ^ 2 = 0)
(hq : q = (9 * a * b * c - 2 * b ^ 3 - 27 * a ^ 2 * d) / (54 * a ^ 3)) (hs3 : s ^ 3 = 2 * q)
(x : K) :
a * x ^ 3 + b * x ^ 2 + c * x + d = 0 ↔
x = s - b / (3 * a) ∨ x = s * ω - b / (3 * a) ∨ x = s * ω ^ 2 - b / (3 * a) := by
have h₁ : ∀ x a₁ a₂ a₃ : K, x = a₁ ∨ x = a₂ ∨ x = a₃ ↔ (x - a₁) * (x - a₂) * (x - a₃) = 0 := by
intros; simp only [mul_eq_zero, sub_eq_zero, or_assoc]
have h54 : (54 : K) = 2 * 3 ^ 3 := by norm_num
have hb2 : b ^ 2 = 3 * a * c := by rw [sub_eq_zero] at hpz; rw [hpz]
have hb3 : b ^ 3 = 3 * a * b * c := by rw [pow_succ, hb2]; ring
have h₂ :=
calc
a * x ^ 3 + b * x ^ 2 + c * x + d =
a * (x + b / (3 * a)) ^ 3 + (c - b ^ 2 / (3 * a)) * x + (d - b ^ 3 * a / (3 * a) ^ 3) := by
field
_ = a * (x + b / (3 * a)) ^ 3 + (d - (9 * a * b * c - 2 * b ^ 3) * a / (3 * a) ^ 3) := by
simp only [hb2, hb3]; field
_ = a * ((x + b / (3 * a)) ^ 3 - s ^ 3) := by simp only [hs3, hq, h54]; field
have h₃ : ∀ x, a * x = 0 ↔ x = 0 := by intro x; simp [ha]
have h₄ : ∀ x : K, x ^ 3 - s ^ 3 = (x - s) * (x - s * ω) * (x - s * ω ^ 2) := by
intro x
calc
x ^ 3 - s ^ 3 = (x - s) * (x ^ 2 + x * s + s ^ 2) := by ring
_ = (x - s) * (x ^ 2 - (ω + ω ^ 2) * x * s + (1 + ω + ω ^ 2) * x * s + s ^ 2) := by ring
_ = (x - s) * (x ^ 2 - (ω + ω ^ 2) * x * s + ω ^ 3 * s ^ 2) := by
rw [hω.pow_eq_one, cube_root_of_unity_sum hω]; simp
_ = (x - s) * (x - s * ω) * (x - s * ω ^ 2) := by ring
rw [h₁, h₂, h₃, h₄ (x + b / (3 * a))]
ring_nf
end Cubic
section Quartic
variable [Invertible (2 : K)]
/-- Roots of a quartic whose cubic term is zero and linear term is nonzero,
In terms of some `u` that satisfies a particular cubic resolvent. -/
theorem quartic_depressed_eq_zero_iff
(hq_nonzero : q ≠ 0)
(hu : u ^ 3 - p * u ^ 2 - 4 * r * u + 4 * p * r - q ^ 2 = 0)
(hs : s ^ 2 = u - p)
(hv : v ^ 2 = 4 * s ^ 2 - 8 * (u - q / s))
(hw : w ^ 2 = 4 * s ^ 2 - 8 * (u + q / s))
(x : K) :
x ^ 4 + p * x ^ 2 + q * x + r = 0 ↔
x = (-2 * s - v) / 4 ∨ x = (-2 * s + v) / 4 ∨ x = (2 * s - w) / 4 ∨ x = (2 * s + w) / 4 := by
have hi2 : (2 : K) ≠ 0 := Invertible.ne_zero _
have h4 : (4 : K) = 2 ^ 2 := by norm_num
have hs_nonzero : s ≠ 0 := by
contrapose! hq_nonzero with hs0
linear_combination (exp := 2) -hu + (4 * r - u ^ 2) * hs + (u ^ 2 * s - 4 * r * s) * hs0
calc
_ ↔ 4 * (x ^ 4 + p * x ^ 2 + q * x + r) = 0 := by simp [h4, hi2]
_ ↔ (2 * (x * x) + 2 * s * x + (u - q / s)) * (2 * (x * x) + -(2 * s) * x + (u + q / s)) =
0 := by
apply Eq.congr_left
field_simp
linear_combination -hu + (-x ^ 2 * s ^ 2 - x ^ 2 * p + x ^ 2 * u) * hw +
(x ^ 2 * w ^ 2 + 8 * x ^ 2 * u + 8 * x ^ 2 * q / s - u ^ 2 + 4 * r) * hs
_ ↔ _ := by
have hv' : discrim 2 (2 * s) (u - q / s) = v * v := by rw [discrim]; linear_combination -hv
have hw' : discrim 2 (-(2 * s)) (u + q / s) = w * w := by rw [discrim]; linear_combination -hw
rw [mul_eq_zero, quadratic_eq_zero_iff hi2 hv', quadratic_eq_zero_iff hi2 hw']
simp [(by norm_num : (2 : K) * 2 = 4), or_assoc, or_comm]
/-- **The Solution of Quartic**.
The roots of a quartic polynomial when `q` is nonzero. See [Zwillinger](zwillinger2003).
Here, `u` needs to satisfy the cubic resolvent. An explicit expression of `u` is possible using
the cubic formula, but would be too long. -/
theorem quartic_eq_zero_iff (ha : a ≠ 0)
(hp : p = (8 * a * c - 3 * b ^ 2) / (8 * a ^ 2))
(hq : q = (b ^ 3 - 4 * a * b * c + 8 * a ^ 2 * d) / (8 * a ^ 3)) (hq_nonzero : q ≠ 0)
(hr : r =
(16 * a * b ^ 2 * c + 256 * a ^ 3 * e - 3 * b ^ 4 - 64 * a ^ 2 * b * d) / (256 * a ^ 4))
(hu : u ^ 3 - p * u ^ 2 - 4 * r * u + 4 * p * r - q ^ 2 = 0)
(hs : s ^ 2 = u - p)
(hv : v ^ 2 = 4 * s ^ 2 - 8 * (u - q / s))
(hw : w ^ 2 = 4 * s ^ 2 - 8 * (u + q / s)) (x : K) :
a * x ^ 4 + b * x ^ 3 + c * x ^ 2 + d * x + e = 0 ↔
x = (-2 * s - v) / 4 - b / (4 * a) ∨ x = (-2 * s + v) / 4 - b / (4 * a) ∨
x = (2 * s - w) / 4 - b / (4 * a) ∨ x = (2 * s + w) / 4 - b / (4 * a) := by
let y := x + b / (4 * a)
have h4 : (4 : K) = 2 ^ 2 := by norm_num
have h8 : (8 : K) = 2 ^ 3 := by norm_num
have h16 : (16 : K) = 2 ^ 4 := by norm_num
have h256 : (256 : K) = 2 ^ 8 := by norm_num
have h₁ : a * x ^ 4 + b * x ^ 3 + c * x ^ 2 + d * x + e =
a * (y ^ 4 + p * y ^ 2 + q * y + r) := by
simp only [h4, hp, h8, hq, hr, h16, h256, y]; field
have h₂ : ∀ x, a * x = 0 ↔ x = 0 := by intro x; simp [ha]
rw [h₁, h₂, quartic_depressed_eq_zero_iff hq_nonzero hu hs hv hw]
simp_rw [y, eq_sub_iff_add_eq]
/-- The roots of a quartic polynomial when `q` equals zero. -/
theorem quartic_eq_zero_iff_of_q_eq_zero (ha : a ≠ 0)
(hp : p = (8 * a * c - 3 * b ^ 2) / (8 * a ^ 2))
(hqz : b ^ 3 - 4 * a * b * c + 8 * a ^ 2 * d = 0)
(hr : r =
(16 * a * b ^ 2 * c + 256 * a ^ 3 * e - 3 * b ^ 4 - 64 * a ^ 2 * b * d) / (256 * a ^ 4))
(ht : t ^ 2 = p ^ 2 - 4 * r)
(hv : v ^ 2 = (-p + t) / 2)
(hw : w ^ 2 = (-p - t) / 2) (x : K) :
a * x ^ 4 + b * x ^ 3 + c * x ^ 2 + d * x + e = 0 ↔
x = v - b / (4 * a) ∨ x = -v - b / (4 * a) ∨ x = w - b / (4 * a) ∨ x = -w - b / (4 * a) := by
let y := x + b / (4 * a)
have h4 : (4 : K) = 2 ^ 2 := by norm_num
have h8 : (8 : K) = 2 ^ 3 := by norm_num
have h16 : (16 : K) = 2 ^ 4 := by norm_num
have h256 : (256 : K) = 2 ^ 8 := by norm_num
have h₁ : a * x ^ 4 + b * x ^ 3 + c * x ^ 2 + d * x + e = a * (y ^ 4 + p * y ^ 2 + r) := by
simp only [hp, hr, y, h4, h8, h16, h256]
linear_combination (norm := field) (4 * a * x + b) * hqz / a ^ 3 / 2 ^ 5
rw [h₁, ha.isUnit.mul_right_eq_zero]
calc
_ ↔ 1 * (y ^ 2 * y ^ 2) + p * y ^ 2 + r = 0 := by
apply Eq.congr_left
ring
_ ↔ y ^ 2 = (-p + t) / 2 ∨ y ^ 2 = (-p - t) / 2 := by
have ht' : discrim 1 p r = t * t := by rw [discrim]; linear_combination -ht
rw [quadratic_eq_zero_iff one_ne_zero ht', mul_one]
_ ↔ _ := by
simp_rw [y, ← hv, ← hw, pow_two, mul_self_eq_mul_self_iff, eq_sub_iff_add_eq, or_assoc]
end Quartic
end Field
end Theorems100 |
.lake/packages/mathlib/Archive/Wiedijk100Theorems/AbelRuffini.lean | import Mathlib.Analysis.Calculus.LocalExtr.Polynomial
import Mathlib.Analysis.Complex.Polynomial.Basic
import Mathlib.FieldTheory.AbelRuffini
import Mathlib.RingTheory.Polynomial.Eisenstein.Criterion
import Mathlib.RingTheory.Int.Basic
import Mathlib.RingTheory.RootsOfUnity.Minpoly
/-!
# Construction of an algebraic number that is not solvable by radicals.
The main ingredients are:
* `solvableByRad.isSolvable'` in `Mathlib/FieldTheory/AbelRuffini.lean` :
an irreducible polynomial with an `IsSolvableByRad` root has solvable Galois group
* `galActionHom_bijective_of_prime_degree'` in `Mathlib/FieldTheory/PolynomialGaloisGroup.lean` :
an irreducible polynomial of prime degree with 1-3 non-real roots has full Galois group
* `Equiv.Perm.not_solvable` in `Mathlib/GroupTheory/Solvable.lean` : the symmetric group is not
solvable
Then all that remains is the construction of a specific polynomial satisfying the conditions of
`galActionHom_bijective_of_prime_degree'`, which is done in this file.
-/
namespace AbelRuffini
open Function Polynomial Polynomial.Gal Ideal
open scoped Polynomial
attribute [local instance] splits_ℚ_ℂ
variable (R : Type*) [CommRing R] (a b : ℕ)
/-- A quintic polynomial that we will show is irreducible -/
noncomputable def Φ : R[X] :=
X ^ 5 - C (a : R) * X + C (b : R)
variable {R}
@[simp]
theorem map_Phi {S : Type*} [CommRing S] (f : R →+* S) : (Φ R a b).map f = Φ S a b := by simp [Φ]
@[simp]
theorem coeff_zero_Phi : (Φ R a b).coeff 0 = (b : R) := by simp [Φ, coeff_X_pow]
@[simp]
theorem coeff_five_Phi : (Φ R a b).coeff 5 = 1 := by
simp [Φ, -map_natCast]
variable [Nontrivial R]
theorem degree_Phi : (Φ R a b).degree = ((5 : ℕ) : WithBot ℕ) := by
suffices degree (X ^ 5 - C (a : R) * X) = ((5 : ℕ) : WithBot ℕ) by
rwa [Φ, degree_add_eq_left_of_degree_lt]
convert (degree_C_le (R := R)).trans_lt (WithBot.coe_lt_coe.mpr (show 0 < 5 by simp))
rw [degree_sub_eq_left_of_degree_lt] <;> rw [degree_X_pow]
exact (degree_C_mul_X_le (a : R)).trans_lt (WithBot.coe_lt_coe.mpr (show 1 < 5 by simp))
theorem natDegree_Phi : (Φ R a b).natDegree = 5 :=
natDegree_eq_of_degree_eq_some (degree_Phi a b)
theorem leadingCoeff_Phi : (Φ R a b).leadingCoeff = 1 := by
rw [Polynomial.leadingCoeff, natDegree_Phi, coeff_five_Phi]
theorem monic_Phi : (Φ R a b).Monic :=
leadingCoeff_Phi a b
theorem irreducible_Phi (p : ℕ) (hp : p.Prime) (hpa : p ∣ a) (hpb : p ∣ b) (hp2b : ¬p ^ 2 ∣ b) :
Irreducible (Φ ℚ a b) := by
rw [← map_Phi a b (Int.castRingHom ℚ), ← IsPrimitive.Int.irreducible_iff_irreducible_map_cast]
on_goal 1 =>
apply irreducible_of_eisenstein_criterion
· rwa [span_singleton_prime (Int.natCast_ne_zero.mpr hp.ne_zero), Int.prime_iff_natAbs_prime]
· rw [leadingCoeff_Phi, mem_span_singleton]
exact mod_cast mt Nat.dvd_one.mp hp.ne_one
· intro n hn
rw [mem_span_singleton]
rw [degree_Phi] at hn; norm_cast at hn
interval_cases n <;>
simp +decide only [Φ, coeff_X_pow, coeff_C, Int.natCast_dvd_natCast.mpr,
hpb, if_true, coeff_C_mul, if_false, coeff_X_zero, hpa, coeff_add, zero_add, mul_zero,
coeff_sub, add_zero, zero_sub, dvd_neg, neg_zero, dvd_mul_of_dvd_left]
· simp only [degree_Phi, ← WithBot.coe_zero]
decide
· rw [coeff_zero_Phi, span_singleton_pow, mem_span_singleton]
exact mt Int.natCast_dvd_natCast.mp hp2b
all_goals exact Monic.isPrimitive (monic_Phi a b)
attribute [local simp] map_ofNat in -- use `ofNat` simp theorem with bad keys
theorem real_roots_Phi_le : Fintype.card ((Φ ℚ a b).rootSet ℝ) ≤ 3 := by
rw [← map_Phi a b (algebraMap ℤ ℚ), Φ, ← one_mul (X ^ 5), ← C_1]
apply (card_rootSet_le_derivative _).trans
(Nat.succ_le_succ ((card_rootSet_le_derivative _).trans (Nat.succ_le_succ _)))
suffices (Polynomial.rootSet (C (20 : ℚ) * X ^ 3) ℝ).Subsingleton by
norm_num [Fintype.card_le_one_iff_subsingleton, ← mul_assoc] at *
exact this
rw [rootSet_C_mul_X_pow] <;>
norm_num
theorem real_roots_Phi_ge_aux (hab : b < a) :
∃ x y : ℝ, x ≠ y ∧ aeval x (Φ ℚ a b) = 0 ∧ aeval y (Φ ℚ a b) = 0 := by
let f : ℝ → ℝ := fun x : ℝ => aeval x (Φ ℚ a b)
have hf : f = fun x : ℝ => x ^ 5 - a * x + b := by simp [f, Φ]
have hc : ∀ s : Set ℝ, ContinuousOn f s := fun s => (Φ ℚ a b).continuousOn_aeval
have ha : (1 : ℝ) ≤ a := Nat.one_le_cast.mpr (Nat.one_le_of_lt hab)
have hle : (0 : ℝ) ≤ 1 := zero_le_one
have hf0 : 0 ≤ f 0 := by simp [hf]
by_cases hb : (1 : ℝ) - a + b < 0
· have hf1 : f 1 < 0 := by simp [hf, hb]
have hfa : 0 ≤ f a := by
simp_rw [hf, ← sq]
refine add_nonneg (sub_nonneg.mpr (pow_right_mono₀ ha ?_)) ?_ <;> norm_num
obtain ⟨x, ⟨-, hx1⟩, hx2⟩ := intermediate_value_Ico' hle (hc _) (Set.mem_Ioc.mpr ⟨hf1, hf0⟩)
obtain ⟨y, ⟨hy1, -⟩, hy2⟩ := intermediate_value_Ioc ha (hc _) (Set.mem_Ioc.mpr ⟨hf1, hfa⟩)
exact ⟨x, y, (hx1.trans hy1).ne, hx2, hy2⟩
· replace hb : (b : ℝ) = a - 1 := by linarith [show (b : ℝ) + 1 ≤ a from mod_cast hab]
have hf1 : f 1 = 0 := by simp [hf, hb]
have hfa :=
calc
f (-a) = (a : ℝ) ^ 2 - (a : ℝ) ^ 5 + b := by
norm_num [hf, ← sq, sub_eq_add_neg, add_comm, Odd.neg_pow (by decide : Odd 5)]
_ ≤ (a : ℝ) ^ 2 - (a : ℝ) ^ 3 + (a - 1) := by gcongr <;> linarith
_ = -((a : ℝ) - 1) ^ 2 * (a + 1) := by ring
_ ≤ 0 := by nlinarith
have ha' := neg_nonpos.mpr (hle.trans ha)
obtain ⟨x, ⟨-, hx1⟩, hx2⟩ := intermediate_value_Icc ha' (hc _) (Set.mem_Icc.mpr ⟨hfa, hf0⟩)
exact ⟨x, 1, (hx1.trans_lt zero_lt_one).ne, hx2, hf1⟩
theorem real_roots_Phi_ge (hab : b < a) : 2 ≤ Fintype.card ((Φ ℚ a b).rootSet ℝ) := by
have q_ne_zero : Φ ℚ a b ≠ 0 := (monic_Phi a b).ne_zero
obtain ⟨x, y, hxy, hx, hy⟩ := real_roots_Phi_ge_aux a b hab
have key : ↑({x, y} : Finset ℝ) ⊆ (Φ ℚ a b).rootSet ℝ := by
simp [Set.insert_subset, mem_rootSet_of_ne q_ne_zero, hx, hy]
convert Fintype.card_le_of_embedding (Set.embeddingOfSubset _ _ key)
simp only [Finset.coe_sort_coe, Fintype.card_coe, Finset.card_singleton,
Finset.card_insert_of_notMem (mt Finset.mem_singleton.mp hxy)]
theorem complex_roots_Phi (h : (Φ ℚ a b).Separable) : Fintype.card ((Φ ℚ a b).rootSet ℂ) = 5 :=
(card_rootSet_eq_natDegree h (IsAlgClosed.splits_codomain _)).trans (natDegree_Phi a b)
theorem gal_Phi (hab : b < a) (h_irred : Irreducible (Φ ℚ a b)) :
Bijective (galActionHom (Φ ℚ a b) ℂ) := by
apply galActionHom_bijective_of_prime_degree' h_irred
· simp only [natDegree_Phi]; decide
· rw [complex_roots_Phi a b h_irred.separable, Nat.succ_le_succ_iff]
exact (real_roots_Phi_le a b).trans (Nat.le_succ 3)
· simp_rw [complex_roots_Phi a b h_irred.separable, Nat.succ_le_succ_iff]
exact real_roots_Phi_ge a b hab
theorem not_solvable_by_rad (p : ℕ) (x : ℂ) (hx : aeval x (Φ ℚ a b) = 0) (hab : b < a)
(hp : p.Prime) (hpa : p ∣ a) (hpb : p ∣ b) (hp2b : ¬p ^ 2 ∣ b) : ¬IsSolvableByRad ℚ x := by
have h_irred := irreducible_Phi a b p hp hpa hpb hp2b
apply mt (solvableByRad.isSolvable' h_irred hx)
intro h
refine Equiv.Perm.not_solvable _ (le_of_eq ?_)
(solvable_of_surjective (gal_Phi a b hab h_irred).2)
rw_mod_cast [Cardinal.mk_fintype, complex_roots_Phi a b h_irred.separable]
theorem not_solvable_by_rad' (x : ℂ) (hx : aeval x (Φ ℚ 4 2) = 0) : ¬IsSolvableByRad ℚ x := by
apply not_solvable_by_rad 4 2 2 x hx <;> decide
/-- **Abel-Ruffini Theorem** -/
theorem exists_not_solvable_by_rad : ∃ x : ℂ, IsAlgebraic ℚ x ∧ ¬IsSolvableByRad ℚ x := by
obtain ⟨x, hx⟩ := exists_root_of_splits (algebraMap ℚ ℂ) (IsAlgClosed.splits_codomain (Φ ℚ 4 2))
(ne_of_eq_of_ne (degree_Phi 4 2) (mt WithBot.coe_eq_coe.mp (show 5 ≠ 0 by simp)))
exact ⟨x, ⟨Φ ℚ 4 2, (monic_Phi 4 2).ne_zero, hx⟩, not_solvable_by_rad' x hx⟩
end AbelRuffini |
.lake/packages/mathlib/Archive/Wiedijk100Theorems/HeronsFormula.lean | import Mathlib.Geometry.Euclidean.Triangle
/-!
# Freek № 57: Heron's Formula
This file proves Theorem 57 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/),
also known as Heron's formula, which gives the area of a triangle based only on its three sides'
lengths.
## References
* https://en.wikipedia.org/wiki/Herons_formula
-/
open Real EuclideanGeometry
open scoped Real EuclideanGeometry
namespace Theorems100
local notation "√" => Real.sqrt
variable {V : Type*} {P : Type*} [NormedAddCommGroup V] [InnerProductSpace ℝ V] [MetricSpace P]
[NormedAddTorsor V P]
/-- **Heron's formula**: The area of a triangle with side lengths `a`, `b`, and `c` is
`√(s * (s - a) * (s - b) * (s - c))` where `s = (a + b + c) / 2` is the semiperimeter.
We show this by equating this formula to `a * b * sin γ`, where `γ` is the angle opposite
the side `c`.
-/
theorem heron {p₁ p₂ p₃ : P} (h1 : p₁ ≠ p₂) (h2 : p₃ ≠ p₂) :
let a := dist p₁ p₂
let b := dist p₃ p₂
let c := dist p₁ p₃
let s := (a + b + c) / 2
1 / 2 * a * b * sin (∠ p₁ p₂ p₃) = √ (s * (s - a) * (s - b) * (s - c)) := by
intro a b c s
let γ := ∠ p₁ p₂ p₃
obtain := (dist_pos.mpr h1).ne', (dist_pos.mpr h2).ne'
have cos_rule : cos γ = (a * a + b * b - c * c) / (2 * a * b) := by
simp [field, a, b, c, γ, mul_comm,
dist_sq_eq_dist_sq_add_dist_sq_sub_two_mul_dist_mul_dist_mul_cos_angle p₁ p₂ p₃]
let numerator := (2 * a * b) ^ 2 - (a * a + b * b - c * c) ^ 2
let denominator := (2 * a * b) ^ 2
have split_to_frac : ↑1 - cos γ ^ 2 = numerator / denominator := by
simp [field, numerator, denominator, cos_rule]
have numerator_nonneg : 0 ≤ numerator := by
have frac_nonneg : 0 ≤ numerator / denominator :=
(sub_nonneg.mpr (cos_sq_le_one γ)).trans_eq split_to_frac
rcases div_nonneg_iff.mp frac_nonneg with h | h
· exact h.left
· simpa [numerator, denominator, a, b, c, h1, h2] using le_antisymm h.right (sq_nonneg _)
have ab2_nonneg : 0 ≤ 2 * a * b := by positivity
calc
1 / 2 * a * b * sin γ = 1 / 2 * a * b * (√ numerator / √ denominator) := by
rw [sin_eq_sqrt_one_sub_cos_sq, split_to_frac, sqrt_div numerator_nonneg] <;>
simp [γ, angle_nonneg, angle_le_pi]
_ = 1 / 4 * √ ((2 * a * b) ^ 2 - (a * a + b * b - c * c) ^ 2) := by
simp (disch := positivity) [field, numerator, denominator, -mul_eq_mul_left_iff]; ring
_ = ↑1 / ↑4 * √ (s * (s - a) * (s - b) * (s - c) * ↑4 ^ 2) := by simp only [s]; ring_nf
_ = √ (s * (s - a) * (s - b) * (s - c)) := by
rw [sqrt_mul', sqrt_sq, div_mul_eq_mul_div, one_mul, mul_div_cancel_right₀] <;> norm_num
end Theorems100 |
.lake/packages/mathlib/Archive/Wiedijk100Theorems/SumOfPrimeReciprocalsDiverges.lean | import Mathlib.Topology.Algebra.InfiniteSum.Real
import Mathlib.Data.Nat.Cast.Order.Field
import Mathlib.Data.Nat.Squarefree
/-!
# Divergence of the Prime Reciprocal Series
This file proves Theorem 81 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/).
The theorem states that the sum of the reciprocals of all prime numbers diverges.
The formalization follows Erdős's proof by upper and lower estimates.
## Proof outline
1. Assume that the sum of the reciprocals of the primes converges.
2. Then there exists a `k : ℕ` such that, for any `x : ℕ`, the sum of the reciprocals of the primes
between `k` and `x + 1` is less than 1/2 (`sum_lt_half_of_not_tendsto`).
3. For any `x : ℕ`, we can partition `range x` into two subsets (`range_sdiff_eq_biUnion`):
* `M x k`, the subset of those `e` for which `e + 1` is a product of powers of primes smaller
than or equal to `k`;
* `U x k`, the subset of those `e` for which there is a prime `p > k` that divides `e + 1`.
4. Then `|U x k|` is bounded by the sum over the primes `p > k` of the number of multiples of `p`
in `(k, x]`, which is at most `x / p`. It follows that `|U x k|` is at most `x` times the sum of
the reciprocals of the primes between `k` and `x + 1`, which is less than 1/2 as noted in (2), so
`|U x k| < x / 2` (`card_le_mul_sum`).
5. By factoring `e + 1 = (m + 1)² * (r + 1)`, `r + 1` squarefree and `m + 1 ≤ √x`, and noting that
squarefree numbers correspond to subsets of `[1, k]`, we find that `|M x k| ≤ 2 ^ k * √x`
(`card_le_two_pow_mul_sqrt`).
6. Finally, setting `x := (2 ^ (k + 1))²` (`√x = 2 ^ (k + 1)`), we find that
`|M x k| ≤ 2 ^ k * 2 ^ (k + 1) = x / 2`. Combined with the strict bound for `|U k x|` from (4),
`x = |M x k| + |U x k| < x / 2 + x / 2 = x`.
## References
https://en.wikipedia.org/wiki/Divergence_of_the_sum_of_the_reciprocals_of_the_primes
-/
open Filter Finset
namespace Theorems100
/-- The primes in `(k, x]`.
-/
def P (x k : ℕ) : Finset ℕ := {p ∈ range (x + 1) | k < p ∧ p.Prime}
/-- The union over those primes `p ∈ (k, x]` of the sets of `e < x` for which `e + 1` is a multiple
of `p`, i.e., those `e < x` for which there is a prime `p ∈ (k, x]` that divides `e + 1`.
-/
def U (x k : ℕ) : Finset ℕ := (P x k).biUnion fun p ↦ {e ∈ range x | p ∣ e + 1}
open Classical in
/-- Those `e < x` for which `e + 1` is a product of powers of primes smaller than or equal to `k`.
-/
noncomputable def M (x k : ℕ) : Finset ℕ := {e ∈ range x | ∀ p : ℕ, p.Prime ∧ p ∣ e + 1 → p ≤ k}
/--
If the sum of the reciprocals of the primes converges, there exists a `k : ℕ` such that the sum of
the reciprocals of the primes greater than `k` is less than 1/2.
More precisely, for any `x : ℕ`, the sum of the reciprocals of the primes between `k` and `x + 1`
is less than 1/2.
-/
theorem sum_lt_half_of_not_tendsto
(h : ¬Tendsto (fun n => ∑ p ∈ range n with p.Prime, 1 / (p : ℝ))
atTop atTop) :
∃ k, ∀ x, ∑ p ∈ P x k, 1 / (p : ℝ) < 1 / 2 := by
have h0 :
(fun n => ∑ p ∈ range n with p.Prime, 1 / (p : ℝ)) = fun n =>
∑ p ∈ range n, ite (Nat.Prime p) (1 / (p : ℝ)) 0 := by
simp only [sum_filter]
have hf : ∀ n : ℕ, 0 ≤ ite (Nat.Prime n) (1 / (n : ℝ)) 0 := by
intro n; split_ifs
· simp only [one_div, inv_nonneg, Nat.cast_nonneg]
· exact le_rfl
rw [h0, ← summable_iff_not_tendsto_nat_atTop_of_nonneg hf, summable_iff_vanishing] at h
obtain ⟨s, h⟩ := h (Set.Ioo (-1) (1 / 2)) (isOpen_Ioo.mem_nhds (by simp))
obtain ⟨k, hk⟩ := exists_nat_subset_range s
use k
intro x
rw [P, ← filter_filter, sum_filter]
refine (h _ ?_).2
rw [disjoint_iff_ne]
simp only [mem_filter]
intro a ha b hb
exact ((mem_range.mp (hk hb)).trans ha.2).ne'
/--
Removing from {0, ..., x - 1} those elements `e` for which `e + 1` is a product of powers of primes
smaller than or equal to `k` leaves those `e` for which there is a prime `p > k` that divides
`e + 1`, or the union over those primes `p > k` of the sets of `e`s for which `e + 1` is a multiple
of `p`.
-/
theorem range_sdiff_eq_biUnion {x k : ℕ} : range x \ M x k = U x k := by
ext e
simp only [mem_biUnion, not_and, mem_sdiff, mem_filter, mem_range, U, M, P]
push_neg
constructor
· rintro ⟨hex, hexh⟩
obtain ⟨p, ⟨hpp, hpe1⟩, hpk⟩ := hexh hex
refine ⟨p, ?_, ⟨hex, hpe1⟩⟩
exact ⟨(Nat.le_of_dvd e.succ_pos hpe1).trans_lt (Nat.succ_lt_succ hex), hpk, hpp⟩
· rintro ⟨p, hpfilter, ⟨hex, hpe1⟩⟩
rw [imp_iff_right hex]
exact ⟨hex, ⟨p, ⟨hpfilter.2.2, hpe1⟩, hpfilter.2.1⟩⟩
/--
The number of `e < x` for which `e + 1` has a prime factor `p > k` is bounded by `x` times the sum
of reciprocals of primes in `(k, x]`.
-/
theorem card_le_mul_sum {x k : ℕ} : #(U x k) ≤ x * ∑ p ∈ P x k, 1 / (p : ℝ) := by
let P := {p ∈ range (x + 1) | k < p ∧ p.Prime}
let N p := {e ∈ range x | p ∣ e + 1}
have h : #(P.biUnion N) ≤ ∑ p ∈ P, #(N p) := card_biUnion_le
calc
(#(P.biUnion N) : ℝ) ≤ ∑ p ∈ P, (#(N p) : ℝ) := by assumption_mod_cast
_ ≤ ∑ p ∈ P, x * (1 / (p : ℝ)) := sum_le_sum fun p _ => ?_
_ = x * ∑ p ∈ P, 1 / (p : ℝ) := by rw [mul_sum]
simp only [N, mul_one_div, Nat.card_multiples, Nat.cast_div_le]
/--
The number of `e < x` for which `e + 1` is a squarefree product of primes smaller than or equal to
`k` is bounded by `2 ^ k`, the number of subsets of `[1, k]`.
-/
theorem card_le_two_pow {x k : ℕ} : #{e ∈ M x k | Squarefree (e + 1)} ≤ 2 ^ k := by
let M₁ := {e ∈ M x k | Squarefree (e + 1)}
let f s := (∏ a ∈ s, a) - 1
let K := powerset (image Nat.succ (range k))
-- Take `e` in `M x k`. If `e + 1` is squarefree, then it is the product of a subset of `[1, k]`.
-- It follows that `e` is one less than such a product.
have h : M₁ ⊆ image f K := by
intro m hm
simp only [f, K, M₁, M, mem_filter, mem_range, mem_powerset, mem_image] at hm ⊢
obtain ⟨⟨-, hmp⟩, hms⟩ := hm
use! (m + 1).primeFactorsList
· rwa [Multiset.coe_nodup, ← Nat.squarefree_iff_nodup_primeFactorsList m.succ_ne_zero]
refine ⟨fun p => ?_, ?_⟩
· suffices p ∈ (m + 1).primeFactorsList → ∃ a : ℕ, a < k ∧ a.succ = p by simpa
simp only [Nat.mem_primeFactorsList m.succ_ne_zero]
intro hp
exact
⟨p.pred, (Nat.pred_lt (Nat.Prime.ne_zero hp.1)).trans_le ((hmp p) hp),
Nat.succ_pred_eq_of_pos (Nat.Prime.pos hp.1)⟩
· simp [Nat.prod_primeFactorsList m.succ_ne_zero, m.add_one_sub_one]
-- The number of elements of `M x k` with `e + 1` squarefree is bounded by the number of subsets
-- of `[1, k]`.
calc
#M₁ ≤ #(image f K) := card_le_card h
_ ≤ #K := card_image_le
_ ≤ 2 ^ #(image Nat.succ (range k)) := by simp only [K, card_powerset]; rfl
_ ≤ 2 ^ #(range k) := pow_right_mono₀ one_le_two card_image_le
_ = 2 ^ k := by rw [card_range k]
/--
The number of `e < x` for which `e + 1` is a product of powers of primes smaller than or equal to
`k` is bounded by `2 ^ k * nat.sqrt x`.
-/
theorem card_le_two_pow_mul_sqrt {x k : ℕ} : #(M x k) ≤ 2 ^ k * Nat.sqrt x := by
let M₁ := {e ∈ M x k | Squarefree (e + 1)}
let M₂ := M (Nat.sqrt x) k
let K := M₁ ×ˢ M₂
let f : ℕ × ℕ → ℕ := fun mn => (mn.2 + 1) ^ 2 * (mn.1 + 1) - 1
-- Every element of `M x k` is one less than the product `(m + 1)² * (r + 1)` with `r + 1`
-- squarefree and `m + 1 ≤ √x`, and both `m + 1` and `r + 1` still only have prime powers
-- smaller than or equal to `k`.
have h1 : M x k ⊆ image f K := by
intro m hm
simp only [f, K, M, M₁, M₂, mem_image, Prod.exists, mem_product,
mem_filter, mem_range] at hm ⊢
have hm' := m.zero_lt_succ
obtain ⟨a, b, hab₁, hab₂⟩ := Nat.sq_mul_squarefree_of_pos' hm'
obtain ⟨ham, hbm⟩ := Dvd.intro_left _ hab₁, Dvd.intro _ hab₁
refine ⟨a, b, ⟨⟨⟨?_, fun p hp => ?_⟩, hab₂⟩, ⟨?_, fun p hp => ?_⟩⟩, by
simp_rw [hab₁, m.add_one_sub_one]⟩
· exact (Nat.succ_le_succ_iff.mp (Nat.le_of_dvd hm' ham)).trans_lt hm.1
· exact hm.2 p ⟨hp.1, hp.2.trans ham⟩
· calc
b < b + 1 := lt_add_one b
_ ≤ (m + 1).sqrt := by simpa only [Nat.le_sqrt, pow_two] using Nat.le_of_dvd hm' hbm
_ ≤ x.sqrt := Nat.sqrt_le_sqrt (Nat.succ_le_iff.mpr hm.1)
· exact hm.2 p ⟨hp.1, hp.2.trans (Nat.dvd_of_pow_dvd one_le_two hbm)⟩
have h2 : #M₂ ≤ Nat.sqrt x := by
rw [← card_range (Nat.sqrt x)]; apply card_le_card; simp [M, M₂]
calc
#(M x k) ≤ #(image f K) := card_le_card h1
_ ≤ #K := card_image_le
_ = #M₁ * #M₂ := card_product M₁ M₂
_ ≤ 2 ^ k * x.sqrt := mul_le_mul' card_le_two_pow h2
theorem Real.tendsto_sum_one_div_prime_atTop :
Tendsto (fun n => ∑ p ∈ range n with p.Prime, 1 / (p : ℝ))
atTop atTop := by
-- Assume that the sum of the reciprocals of the primes converges.
by_contra h
-- Then there is a natural number `k` such that for all `x`, the sum of the reciprocals of primes
-- between `k` and `x` is less than 1/2.
obtain ⟨k, h1⟩ := sum_lt_half_of_not_tendsto h
-- Choose `x` sufficiently large for the argument below to work, and use a perfect square so we
-- can easily take the square root.
let x := 2 ^ (k + 1) * 2 ^ (k + 1)
-- We will partition `range x` into two subsets:
-- * `M`, the subset of those `e` for which `e + 1` is a product of powers of primes smaller
-- than or equal to `k`;
set M' := M x k with hM'
-- * `U`, the subset of those `e` for which there is a prime `p > k` that divides `e + 1`.
let P := {p ∈ range (x + 1) | k < p ∧ p.Prime}
set U' := U x k with hU'
-- This is indeed a partition, so `|U| + |M| = |range x| = x`.
have h2 : x = #U' + #M' := by
rw [← card_range x, hU', hM', ← range_sdiff_eq_biUnion]
classical
exact (card_sdiff_add_card_eq_card (Finset.filter_subset _ _)).symm
-- But for the `x` we have chosen above, both `|U|` and `|M|` are less than or equal to `x / 2`,
-- and for U, the inequality is strict.
have h3 :=
calc
(#U' : ℝ) ≤ x * ∑ p ∈ P, 1 / (p : ℝ) := card_le_mul_sum
_ < x * (1 / 2) := mul_lt_mul_of_pos_left (h1 x) (by simp [x])
_ = x / 2 := mul_one_div (x : ℝ) 2
have h4 :=
calc
(#M' : ℝ) ≤ 2 ^ k * x.sqrt := by exact mod_cast card_le_two_pow_mul_sqrt
_ = 2 ^ k * (2 ^ (k + 1) : ℕ) := by rw [Nat.sqrt_eq]
_ = x / 2 := by simp [field, x, ← pow_succ]
refine lt_irrefl (x : ℝ) ?_
calc
(x : ℝ) = (#U' : ℝ) + (#M' : ℝ) := by assumption_mod_cast
_ < x / 2 + x / 2 := add_lt_add_of_lt_of_le h3 h4
_ = x := add_halves (x : ℝ)
end Theorems100 |
.lake/packages/mathlib/Archive/Wiedijk100Theorems/InverseTriangleSum.lean | import Mathlib.Algebra.BigOperators.Group.Finset.Powerset
import Mathlib.Data.Real.Basic
import Mathlib.Tactic.FieldSimp
import Mathlib.Tactic.Positivity.Basic
import Mathlib.Tactic.Ring
/-!
# Sum of the Reciprocals of the Triangular Numbers
This file proves Theorem 42 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/).
We interpret “triangular numbers” as naturals of the form $\frac{k(k+1)}{2}$ for natural `k`.
We prove that the sum of the reciprocals of the first `n` triangular numbers is $2 - \frac2n$.
## Tags
discrete_sum
-/
open Finset
/-- **Sum of the Reciprocals of the Triangular Numbers** -/
theorem Theorems100.inverse_triangle_sum (n : ℕ) :
∑ k ∈ range n, (2 : ℚ) / (k * (k + 1)) = if n = 0 then 0 else 2 - (2 : ℚ) / n := by
apply sum_range_induction _ _ rfl
rintro (_ | _)
· norm_num
· simp [field]
ring_nf
simp |
.lake/packages/mathlib/Archive/Wiedijk100Theorems/FriendshipGraphs.lean | import Mathlib.Combinatorics.SimpleGraph.AdjMatrix
import Mathlib.LinearAlgebra.Matrix.Charpoly.FiniteField
/-!
# The Friendship Theorem
## Definitions and Statement
- A `Friendship` graph is one in which any two distinct vertices have exactly one neighbor in common
- A `Politician`, at least in the context of this problem, is a vertex in a graph which is adjacent
to every other vertex.
- The friendship theorem (Erdős, Rényi, Sós 1966) states that every finite friendship graph has a
politician.
## Proof outline
The proof revolves around the theory of adjacency matrices, although some steps could equivalently
be phrased in terms of counting walks.
- Assume `G` is a finite friendship graph.
- First we show that any two nonadjacent vertices have the same degree
- Assume for contradiction that `G` does not have a politician.
- Conclude from the last two points that `G` is `d`-regular for some `d : ℕ`.
- Show that `G` has `d ^ 2 - d + 1` vertices.
- By casework, show that if `d = 0, 1, 2`, then `G` has a politician.
- If `3 ≤ d`, let `p` be a prime factor of `d - 1`.
- If `A` is the adjacency matrix of `G` with entries in `ℤ/pℤ`, we show that `A ^ p` has trace `1`.
- This gives a contradiction, as `A` has trace `0`, and thus `A ^ p` has trace `0`.
## References
- [P. Erdős, A. Rényi, V. Sós, *On A Problem of Graph Theory*][erdosrenyisos]
- [C. Huneke, *The Friendship Theorem*][huneke2002]
-/
namespace Theorems100
noncomputable section
open Finset SimpleGraph Matrix
universe u v
variable {V : Type u} {R : Type v} [Semiring R]
section FriendshipDef
variable (G : SimpleGraph V)
open scoped Classical in
/-- This property of a graph is the hypothesis of the friendship theorem:
every pair of nonadjacent vertices has exactly one common friend,
a vertex to which both are adjacent.
-/
def Friendship [Fintype V] : Prop :=
∀ ⦃v w : V⦄, v ≠ w → Fintype.card (G.commonNeighbors v w) = 1
/-- A politician is a vertex that is adjacent to all other vertices.
-/
def ExistsPolitician : Prop :=
∃ v : V, ∀ w : V, v ≠ w → G.Adj v w
end FriendshipDef
variable [Fintype V] {G : SimpleGraph V} {d : ℕ} (hG : Friendship G)
namespace Friendship
variable (R)
open scoped Classical in
include hG in
/-- One characterization of a friendship graph is that there is exactly one walk of length 2
between distinct vertices. These walks are counted in off-diagonal entries of the square of
the adjacency matrix, so for a friendship graph, those entries are all 1. -/
theorem adjMatrix_sq_of_ne {v w : V} (hvw : v ≠ w) :
(G.adjMatrix R ^ 2 : Matrix V V R) v w = 1 := by
rw [sq, ← Nat.cast_one, ← hG hvw]
simp only [mul_adjMatrix_apply, neighborFinset_eq_filter, adjMatrix_apply,
sum_boole, filter_filter, and_comm, commonNeighbors,
Fintype.card_ofFinset (s := filter (fun x ↦ x ∈ G.neighborSet v ∩ G.neighborSet w) univ),
Set.mem_inter_iff, mem_neighborSet]
open scoped Classical in
include hG in
/-- This calculation amounts to counting the number of length 3 walks between nonadjacent vertices.
We use it to show that nonadjacent vertices have equal degrees. -/
theorem adjMatrix_pow_three_of_not_adj {v w : V} (non_adj : ¬G.Adj v w) :
(G.adjMatrix R ^ 3 : Matrix V V R) v w = degree G v := by
rw [pow_succ', adjMatrix_mul_apply, degree, card_eq_sum_ones, Nat.cast_sum]
apply sum_congr rfl
intro x hx
rw [adjMatrix_sq_of_ne _ hG, Nat.cast_one]
rintro ⟨rfl⟩
rw [mem_neighborFinset] at hx
exact non_adj hx
variable {R}
open scoped Classical in
include hG in
/-- As `v` and `w` not being adjacent implies
`degree G v = ((G.adjMatrix R) ^ 3) v w` and `degree G w = ((G.adjMatrix R) ^ 3) v w`,
the degrees are equal if `((G.adjMatrix R) ^ 3) v w = ((G.adjMatrix R) ^ 3) w v`
This is true as the adjacency matrix is symmetric. -/
theorem degree_eq_of_not_adj {v w : V} (hvw : ¬G.Adj v w) : degree G v = degree G w := by
rw [← Nat.cast_id (G.degree v), ← Nat.cast_id (G.degree w),
← adjMatrix_pow_three_of_not_adj ℕ hG hvw,
← adjMatrix_pow_three_of_not_adj ℕ hG fun h => hvw (G.symm h)]
conv_lhs => rw [← transpose_adjMatrix]
simp only [pow_succ _ 2, sq, ← transpose_mul, transpose_apply]
simp only [mul_assoc]
open scoped Classical in
include hG in
/-- Let `A` be the adjacency matrix of a graph `G`.
If `G` is a friendship graph, then all of the off-diagonal entries of `A^2` are 1.
If `G` is `d`-regular, then all of the diagonal entries of `A^2` are `d`.
Putting these together determines `A^2` exactly for a `d`-regular friendship graph. -/
theorem adjMatrix_sq_of_regular (hd : G.IsRegularOfDegree d) :
G.adjMatrix R ^ 2 = of fun v w => if v = w then (d : R) else (1 : R) := by
ext (v w); by_cases h : v = w
· rw [h, sq, adjMatrix_mul_self_apply_self, hd]; simp
· rw [adjMatrix_sq_of_ne R hG h, of_apply, if_neg h]
open scoped Classical in
include hG in
theorem adjMatrix_sq_mod_p_of_regular {p : ℕ} (dmod : (d : ZMod p) = 1)
(hd : G.IsRegularOfDegree d) : G.adjMatrix (ZMod p) ^ 2 = of fun _ _ => 1 := by
simp [adjMatrix_sq_of_regular hG hd, dmod]
section Nonempty
variable [Nonempty V]
open scoped Classical in
include hG in
/-- If `G` is a friendship graph without a politician (a vertex adjacent to all others), then
it is regular. We have shown that nonadjacent vertices of a friendship graph have the same degree,
and if there isn't a politician, we can show this for adjacent vertices by finding a vertex
neither is adjacent to, and then using transitivity. -/
theorem isRegularOf_not_existsPolitician (hG' : ¬ExistsPolitician G) :
∃ d : ℕ, G.IsRegularOfDegree d := by
have v := Classical.arbitrary V
use G.degree v
intro x
by_cases hvx : G.Adj v x; swap; · exact (degree_eq_of_not_adj hG hvx).symm
dsimp only [Theorems100.ExistsPolitician] at hG'
push_neg at hG'
rcases hG' v with ⟨w, hvw', hvw⟩
rcases hG' x with ⟨y, hxy', hxy⟩
by_cases hxw : G.Adj x w
swap; · rw [degree_eq_of_not_adj hG hvw]; exact degree_eq_of_not_adj hG hxw
rw [degree_eq_of_not_adj hG hxy]
by_cases hvy : G.Adj v y
swap; · exact (degree_eq_of_not_adj hG hvy).symm
rw [degree_eq_of_not_adj hG hvw]
apply degree_eq_of_not_adj hG
intro hcontra
rcases Finset.card_eq_one.mp (hG hvw') with ⟨⟨a, ha⟩, h⟩
have key : ∀ {x}, x ∈ G.commonNeighbors v w → x = a := by
intro x hx
have h' : ⟨x, hx⟩ ∈ (univ : Finset (G.commonNeighbors v w)) := mem_univ (Subtype.mk x hx)
rw [h, mem_singleton] at h'
injection h'
apply hxy'
rw [key ((mem_commonNeighbors G).mpr ⟨hvx, G.symm hxw⟩),
key ((mem_commonNeighbors G).mpr ⟨hvy, G.symm hcontra⟩)]
open scoped Classical in
include hG in
/-- Let `A` be the adjacency matrix of a `d`-regular friendship graph, and let `v` be a vector
all of whose components are `1`. Then `v` is an eigenvector of `A ^ 2`, and we can compute
the eigenvalue to be `d * d`, or as `d + (Fintype.card V - 1)`, so those quantities must be equal.
This essentially means that the graph has `d ^ 2 - d + 1` vertices. -/
theorem card_of_regular (hd : G.IsRegularOfDegree d) : d + (Fintype.card V - 1) = d * d := by
have v := Classical.arbitrary V
trans ((G.adjMatrix ℕ ^ 2) *ᵥ (fun _ => 1)) v
· rw [adjMatrix_sq_of_regular hG hd, mulVec, dotProduct, ← insert_erase (mem_univ v)]
simp only [sum_insert, mul_one, if_true, Nat.cast_id, mem_erase, not_true,
Ne, not_false_iff, add_right_inj, false_and, of_apply]
rw [Finset.sum_const_nat, card_erase_of_mem (mem_univ v), mul_one]; · rfl
intro x hx; simp [(ne_of_mem_erase hx).symm]
· rw [sq, ← mulVec_mulVec]
simp only [adjMatrix_mulVec_const_apply_of_regular hd, neighborFinset,
card_neighborSet_eq_degree, hd v, Function.const_def, adjMatrix_mulVec_apply _ _ (mulVec _ _),
mul_one, sum_const, Set.toFinset_card, Algebra.id.smul_eq_mul, Nat.cast_id]
open scoped Classical in
include hG in
/-- The size of a `d`-regular friendship graph is `1 mod (d-1)`, and thus `1 mod p` for a
factor `p ∣ d-1`. -/
theorem card_mod_p_of_regular {p : ℕ} (dmod : (d : ZMod p) = 1) (hd : G.IsRegularOfDegree d) :
(Fintype.card V : ZMod p) = 1 := by
have hpos : 0 < Fintype.card V := Fintype.card_pos_iff.mpr inferInstance
rw [← Nat.succ_pred_eq_of_pos hpos, Nat.succ_eq_add_one, Nat.pred_eq_sub_one]
simp only [add_eq_right, Nat.cast_add, Nat.cast_one]
have h := congr_arg (fun n : ℕ => (n : ZMod p)) (card_of_regular hG hd)
revert h; simp [dmod]
end Nonempty
open scoped Classical in
theorem adjMatrix_sq_mul_const_one_of_regular (hd : G.IsRegularOfDegree d) :
G.adjMatrix R * of (fun _ _ => 1) = of (fun _ _ => (d : R)) := by
ext x
simp only [← hd x, degree, adjMatrix_mul_apply, sum_const, Nat.smul_one_eq_cast,
of_apply]
open scoped Classical in
theorem adjMatrix_mul_const_one_mod_p_of_regular {p : ℕ} (dmod : (d : ZMod p) = 1)
(hd : G.IsRegularOfDegree d) :
G.adjMatrix (ZMod p) * of (fun _ _ => 1) = of (fun _ _ => 1) := by
rw [adjMatrix_sq_mul_const_one_of_regular hd, dmod]
open scoped Classical in
include hG in
/-- Modulo a factor of `d-1`, the square and all higher powers of the adjacency matrix
of a `d`-regular friendship graph reduce to the matrix whose entries are all 1. -/
theorem adjMatrix_pow_mod_p_of_regular {p : ℕ} (dmod : (d : ZMod p) = 1)
(hd : G.IsRegularOfDegree d) {k : ℕ} (hk : 2 ≤ k) :
G.adjMatrix (ZMod p) ^ k = of (fun _ _ => 1) := by
match k with
| 0 | 1 => exfalso; linarith
| k + 2 =>
induction k with
| zero => exact adjMatrix_sq_mod_p_of_regular hG dmod hd
| succ k hind =>
rw [pow_succ', hind (Nat.le_add_left 2 k)]
exact adjMatrix_mul_const_one_mod_p_of_regular dmod hd
variable [Nonempty V]
open scoped Classical in
include hG in
/-- This is the main proof. Assuming that `3 ≤ d`, we take `p` to be a prime factor of `d-1`.
Then the `p`th power of the adjacency matrix of a `d`-regular friendship graph must have trace 1
mod `p`, but we can also show that the trace must be the `p`th power of the trace of the original
adjacency matrix, which is 0, a contradiction.
-/
theorem false_of_three_le_degree (hd : G.IsRegularOfDegree d) (h : 3 ≤ d) : False := by
-- get a prime factor of d - 1
let p : ℕ := (d - 1).minFac
have p_dvd_d_pred := (ZMod.natCast_eq_zero_iff _ _).mpr (d - 1).minFac_dvd
have dpos : 1 ≤ d := by omega
have d_cast : ↑(d - 1) = (d : ℤ) - 1 := by norm_cast
haveI : Fact p.Prime := ⟨Nat.minFac_prime (by omega)⟩
have hp2 : 2 ≤ p := (Fact.out (p := p.Prime)).two_le
have dmod : (d : ZMod p) = 1 := by
rw [← Nat.succ_pred_eq_of_pos dpos, Nat.succ_eq_add_one, Nat.pred_eq_sub_one]
simp only [add_eq_right, Nat.cast_add, Nat.cast_one]
exact p_dvd_d_pred
have Vmod := card_mod_p_of_regular hG dmod hd
-- now we reduce to a trace calculation
have := ZMod.trace_pow_card (G.adjMatrix (ZMod p))
contrapose! this; clear this
-- the trace is 0 mod p when computed one way
rw [trace_adjMatrix, zero_pow this.out.ne_zero]
-- but the trace is 1 mod p when computed the other way
rw [adjMatrix_pow_mod_p_of_regular hG dmod hd hp2]
dsimp only [Fintype.card] at Vmod
simp only [Matrix.trace, Matrix.diag, mul_one, nsmul_eq_mul, sum_const,
of_apply, Ne]
rw [Vmod, ← Nat.cast_one (R := ZMod (Nat.minFac (d - 1))), ZMod.natCast_eq_zero_iff,
Nat.dvd_one, Nat.minFac_eq_one_iff]
omega
open scoped Classical in
include hG in
/-- If `d ≤ 1`, a `d`-regular friendship graph has at most one vertex, which is
trivially a politician. -/
theorem existsPolitician_of_degree_le_one (hd : G.IsRegularOfDegree d) (hd1 : d ≤ 1) :
ExistsPolitician G := by
have sq : d * d = d := by interval_cases d <;> norm_num
have h := card_of_regular hG hd
rw [sq] at h
have : Fintype.card V ≤ 1 := by
cases hn : Fintype.card V with
| zero => exact zero_le _
| succ n => omega
use Classical.arbitrary V
intro w h; exfalso
apply h
apply Fintype.card_le_one_iff.mp this
open scoped Classical in
include hG in
/-- If `d = 2`, a `d`-regular friendship graph has 3 vertices, so it must be complete graph,
and all the vertices are politicians. -/
theorem neighborFinset_eq_of_degree_eq_two (hd : G.IsRegularOfDegree 2) (v : V) :
G.neighborFinset v = Finset.univ.erase v := by
apply Finset.eq_of_subset_of_card_le
· rw [Finset.subset_iff]
intro x
rw [mem_neighborFinset, Finset.mem_erase]
exact fun h => ⟨(G.ne_of_adj h).symm, Finset.mem_univ _⟩
convert_to 2 ≤ _
· convert_to _ = Fintype.card V - 1
· have hfr := card_of_regular hG hd
omega
· exact Finset.card_erase_of_mem (Finset.mem_univ _)
· dsimp only [IsRegularOfDegree, degree] at hd
rw [hd]
open scoped Classical in
include hG in
theorem existsPolitician_of_degree_eq_two (hd : G.IsRegularOfDegree 2) : ExistsPolitician G := by
have v := Classical.arbitrary V
use v
intro w hvw
rw [← mem_neighborFinset, neighborFinset_eq_of_degree_eq_two hG hd v, Finset.mem_erase]
exact ⟨hvw.symm, Finset.mem_univ _⟩
open scoped Classical in
include hG in
theorem existsPolitician_of_degree_le_two (hd : G.IsRegularOfDegree d) (h : d ≤ 2) :
ExistsPolitician G := by
interval_cases d
iterate 2 apply existsPolitician_of_degree_le_one hG hd; norm_num
exact existsPolitician_of_degree_eq_two hG hd
end Friendship
include hG in
/-- **Friendship theorem**: We wish to show that a friendship graph has a politician (a vertex
adjacent to all others). We proceed by contradiction, and assume the graph has no politician.
We have already proven that a friendship graph with no politician is `d`-regular for some `d`,
and now we do casework on `d`.
If the degree is at most 2, we observe by casework that it has a politician anyway.
If the degree is at least 3, the graph cannot exist. -/
theorem friendship_theorem [Nonempty V] : ExistsPolitician G := by
by_contra npG
rcases hG.isRegularOf_not_existsPolitician npG with ⟨d, dreg⟩
rcases lt_or_ge d 3 with dle2 | dge3
· exact npG (hG.existsPolitician_of_degree_le_two dreg (Nat.lt_succ_iff.mp dle2))
· exact hG.false_of_three_le_degree dreg dge3
end
end Theorems100 |
.lake/packages/mathlib/Archive/Wiedijk100Theorems/BallotProblem.lean | import Mathlib.Probability.UniformOn
/-!
# Ballot problem
This file proves Theorem 30 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/).
The ballot problem asks, if in an election, candidate A receives `p` votes whereas candidate B
receives `q` votes where `p > q`, what is the probability that candidate A is strictly ahead
throughout the count. The probability of this is `(p - q) / (p + q)`.
## Main definitions
* `countedSequence`: given natural numbers `p` and `q`, `countedSequence p q` is the set of
all lists containing `p` of `1`s and `q` of `-1`s representing the votes of candidate A and B
respectively.
* `staysPositive`: is the set of lists of integers which suffix has positive sum. In particular,
the intersection of this set with `countedSequence` is the set of lists where candidate A is
strictly ahead.
## Main result
* `ballot_problem`: the ballot problem.
-/
open Set ProbabilityTheory MeasureTheory
open scoped ENNReal
namespace Ballot
/-- The set of nonempty lists of integers which suffix has positive sum. -/
def staysPositive : Set (List ℤ) :=
{l | ∀ l₂, l₂ ≠ [] → l₂ <:+ l → 0 < l₂.sum}
@[simp]
theorem staysPositive_nil : [] ∈ staysPositive :=
fun _ hl hl₁ => (hl (List.eq_nil_of_suffix_nil hl₁)).elim
theorem staysPositive_suffix {l₁ l₂ : List ℤ} (hl₂ : l₂ ∈ staysPositive) (h : l₁ <:+ l₂) :
l₁ ∈ staysPositive := fun l hne hl ↦ hl₂ l hne <| hl.trans h
theorem staysPositive_cons {x : ℤ} {l : List ℤ} :
x::l ∈ staysPositive ↔ l ∈ staysPositive ∧ 0 < x + l.sum := by
simp [staysPositive, List.suffix_cons_iff, or_imp, forall_and, @imp.swap _ (_ = _), and_comm]
theorem sum_nonneg_of_staysPositive : ∀ {l : List ℤ}, l ∈ staysPositive → 0 ≤ l.sum
| [], _ => le_rfl
| (_::_), h => (h _ (List.cons_ne_nil _ _) List.suffix_rfl).le
theorem staysPositive_cons_pos (x : ℤ) (hx : 0 < x) (l : List ℤ) :
(x::l) ∈ staysPositive ↔ l ∈ staysPositive := by
rw [staysPositive_cons, and_iff_left_iff_imp]
intro h
positivity [sum_nonneg_of_staysPositive h]
/-- `countedSequence p q` is the set of lists of integers for which every element is `+1` or `-1`,
there are `p` lots of `+1` and `q` lots of `-1`.
This represents vote sequences where candidate `+1` receives `p` votes and candidate `-1` receives
`q` votes.
-/
def countedSequence (p q : ℕ) : Set (List ℤ) :=
{l | l.count 1 = p ∧ l.count (-1) = q ∧ ∀ x ∈ l, x = (1 : ℤ) ∨ x = -1}
open scoped List in
/-- An alternative definition of `countedSequence` that uses `List.Perm`. -/
theorem mem_countedSequence_iff_perm {p q l} :
l ∈ countedSequence p q ↔ l ~ List.replicate p (1 : ℤ) ++ List.replicate q (-1) := by
rw [List.perm_replicate_append_replicate]
· simp only [countedSequence, List.subset_def, mem_setOf_eq, List.mem_cons (b := (1 : ℤ)),
List.mem_singleton]
· norm_num1
@[simp]
theorem counted_right_zero (p : ℕ) : countedSequence p 0 = {List.replicate p 1} := by
ext l; simp [mem_countedSequence_iff_perm]
@[simp]
theorem counted_left_zero (q : ℕ) : countedSequence 0 q = {List.replicate q (-1)} := by
ext l; simp [mem_countedSequence_iff_perm]
theorem mem_of_mem_countedSequence {p q} {l} (hl : l ∈ countedSequence p q) {x : ℤ} (hx : x ∈ l) :
x = 1 ∨ x = -1 :=
hl.2.2 x hx
theorem length_of_mem_countedSequence {p q} {l : List ℤ} (hl : l ∈ countedSequence p q) :
l.length = p + q := by simp [(mem_countedSequence_iff_perm.1 hl).length_eq]
theorem counted_eq_nil_iff {p q : ℕ} {l : List ℤ} (hl : l ∈ countedSequence p q) :
l = [] ↔ p = 0 ∧ q = 0 :=
List.length_eq_zero_iff.symm.trans <| by simp [length_of_mem_countedSequence hl]
theorem counted_ne_nil_left {p q : ℕ} (hp : p ≠ 0) {l : List ℤ} (hl : l ∈ countedSequence p q) :
l ≠ [] := by simp [counted_eq_nil_iff hl, hp]
theorem counted_ne_nil_right {p q : ℕ} (hq : q ≠ 0) {l : List ℤ} (hl : l ∈ countedSequence p q) :
l ≠ [] := by simp [counted_eq_nil_iff hl, hq]
theorem counted_succ_succ (p q : ℕ) :
countedSequence (p + 1) (q + 1) =
List.cons 1 '' countedSequence p (q + 1) ∪ List.cons (-1) '' countedSequence (p + 1) q := by
ext l
rw [countedSequence, countedSequence, countedSequence]
constructor
· intro hl
have hlnil := counted_ne_nil_left (Nat.succ_ne_zero p) hl
obtain ⟨hl₀, hl₁, hl₂⟩ := hl
obtain hlast | hlast := hl₂ (l.head hlnil) (List.head_mem hlnil)
· refine Or.inl ⟨l.tail, ⟨?_, ?_, ?_⟩, ?_⟩
· rw [List.count_tail, hl₀, List.head?_eq_head hlnil, hlast, beq_self_eq_true, if_pos rfl,
Nat.add_sub_cancel]
· rw [List.count_tail, hl₁, List.head?_eq_head hlnil, hlast, if_neg (by decide), Nat.sub_zero]
· exact fun x hx => hl₂ x (List.mem_of_mem_tail hx)
· rw [← hlast, List.cons_head_tail]
· refine Or.inr ⟨l.tail, ⟨?_, ?_, ?_⟩, ?_⟩
· rw [List.count_tail, hl₀, List.head?_eq_head hlnil, hlast, if_neg (by decide), Nat.sub_zero]
· rw [List.count_tail, hl₁, List.head?_eq_head hlnil, hlast, beq_self_eq_true, if_pos rfl,
Nat.add_sub_cancel]
· exact fun x hx => hl₂ x (List.mem_of_mem_tail hx)
· rw [← hlast, List.cons_head_tail]
· rintro (⟨t, ⟨ht₀, ht₁, ht₂⟩, rfl⟩ | ⟨t, ⟨ht₀, ht₁, ht₂⟩, rfl⟩)
· refine ⟨?_, ?_, ?_⟩
· rw [List.count_cons, beq_self_eq_true, if_pos rfl, ht₀]
· rw [List.count_cons, if_neg, ht₁]
norm_num
· simpa
· refine ⟨?_, ?_, ?_⟩
· rw [List.count_cons, if_neg, ht₀]
norm_num
· rw [List.count_cons, beq_self_eq_true, if_pos rfl, ht₁]
· simpa
theorem countedSequence_finite : ∀ p q : ℕ, (countedSequence p q).Finite
| 0, q => by simp
| p + 1, 0 => by simp
| p + 1, q + 1 => by
rw [counted_succ_succ, Set.finite_union, Set.finite_image_iff List.cons_injective.injOn,
Set.finite_image_iff List.cons_injective.injOn]
exact ⟨countedSequence_finite _ _, countedSequence_finite _ _⟩
theorem countedSequence_nonempty : ∀ p q : ℕ, (countedSequence p q).Nonempty
| 0, q => by simp
| p + 1, 0 => by simp
| p + 1, q + 1 => by
rw [counted_succ_succ, union_nonempty, image_nonempty]
exact Or.inl (countedSequence_nonempty _ _)
theorem sum_of_mem_countedSequence {p q} {l : List ℤ} (hl : l ∈ countedSequence p q) :
l.sum = p - q := by simp [(mem_countedSequence_iff_perm.1 hl).sum_eq, sub_eq_add_neg]
theorem disjoint_bits (p q : ℕ) :
Disjoint (List.cons 1 '' countedSequence p (q + 1))
(List.cons (-1) '' countedSequence (p + 1) q) := by
simp_rw [disjoint_left, mem_image, not_exists, exists_imp]
rintro _ _ ⟨_, rfl⟩ _ ⟨_, _, _⟩
open MeasureTheory.Measure
private def measurableSpace_list_int : MeasurableSpace (List ℤ) := ⊤
attribute [local instance] measurableSpace_list_int
private theorem measurableSingletonClass_list_int : MeasurableSingletonClass (List ℤ) :=
{ measurableSet_singleton := fun _ => trivial }
attribute [local instance] measurableSingletonClass_list_int
private theorem list_int_measurableSet {s : Set (List ℤ)} : MeasurableSet s := trivial
theorem count_countedSequence : ∀ p q : ℕ, count (countedSequence p q) = (p + q).choose p
| p, 0 => by simp [counted_right_zero]
| 0, q => by simp [counted_left_zero]
| p + 1, q + 1 => by
rw [counted_succ_succ, measure_union (disjoint_bits _ _) list_int_measurableSet,
count_injective_image List.cons_injective, count_countedSequence _ _,
count_injective_image List.cons_injective, count_countedSequence _ _]
norm_cast
rw [add_assoc, add_comm 1 q, ← Nat.choose_succ_succ, Nat.succ_eq_add_one, add_right_comm]
theorem first_vote_pos :
∀ p q,
0 < p + q → uniformOn (countedSequence p q : Set (List ℤ)) {l | l.headI = 1} = p / (p + q)
| p + 1, 0, _ => by
rw [counted_right_zero, uniformOn_singleton]
simp [ENNReal.div_self _ _, List.replicate_succ]
| 0, q + 1, _ => by
rw [counted_left_zero, uniformOn_singleton]
simp [List.replicate]
| p + 1, q + 1, _ => by
simp_rw [counted_succ_succ]
rw [← uniformOn_disjoint_union ((countedSequence_finite _ _).image _)
((countedSequence_finite _ _).image _) (disjoint_bits _ _),
← counted_succ_succ,
uniformOn_eq_one_of ((countedSequence_finite p (q + 1)).image _)
((countedSequence_nonempty _ _).image _)]
· have : List.cons (-1) '' countedSequence (p + 1) q ∩ {l : List ℤ | l.headI = 1} = ∅ := by
ext
simp only [mem_inter_iff, mem_image, mem_setOf_eq, mem_empty_iff_false, iff_false,
not_and, forall_exists_index, and_imp]
rintro l _ rfl
norm_num
have hint :
countedSequence (p + 1) (q + 1) ∩ List.cons 1 '' countedSequence p (q + 1) =
List.cons 1 '' countedSequence p (q + 1) := by
rw [inter_eq_right, counted_succ_succ]
exact subset_union_left
rw [(uniformOn_eq_zero_iff <| (countedSequence_finite _ _).image _).2 this, uniformOn,
cond_apply list_int_measurableSet, hint, count_injective_image List.cons_injective,
count_countedSequence, count_countedSequence, one_mul, zero_mul, add_zero,
Nat.cast_add, Nat.cast_one, mul_comm, ← div_eq_mul_inv, ENNReal.div_eq_div_iff]
· norm_cast
rw [mul_comm _ (p + 1), ← Nat.succ_eq_add_one p, Nat.succ_add, Nat.succ_mul_choose_eq,
mul_comm]
all_goals simp [(Nat.choose_pos <| le_add_of_nonneg_right zero_le').ne']
· simp
theorem headI_mem_of_nonempty {α : Type*} [Inhabited α] : ∀ {l : List α} (_ : l ≠ []), l.headI ∈ l
| [], h => (h rfl).elim
| _::_, _ => List.mem_cons_self
theorem first_vote_neg (p q : ℕ) (h : 0 < p + q) :
uniformOn (countedSequence p q) {l | l.headI = 1}ᶜ = q / (p + q) := by
have h' : (p + q : ℝ≥0∞) ≠ 0 := mod_cast h.ne'
have := uniformOn_compl
{l : List ℤ | l.headI = 1}ᶜ (countedSequence_finite p q) (countedSequence_nonempty p q)
rw [compl_compl, first_vote_pos _ _ h] at this
rw [ENNReal.eq_sub_of_add_eq _ this, ENNReal.eq_div_iff, ENNReal.mul_sub, mul_one,
ENNReal.mul_div_cancel, ENNReal.add_sub_cancel_left]
all_goals simp_all [ENNReal.div_eq_top]
theorem ballot_same (p : ℕ) : uniformOn (countedSequence (p + 1) (p + 1)) staysPositive = 0 := by
rw [uniformOn_eq_zero_iff (countedSequence_finite _ _), eq_empty_iff_forall_notMem]
rintro x ⟨hx, t⟩
apply ne_of_gt (t x _ x.suffix_refl)
· simpa using sum_of_mem_countedSequence hx
· refine List.ne_nil_of_length_pos ?_
rw [length_of_mem_countedSequence hx]
exact Nat.add_pos_left (Nat.succ_pos _) _
theorem ballot_edge (p : ℕ) : uniformOn (countedSequence (p + 1) 0) staysPositive = 1 := by
rw [counted_right_zero]
refine uniformOn_eq_one_of (finite_singleton _) (singleton_nonempty _) ?_
refine singleton_subset_iff.2 fun l hl₁ hl₂ => List.sum_pos _ (fun x hx => ?_) hl₁
rw [List.eq_of_mem_replicate (hl₂.mem hx)]
norm_num
theorem countedSequence_int_pos_counted_succ_succ (p q : ℕ) :
countedSequence (p + 1) (q + 1) ∩ {l | l.headI = 1} =
(countedSequence p (q + 1)).image (List.cons 1) := by
rw [counted_succ_succ, union_inter_distrib_right,
(_ : List.cons (-1) '' countedSequence (p + 1) q ∩ {l | l.headI = 1} = ∅), union_empty] <;>
· ext
simp only [mem_inter_iff, mem_image, mem_setOf_eq, and_iff_left_iff_imp, mem_empty_iff_false,
iff_false, not_and, forall_exists_index, and_imp]
rintro y _ rfl
norm_num
theorem ballot_pos (p q : ℕ) :
uniformOn (countedSequence (p + 1) (q + 1) ∩ {l | l.headI = 1}) staysPositive =
uniformOn (countedSequence p (q + 1)) staysPositive := by
rw [countedSequence_int_pos_counted_succ_succ, uniformOn, uniformOn,
cond_apply list_int_measurableSet, cond_apply list_int_measurableSet,
count_injective_image List.cons_injective]
congr 1
have : (1 :: ·) '' countedSequence p (q + 1) ∩ staysPositive =
(1 :: ·) '' (countedSequence p (q + 1) ∩ staysPositive) := by
simp only [image_inter List.cons_injective, Set.ext_iff, mem_inter_iff, and_congr_right_iff,
forall_mem_image, List.cons_injective.mem_set_image, staysPositive_cons_pos _ one_pos]
exact fun _ _ ↦ trivial
rw [this, count_injective_image]
exact List.cons_injective
theorem countedSequence_int_neg_counted_succ_succ (p q : ℕ) :
countedSequence (p + 1) (q + 1) ∩ {l | l.headI = 1}ᶜ =
(countedSequence (p + 1) q).image (List.cons (-1)) := by
rw [counted_succ_succ, union_inter_distrib_right,
(_ : List.cons 1 '' countedSequence p (q + 1) ∩ {l : List ℤ | l.headI = 1}ᶜ = ∅),
empty_union] <;>
· ext
simp only [mem_inter_iff, mem_image, and_iff_left_iff_imp, mem_empty_iff_false,
iff_false, not_and, forall_exists_index, and_imp]
rintro y _ rfl
norm_num
theorem ballot_neg (p q : ℕ) (qp : q < p) :
uniformOn (countedSequence (p + 1) (q + 1) ∩ {l | l.headI = 1}ᶜ) staysPositive =
uniformOn (countedSequence (p + 1) q) staysPositive := by
rw [countedSequence_int_neg_counted_succ_succ, uniformOn, uniformOn,
cond_apply list_int_measurableSet, cond_apply list_int_measurableSet,
count_injective_image List.cons_injective]
congr 1
have : List.cons (-1) '' countedSequence (p + 1) q ∩ staysPositive =
List.cons (-1) '' (countedSequence (p + 1) q ∩ staysPositive) := by
simp only [image_inter List.cons_injective, Set.ext_iff, mem_inter_iff, and_congr_right_iff,
forall_mem_image, List.cons_injective.mem_set_image, staysPositive_cons, and_iff_left_iff_imp]
intro l hl _
simp [sum_of_mem_countedSequence hl, lt_sub_iff_add_lt', qp]
rw [this, count_injective_image]
exact List.cons_injective
theorem ballot_problem' :
∀ q p, q < p → (uniformOn (countedSequence p q) staysPositive).toReal = (p - q) / (p + q) := by
classical
apply Nat.diag_induction
· intro p
rw [ballot_same]
simp
· intro p
rw [ballot_edge]
simp only [ENNReal.toReal_one, Nat.cast_add, Nat.cast_one, Nat.cast_zero, sub_zero, add_zero]
rw [div_self]
exact Nat.cast_add_one_ne_zero p
· intro q p qp h₁ h₂
haveI := uniformOn_isProbabilityMeasure
(countedSequence_finite p (q + 1)) (countedSequence_nonempty _ _)
haveI := uniformOn_isProbabilityMeasure
(countedSequence_finite (p + 1) q) (countedSequence_nonempty _ _)
have h₃ : p + 1 + (q + 1) > 0 := Nat.add_pos_left (Nat.succ_pos _) _
rw [← uniformOn_add_compl_eq {l : List ℤ | l.headI = 1} _ (countedSequence_finite _ _),
first_vote_pos _ _ h₃, first_vote_neg _ _ h₃, ballot_pos, ballot_neg _ _ qp]
rw [ENNReal.toReal_add, ENNReal.toReal_mul, ENNReal.toReal_mul, ← Nat.cast_add,
ENNReal.toReal_div, ENNReal.toReal_div, ENNReal.toReal_natCast, ENNReal.toReal_natCast,
ENNReal.toReal_natCast, h₁, h₂]
· have h₄ : (p + 1 : ℝ) + (q + 1 : ℝ) ≠ (0 : ℝ) := by
apply ne_of_gt
assumption_mod_cast
have h₅ : (p + 1 : ℝ) + ↑q ≠ (0 : ℝ) := by
apply ne_of_gt
norm_cast
linarith
have h₆ : ↑p + (q + 1 : ℝ) ≠ (0 : ℝ) := by
apply ne_of_gt
norm_cast
linarith
simp [field, h₄, h₅, h₆] at *
ring
all_goals exact ENNReal.mul_ne_top (by finiteness) (by simp [Ne, ENNReal.div_eq_top])
/-- The ballot problem. -/
theorem ballot_problem :
∀ q p, q < p → uniformOn (countedSequence p q) staysPositive = (p - q) / (p + q) := by
intro q p qp
haveI :=
uniformOn_isProbabilityMeasure (countedSequence_finite p q) (countedSequence_nonempty _ _)
have :
(uniformOn (countedSequence p q) staysPositive).toReal =
((p - q) / (p + q) : ℝ≥0∞).toReal := by
rw [ballot_problem' q p qp]
rw [ENNReal.toReal_div, ← Nat.cast_add, ← Nat.cast_add, ENNReal.toReal_natCast,
ENNReal.toReal_sub_of_le, ENNReal.toReal_natCast, ENNReal.toReal_natCast]
exacts [Nat.cast_le.2 qp.le, ENNReal.natCast_ne_top _]
rwa [ENNReal.toReal_eq_toReal_iff' (measure_lt_top _ _).ne] at this
simp only [Ne, ENNReal.div_eq_top, tsub_eq_zero_iff_le, Nat.cast_le, not_le,
add_eq_zero, Nat.cast_eq_zero, ENNReal.add_eq_top, ENNReal.natCast_ne_top, or_self_iff,
not_false_iff, and_true]
push_neg
exact ⟨fun _ _ => by linarith, (tsub_le_self.trans_lt (ENNReal.natCast_ne_top p).lt_top).ne⟩
end Ballot |
.lake/packages/mathlib/Archive/Wiedijk100Theorems/PerfectNumbers.lean | import Mathlib.NumberTheory.ArithmeticFunction
import Mathlib.NumberTheory.LucasLehmer
import Mathlib.Tactic.NormNum.Prime
/-!
# Perfect Numbers
This file proves Theorem 70 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/).
The theorem characterizes even perfect numbers.
Euclid proved that if `2 ^ (k + 1) - 1` is prime (these primes are known as Mersenne primes),
then `2 ^ k * (2 ^ (k + 1) - 1)` is perfect.
Euler proved the converse, that if `n` is even and perfect, then there exists `k` such that
`n = 2 ^ k * (2 ^ (k + 1) - 1)` and `2 ^ (k + 1) - 1` is prime.
## References
https://en.wikipedia.org/wiki/Euclid%E2%80%93Euler_theorem
-/
namespace Theorems100
namespace Nat
open ArithmeticFunction Finset
-- access notation `σ`
open scoped sigma
theorem sigma_two_pow_eq_mersenne_succ (k : ℕ) : σ 1 (2 ^ k) = mersenne (k + 1) := by
simp_rw [sigma_one_apply, mersenne, ← one_add_one_eq_two, ← geom_sum_mul_add 1 (k + 1)]
norm_num
/-- Euclid's theorem that Mersenne primes induce perfect numbers -/
theorem perfect_two_pow_mul_mersenne_of_prime (k : ℕ) (pr : (mersenne (k + 1)).Prime) :
Nat.Perfect (2 ^ k * mersenne (k + 1)) := by
rw [Nat.perfect_iff_sum_divisors_eq_two_mul, ← mul_assoc, ← pow_succ', ← sigma_one_apply,
mul_comm,
isMultiplicative_sigma.map_mul_of_coprime ((Odd.coprime_two_right (by simp)).pow_right _),
sigma_two_pow_eq_mersenne_succ]
· simp [pr, sigma_one_apply]
· positivity
theorem ne_zero_of_prime_mersenne (k : ℕ) (pr : (mersenne (k + 1)).Prime) : k ≠ 0 := by
intro H
simp [H, mersenne, Nat.not_prime_one] at pr
theorem even_two_pow_mul_mersenne_of_prime (k : ℕ) (pr : (mersenne (k + 1)).Prime) :
Even (2 ^ k * mersenne (k + 1)) := by simp [ne_zero_of_prime_mersenne k pr, parity_simps]
theorem eq_two_pow_mul_odd {n : ℕ} (hpos : 0 < n) : ∃ k m : ℕ, n = 2 ^ k * m ∧ ¬Even m := by
have h := Nat.finiteMultiplicity_iff.2 ⟨Nat.prime_two.ne_one, hpos⟩
obtain ⟨m, hm⟩ := pow_multiplicity_dvd 2 n
use multiplicity 2 n, m
refine ⟨hm, ?_⟩
rw [even_iff_two_dvd]
have hg := h.not_pow_dvd_of_multiplicity_lt (Nat.lt_succ_self _)
contrapose! hg
rcases hg with ⟨k, rfl⟩
apply Dvd.intro k
rw [pow_succ, mul_assoc, ← hm]
/-- **Perfect Number Theorem**: Euler's theorem that even perfect numbers can be factored as a
power of two times a Mersenne prime. -/
theorem eq_two_pow_mul_prime_mersenne_of_even_perfect {n : ℕ} (ev : Even n) (perf : Nat.Perfect n) :
∃ k : ℕ, Nat.Prime (mersenne (k + 1)) ∧ n = 2 ^ k * mersenne (k + 1) := by
have hpos := perf.2
rcases eq_two_pow_mul_odd hpos with ⟨k, m, rfl, hm⟩
use k
rw [even_iff_two_dvd] at hm
rw [Nat.perfect_iff_sum_divisors_eq_two_mul hpos, ← sigma_one_apply,
isMultiplicative_sigma.map_mul_of_coprime (Nat.prime_two.coprime_pow_of_not_dvd hm).symm,
sigma_two_pow_eq_mersenne_succ, ← mul_assoc, ← pow_succ'] at perf
obtain ⟨j, rfl⟩ := ((Odd.coprime_two_right (by simp)).pow_right _).dvd_of_dvd_mul_left
(Dvd.intro _ perf)
rw [← mul_assoc, mul_comm _ (mersenne _), mul_assoc] at perf
have h := mul_left_cancel₀ (by positivity) perf
rw [sigma_one_apply, Nat.sum_divisors_eq_sum_properDivisors_add_self, ← succ_mersenne, add_mul,
one_mul, add_comm] at h
have hj := add_left_cancel h
cases Nat.sum_properDivisors_dvd (by rw [hj]; apply Dvd.intro_left (mersenne (k + 1)) rfl) with
| inl h_1 =>
have j1 : j = 1 := Eq.trans hj.symm h_1
rw [j1, mul_one, Nat.sum_properDivisors_eq_one_iff_prime] at h_1
simp [h_1, j1]
| inr h_1 =>
have jcon := Eq.trans hj.symm h_1
rw [← one_mul j, ← mul_assoc, mul_one] at jcon
have jcon2 := mul_right_cancel₀ ?_ jcon
· exfalso
match k with
| 0 =>
apply hm
rw [← jcon2, pow_zero, one_mul, one_mul] at ev
rw [← jcon2, one_mul]
exact even_iff_two_dvd.mp ev
| .succ k =>
apply ne_of_lt _ jcon2
rw [mersenne, ← Nat.pred_eq_sub_one, Nat.lt_pred_iff, ← pow_one (Nat.succ 1)]
apply pow_lt_pow_right₀ (Nat.lt_succ_self 1) (Nat.succ_lt_succ k.succ_pos)
contrapose! hm
simp [hm]
/-- The Euclid-Euler theorem characterizing even perfect numbers -/
theorem even_and_perfect_iff {n : ℕ} :
Even n ∧ Nat.Perfect n ↔ ∃ k : ℕ, Nat.Prime (mersenne (k + 1)) ∧
n = 2 ^ k * mersenne (k + 1) := by
constructor
· rintro ⟨ev, perf⟩
exact Nat.eq_two_pow_mul_prime_mersenne_of_even_perfect ev perf
· rintro ⟨k, pr, rfl⟩
exact ⟨even_two_pow_mul_mersenne_of_prime k pr, perfect_two_pow_mul_mersenne_of_prime k pr⟩
end Nat
end Theorems100 |
.lake/packages/mathlib/Archive/Wiedijk100Theorems/README.md | # "Formalizing 100 Theorems" in Lean
In this folder, we keep proofs of theorems on Freek Wiedijk's [100 theorems list](https://www.cs.ru.nl/~freek/100/) which don't fit naturally elsewhere in mathlib or in other Lean repositories.
See [this page](https://leanprover-community.github.io/100.html) for more information about theorems from the list above which have been formalized in Lean. If you prove a new theorem from that list, you should add the appropriate data to this file:
https://github.com/leanprover-community/mathlib4/blob/master/docs/100.yaml |
.lake/packages/mathlib/Archive/Wiedijk100Theorems/BuffonsNeedle.lean | import Mathlib.Analysis.SpecialFunctions.Integrals.Basic
import Mathlib.MeasureTheory.Integral.Prod
import Mathlib.Probability.Density
import Mathlib.Probability.Distributions.Uniform
import Mathlib.Probability.Notation
/-!
# Freek № 99: Buffon's Needle
This file proves Theorem 99 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/), also
known as Buffon's Needle, which gives the probability of a needle of length `l > 0` crossing any
one of infinite vertical lines spaced out `d > 0` apart.
The two cases are proven in `buffon_short` and `buffon_long`.
## Overview of the Proof
We define a random variable `B : Ω → ℝ × ℝ` with a uniform distribution on `[-d/2, d/2] × [0, π]`.
This represents the needle's x-position and angle with respect to a vertical line. By symmetry, we
need to consider only a single vertical line positioned at `x = 0`. A needle therefore crosses the
vertical line if its projection onto the x-axis contains `0`.
We define a random variable `N : Ω → ℝ` that is `1` if the needle crosses a vertical line, and `0`
otherwise. This is defined as `fun ω => Set.indicator (needleProjX l (B ω).1 (B ω).2) 1 0`.
f
As in many references, the problem is split into two cases, `l ≤ d` (`buffon_short`), and `d ≤ l`
(`buffon_long`). For both cases, we show that
```lean
ℙ[N] = (d * π) ⁻¹ *
∫ θ in 0..π,
∫ x in Set.Icc (-d / 2) (d / 2) ∩ Set.Icc (-θ.sin * l / 2) (θ.sin * l / 2), 1
```
In the short case `l ≤ d`, we show that `[-l * θ.sin/2, l * θ.sin/2] ⊆ [-d/2, d/2]`
(`short_needle_inter_eq`), and therefore the inner integral simplifies to
```lean
∫ x in (-θ.sin * l / 2)..(θ.sin * l / 2), 1 = θ.sin * l
```
Which then concludes in the short case being `ℙ[N] = (2 * l) / (d * π)`.
In the long case, `l ≤ d` (`buffon_long`), we show the outer integral simplifies to
```lean
∫ θ in 0..π, min d (θ.sin * l)
```
which can be expanded to
```lean
2 * (
∫ θ in 0..(d / l).arcsin, min d (θ.sin * l) +
∫ θ in (d / l).arcsin..(π / 2), min d (θ.sin * l)
)
```
We then show the two integrals equal their respective values `l - √(l^2 - d^2)` and
`(π / 2 - (d / l).arcsin) * d`. Then with some algebra we conclude
```lean
ℙ[N] = (2 * l) / (d * π) - 2 / (d * π) * (√(l^2 - d^2) + d * (d / l).arcsin) + 1
```
## References
* https://en.wikipedia.org/wiki/Buffon%27s_needle_problem
* https://www.math.leidenuniv.nl/~hfinkeln/seminarium/stelling_van_Buffon.pdf
* https://www.isa-afp.org/entries/Buffons_Needle.html
-/
open MeasureTheory (MeasureSpace IsProbabilityMeasure Measure pdf.IsUniform)
open ProbabilityTheory Real
namespace BuffonsNeedle
variable
/- Probability theory variables. -/
{Ω : Type*} [MeasureSpace Ω]
/- Buffon's needle variables. -/
/-
- `d > 0` is the distance between parallel lines.
- `l > 0` is the length of the needle.
-/
(d l : ℝ)
(hd : 0 < d)
(hl : 0 < l)
/- `B = (X, Θ)` is the joint random variable for the x-position and angle of the needle. -/
(B : Ω → ℝ × ℝ)
(hBₘ : Measurable B)
/- `B` is uniformly distributed on `[-d/2, d/2] × [0, π]`. -/
(hB : pdf.IsUniform B ((Set.Icc (-d / 2) (d / 2)) ×ˢ (Set.Icc 0 π)) ℙ)
/--
Projection of a needle onto the x-axis. The needle's center is at x-coordinate `x`, of length
`l` and angle `θ`. Note, `θ` is measured relative to the y-axis, that is, a vertical needle has
`θ = 0`.
-/
def needleProjX (x θ : ℝ) : Set ℝ := Set.Icc (x - θ.sin * l / 2) (x + θ.sin * l / 2)
/--
The indicator function of whether a needle at position `⟨x, θ⟩ : ℝ × ℝ` crosses the line `x = 0`.
In order to faithfully model the problem, we compose `needleCrossesIndicator` with a random
variable `B : Ω → ℝ × ℝ` with uniform distribution on `[-d/2, d/2] × [0, π]`. Then, by symmetry,
the probability that the needle crosses `x = 0`, is the same as the probability of a needle
crossing any of the infinitely spaced vertical lines distance `d` apart.
-/
noncomputable def needleCrossesIndicator (p : ℝ × ℝ) : ℝ :=
Set.indicator (needleProjX l p.1 p.2) 1 0
/--
A random variable representing whether the needle crosses a line.
The line is at `x = 0`, and therefore a needle crosses the line if its projection onto the x-axis
contains `0`. This random variable is `1` if the needle crosses the line, and `0` otherwise.
-/
noncomputable def N : Ω → ℝ := needleCrossesIndicator l ∘ B
/--
The possible x-positions and angle relative to the y-axis of a needle.
-/
abbrev needleSpace : Set (ℝ × ℝ) := Set.Icc (-d / 2) (d / 2) ×ˢ Set.Icc 0 π
include hd in
lemma volume_needleSpace : ℙ (needleSpace d) = ENNReal.ofReal (d * π) := by
simp_rw [MeasureTheory.Measure.volume_eq_prod, MeasureTheory.Measure.prod_prod, Real.volume_Icc,
ENNReal.ofReal_mul hd.le]
ring_nf
lemma measurable_needleCrossesIndicator : Measurable (needleCrossesIndicator l) := by
unfold needleCrossesIndicator
refine Measurable.indicator measurable_const (IsClosed.measurableSet (IsClosed.and ?l ?r))
all_goals simp only [tsub_le_iff_right, zero_add, ← neg_le_iff_add_nonneg']
case' l => refine isClosed_le continuous_fst ?_
case' r => refine isClosed_le (Continuous.neg continuous_fst) ?_
all_goals
refine Continuous.mul (Continuous.mul ?_ continuous_const) continuous_const
simp_rw [← Function.comp_apply (f := Real.sin) (g := Prod.snd),
Continuous.comp Real.continuous_sin continuous_snd]
lemma stronglyMeasurable_needleCrossesIndicator :
MeasureTheory.StronglyMeasurable (needleCrossesIndicator l) := by
refine stronglyMeasurable_iff_measurable_separable.mpr
⟨measurable_needleCrossesIndicator l, {0, 1}, ?separable⟩
have range_finite : Set.Finite ({0, 1} : Set ℝ) := by
simp only [Set.finite_singleton, Set.Finite.insert]
refine ⟨range_finite.countable, ?subset_closure⟩
rw [IsClosed.closure_eq range_finite.isClosed, Set.subset_def, Set.range]
intro x ⟨p, hxp⟩
by_cases hp : 0 ∈ needleProjX l p.1 p.2
· simp_rw [needleCrossesIndicator, Set.indicator_of_mem hp, Pi.one_apply] at hxp
apply Or.inr hxp.symm
· simp_rw [needleCrossesIndicator, Set.indicator_of_notMem hp] at hxp
apply Or.inl hxp.symm
include hd in
lemma integrable_needleCrossesIndicator :
MeasureTheory.Integrable (needleCrossesIndicator l)
(Measure.prod
(Measure.restrict ℙ (Set.Icc (-d / 2) (d / 2)))
(Measure.restrict ℙ (Set.Icc 0 π))) := by
have needleCrossesIndicator_nonneg p : 0 ≤ needleCrossesIndicator l p := by
apply Set.indicator_apply_nonneg
simp only [Pi.one_apply, zero_le_one, implies_true]
have needleCrossesIndicator_le_one p : needleCrossesIndicator l p ≤ 1 := by
unfold needleCrossesIndicator
by_cases hp : 0 ∈ needleProjX l p.1 p.2
· simp_rw [Set.indicator_of_mem hp, Pi.one_apply, le_refl]
· simp_rw [Set.indicator_of_notMem hp, zero_le_one]
refine And.intro
(stronglyMeasurable_needleCrossesIndicator l).aestronglyMeasurable
((MeasureTheory.hasFiniteIntegral_iff_norm (needleCrossesIndicator l)).mpr ?_)
refine lt_of_le_of_lt (MeasureTheory.lintegral_mono (g := 1) ?le_const) ?lt_top
case le_const =>
intro p
simp only [Real.norm_eq_abs, abs_of_nonneg (needleCrossesIndicator_nonneg _),
ENNReal.ofReal_le_one, Pi.one_apply]
exact needleCrossesIndicator_le_one p
case lt_top =>
simp_rw [Pi.one_apply, MeasureTheory.lintegral_const, one_mul, Measure.prod_restrict,
Measure.restrict_apply MeasurableSet.univ, Set.univ_inter, Measure.prod_prod, Real.volume_Icc,
neg_div, sub_neg_eq_add, add_halves, sub_zero, ← ENNReal.ofReal_mul hd.le,
ENNReal.ofReal_lt_top]
include hd hB hBₘ in
/--
This is a common step in both the short and the long case to simplify the expectation of the
needle crossing a line to a double integral.
```lean
∫ (θ : ℝ) in Set.Icc 0 π,
∫ (x : ℝ) in Set.Icc (-d / 2) (d / 2) ∩ Set.Icc (-θ.sin * l / 2) (θ.sin * l / 2), 1
```
The domain of the inner integral is simpler in the short case, where the intersection is
equal to `Set.Icc (-θ.sin * l / 2) (θ.sin * l / 2)` by `short_needle_inter_eq`.
-/
lemma buffon_integral :
𝔼[N l B] = (d * π) ⁻¹ *
∫ (θ : ℝ) in Set.Icc 0 π,
∫ (_ : ℝ) in Set.Icc (-d / 2) (d / 2) ∩ Set.Icc (-θ.sin * l / 2) (θ.sin * l / 2), 1 := by
simp_rw [N, Function.comp_apply]
rw [
← MeasureTheory.integral_map hBₘ.aemeasurable
(stronglyMeasurable_needleCrossesIndicator l).aestronglyMeasurable,
hB, ProbabilityTheory.cond, MeasureTheory.integral_smul_measure, volume_needleSpace d hd,
← ENNReal.ofReal_inv_of_pos (mul_pos hd Real.pi_pos),
ENNReal.toReal_ofReal (inv_nonneg.mpr (mul_nonneg hd.le Real.pi_pos.le)), smul_eq_mul,
]
refine mul_eq_mul_left_iff.mpr (Or.inl ?_)
have : MeasureTheory.IntegrableOn (needleCrossesIndicator l)
(Set.Icc (-d / 2) (d / 2) ×ˢ Set.Icc 0 π) := by
simp_rw [MeasureTheory.IntegrableOn, Measure.volume_eq_prod, ← Measure.prod_restrict,
integrable_needleCrossesIndicator d l hd]
rw [Measure.volume_eq_prod, MeasureTheory.setIntegral_prod _ this,
MeasureTheory.integral_integral_swap ?integrable]
case integrable => simp_rw [Function.uncurry_def, Prod.mk.eta,
integrable_needleCrossesIndicator d l hd]
simp only [needleCrossesIndicator, needleProjX]
have indicator_eq (x θ : ℝ) :
Set.indicator (Set.Icc (x - θ.sin * l / 2) (x + θ.sin * l / 2)) 1 0 =
Set.indicator (Set.Icc (-θ.sin * l / 2) (θ.sin * l / 2)) (1 : ℝ → ℝ) x := by
simp_rw [Set.indicator, Pi.one_apply, Set.mem_Icc, tsub_le_iff_right, zero_add, neg_mul]
have :
x ≤ Real.sin θ * l / 2 ∧ 0 ≤ x + Real.sin θ * l / 2 ↔
-(Real.sin θ * l) / 2 ≤ x ∧ x ≤ Real.sin θ * l / 2 := by
rw [neg_div, and_comm, ← tsub_le_iff_right, zero_sub]
by_cases h : x ≤ Real.sin θ * l / 2 ∧ 0 ≤ x + Real.sin θ * l / 2
· rw [if_pos h, if_pos (this.mp h)]
· rw [if_neg h, if_neg (this.not.mp h)]
simp_rw [indicator_eq, MeasureTheory.setIntegral_indicator measurableSet_Icc, Pi.one_apply]
include hl in
/--
From `buffon_integral`, in both the short and the long case, we have
```lean
𝔼[N l B] = (d * π)⁻¹ *
∫ (θ : ℝ) in Set.Icc 0 π,
∫ (x : ℝ) in Set.Icc (-d / 2) (d / 2) ∩ Set.Icc (-θ.sin * l / 2) (θ.sin * l / 2), 1
```
With this lemma, in the short case, the inner integral's domain simplifies to
`Set.Icc (-θ.sin * l / 2) (θ.sin * l / 2)`.
-/
lemma short_needle_inter_eq (h : l ≤ d) (θ : ℝ) :
Set.Icc (-d / 2) (d / 2) ∩ Set.Icc (-θ.sin * l / 2) (θ.sin * l / 2) =
Set.Icc (-θ.sin * l / 2) (θ.sin * l / 2) := by
rw [Set.Icc_inter_Icc, max_div_div_right zero_le_two,
min_div_div_right zero_le_two, neg_mul, max_neg_neg, mul_comm,
min_eq_right ((mul_le_of_le_one_right hl.le θ.sin_le_one).trans h)]
include hd hBₘ hB hl in
/--
Buffon's Needle, the short case (`l ≤ d`). The probability of the needle crossing a line
equals `(2 * l) / (d * π)`.
-/
theorem buffon_short (h : l ≤ d) : ℙ[N l B] = (2 * l) * (d * π)⁻¹ := by
simp_rw [buffon_integral d l hd B hBₘ hB, short_needle_inter_eq d l hl h _,
MeasureTheory.setIntegral_const, MeasureTheory.measureReal_def,
Real.volume_Icc, smul_eq_mul, mul_one, mul_comm (d * π)⁻¹ _,
mul_eq_mul_right_iff]
apply Or.inl
ring_nf
have : ∀ᵐ θ, θ ∈ Set.Icc 0 π → ENNReal.toReal (ENNReal.ofReal (θ.sin * l)) = θ.sin * l := by
have (θ : ℝ) (hθ : θ ∈ Set.Icc 0 π) : 0 ≤ θ.sin * l :=
mul_nonneg (Real.sin_nonneg_of_mem_Icc hθ) hl.le
simp_rw [ENNReal.toReal_ofReal_eq_iff, MeasureTheory.ae_of_all _ this]
simp_rw [MeasureTheory.setIntegral_congr_ae measurableSet_Icc this,
← smul_eq_mul, integral_smul_const, smul_eq_mul, mul_comm, mul_eq_mul_left_iff,
MeasureTheory.integral_Icc_eq_integral_Ioc, ← intervalIntegral.integral_of_le Real.pi_pos.le,
integral_sin, Real.cos_zero, Real.cos_pi, sub_neg_eq_add, one_add_one_eq_two, true_or]
/--
The integrand in the long case is `min d (θ.sin * l)` and its integrability is necessary for
the integral lemmas below.
-/
lemma intervalIntegrable_min_const_sin_mul (a b : ℝ) :
IntervalIntegrable (fun (θ : ℝ) => min d (θ.sin * l)) ℙ a b := by
apply Continuous.intervalIntegrable
exact Continuous.min continuous_const (Continuous.mul Real.continuous_sin continuous_const)
/--
This equality is useful since `θ.sin` is increasing in `0..π / 2` (but not in `0..π`).
Then, `∫ θ in 0..π / 2, min d (θ.sin * l)` can be split into two adjacent integrals, at the
point where `d = θ.sin * l`, which is `θ = (d / l).arcsin`.
-/
lemma integral_min_eq_two_mul :
∫ θ in 0..π, min d (θ.sin * l) = 2 * ∫ θ in 0..π / 2, min d (θ.sin * l) := by
rw [← intervalIntegral.integral_add_adjacent_intervals (b := π / 2) (c := π)]
conv => lhs; arg 2; arg 1; intro θ; rw [← neg_neg θ, Real.sin_neg]
· simp_rw [intervalIntegral.integral_comp_neg fun θ => min d (-θ.sin * l), ← Real.sin_add_pi,
intervalIntegral.integral_comp_add_right (fun θ => min d (θ.sin * l)), neg_add_cancel,
(by ring : -(π / 2) + π = π / 2), two_mul]
all_goals exact intervalIntegrable_min_const_sin_mul d l _ _
include hd hl in
/--
The first of two adjacent integrals in the long case. In the range `0..(d / l).arcsin`, we
have that `θ.sin * l ≤ d`, and thus the integral is `∫ θ in 0..(d / l).arcsin, θ.sin * l`.
-/
lemma integral_zero_to_arcsin_min :
∫ θ in 0..(d / l).arcsin, min d (θ.sin * l) = (1 - √(1 - (d / l) ^ 2)) * l := by
have : Set.EqOn (fun θ => min d (θ.sin * l)) (Real.sin · * l) (Set.uIcc 0 (d / l).arcsin) := by
intro θ ⟨hθ₁, hθ₂⟩
have : 0 ≤ (d / l).arcsin := Real.arcsin_nonneg.mpr (div_nonneg hd.le hl.le)
simp only [min_eq_left this, max_eq_right this] at hθ₁ hθ₂
have hθ_mem : θ ∈ Set.Ioc (-(π / 2)) (π / 2) := by
exact ⟨lt_of_lt_of_le (neg_lt_zero.mpr (div_pos Real.pi_pos two_pos)) hθ₁,
le_trans hθ₂ (d / l).arcsin_mem_Icc.right⟩
simp_rw [min_eq_right ((le_div_iff₀ hl).mp ((Real.le_arcsin_iff_sin_le' hθ_mem).mp hθ₂))]
rw [intervalIntegral.integral_congr this, intervalIntegral.integral_mul_const, integral_sin,
Real.cos_zero, Real.cos_arcsin]
include hl in
/--
The second of two adjacent integrals in the long case. In the range `(d / l).arcsin..(π / 2)`, we
have that `d ≤ θ.sin * l`, and thus the integral is `∫ θ in (d / l).arcsin..(π / 2), d`.
-/
lemma integral_arcsin_to_pi_div_two_min (h : d ≤ l) :
∫ θ in (d / l).arcsin..(π / 2), min d (θ.sin * l) = (π / 2 - (d / l).arcsin) * d := by
have : Set.EqOn (fun θ => min d (θ.sin * l)) (fun _ => d) (Set.uIcc (d / l).arcsin (π / 2)) := by
intro θ ⟨hθ₁, hθ₂⟩
wlog hθ_ne_pi_div_two : θ ≠ π / 2
· simp only [ne_eq, not_not] at hθ_ne_pi_div_two
simp only [hθ_ne_pi_div_two, Real.sin_pi_div_two, one_mul, min_eq_left h]
simp only [min_eq_left (d / l).arcsin_le_pi_div_two,
max_eq_right (d / l).arcsin_le_pi_div_two] at hθ₁ hθ₂
have hθ_mem : θ ∈ Set.Ico (-(π / 2)) (π / 2) := by
exact ⟨le_trans (Real.arcsin_mem_Icc (d / l)).left hθ₁, lt_of_le_of_ne hθ₂ hθ_ne_pi_div_two⟩
simp_rw [min_eq_left ((div_le_iff₀ hl).mp ((Real.arcsin_le_iff_le_sin' hθ_mem).mp hθ₁))]
rw [intervalIntegral.integral_congr this, intervalIntegral.integral_const, smul_eq_mul]
include hd hBₘ hB hl in
/-- Buffon's Needle, the long case (`d ≤ l`) -/
theorem buffon_long (h : d ≤ l) :
ℙ[N l B] = (2 * l) / (d * π) - 2 / (d * π) * (√(l^2 - d^2) + d * (d / l).arcsin) + 1 := by
simp only [
buffon_integral d l hd B hBₘ hB, MeasureTheory.integral_const, smul_eq_mul, mul_one,
MeasurableSet.univ, Measure.restrict_apply, Set.univ_inter, Set.Icc_inter_Icc, Real.volume_Icc,
min_div_div_right zero_le_two d, max_div_div_right zero_le_two (-d),
div_sub_div_same, neg_mul, max_neg_neg, sub_neg_eq_add, ← mul_two,
mul_div_cancel_right₀ (min d (Real.sin _ * l)) two_ne_zero, MeasureTheory.measureReal_def
]
have : ∀ᵐ θ, θ ∈ Set.Icc 0 π →
ENNReal.toReal (ENNReal.ofReal (min d (θ.sin * l))) = min d (θ.sin * l) := by
have (θ : ℝ) (hθ : θ ∈ Set.Icc 0 π) : 0 ≤ min d (θ.sin * l) := by
by_cases! h : d ≤ θ.sin * l
· rw [min_eq_left h]; exact hd.le
· rw [min_eq_right h.le]; exact mul_nonneg (Real.sin_nonneg_of_mem_Icc hθ) hl.le
simp_rw [ENNReal.toReal_ofReal_eq_iff, MeasureTheory.ae_of_all _ this]
rw [MeasureTheory.setIntegral_congr_ae measurableSet_Icc this,
MeasureTheory.integral_Icc_eq_integral_Ioc,
← intervalIntegral.integral_of_le Real.pi_pos.le, integral_min_eq_two_mul,
← intervalIntegral.integral_add_adjacent_intervals
(intervalIntegrable_min_const_sin_mul d l _ _) (intervalIntegrable_min_const_sin_mul d l _ _),
integral_zero_to_arcsin_min d l hd hl, integral_arcsin_to_pi_div_two_min d l hl h]
field_simp
simp (disch := positivity)
field
end BuffonsNeedle |
.lake/packages/mathlib/Archive/Wiedijk100Theorems/CubingACube.lean | import Mathlib.Algebra.Order.Interval.Set.Group
import Mathlib.Data.Real.Basic
import Mathlib.Data.Set.Finite.Lemmas
import Mathlib.Order.Interval.Set.Disjoint
/-!
Proof that a cube (in dimension n ≥ 3) cannot be cubed:
There does not exist a partition of a cube into finitely many smaller cubes (at least two)
of different sizes.
We follow the proof described here:
http://www.alaricstephen.com/main-featured/2017/9/28/cubing-a-cube-proof
-/
open Real Set Function Fin
namespace Theorems100
noncomputable section
namespace «82»
variable {n : ℕ}
/-- Given three intervals `I, J, K` such that `J ⊂ I`,
neither endpoint of `J` coincides with an endpoint of `I`, `¬ (K ⊆ J)` and
`K` does not lie completely to the left nor completely to the right of `J`.
Then `I ∩ K \ J` is nonempty. -/
theorem Ico_lemma {α} [LinearOrder α] {x₁ x₂ y₁ y₂ z₁ z₂ w : α} (h₁ : x₁ < y₁) (hy : y₁ < y₂)
(h₂ : y₂ < x₂) (hz₁ : z₁ ≤ y₂) (hz₂ : y₁ ≤ z₂) (hw : w ∉ Ico y₁ y₂ ∧ w ∈ Ico z₁ z₂) :
∃ w, w ∈ Ico x₁ x₂ ∧ w ∉ Ico y₁ y₂ ∧ w ∈ Ico z₁ z₂ := by
simp only [not_and, not_lt, mem_Ico] at hw
refine ⟨max x₁ (min w y₂), ?_, ?_, ?_⟩
· simp [lt_trans h₁ (lt_trans hy h₂), h₂]
· simp +contextual [hw, not_le_of_gt h₁]
· simp [hw.2.1, hw.2.2, hz₁, lt_of_lt_of_le h₁ hz₂]
/-- A (hyper)-cube (in standard orientation) is a vector `b` consisting of the bottom-left point
of the cube, a width `w` and a proof that `w > 0`. We use functions from `Fin n` to denote vectors.
-/
structure Cube (n : ℕ) : Type where
b : Fin n → ℝ -- bottom-left coordinate
w : ℝ -- width
hw : 0 < w
namespace Cube
theorem hw' (c : Cube n) : 0 ≤ c.w :=
le_of_lt c.hw
/-- The j-th side of a cube is the half-open interval `[b j, b j + w)` -/
def side (c : Cube n) (j : Fin n) : Set ℝ :=
Ico (c.b j) (c.b j + c.w)
@[simp]
theorem b_mem_side (c : Cube n) (j : Fin n) : c.b j ∈ c.side j := by simp [side, Cube.hw, le_refl]
def toSet (c : Cube n) : Set (Fin n → ℝ) :=
{x | ∀ j, x j ∈ side c j}
theorem side_nonempty (c : Cube n) (i : Fin n) : (side c i).Nonempty := by simp [side, c.hw]
theorem univ_pi_side (c : Cube n) : pi univ (side c) = c.toSet :=
ext fun _ => mem_univ_pi
theorem toSet_subset {c c' : Cube n} : c.toSet ⊆ c'.toSet ↔ ∀ j, c.side j ⊆ c'.side j := by
simp only [← univ_pi_side, univ_pi_subset_univ_pi_iff, (c.side_nonempty _).ne_empty, exists_false,
or_false]
theorem toSet_disjoint {c c' : Cube n} :
Disjoint c.toSet c'.toSet ↔ ∃ j, Disjoint (c.side j) (c'.side j) := by
simp only [← univ_pi_side, disjoint_univ_pi]
theorem b_mem_toSet (c : Cube n) : c.b ∈ c.toSet := by simp [toSet]
protected def tail (c : Cube (n + 1)) : Cube n :=
⟨tail c.b, c.w, c.hw⟩
theorem side_tail (c : Cube (n + 1)) (j : Fin n) : c.tail.side j = c.side j.succ :=
rfl
def bottom (c : Cube (n + 1)) : Set (Fin (n + 1) → ℝ) :=
{x | x 0 = c.b 0 ∧ tail x ∈ c.tail.toSet}
theorem b_mem_bottom (c : Cube (n + 1)) : c.b ∈ c.bottom := by
simp [bottom, toSet, side, Cube.hw, le_refl, Cube.tail]
def xm (c : Cube (n + 1)) : ℝ :=
c.b 0 + c.w
theorem b_lt_xm (c : Cube (n + 1)) : c.b 0 < c.xm := by simp [xm, hw]
theorem b_ne_xm (c : Cube (n + 1)) : c.b 0 ≠ c.xm :=
ne_of_lt c.b_lt_xm
def shiftUp (c : Cube (n + 1)) : Cube (n + 1) :=
⟨cons c.xm <| tail c.b, c.w, c.hw⟩
@[simp]
theorem tail_shiftUp (c : Cube (n + 1)) : c.shiftUp.tail = c.tail := by simp [shiftUp, Cube.tail]
@[simp]
theorem head_shiftUp (c : Cube (n + 1)) : c.shiftUp.b 0 = c.xm :=
rfl
def unitCube : Cube n :=
⟨fun _ => 0, 1, by simp⟩
@[simp]
theorem side_unitCube {j : Fin n} : unitCube.side j = Ico 0 1 := by
norm_num [unitCube, side]
end Cube
open Cube
variable {ι : Type} {cs : ι → Cube (n + 1)} {i i' : ι}
/-- A finite family of (at least 2) cubes partitioning the unit cube with different sizes -/
structure Correct (cs : ι → Cube n) : Prop where
PairwiseDisjoint : Pairwise (Disjoint on Cube.toSet ∘ cs)
iUnion_eq : ⋃ i : ι, (cs i).toSet = unitCube.toSet
Injective : Injective (Cube.w ∘ cs)
three_le : 3 ≤ n
namespace Correct
variable (h : Correct cs)
include h
theorem toSet_subset_unitCube {i} : (cs i).toSet ⊆ unitCube.toSet := by
convert h.iUnion_eq ▸ subset_iUnion _ i
theorem side_subset {i j} : (cs i).side j ⊆ Ico 0 1 := by
simpa only [side_unitCube] using toSet_subset.1 h.toSet_subset_unitCube j
theorem zero_le_of_mem_side {i j x} (hx : x ∈ (cs i).side j) : 0 ≤ x :=
(side_subset h hx).1
theorem zero_le_of_mem {i p} (hp : p ∈ (cs i).toSet) (j) : 0 ≤ p j :=
zero_le_of_mem_side h (hp j)
theorem zero_le_b {i j} : 0 ≤ (cs i).b j :=
zero_le_of_mem h (cs i).b_mem_toSet j
theorem b_add_w_le_one {j} : (cs i).b j + (cs i).w ≤ 1 := by
have : side (cs i) j ⊆ Ico 0 1 := side_subset h
rw [side, Ico_subset_Ico_iff] at this
· convert this.2
· simp [hw]
theorem nontrivial_fin : Nontrivial (Fin n) :=
Fin.nontrivial_iff_two_le.2 (Nat.le_of_succ_le_succ h.three_le)
/-- The width of any cube in the partition cannot be 1. -/
theorem w_ne_one [Nontrivial ι] (i : ι) : (cs i).w ≠ 1 := by
intro hi
obtain ⟨i', hi'⟩ := exists_ne i
let p := (cs i').b
have hp : p ∈ (cs i').toSet := (cs i').b_mem_toSet
have h2p : p ∈ (cs i).toSet := by
intro j; constructor
· trans (0 : ℝ)
· rw [← add_le_add_iff_right (1 : ℝ)]; convert b_add_w_le_one h
· rw [hi]
· rw [zero_add]
· apply zero_le_b h
· apply lt_of_lt_of_le (side_subset h <| (cs i').b_mem_side j).2
simp [hi, zero_le_b h]
exact (h.PairwiseDisjoint hi').le_bot ⟨hp, h2p⟩
/-- The top of a cube (which is the bottom of the cube shifted up by its width) must be covered by
bottoms of (other) cubes in the family. -/
theorem shiftUp_bottom_subset_bottoms (hc : (cs i).xm ≠ 1) :
(cs i).shiftUp.bottom ⊆ ⋃ i : ι, (cs i).bottom := by
intro p hp; obtain ⟨hp0, hps⟩ := hp; rw [tail_shiftUp] at hps
have : p ∈ (unitCube : Cube (n + 1)).toSet := by
simp only [toSet, forall_iff_succ, hp0, side_unitCube, mem_setOf_eq, mem_Ico, head_shiftUp]
refine ⟨⟨?_, ?_⟩, ?_⟩
· rw [← zero_add (0 : ℝ)]; apply add_le_add
· apply zero_le_b h
· apply (cs i).hw'
· exact lt_of_le_of_ne (b_add_w_le_one h) hc
intro j; exact side_subset h (hps j)
rw [← h.2, mem_iUnion] at this; rcases this with ⟨i', hi'⟩
rw [mem_iUnion]; use i'; refine ⟨?_, fun j => hi' j.succ⟩
have : i ≠ i' := by rintro rfl; apply not_le_of_gt (hi' 0).2; rw [hp0]; rfl
have := h.1 this
rw [onFun, comp_apply, comp_apply, toSet_disjoint, exists_fin_succ] at this
rcases this with (h0 | ⟨j, hj⟩)
· rw [hp0]; symm; apply eq_of_Ico_disjoint h0 (by simp [hw]) _
convert hi' 0; rw [hp0]; rfl
· exfalso; apply not_disjoint_iff.mpr ⟨tail p j, hps j, hi' j.succ⟩ hj
end Correct
/-- A valley is a square on which cubes in the family of cubes are placed, so that the cubes
completely cover the valley and none of those cubes is partially outside the square.
We also require that no cube on it has the same size as the valley (so that there are at least
two cubes on the valley).
This is the main concept in the formalization.
We prove that the smallest cube on a valley has another valley on the top of it, which
gives an infinite sequence of cubes in the partition, which contradicts the finiteness.
A valley is characterized by a cube `c` (which is not a cube in the family `cs`) by considering
the bottom face of `c`. -/
def Valley (cs : ι → Cube (n + 1)) (c : Cube (n + 1)) : Prop :=
(c.bottom ⊆ ⋃ i : ι, (cs i).bottom) ∧
(∀ i, (cs i).b 0 = c.b 0 →
(∃ x, x ∈ (cs i).tail.toSet ∩ c.tail.toSet) → (cs i).tail.toSet ⊆ c.tail.toSet) ∧
∀ i : ι, (cs i).b 0 = c.b 0 → (cs i).w ≠ c.w
variable {c : Cube (n + 1)} (h : Correct cs) (v : Valley cs c)
/-- The bottom of the unit cube is a valley -/
theorem valley_unitCube [Nontrivial ι] (h : Correct cs) : Valley cs unitCube := by
refine ⟨?_, ?_, ?_⟩
· intro v
simp only [bottom, and_imp, mem_iUnion, mem_setOf_eq]
intro h0 hv
have : v ∈ (unitCube : Cube (n + 1)).toSet := by
dsimp only [toSet, unitCube, mem_setOf_eq]
rw [forall_iff_succ, h0]; constructor
· norm_num [side, unitCube]
· exact hv
rw [← h.2, mem_iUnion] at this; rcases this with ⟨i, hi⟩
use i
constructor
· apply le_antisymm
· rw [h0]; exact h.zero_le_b
· exact (hi 0).1
intro j; exact hi _
· intro i _ _; rw [toSet_subset]; intro j; convert h.side_subset using 1; simp [side_tail]
· intro i _; exact h.w_ne_one i
/-- the cubes which lie in the valley `c` -/
def bcubes (cs : ι → Cube (n + 1)) (c : Cube (n + 1)) : Set ι :=
{i : ι | (cs i).b 0 = c.b 0 ∧ (cs i).tail.toSet ⊆ c.tail.toSet}
/-- A cube which lies on the boundary of a valley in dimension `j` -/
def OnBoundary (_ : i ∈ bcubes cs c) (j : Fin n) : Prop :=
c.b j.succ = (cs i).b j.succ ∨ (cs i).b j.succ + (cs i).w = c.b j.succ + c.w
theorem tail_sub (hi : i ∈ bcubes cs c) : ∀ j, (cs i).tail.side j ⊆ c.tail.side j := by
rw [← toSet_subset]; exact hi.2
theorem bottom_mem_side (hi : i ∈ bcubes cs c) : c.b 0 ∈ (cs i).side 0 := by
convert b_mem_side (cs i) _ using 1; rw [hi.1]
theorem b_le_b (hi : i ∈ bcubes cs c) (j : Fin n) : c.b j.succ ≤ (cs i).b j.succ :=
(tail_sub hi j <| b_mem_side _ _).1
theorem t_le_t (hi : i ∈ bcubes cs c) (j : Fin n) :
(cs i).b j.succ + (cs i).w ≤ c.b j.succ + c.w := by
have h' := tail_sub hi j; dsimp only [side] at h'; rw [Ico_subset_Ico_iff] at h'
· exact h'.2
· simp [hw]
section
include h v
/-- Every cube in the valley must be smaller than it -/
theorem w_lt_w (hi : i ∈ bcubes cs c) : (cs i).w < c.w := by
apply lt_of_le_of_ne _ (v.2.2 i hi.1)
have j : Fin n := ⟨1, Nat.le_of_succ_le_succ h.three_le⟩
rw [← add_le_add_iff_left ((cs i).b j.succ)]
apply le_trans (t_le_t hi j); gcongr; apply b_le_b hi
/-- There are at least two cubes in a valley -/
theorem nontrivial_bcubes : (bcubes cs c).Nontrivial := by
rcases v.1 c.b_mem_bottom with ⟨_, ⟨i, rfl⟩, hi⟩
have h2i : i ∈ bcubes cs c :=
⟨hi.1.symm, v.2.1 i hi.1.symm ⟨tail c.b, hi.2, fun j => c.b_mem_side j.succ⟩⟩
let j : Fin (n + 1) := ⟨2, h.three_le⟩
have hj : 0 ≠ j := by simp only [j, Fin.ext_iff, Ne]; norm_num
let p : Fin (n + 1) → ℝ := fun j' => if j' = j then c.b j + (cs i).w else c.b j'
have hp : p ∈ c.bottom := by
constructor
· simp only [p, if_neg hj]
intro j'; simp only [tail, side_tail]
by_cases hj' : j'.succ = j
· simp [p, if_pos, side, hj', hw', w_lt_w h v h2i]
· simp [p, if_neg hj']
rcases v.1 hp with ⟨_, ⟨i', rfl⟩, hi'⟩
have h2i' : i' ∈ bcubes cs c := ⟨hi'.1.symm, v.2.1 i' hi'.1.symm ⟨tail p, hi'.2, hp.2⟩⟩
refine ⟨i, h2i, i', h2i', ?_⟩
rintro rfl
apply not_le_of_gt (hi'.2 ⟨1, Nat.le_of_succ_le_succ h.three_le⟩).2
simp only [tail, Cube.tail, p]
rw [if_pos]
· gcongr
exact (hi.2 _).1
simp [j]
/-- There is a cube in the valley -/
theorem nonempty_bcubes : (bcubes cs c).Nonempty :=
(nontrivial_bcubes h v).nonempty
variable [Finite ι]
/-- There is a smallest cube in the valley -/
theorem exists_mi : ∃ i ∈ bcubes cs c, ∀ i' ∈ bcubes cs c, (cs i).w ≤ (cs i').w :=
(bcubes cs c).exists_min_image (fun i => (cs i).w) (Set.toFinite _) (nonempty_bcubes h v)
/-- We let `mi` be the (index for the) smallest cube in the valley `c` -/
def mi : ι :=
Classical.choose <| exists_mi h v
variable {h v}
theorem mi_mem_bcubes : mi h v ∈ bcubes cs c :=
(Classical.choose_spec <| exists_mi h v).1
theorem mi_minimal (hi : i ∈ bcubes cs c) : (cs <| mi h v).w ≤ (cs i).w :=
(Classical.choose_spec <| exists_mi h v).2 i hi
theorem mi_strict_minimal (hii' : mi h v ≠ i) (hi : i ∈ bcubes cs c) :
(cs <| mi h v).w < (cs i).w :=
(mi_minimal hi).lt_of_ne <| h.Injective.ne hii'
/-- The top of `mi` cannot be 1, since there is a larger cube in the valley -/
theorem mi_xm_ne_one : (cs <| mi h v).xm ≠ 1 := by
apply ne_of_lt; rcases (nontrivial_bcubes h v).exists_ne (mi h v) with ⟨i, hi, h2i⟩
· apply lt_of_lt_of_le _ h.b_add_w_le_one
· exact i
· exact 0
rw [xm, mi_mem_bcubes.1, hi.1, add_lt_add_iff_left]
exact mi_strict_minimal h2i.symm hi
/-- If `mi` lies on the boundary of the valley in dimension j, then this lemma expresses that all
other cubes on the same boundary extend further from the boundary.
More precisely, there is a j-th coordinate `x : ℝ` in the valley, but not in `mi`,
such that every cube that shares a (particular) j-th coordinate with `mi` also contains j-th
coordinate `x` -/
theorem smallest_onBoundary {j} (bi : OnBoundary (mi_mem_bcubes : mi h v ∈ _) j) :
∃ x : ℝ, x ∈ c.side j.succ \ (cs <| mi h v).side j.succ ∧
∀ ⦃i'⦄ (_ : i' ∈ bcubes cs c),
i' ≠ mi h v → (cs <| mi h v).b j.succ ∈ (cs i').side j.succ → x ∈ (cs i').side j.succ := by
let i := mi h v; have hi : i ∈ bcubes cs c := mi_mem_bcubes
obtain bi | bi := bi
· refine ⟨(cs i).b j.succ + (cs i).w, ⟨?_, ?_⟩, ?_⟩
· simp [i, side, bi, hw', w_lt_w h v hi]
· intro h'; simpa [i, lt_irrefl] using h'.2
intro i' hi' i'_i h2i'; constructor
· apply le_trans h2i'.1
simp [i, hw']
apply lt_of_lt_of_le (add_lt_add_left (mi_strict_minimal i'_i.symm hi') _)
simp [i, bi.symm, b_le_b hi']
let s := bcubes cs c \ {i}
have hs : s.Nonempty := by
rcases (nontrivial_bcubes h v).exists_ne i with ⟨i', hi', h2i'⟩
exact ⟨i', hi', h2i'⟩
rcases Set.exists_min_image s (w <| cs ·) (Set.toFinite _) hs with ⟨i', ⟨hi', h2i'⟩, h3i'⟩
rw [mem_singleton_iff] at h2i'
let x := c.b j.succ + c.w - (cs i').w
have hx : x < (cs i).b j.succ := by
dsimp only [x]; rw [← bi, add_sub_assoc, add_lt_iff_neg_left, sub_lt_zero]
apply mi_strict_minimal (Ne.symm h2i') hi'
refine ⟨x, ⟨?_, ?_⟩, ?_⟩
· simp only [side, neg_lt_zero, hw, add_lt_iff_neg_left, and_true, mem_Ico, sub_eq_add_neg, x]
rw [add_assoc, le_add_iff_nonneg_right, ← sub_eq_add_neg, sub_nonneg]
apply le_of_lt (w_lt_w h v hi')
· simp only [side, not_and_or, not_lt, not_le, mem_Ico]; left; exact hx
intro i'' hi'' h2i'' h3i''; constructor; swap; · apply lt_trans hx h3i''.2
rw [le_sub_iff_add_le]
grw [← t_le_t hi'', h3i' i'' ⟨hi'', h2i''⟩]
variable (h v)
/-- `mi` cannot lie on the boundary of the valley. Otherwise, the cube adjacent to it in the `j`-th
direction will intersect one of the neighbouring cubes on the same boundary as `mi`. -/
theorem mi_not_onBoundary (j : Fin n) : ¬OnBoundary (mi_mem_bcubes : mi h v ∈ _) j := by
let i := mi h v; have hi : i ∈ bcubes cs c := mi_mem_bcubes
haveI := h.nontrivial_fin
rcases exists_ne j with ⟨j', hj'⟩
intro hj
rcases smallest_onBoundary hj with ⟨x, ⟨hx, h2x⟩, h3x⟩
let p : Fin (n + 1) → ℝ := cons (c.b 0) fun j₂ => if j₂ = j then x else (cs i).b j₂.succ
have hp : p ∈ c.bottom := by
suffices ∀ j' : Fin n, ite (j' = j) x ((cs i).b j'.succ) ∈ c.side j'.succ by
simpa [p, bottom, toSet, tail, side_tail]
intro j₂
by_cases hj₂ : j₂ = j
· simp [hj₂, hx]
simp only [hj₂, if_false]; apply tail_sub hi; apply b_mem_side
rcases v.1 hp with ⟨_, ⟨i', rfl⟩, hi'⟩
have h2i' : i' ∈ bcubes cs c := ⟨hi'.1.symm, v.2.1 i' hi'.1.symm ⟨tail p, hi'.2, hp.2⟩⟩
have i_i' : i ≠ i' := by rintro rfl; simpa [i, p, side_tail, h2x] using hi'.2 j
have : Nonempty (↥((cs i').tail.side j' \ (cs i).tail.side j')) := by
apply nonempty_Ico_sdiff
· apply mi_strict_minimal i_i' h2i'
· apply hw
rcases this with ⟨⟨x', hx'⟩⟩
let p' : Fin (n + 1) → ℝ := cons (c.b 0) fun j₂ => if j₂ = j' then x' else (cs i).b j₂.succ
have hp' : p' ∈ c.bottom := by
suffices ∀ j : Fin n, ite (j = j') x' ((cs i).b j.succ) ∈ c.side j.succ by
simpa [p', bottom, toSet, tail, side_tail]
intro j₂
by_cases hj₂ : j₂ = j'; · simpa [hj₂] using tail_sub h2i' _ hx'.1
simp only [if_false, hj₂]; apply tail_sub hi; apply b_mem_side
rcases v.1 hp' with ⟨_, ⟨i'', rfl⟩, hi''⟩
have h2i'' : i'' ∈ bcubes cs c := ⟨hi''.1.symm, v.2.1 i'' hi''.1.symm ⟨tail p', hi''.2, hp'.2⟩⟩
have i'_i'' : i' ≠ i'' := by
rintro ⟨⟩
have : (cs i).b ∈ (cs i').toSet := by
simp only [toSet, forall_iff_succ, hi.1, bottom_mem_side h2i', true_and, mem_setOf_eq]
intro j₂; by_cases hj₂ : j₂ = j
· simpa [p', side_tail, hj'.symm, hj₂] using hi''.2 j
· simpa [p, hj₂] using hi'.2 j₂
apply not_disjoint_iff.mpr ⟨(cs i).b, (cs i).b_mem_toSet, this⟩ (h.1 i_i')
have i_i'' : i ≠ i'' := by intro h; induction h; simpa [p', hx'.2] using hi''.2 j'
apply Not.elim _ (h.1 i'_i'')
simp_rw [onFun, comp, toSet_disjoint, not_exists, not_disjoint_iff, forall_iff_succ]
refine ⟨⟨c.b 0, bottom_mem_side h2i', bottom_mem_side h2i''⟩, ?_⟩
intro j₂
by_cases hj₂ : j₂ = j
· cases hj₂; refine ⟨x, ?_, ?_⟩
· convert hi'.2 j using 1; simp [i, p]
apply h3x h2i'' i_i''.symm; convert hi''.2 j using 1; simp [i, p', hj'.symm]
by_cases h2j₂ : j₂ = j'
· cases h2j₂; refine ⟨x', hx'.1, ?_⟩; convert hi''.2 j' using 1; simp [p']
refine ⟨(cs i).b j₂.succ, ?_, ?_⟩
· convert hi'.2 j₂ using 1; simp [p, hj₂]
· convert hi''.2 j₂ using 1; simp [p', h2j₂]
variable {h v}
/-- The same result that `mi` cannot lie on the boundary of the valley written as inequalities. -/
theorem mi_not_onBoundary' (j : Fin n) :
c.tail.b j < (cs (mi h v)).tail.b j ∧
(cs (mi h v)).tail.b j + (cs (mi h v)).w < c.tail.b j + c.w := by
have := mi_not_onBoundary h v j
simp only [OnBoundary, not_or] at this; obtain ⟨h1, h2⟩ := this
constructor
· apply lt_of_le_of_ne (b_le_b mi_mem_bcubes _) h1
apply lt_of_le_of_ne _ h2
apply ((Ico_subset_Ico_iff _).mp (tail_sub mi_mem_bcubes j)).2
simp [hw]
/-- The top of `mi` gives rise to a new valley, since the neighbouring cubes extend further upward
than `mi`. -/
theorem valley_mi : Valley cs (cs (mi h v)).shiftUp := by
let i := mi h v; have hi : i ∈ bcubes cs c := mi_mem_bcubes
refine ⟨?_, ?_, ?_⟩
· intro p; apply h.shiftUp_bottom_subset_bottoms mi_xm_ne_one
· rintro i' hi' ⟨p2, hp2, h2p2⟩; simp only [head_shiftUp] at hi'
classical
by_contra h2i'
rw [tail_shiftUp] at h2p2
simp only [not_subset, tail_shiftUp] at h2i'
rcases h2i' with ⟨p1, hp1, h2p1⟩
have : ∃ p3, p3 ∈ (cs i').tail.toSet ∧ p3 ∉ (cs i).tail.toSet ∧ p3 ∈ c.tail.toSet := by
simp only [toSet, not_forall, mem_setOf_eq] at h2p1; obtain ⟨j, hj⟩ := h2p1
rcases Ico_lemma (mi_not_onBoundary' j).1 (by simp [hw]) (mi_not_onBoundary' j).2
(le_trans (hp2 j).1 <| le_of_lt (h2p2 j).2) (le_trans (h2p2 j).1 <| le_of_lt (hp2 j).2)
⟨hj, hp1 j⟩ with
⟨w, hw, h2w, h3w⟩
refine ⟨fun j' => if j' = j then w else p2 j', ?_, ?_, ?_⟩
· intro j'; by_cases h : j' = j
· simp only [if_pos h]; exact h ▸ h3w
· simp only [if_neg h]; exact hp2 j'
· simp only [toSet, not_forall, mem_setOf_eq]; use j; rw [if_pos rfl]; convert h2w
· intro j'; by_cases h : j' = j
· simp only [if_pos h, side_tail]; exact h ▸ hw
· simp only [if_neg h]; apply hi.2; apply h2p2
rcases this with ⟨p3, h1p3, h2p3, h3p3⟩
let p := @cons n (fun _ => ℝ) (c.b 0) p3
have hp : p ∈ c.bottom := by refine ⟨rfl, ?_⟩; rwa [tail_cons]
rcases v.1 hp with ⟨_, ⟨i'', rfl⟩, hi''⟩
have h2i'' : i'' ∈ bcubes cs c := by
use hi''.1.symm; apply v.2.1 i'' hi''.1.symm
use tail p; constructor
· exact hi''.2
· rw [tail_cons]; exact h3p3
have h3i'' : (cs i).w < (cs i'').w := by
apply mi_strict_minimal _ h2i''; rintro rfl; apply h2p3; convert hi''.2
let p' := @cons n (fun _ => ℝ) (cs i).xm p3
have hp' : p' ∈ (cs i').toSet := by simpa [i, p', toSet, forall_iff_succ, hi'.symm] using h1p3
have h2p' : p' ∈ (cs i'').toSet := by
simp only [p', toSet, forall_iff_succ, cons_succ, cons_zero, mem_setOf_eq]
refine ⟨?_, by simpa [toSet] using hi''.2⟩
have : (cs i).b 0 = (cs i'').b 0 := by rw [hi.1, h2i''.1]
simp [side, hw', xm, this, h3i'']
apply not_disjoint_iff.mpr ⟨p', hp', h2p'⟩
apply h.1
rintro rfl
apply (cs i).b_ne_xm
rw [← hi', ← hi''.1, hi.1]
rfl
· intro i' hi' h2i'
dsimp only [shiftUp] at h2i'
replace h2i' := h.Injective h2i'.symm
induction h2i'
exact b_ne_xm (cs i) hi'
variable (h) [Nontrivial ι]
/-- We get a sequence of cubes whose size is decreasing -/
noncomputable def sequenceOfCubes : ℕ → { i : ι // Valley cs (cs i).shiftUp }
| 0 =>
let v := valley_unitCube h
⟨mi h v, valley_mi⟩
| k + 1 =>
let v := (sequenceOfCubes k).2
⟨mi h v, valley_mi⟩
def decreasingSequence (k : ℕ) : ℝ :=
(cs (sequenceOfCubes h k).1).w
end
variable [Finite ι] [Nontrivial ι]
include h in
theorem strictAnti_sequenceOfCubes : StrictAnti <| decreasingSequence h :=
strictAnti_nat_of_succ_lt fun k => by
let v := (sequenceOfCubes h k).2; dsimp only [decreasingSequence, sequenceOfCubes]
apply w_lt_w h v (mi_mem_bcubes : mi h v ∈ _)
theorem injective_sequenceOfCubes : Injective (sequenceOfCubes h) :=
@Injective.of_comp _ _ _ (fun x : { _i : ι // _ } => (cs x.1).w) _
(strictAnti_sequenceOfCubes h).injective
/-- The infinite sequence of cubes contradicts the finiteness of the family. -/
theorem not_correct : ¬Correct cs := fun h =>
(Finite.of_injective _ <| injective_sequenceOfCubes h).false
/-- **Dissection of Cubes**: A cube cannot be cubed. -/
theorem cannot_cube_a_cube :
∀ {n : ℕ}, n ≥ 3 → -- In ℝ^n for n ≥ 3
∀ {s : Set (Cube n)}, s.Finite → -- given a finite collection of (hyper)cubes
s.Nontrivial → -- containing at least two elements
s.PairwiseDisjoint Cube.toSet → -- which is pairwise disjoint
⋃ c ∈ s, Cube.toSet c = unitCube.toSet → -- whose union is the unit cube
InjOn Cube.w s → -- such that the widths of all cubes are different
False := by -- then we can derive a contradiction
intro n hn s hfin h2 hd hU hinj
rcases n with - | n
· cases hn
exact @not_correct n s (↑) hfin.to_subtype h2.coe_sort
⟨hd.subtype _ _, (iUnion_subtype _ _).trans hU, hinj.injective, hn⟩
end «82»
end
end Theorems100 |
.lake/packages/mathlib/Archive/Wiedijk100Theorems/Konigsberg.lean | import Mathlib.Combinatorics.SimpleGraph.Trails
import Mathlib.Tactic.DeriveFintype
import Mathlib.Tactic.NormNum
/-!
# The Königsberg bridges problem
We show that a graph that represents the islands and mainlands of Königsberg and seven bridges
between them has no Eulerian trail.
-/
namespace Konigsberg
/-- The vertices for the Königsberg graph; four vertices for the bodies of land and seven
vertices for the bridges. -/
inductive Verts : Type
-- The islands and mainlands
| V1 | V2 | V3 | V4
-- The bridges
| B1 | B2 | B3 | B4 | B5 | B6 | B7
deriving DecidableEq, Fintype
open Verts
/-- Each of the connections between the islands/mainlands and the bridges.
These are ordered pairs, but the data becomes symmetric in `Konigsberg.adj`. -/
def edges : List (Verts × Verts) :=
[(V1, B1), (V1, B2), (V1, B3), (V1, B4), (V1, B5),
(B1, V2), (B2, V2), (B3, V4), (B4, V3), (B5, V3),
(V2, B6), (B6, V4),
(V3, B7), (B7, V4)]
/-- The adjacency relation for the Königsberg graph. -/
def adj (v w : Verts) : Bool := (v, w) ∈ edges || (w, v) ∈ edges
/-- The Königsberg graph structure. While the Königsberg bridge problem
is usually described using a multigraph, we use a "mediant" construction
to transform it into a simple graph -- every edge in the multigraph is subdivided
into a path of two edges. This construction preserves whether a graph is Eulerian.
(TODO: once mathlib has multigraphs, either prove the mediant construction preserves the
Eulerian property or switch this file to use multigraphs. -/
@[simps]
def graph : SimpleGraph Verts where
Adj v w := adj v w
symm := by
dsimp [Symmetric, adj]
decide
loopless := by
dsimp [Irreflexive, adj]
decide
instance : DecidableRel graph.Adj := fun a b => inferInstanceAs <| Decidable (adj a b)
/-- To speed up the proof, this is a cache of all the degrees of each vertex,
proved in `Konigsberg.degree_eq_degree`. -/
def degree : Verts → ℕ
| V1 => 5 | V2 => 3 | V3 => 3 | V4 => 3
| B1 => 2 | B2 => 2 | B3 => 2 | B4 => 2 | B5 => 2 | B6 => 2 | B7 => 2
@[simp]
lemma degree_eq_degree (v : Verts) : graph.degree v = degree v := by cases v <;> rfl
lemma not_even_degree_iff (w : Verts) : ¬Even (degree w) ↔ w = V1 ∨ w = V2 ∨ w = V3 ∨ w = V4 := by
cases w <;> decide
lemma setOf_odd_degree_eq :
{v | Odd (graph.degree v)} = {Verts.V1, Verts.V2, Verts.V3, Verts.V4} := by
ext w
simp [not_even_degree_iff, ← Nat.not_even_iff_odd]
/-- The Königsberg graph is not Eulerian. -/
theorem not_isEulerian {u v : Verts} (p : graph.Walk u v) (h : p.IsEulerian) : False := by
have h := h.card_odd_degree
have h' := setOf_odd_degree_eq
apply_fun Fintype.card at h'
rw [h'] at h
simp at h
end Konigsberg |
.lake/packages/mathlib/Archive/Wiedijk100Theorems/Partition.lean | import Mathlib.Algebra.Order.Antidiag.Finsupp
import Mathlib.Algebra.Order.Ring.Abs
import Mathlib.Combinatorics.Enumerative.Partition.Basic
import Mathlib.Data.Finset.NatAntidiagonal
import Mathlib.Data.Fin.Tuple.NatAntidiagonal
import Mathlib.RingTheory.PowerSeries.Inverse
import Mathlib.RingTheory.PowerSeries.Order
import Mathlib.Tactic.ApplyFun
import Mathlib.Tactic.IntervalCases
/-!
# Euler's Partition Theorem
This file proves Theorem 45 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/).
The theorem concerns the counting of integer partitions -- ways of
writing a positive integer `n` as a sum of positive integer parts.
Specifically, Euler proved that the number of integer partitions of `n`
into *distinct* parts equals the number of partitions of `n` into *odd*
parts.
## Proof outline
The proof is based on the generating functions for odd and distinct partitions, which turn out to be
equal:
$$\prod_{i=0}^\infty \frac {1}{1-X^{2i+1}} = \prod_{i=0}^\infty (1+X^{i+1})$$
In fact, we do not take a limit: it turns out that comparing the `n`-th coefficients of the partial
products up to `m := n + 1` is sufficient.
In particular, we
1. define the partial product for the generating function for odd partitions `partialOddGF m` :=
$$\prod_{i=0}^m \frac {1}{1-X^{2i+1}}$$;
2. prove `oddGF_prop`: if `m` is big enough (`m * 2 > n`), the partial product's coefficient counts
the number of odd partitions;
3. define the partial product for the generating function for distinct partitions
`partialDistinctGF m` := $$\prod_{i=0}^m (1+X^{i+1})$$;
4. prove `distinctGF_prop`: if `m` is big enough (`m + 1 > n`), the `n`th coefficient of the
partial product counts the number of distinct partitions of `n`;
5. prove `same_coeffs`: if m is big enough (`m ≥ n`), the `n`th coefficient of the partial products
are equal;
6. combine the above in `partition_theorem`.
## References
https://en.wikipedia.org/wiki/Partition_(number_theory)#Odd_parts_and_distinct_parts
-/
open PowerSeries
namespace Theorems100
noncomputable section
open Finset
/-- The partial product for the generating function for odd partitions.
TODO: As `m` tends to infinity, this converges (in the `X`-adic topology).
If `m` is sufficiently large, the `i`th coefficient gives the number of odd partitions of the
natural number `i`: proved in `oddGF_prop`.
It is stated for an arbitrary field `α`, though it usually suffices to use `ℚ` or `ℝ`.
-/
def partialOddGF (α : Type*) (m : ℕ) [Field α] :=
∏ i ∈ range m, (1 - (X : PowerSeries α) ^ (2 * i + 1))⁻¹
/-- The partial product for the generating function for distinct partitions.
TODO: As `m` tends to infinity, this converges (in the `X`-adic topology).
If `m` is sufficiently large, the `i`th coefficient gives the number of distinct partitions of the
natural number `i`: proved in `distinctGF_prop`.
It is stated for an arbitrary commutative semiring `α`, though it usually suffices to use `ℕ`, `ℚ`
or `ℝ`.
-/
def partialDistinctGF (α : Type*) (m : ℕ) [CommSemiring α] :=
∏ i ∈ range m, (1 + (X : PowerSeries α) ^ (i + 1))
open Finset.HasAntidiagonal
universe u
variable {α : Type*} {ι : Type u}
open scoped Classical in
/-- A convenience constructor for the power series whose coefficients indicate a subset. -/
def indicatorSeries (α : Type*) [Semiring α] (s : Set ℕ) : PowerSeries α :=
PowerSeries.mk fun n => if n ∈ s then 1 else 0
theorem coeff_indicator (s : Set ℕ) [Semiring α] (n : ℕ) [Decidable (n ∈ s)] :
coeff n (indicatorSeries α s) = if n ∈ s then 1 else 0 := by
convert coeff_mk _ _
theorem coeff_indicator_pos (s : Set ℕ) [Semiring α] (n : ℕ) (h : n ∈ s) [Decidable (n ∈ s)] :
coeff n (indicatorSeries α s) = 1 := by rw [coeff_indicator, if_pos h]
theorem coeff_indicator_neg (s : Set ℕ) [Semiring α] (n : ℕ) (h : n ∉ s) [Decidable (n ∈ s)] :
coeff n (indicatorSeries α s) = 0 := by rw [coeff_indicator, if_neg h]
theorem constantCoeff_indicator (s : Set ℕ) [Semiring α] [Decidable (0 ∈ s)] :
constantCoeff (indicatorSeries α s) = if 0 ∈ s then 1 else 0 := by
simp [indicatorSeries]
theorem two_series (i : ℕ) [Semiring α] :
1 + (X : PowerSeries α) ^ i.succ = indicatorSeries α {0, i.succ} := by
ext n
simp only [coeff_indicator, coeff_one, coeff_X_pow, Set.mem_insert_iff, Set.mem_singleton_iff,
map_add]
rcases n with - | d
· simp
· simp
theorem num_series' [Field α] (i : ℕ) :
(1 - (X : PowerSeries α) ^ (i + 1))⁻¹ = indicatorSeries α {k | i + 1 ∣ k} := by
rw [PowerSeries.inv_eq_iff_mul_eq_one]
· ext n
cases n with
| zero => simp [mul_sub, zero_pow, constantCoeff_indicator]
| succ n =>
simp only [coeff_one, if_false, mul_sub, mul_one, coeff_indicator,
LinearMap.map_sub, reduceCtorEq]
simp_rw [coeff_mul, coeff_X_pow, coeff_indicator, @boole_mul _ _ _ _]
rw [sum_ite, sum_ite]
simp_rw [@filter_filter _ _ _ _ _, sum_const_zero, add_zero, sum_const, nsmul_eq_mul, mul_one,
sub_eq_iff_eq_add, zero_add]
symm
split_ifs with h
· suffices #{a ∈ antidiagonal (n + 1) | i + 1 ∣ a.fst ∧ a.snd = i + 1} = 1 by
simp only [Set.mem_setOf_eq]; convert congr_arg ((↑) : ℕ → α) this; norm_cast
rw [card_eq_one]
obtain ⟨p, hp⟩ := h
refine ⟨((i + 1) * (p - 1), i + 1), ?_⟩
ext ⟨a₁, a₂⟩
simp only [mem_filter, Prod.mk_inj, mem_antidiagonal, mem_singleton]
constructor
· rintro ⟨a_left, ⟨a, rfl⟩, rfl⟩
refine ⟨?_, rfl⟩
rw [Nat.mul_sub_left_distrib, ← hp, ← a_left, mul_one, Nat.add_sub_cancel]
· rintro ⟨rfl, rfl⟩
match p with
| 0 => rw [mul_zero] at hp; cases hp
| p + 1 => rw [hp]; simp [mul_add]
· suffices #{a ∈ antidiagonal (n + 1) | i + 1 ∣ a.fst ∧ a.snd = i + 1} = 0 by
simp only [Set.mem_setOf_eq]; convert congr_arg ((↑) : ℕ → α) this; norm_cast
rw [card_eq_zero]
apply eq_empty_of_forall_notMem
simp only [Prod.forall, mem_filter, not_and, mem_antidiagonal]
rintro _ h₁ h₂ ⟨a, rfl⟩ rfl
apply h
simp [← h₂]
· simp [zero_pow]
def mkOdd : ℕ ↪ ℕ :=
⟨fun i => 2 * i + 1, fun x y h => by linarith⟩
open scoped Classical in
-- The main workhorse of the partition theorem proof.
theorem partialGF_prop (α : Type*) [CommSemiring α] (n : ℕ) (s : Finset ℕ) (hs : ∀ i ∈ s, 0 < i)
(c : ℕ → Set ℕ) (hc : ∀ i, i ∉ s → 0 ∈ c i) :
#{p : n.Partition | (∀ j, p.parts.count j ∈ c j) ∧ ∀ j ∈ p.parts, j ∈ s} =
coeff n (∏ i ∈ s, indicatorSeries α ((· * i) '' c i)) := by
simp_rw [coeff_prod, coeff_indicator, prod_boole, sum_boole]
apply congr_arg
simp only [Set.mem_image]
set φ : (a : Nat.Partition n) →
a ∈ filter (fun p ↦ (∀ (j : ℕ), Multiset.count j p.parts ∈ c j) ∧ ∀ j ∈ p.parts, j ∈ s) univ →
ℕ →₀ ℕ := fun p _ => {
toFun := fun i => Multiset.count i p.parts • i
support := Finset.filter (fun i => i ≠ 0) p.parts.toFinset
mem_support_toFun := fun a => by
simp only [smul_eq_mul, ne_eq, mul_eq_zero, Multiset.count_eq_zero]
rw [not_or, not_not]
simp only [Multiset.mem_toFinset, mem_filter] }
refine Finset.card_bij φ ?_ ?_ ?_
· intro a ha
simp only [φ, mem_filter]
rw [mem_finsuppAntidiag]
dsimp only [ne_eq, smul_eq_mul, id_eq, eq_mpr_eq_cast, le_eq_subset, Finsupp.coe_mk]
rw [mem_filter_univ] at ha
refine ⟨⟨?_, fun i ↦ ?_⟩, fun i _ ↦ ⟨a.parts.count i, ha.1 i, rfl⟩⟩
· conv_rhs => simp [← a.parts_sum]
rw [sum_multiset_count_of_subset _ s]
· simp only [smul_eq_mul]
· intro i
simp only [Multiset.mem_toFinset]
apply ha.2
· simp only [Multiset.mem_toFinset, mem_filter, and_imp]
exact fun hi _ ↦ ha.2 i hi
· dsimp only
intro p₁ hp₁ p₂ hp₂ h
apply Nat.Partition.ext
rw [mem_filter_univ] at hp₁ hp₂
ext i
simp only [φ, ne_eq, smul_eq_mul, Finsupp.mk.injEq] at h
by_cases hi : i = 0
· rw [hi]
rw [Multiset.count_eq_zero_of_notMem]
· rw [Multiset.count_eq_zero_of_notMem]
intro a; exact Nat.lt_irrefl 0 (hs 0 (hp₂.2 0 a))
intro a; exact Nat.lt_irrefl 0 (hs 0 (hp₁.2 0 a))
· rw [← mul_left_inj' hi]
rw [funext_iff] at h
exact h.2 i
· simp_rw [φ, mem_filter_univ, mem_filter, mem_finsuppAntidiag, exists_prop, and_assoc]
rintro f ⟨hf, hf₃, hf₄⟩
have hf' : f ∈ finsuppAntidiag s n := mem_finsuppAntidiag.mpr ⟨hf, hf₃⟩
simp only [mem_finsuppAntidiag] at hf'
refine ⟨⟨∑ i ∈ s, Multiset.replicate (f i / i) i, ?_, ?_⟩, ?_, ?_, ?_⟩
· intro i hi
simp only [Multiset.mem_sum] at hi
rcases hi with ⟨t, ht, z⟩
apply hs
rwa [Multiset.eq_of_mem_replicate z]
· simp_rw [Multiset.sum_sum, Multiset.sum_replicate, Nat.nsmul_eq_mul]
rw [← hf'.1]
refine sum_congr rfl fun i hi => Nat.div_mul_cancel ?_
rcases hf₄ i hi with ⟨w, _, hw₂⟩
rw [← hw₂]
exact dvd_mul_left _ _
· intro i
simp_rw [Multiset.count_sum', Multiset.count_replicate, sum_ite_eq']
split_ifs with h
· rcases hf₄ i h with ⟨w, hw₁, hw₂⟩
rwa [← hw₂, Nat.mul_div_cancel _ (hs i h)]
· exact hc _ h
· intro i hi
rw [Multiset.mem_sum] at hi
rcases hi with ⟨j, hj₁, hj₂⟩
rwa [Multiset.eq_of_mem_replicate hj₂]
· ext i
simp_rw [Multiset.count_sum', Multiset.count_replicate, sum_ite_eq']
simp only [ne_eq, smul_eq_mul, ite_mul, zero_mul, Finsupp.coe_mk]
split_ifs with h
· apply Nat.div_mul_cancel
rcases hf₄ i h with ⟨w, _, hw₂⟩
apply Dvd.intro_left _ hw₂
· apply symm
rw [← Finsupp.notMem_support_iff]
exact notMem_mono hf'.2 h
theorem partialOddGF_prop [Field α] (n m : ℕ) :
#{p : n.Partition | ∀ j ∈ p.parts, j ∈ (range m).map mkOdd} = coeff n (partialOddGF α m) := by
rw [partialOddGF]
convert partialGF_prop α n
((range m).map mkOdd) _ (fun _ => Set.univ) (fun _ _ => trivial) using 2
· congr
simp only [true_and, forall_const, Set.mem_univ]
· rw [Finset.prod_map]
simp_rw [num_series']
congr! 2 with x
ext k
constructor
· rintro ⟨p, rfl⟩
refine ⟨p, ⟨⟩, ?_⟩
apply mul_comm
rintro ⟨a_w, -, rfl⟩
apply Dvd.intro_left a_w rfl
· intro i
rw [mem_map]
rintro ⟨a, -, rfl⟩
exact Nat.succ_pos _
/-- If m is big enough, the partial product's coefficient counts the number of odd partitions -/
theorem oddGF_prop [Field α] (n m : ℕ) (h : n < m * 2) :
#(Nat.Partition.odds n) = coeff n (partialOddGF α m) := by
rw [← partialOddGF_prop, Nat.Partition.odds]
congr with p
apply forall₂_congr
intro i hi
have hin : i ≤ n := by
simpa [p.parts_sum] using Multiset.single_le_sum (fun _ _ => Nat.zero_le _) _ hi
simp only [mkOdd, mem_range, Function.Embedding.coeFn_mk, mem_map]
constructor
· intro hi₂
have := Nat.mod_add_div i 2
rw [Nat.not_even_iff] at hi₂
rw [hi₂, add_comm] at this
refine ⟨i / 2, ?_, this⟩
rw [Nat.div_lt_iff_lt_mul zero_lt_two]
exact lt_of_le_of_lt hin h
· rintro ⟨a, -, rfl⟩
rw [even_iff_two_dvd]
apply Nat.two_not_dvd_two_mul_add_one
theorem partialDistinctGF_prop [CommSemiring α] (n m : ℕ) :
#{p : n.Partition |
p.parts.Nodup ∧ ∀ j ∈ p.parts, j ∈ (range m).map ⟨Nat.succ, Nat.succ_injective⟩} =
coeff n (partialDistinctGF α m) := by
rw [partialDistinctGF]
convert partialGF_prop α n
((range m).map ⟨Nat.succ, Nat.succ_injective⟩) _ (fun _ => {0, 1}) (fun _ _ => Or.inl rfl)
using 2
· congr! with p
rw [Multiset.nodup_iff_count_le_one]
congr! 1 with i
rcases Multiset.count i p.parts with (_ | _ | ms) <;> simp
· simp_rw [Finset.prod_map, two_series]
congr with i
simp [Set.image_pair]
· simp only [mem_map, Function.Embedding.coeFn_mk]
rintro i ⟨_, _, rfl⟩
apply Nat.succ_pos
/-- If m is big enough, the partial product's coefficient counts the number of distinct partitions
-/
theorem distinctGF_prop [CommSemiring α] (n m : ℕ) (h : n < m + 1) :
#(Nat.Partition.distincts n) = coeff n (partialDistinctGF α m) := by
rw [← partialDistinctGF_prop, Nat.Partition.distincts]
congr with p
apply (and_iff_left _).symm
intro i hi
have : i ≤ n := by
simpa [p.parts_sum] using Multiset.single_le_sum (fun _ _ => Nat.zero_le _) _ hi
simp only [mem_range, Function.Embedding.coeFn_mk, mem_map]
refine ⟨i - 1, ?_, Nat.succ_pred_eq_of_pos (p.parts_pos hi)⟩
rw [tsub_lt_iff_right (Nat.one_le_iff_ne_zero.mpr (p.parts_pos hi).ne')]
exact lt_of_le_of_lt this h
/-- The key proof idea for the partition theorem, showing that the generating functions for both
sequences are ultimately the same (since the factor converges to 0 as m tends to infinity).
It's enough to not take the limit though, and just consider large enough `m`.
-/
theorem same_gf [Field α] (m : ℕ) :
(partialOddGF α m * (range m).prod fun i => 1 - (X : PowerSeries α) ^ (m + i + 1)) =
partialDistinctGF α m := by
rw [partialOddGF, partialDistinctGF]
induction m with
| zero => simp
| succ m ih => ?_
set! π₀ : PowerSeries α := ∏ i ∈ range m, (1 - X ^ (m + 1 + i + 1)) with hπ₀
set! π₁ : PowerSeries α := ∏ i ∈ range m, (1 - X ^ (2 * i + 1))⁻¹ with hπ₁
set! π₂ : PowerSeries α := ∏ i ∈ range m, (1 - X ^ (m + i + 1)) with hπ₂
set! π₃ : PowerSeries α := ∏ i ∈ range m, (1 + X ^ (i + 1)) with hπ₃
rw [← hπ₃] at ih
have h : constantCoeff (1 - X ^ (2 * m + 1) : α⟦X⟧) ≠ 0 := by
rw [RingHom.map_sub, RingHom.map_pow, constantCoeff_one, constantCoeff_X,
zero_pow (2 * m).succ_ne_zero, sub_zero]
exact one_ne_zero
calc
(∏ i ∈ range (m + 1), (1 - X ^ (2 * i + 1))⁻¹) *
∏ i ∈ range (m + 1), (1 - X ^ (m + 1 + i + 1)) =
π₁ * (1 - X ^ (2 * m + 1))⁻¹ * (π₀ * (1 - X ^ (m + 1 + m + 1))) := by
rw [prod_range_succ _ m, ← hπ₁, prod_range_succ _ m, ← hπ₀]
_ = π₁ * (1 - X ^ (2 * m + 1))⁻¹ * (π₀ * ((1 + X ^ (m + 1)) * (1 - X ^ (m + 1)))) := by
rw [← sq_sub_sq, one_pow, add_assoc _ m 1, ← two_mul (m + 1), pow_mul']
_ = π₀ * (1 - X ^ (m + 1)) * (1 - X ^ (2 * m + 1))⁻¹ * (π₁ * (1 + X ^ (m + 1))) := by ring
_ =
(∏ i ∈ range (m + 1), (1 - X ^ (m + 1 + i))) * (1 - X ^ (2 * m + 1))⁻¹ *
(π₁ * (1 + X ^ (m + 1))) := by
rw [prod_range_succ', add_zero, hπ₀]; simp_rw [← add_assoc]
_ = π₂ * (1 - X ^ (m + 1 + m)) * (1 - X ^ (2 * m + 1))⁻¹ * (π₁ * (1 + X ^ (m + 1))) := by
rw [add_right_comm, hπ₂, ← prod_range_succ]; simp_rw [add_right_comm]
_ = π₂ * (1 - X ^ (2 * m + 1)) * (1 - X ^ (2 * m + 1))⁻¹ * (π₁ * (1 + X ^ (m + 1))) := by
rw [two_mul, add_right_comm _ m 1]
_ = (1 - X ^ (2 * m + 1)) * (1 - X ^ (2 * m + 1))⁻¹ * π₂ * (π₁ * (1 + X ^ (m + 1))) := by ring
_ = π₂ * (π₁ * (1 + X ^ (m + 1))) := by rw [PowerSeries.mul_inv_cancel _ h, one_mul]
_ = π₁ * π₂ * (1 + X ^ (m + 1)) := by ring
_ = π₃ * (1 + X ^ (m + 1)) := by rw [ih]
_ = _ := by rw [prod_range_succ]
theorem same_coeffs [Field α] (m n : ℕ) (h : n ≤ m) :
coeff n (partialOddGF α m) = coeff n (partialDistinctGF α m) := by
rw [← same_gf, coeff_mul_prod_one_sub_of_lt_order]
rintro i -
rw [order_X_pow]
exact mod_cast Nat.lt_succ_of_le (le_add_right h)
theorem partition_theorem (n : ℕ) : #(Nat.Partition.odds n) = #(Nat.Partition.distincts n) := by
-- We need the counts to live in some field (which contains ℕ), so let's just use ℚ
suffices (#(Nat.Partition.odds n) : ℚ) = #(Nat.Partition.distincts n) from
mod_cast this
rw [distinctGF_prop n (n + 1) (by linarith)]
rw [oddGF_prop n (n + 1) (by linarith)]
apply same_coeffs (n + 1) n n.le_succ
end
end Theorems100 |
.lake/packages/mathlib/Archive/Wiedijk100Theorems/AreaOfACircle.lean | import Mathlib.Analysis.SpecialFunctions.Sqrt
import Mathlib.Analysis.SpecialFunctions.Trigonometric.InverseDeriv
import Mathlib.MeasureTheory.Integral.IntervalIntegral.FundThmCalculus
import Mathlib.MeasureTheory.Measure.Lebesgue.Integral
/-!
# Freek № 9: The Area of a Circle
In this file we show that the area of a disc with nonnegative radius `r` is `π * r^2`. The main
tools our proof uses are `volume_regionBetween_eq_integral`, which allows us to represent the area
of the disc as an integral, and `intervalIntegral.integral_eq_sub_of_hasDerivAt_of_le`, the
second fundamental theorem of calculus.
We begin by defining `disc` in `ℝ × ℝ`, then show that `disc` can be represented as the
`regionBetween` two functions.
Though not necessary for the main proof, we nonetheless choose to include a proof of the
measurability of the disc in order to convince the reader that the set whose volume we will be
calculating is indeed measurable and our result is therefore meaningful.
In the main proof, `area_disc`, we use `volume_regionBetween_eq_integral` followed by
`intervalIntegral.integral_of_le` to reduce our goal to a single `intervalIntegral`:
`∫ (x : ℝ) in -r..r, 2 * sqrt (r ^ 2 - x ^ 2) = π * r ^ 2`.
After disposing of the trivial case `r = 0`, we show that `fun x => 2 * sqrt (r ^ 2 - x ^ 2)` is
equal to the derivative of `fun x => r ^ 2 * arcsin (x / r) + x * sqrt (r ^ 2 - x ^ 2)` everywhere
on `Ioo (-r) r` and that those two functions are continuous, then apply the second fundamental
theorem of calculus with those facts. Some simple algebra then completes the proof.
Note that we choose to define `disc` as a set of points in `ℝ × ℝ`. This is admittedly not ideal; it
would be more natural to define `disc` as a `Metric.ball` in `EuclideanSpace ℝ (Fin 2)` (as well as
to provide a more general proof in higher dimensions). However, our proof indirectly relies on a
number of theorems (particularly `MeasureTheory.Measure.prod_apply`) which do not yet exist for
Euclidean space, thus forcing us to use this less-preferable definition. As `MeasureTheory.pi`
continues to develop, it should eventually become possible to redefine `disc` and extend our proof
to the n-ball.
-/
open Set Real MeasureTheory intervalIntegral
open scoped Real NNReal
namespace Theorems100
/-- A disc of radius `r` is defined as the collection of points `(p.1, p.2)` in `ℝ × ℝ` such that
`p.1 ^ 2 + p.2 ^ 2 < r ^ 2`.
Note that this definition is not equivalent to `Metric.ball (0 : ℝ × ℝ) r`. This was done
intentionally because `dist` in `ℝ × ℝ` is defined as the uniform norm, making the `Metric.ball`
in `ℝ × ℝ` a square, not a disc.
See the module docstring for an explanation of why we don't define the disc in Euclidean space. -/
def disc (r : ℝ) :=
{p : ℝ × ℝ | p.1 ^ 2 + p.2 ^ 2 < r ^ 2}
variable (r : ℝ≥0)
/-- A disc of radius `r` can be represented as the region between the two curves
`fun x => - sqrt (r ^ 2 - x ^ 2)` and `fun x => sqrt (r ^ 2 - x ^ 2)`. -/
theorem disc_eq_regionBetween :
disc r =
regionBetween
(fun x => -sqrt (r ^ 2 - x ^ 2)) (fun x => sqrt (r ^ 2 - x ^ 2)) (Ioc (-r) r) := by
ext p
simp only [disc, regionBetween, mem_setOf_eq, mem_Ioo, mem_Ioc]
constructor <;> intro h
· cases abs_lt_of_sq_lt_sq' (lt_of_add_lt_of_nonneg_left h (sq_nonneg p.2)) r.2 with
| intro left right =>
rw [add_comm, ← lt_sub_iff_add_lt] at h
exact ⟨⟨left, right.le⟩, sq_lt.mp h⟩
· rw [add_comm, ← lt_sub_iff_add_lt]
exact sq_lt.mpr h.2
/-- The disc is a `MeasurableSet`. -/
theorem measurableSet_disc : MeasurableSet (disc r) := by
apply measurableSet_lt <;> apply Continuous.measurable <;> continuity
/-- **Area of a Circle**: The area of a disc with radius `r` is `π * r ^ 2`. -/
theorem area_disc : volume (disc r) = NNReal.pi * r ^ 2 := by
let f x := sqrt (r ^ 2 - x ^ 2)
let F x := (r : ℝ) ^ 2 * arcsin (r⁻¹ * x) + x * sqrt (r ^ 2 - x ^ 2)
have hf : Continuous f := by fun_prop
suffices ∫ x in -r..r, 2 * f x = NNReal.pi * r ^ 2 by
have h : IntegrableOn f (Ioc (-r) r) := hf.integrableOn_Icc.mono_set Ioc_subset_Icc_self
calc
volume (disc r) = volume (regionBetween (fun x => -f x) f (Ioc (-r) r)) := by
rw [disc_eq_regionBetween]
_ = ENNReal.ofReal (∫ x in Ioc (-r : ℝ) r, (f - Neg.neg ∘ f) x) :=
(volume_regionBetween_eq_integral h.neg h measurableSet_Ioc fun x _ =>
neg_le_self (sqrt_nonneg _))
_ = ENNReal.ofReal (∫ x in (-r : ℝ)..r, 2 * f x) := by
rw [integral_of_le] <;> simp [two_mul]
_ = NNReal.pi * r ^ 2 := by rw_mod_cast [this, ← ENNReal.coe_nnreal_eq]
have hle := NNReal.coe_nonneg r
obtain heq | hlt := hle.eq_or_lt; · simp [← heq]
have hderiv : ∀ x ∈ Ioo (-r : ℝ) r, HasDerivAt F (2 * f x) x := by
rintro x ⟨hx1, hx2⟩
convert
((hasDerivAt_const x ((r : ℝ) ^ 2)).fun_mul
((hasDerivAt_arcsin _ _).comp x
((hasDerivAt_const x (r : ℝ)⁻¹).fun_mul (hasDerivAt_id' x)))).fun_add
((hasDerivAt_id' x).fun_mul
((((hasDerivAt_id' x).fun_pow 2).const_sub ((r : ℝ) ^ 2)).sqrt _))
using 1
· have h₁ : (r:ℝ) ^ 2 - x ^ 2 > 0 := sub_pos_of_lt (sq_lt_sq' hx1 hx2)
have h : sqrt ((r:ℝ) ^ 2 - x ^ 2) ^ 3 = ((r:ℝ) ^ 2 - x ^ 2) * sqrt ((r: ℝ) ^ 2 - x ^ 2) := by
rw [pow_three, ← mul_assoc, mul_self_sqrt (by positivity)]
simp [f]
field_simp
simp (disch := positivity)
field
· suffices -(1 : ℝ) < (r : ℝ)⁻¹ * x by exact this.ne'
calc
-(1 : ℝ) = (r : ℝ)⁻¹ * -r := by simp [inv_mul_cancel₀ hlt.ne']
_ < (r : ℝ)⁻¹ * x := by nlinarith [inv_pos.mpr hlt]
· suffices (r : ℝ)⁻¹ * x < 1 by exact this.ne
calc
(r : ℝ)⁻¹ * x < (r : ℝ)⁻¹ * r := by nlinarith [inv_pos.mpr hlt]
_ = 1 := inv_mul_cancel₀ hlt.ne'
· nlinarith
calc
∫ x in -r..r, 2 * f x = F r - F (-r) :=
integral_eq_sub_of_hasDerivAt_of_le (neg_le_self r.2) (by fun_prop) hderiv
(continuous_const.mul hf).continuousOn.intervalIntegrable
_ = NNReal.pi * (r : ℝ) ^ 2 := by
norm_num [F, inv_mul_cancel₀ hlt.ne', ← mul_div_assoc, mul_comm π]
end Theorems100 |
.lake/packages/mathlib/Archive/Wiedijk100Theorems/BirthdayProblem.lean | import Mathlib.Data.Fintype.CardEmbedding
import Mathlib.Probability.UniformOn
import Mathlib.Probability.Notation
/-!
# Birthday Problem
This file proves Theorem 93 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/).
As opposed to the standard probabilistic statement, we instead state the birthday problem
in terms of injective functions. The general result about `Fintype.card (α ↪ β)` which this proof
uses is `Fintype.card_embedding_eq`.
-/
namespace Theorems100
local notation "|" x "|" => Finset.card x
local notation "‖" x "‖" => Fintype.card x
/-- **Birthday Problem**: set cardinality interpretation. -/
theorem birthday :
2 * ‖Fin 23 ↪ Fin 365‖ < ‖Fin 23 → Fin 365‖ ∧ 2 * ‖Fin 22 ↪ Fin 365‖ > ‖Fin 22 → Fin 365‖ := by
simp only [Fintype.card_fin, Fintype.card_embedding_eq, Fintype.card_fun]
decide
section MeasureTheory
open MeasureTheory ProbabilityTheory
open scoped ProbabilityTheory ENNReal
variable {n m : ℕ}
/- In order for Lean to understand that we can take probabilities in `Fin 23 → Fin 365`, we must
tell Lean that there is a `MeasurableSpace` structure on the space. Note that this instance
is only for `Fin m` - Lean automatically figures out that the function space `Fin n → Fin m`
is _also_ measurable, by using `MeasurableSpace.pi`, and furthermore that all sets are measurable,
from `MeasurableSingletonClass.pi`. -/
instance : MeasurableSpace (Fin m) :=
⊤
instance : MeasurableSingletonClass (Fin m) :=
⟨fun _ => trivial⟩
/- We then endow the space with a canonical measure, which is called ℙ.
We define this to be the conditional counting measure. -/
noncomputable instance measureSpace : MeasureSpace (Fin n → Fin m) :=
⟨uniformOn Set.univ⟩
-- The canonical measure on `Fin n → Fin m` is a probability measure (except on an empty space).
instance : IsProbabilityMeasure (ℙ : Measure (Fin n → Fin (m + 1))) :=
uniformOn_isProbabilityMeasure Set.finite_univ Set.univ_nonempty
theorem FinFin.measure_apply {s : Set <| Fin n → Fin m} :
ℙ s = |s.toFinite.toFinset| / ‖Fin n → Fin m‖ := by
rw [volume, measureSpace, uniformOn_univ, Measure.count_apply_finite]
/-- **Birthday Problem**: first probabilistic interpretation. -/
theorem birthday_measure :
ℙ ({f | (Function.Injective f)} : Set ((Fin 23) → (Fin 365))) < 1 / 2 := by
rw [FinFin.measure_apply]
generalize_proofs hfin
have : |hfin.toFinset| = 42200819302092359872395663074908957253749760700776448000000 := by
trans ‖Fin 23 ↪ Fin 365‖
· rw [← Fintype.card_coe]
apply Fintype.card_congr
rw [Set.Finite.coeSort_toFinset, Set.coe_setOf]
exact Equiv.subtypeInjectiveEquivEmbedding _ _
· rw [Fintype.card_embedding_eq, Fintype.card_fin, Fintype.card_fin]
rfl
rw [this, ENNReal.lt_div_iff_mul_lt, mul_comm, mul_div, ENNReal.div_lt_iff]
all_goals
simp only [Fintype.card_pi, Fintype.card_fin, Finset.prod_const, Finset.card_univ]
norm_num
end MeasureTheory
end Theorems100 |
.lake/packages/mathlib/Archive/Imo/Imo2019Q1.lean | import Mathlib.Tactic.Linarith
import Mathlib.Tactic.Ring
/-!
# IMO 2019 Q1
Determine all functions `f : ℤ → ℤ` such that, for all integers `a` and `b`,
`f(2a) + 2f(b) = f(f(a+b))`.
The desired theorem is that either:
- `f = fun _ ↦ 0`
- `∃ c, f = fun x ↦ 2 * x + c`
Note that there is a much more compact proof of this fact in Isabelle/HOL
- http://downthetypehole.de/paste/4YbGgqb4
-/
theorem imo2019_q1 (f : ℤ → ℤ) :
(∀ a b : ℤ, f (2 * a) + 2 * f b = f (f (a + b))) ↔ f = 0 ∨ ∃ c, f = fun x => 2 * x + c := by
constructor; swap
-- easy way: f(x)=0 and f(x)=2x+c work.
· rintro (rfl | ⟨c, rfl⟩) <;> intros <;> norm_num; ring
-- hard way.
intro hf
-- functional equation
-- Using `h` for `(0, b)` and `(-1, b + 1)`, we get `f (b + 1) = f b + m`
obtain ⟨m, H⟩ : ∃ m, ∀ b, f (b + 1) = f b + m := by
refine ⟨(f 0 - f (-2)) / 2, fun b => ?_⟩
refine sub_eq_iff_eq_add'.1 (Int.eq_ediv_of_mul_eq_right two_ne_zero ?_)
have h1 : f 0 + 2 * f b = f (f b) := by simpa using hf 0 b
have h2 : f (-2) + 2 * f (b + 1) = f (f b) := by simpa using hf (-1) (b + 1)
linarith
-- Hence, `f` is an affine map, `f b = f 0 + m * b`
obtain ⟨c, H⟩ : ∃ c, ∀ b, f b = c + m * b := by
refine ⟨f 0, fun b => ?_⟩
induction b with
| zero => simp
| succ b ihb => simp [H, ihb, mul_add, add_assoc]
| pred b ihb =>
rw [← sub_eq_of_eq_add (H _)]
simp [ihb]; ring
-- Now use `hf 0 0` and `hf 0 1` to show that `m ∈ {0, 2}`
have H3 : 2 * c = m * c := by simpa [H, mul_add] using hf 0 0
obtain rfl | rfl : 2 = m ∨ m = 0 := by simpa [H, mul_add, H3] using hf 0 1
· right; use c; ext b; simp [H, add_comm]
· left; ext b; simpa [H, two_ne_zero] using H3 |
.lake/packages/mathlib/Archive/Imo/Imo2024Q3.lean | import Mathlib.Algebra.Order.Sub.Basic
import Mathlib.Algebra.Ring.Parity
import Mathlib.Data.Fintype.Pigeonhole
import Mathlib.Data.Nat.Nth
import Mathlib.Tactic.ApplyFun
/-!
# IMO 2024 Q3
Let $a_1, a_2, a_3, \ldots$ be an infinite sequence of positive integers, and let $N$ be a
positive integer. Suppose that, for each $n > N$, $a_n$ is equal to the number of times
$a_{n-1}$ appears in the list $a_1, a_2, \ldots, a_{n-1}$.
Prove that at least one of the sequences $a_1, a_3, a_5, \ldots$ and $a_2, a_4, a_6, \ldots$
is eventually periodic.
We follow Solution 1 from the
[official solutions](https://www.imo2024.uk/s/IMO2024-solutions-updated.pdf). We show that
the positive integers up to some positive integer $k$ (referred to as small numbers) all appear
infinitely often in the given sequence while all larger positive integers appear only finitely
often and then that the sequence eventually alternates between small numbers and larger integers.
A further detailed analysis of the eventual behavior of the sequence ends up showing that the
sequence of small numbers is eventually periodic with period at most $k$ (in fact exactly $k$).
-/
open scoped Finset
namespace Imo2024Q3
/-- The condition of the problem. Following usual Lean conventions, this is expressed with
indices starting from 0, rather than from 1 as in the informal statement (but `N` remains as the
index of the last term for which `a n` is not defined in terms of previous terms). -/
def Condition (a : ℕ → ℕ) (N : ℕ) : Prop :=
(∀ i, 0 < a i) ∧ ∀ n, N < n → a n = #{i ∈ Finset.range n | a i = a (n - 1)}
/-- The property of a sequence being eventually periodic. -/
def EventuallyPeriodic (b : ℕ → ℕ) : Prop := ∃ p M, 0 < p ∧ ∀ m, M ≤ m → b (m + p) = b m
/-! ### Definitions and lemmas about the sequence that do not actually need the condition of
the problem -/
/-- A number greater than any of the initial terms `a 0` through `a N` (otherwise arbitrary). -/
def M (a : ℕ → ℕ) (N : ℕ) : ℕ := (Finset.range (N + 1)).sup a + 1
lemma M_pos (a : ℕ → ℕ) (N : ℕ) : 0 < M a N :=
Nat.add_one_pos _
lemma one_le_M (a : ℕ → ℕ) (N : ℕ) : 1 ≤ M a N :=
Nat.lt_iff_add_one_le.1 (M_pos a N)
lemma apply_lt_M_of_le_N (a : ℕ → ℕ) {N i : ℕ} (h : i ≤ N) : a i < M a N :=
Nat.lt_add_one_iff.2 (Finset.le_sup (by grind))
lemma N_lt_of_M_le_apply {a : ℕ → ℕ} {N i : ℕ} (h : M a N ≤ a i) : N < i := by
by_contra! hi
exact Nat.not_succ_le_self _ (h.trans (Finset.le_sup (by grind)))
lemma ne_zero_of_M_le_apply {a : ℕ → ℕ} {N i : ℕ} (h : M a N ≤ a i) : i ≠ 0 :=
Nat.ne_zero_of_lt (N_lt_of_M_le_apply h)
lemma apply_lt_of_M_le_apply {a : ℕ → ℕ} {N i j : ℕ} (hi : M a N ≤ a i) (hj : j ≤ N) :
a j < a i :=
(apply_lt_M_of_le_N a hj).trans_le hi
lemma apply_ne_of_M_le_apply {a : ℕ → ℕ} {N i j : ℕ} (hi : M a N ≤ a i) (hj : j ≤ N) :
a j ≠ a i :=
(apply_lt_of_M_le_apply hi hj).ne
lemma toFinset_card_pos {a : ℕ → ℕ} {i : ℕ} (hf : {j | a j = a i}.Finite) : 0 < #hf.toFinset :=
Finset.card_pos.mpr ((Set.Finite.toFinset_nonempty _).mpr ⟨i, rfl⟩)
lemma apply_nth_zero (a : ℕ → ℕ) (i : ℕ) : a (Nat.nth (a · = a i) 0) = a i :=
Nat.nth_mem (p := (a · = a i)) 0 toFinset_card_pos
lemma map_add_one_range (p : ℕ → Prop) [DecidablePred p] (n : ℕ) (h0 : ¬ p 0) :
{x ∈ Finset.range n | p (x + 1)}.map ⟨(· + 1), add_left_injective 1⟩ =
{x ∈ Finset.range (n + 1) | p x } := by
ext x
simp only [Finset.mem_map]
constructor
· aesop
· intro hx
use x - 1
cases x <;> simp_all
namespace Condition
/-! ### The basic structure of the sequence, eventually alternating small and large numbers -/
variable {a : ℕ → ℕ} {N : ℕ} (hc : Condition a N)
include hc
protected lemma pos (n : ℕ) : 0 < a n := hc.1 n
@[simp] lemma apply_ne_zero (n : ℕ) : a n ≠ 0 :=
(hc.pos _).ne'
lemma one_le_apply (n : ℕ) : 1 ≤ a n :=
Nat.one_le_iff_ne_zero.2 (hc.apply_ne_zero n)
lemma apply_eq_card {n : ℕ} (h : N < n) : a n = #{i ∈ Finset.range n | a i = a (n - 1)} :=
hc.2 n h
lemma apply_add_one_eq_card {n : ℕ} (h : N ≤ n) :
a (n + 1) = #{i ∈ Finset.range (n + 1) | a i = a n} := by
rw [hc.apply_eq_card (Nat.lt_add_one_of_le h)]
simp
@[simp] lemma nth_apply_eq_zero (n : ℕ) : Nat.nth (a · = 0) n = 0 := by
convert Nat.nth_false _ with i
simp only [(hc.pos i).ne']
lemma nth_apply_add_one_eq {n : ℕ} (h : N ≤ n) : Nat.nth (a · = a n) (a (n + 1) - 1) = n := by
rw [hc.apply_add_one_eq_card h]
nth_rw 5 [← Nat.nth_count (p := (a · = a n)) rfl]
simp [Finset.range_add_one, Finset.filter_insert, Nat.count_eq_card_filter_range]
lemma apply_nth_add_one_eq {m n : ℕ} (hfc : ∀ hf : {i | a i = m}.Finite, n < #hf.toFinset)
(hn : N ≤ Nat.nth (a · = m) n) : a (Nat.nth (a · = m) n + 1) = n + 1 := by
rw [hc.apply_eq_card (Nat.lt_add_one_of_le hn), add_tsub_cancel_right,
← Nat.count_eq_card_filter_range, Nat.nth_mem n hfc, Nat.count_nth_succ hfc]
lemma apply_nth_add_one_eq_of_infinite {m n : ℕ} (hi : {i | a i = m}.Infinite)
(hn : N ≤ Nat.nth (a · = m) n) : a (Nat.nth (a · = m) n + 1) = n + 1 :=
hc.apply_nth_add_one_eq (fun hf ↦ absurd hf hi) hn
lemma apply_nth_add_one_eq_of_lt {m n : ℕ} (hn : N < Nat.nth (a · = m) n) :
a (Nat.nth (a · = m) n + 1) = n + 1 := by
refine hc.apply_nth_add_one_eq ?_ hn.le
by_contra! hf
have := Nat.nth_eq_zero.2 (.inr hf)
omega
lemma lt_toFinset_card {j : ℕ} (h : M a N ≤ a (j + 1)) (hf : {i | a i = a j}.Finite) :
M a N - 1 < #hf.toFinset := by
rw [Nat.sub_lt_iff_lt_add' (M_pos _ _), Nat.lt_one_add_iff]
exact (hc.apply_eq_card (N_lt_of_M_le_apply h) ▸ h).trans (Finset.card_le_card (by simp))
lemma nth_ne_zero_of_M_le_of_lt {i k : ℕ} (hi : M a N ≤ a i) (hk : k < a (i + 1)) :
Nat.nth (a · = a i) k ≠ 0 :=
Nat.nth_ne_zero_anti (apply_ne_of_M_le_apply hi (Nat.zero_le _)) (by omega)
(hc.nth_apply_add_one_eq (N_lt_of_M_le_apply hi).le ▸ ne_zero_of_M_le_apply hi)
lemma apply_add_one_lt_of_apply_eq {i j : ℕ} (hi : N ≤ i) (hij : i < j) (ha : a i = a j) :
a (i + 1) < a (j + 1) := by
rw [hc.apply_add_one_eq_card hi, hc.apply_add_one_eq_card (by omega), ha]
refine Finset.card_lt_card (Finset.ssubset_def.mp ⟨Finset.filter_subset_filter _
(by simp [hij.le]), Finset.not_subset.mpr ⟨j, ?_⟩⟩)
simp only [Finset.mem_filter, Finset.mem_range, lt_add_iff_pos_right, and_true]
omega
lemma apply_add_one_ne_of_apply_eq {i j : ℕ} (hi : N ≤ i) (hj : N ≤ j) (hij : i ≠ j)
(ha : a i = a j) : a (i + 1) ≠ a (j + 1) :=
hij.lt_or_gt.elim (fun h ↦ (hc.apply_add_one_lt_of_apply_eq hi h ha).ne) fun h ↦
(hc.apply_add_one_lt_of_apply_eq hj h ha.symm).ne'
lemma exists_infinite_setOf_apply_eq : ∃ m, {i | a i = m}.Infinite := by
by_contra hi
have hr : (Set.range a).Infinite := by
contrapose! hi with hr
rw [Set.not_infinite, ← Set.finite_coe_iff] at hr
obtain ⟨n, hn⟩ := Finite.exists_infinite_fiber (Set.rangeFactorization a)
rw [Set.infinite_coe_iff, Set.preimage] at hn
simp only [Set.mem_singleton_iff, Set.rangeFactorization, Subtype.ext_iff] at hn
exact ⟨↑n, hn⟩
simp only [not_exists, Set.not_infinite] at hi
have hinj : Set.InjOn (fun i ↦ Nat.nth (a · = i) 0 + 1) (Set.range a \ Set.Ico 0 (M a N)) := by
rintro _ ⟨⟨_, rfl⟩, hi⟩ _ ⟨⟨_, rfl⟩, hj⟩ h
simp only [Set.mem_Ico, zero_le, true_and, not_lt] at hi hj
simp only [add_left_inj] at h
convert congr(a $h) using 1 <;> simp [apply_nth_zero]
refine Set.not_infinite.2 (hi 1) (Set.infinite_of_injOn_mapsTo hinj (fun i hi ↦ ?_)
(hr.diff (Set.finite_Ico _ _)))
simp only [Set.mem_diff, Set.mem_range, Set.mem_Ico, zero_le, true_and, not_lt] at hi
rcases hi with ⟨⟨_, rfl⟩, hi⟩
exact hc.apply_nth_add_one_eq toFinset_card_pos
(N_lt_of_M_le_apply (a := a) (by simp only [apply_nth_zero, hi])).le
lemma nonempty_setOf_infinite_setOf_apply_eq : {m | {i | a i = m}.Infinite}.Nonempty :=
hc.exists_infinite_setOf_apply_eq
lemma injOn_setOf_apply_add_one_eq_of_M_le {n : ℕ} (h : M a N ≤ n) :
Set.InjOn a {i | a (i + 1) = n} := by
intro i hi j hj hij
have hi' := hi ▸ hc.nth_apply_add_one_eq (Nat.lt_add_one_iff.mp (N_lt_of_M_le_apply (hi ▸ h)))
have hj' := hj ▸ hc.nth_apply_add_one_eq (Nat.lt_add_one_iff.mp (N_lt_of_M_le_apply (hj ▸ h)))
rw [← hi', ← hj', hij]
lemma empty_consecutive_apply_ge_M : {i | M a N ≤ a i ∧ M a N ≤ a (i + 1)} = ∅ := by
rw [Set.eq_empty_iff_forall_notMem]
intro i
induction i using Nat.strong_induction_on with | h i ih =>
-- Let i be the first index where both `a i` and `a (i + 1)` are at least M.
rintro ⟨hi1, hi2⟩
have hi : ∀ j < i, M a N ≤ a j → a (j + 1) < M a N := by simp_all
-- t is the set of indices before an appearance of the integer (a i). For each j ∈ t, (a j)
-- is the (a i)th appearance of that value, so each such value before index i appears at least
-- M times before that index; since (a i) is the (at least) Mth appearance of that value, there
-- are at least M positive integers appearing M times before (a i), a contradiction because one of
-- those must be at least M.
let t : Finset ℕ := {j ∈ Finset.range i | a (j + 1) = a i}
let t' : Finset ℕ := {j ∈ Finset.range (i + 1) | a j = a i}
have t_map_eq_t' : t.map ⟨(· + 1), add_left_injective 1⟩ = t' := by
refine map_add_one_range (a · = a i) i ?_
intro H
rw [←H, M] at hi1
have a0_le : a 0 ≤ (Finset.range (N + 1)).sup a := Finset.le_sup (by simp)
omega
have card_t_eq_card_t' : #t = #t' := by simp [← t_map_eq_t', t]
have htM : ∀ j ∈ t, a j < M a N := by
intro j hj
simp only [t, Finset.mem_filter, Finset.mem_range] at hj
grind
have N_le_i : N ≤ i := by
unfold M at hi1
by_contra! HH
have i_in_range : i ∈ Finset.range (N + 1) := by rw [Finset.mem_range]; omega
have ai_le_sup : a i ≤ (Finset.range (N + 1)).sup a := Finset.le_sup i_in_range
omega
have ht' : a (i + 1) = #t' := hc.apply_add_one_eq_card N_le_i
rw [← card_t_eq_card_t'] at ht'
have ht'inj : Set.InjOn a t := by
refine (hc.injOn_setOf_apply_add_one_eq_of_M_le hi1).mono ?_
simp_all [t, t']
have card_image_eq_card_t : #(Finset.image a t) = #t := Finset.card_image_of_injOn ht'inj
have card_image_lt_M : #(Finset.image a t) < M a N := by
refine (Finset.card_le_card (t := Finset.Ico 1 (M a N)) ?_).trans_lt ?_
· simp only [Finset.subset_iff, Finset.mem_image, Finset.mem_Ico, forall_exists_index, and_imp,
forall_apply_eq_imp_iff₂]
exact fun j hj ↦ ⟨hc.pos _, htM j hj⟩
· simpa using M_pos a N
omega
lemma card_lt_M_of_M_le {n : ℕ} (h : M a N ≤ n) :
∃ hf : {i | a i = n}.Finite, #hf.toFinset < M a N := by
have := empty_consecutive_apply_ge_M hc
contrapose! this with hin
use Nat.nth (a · = n) (M a N - 1)
have hin' := fun hf ↦ Nat.sub_one_lt_of_le (M_pos a N) (hin hf)
have ha : M a N ≤ a (Nat.nth (a · = n) (M a N - 1)) := (Nat.nth_mem _ hin').symm ▸ h
refine ⟨ha, ?_⟩
suffices H : a (Nat.nth (fun x ↦ a x = n) (M a N - 1) + 1) = M a N from Nat.le_of_eq H.symm
convert hc.apply_nth_add_one_eq hin' (N_lt_of_M_le_apply ha).le using 1
lemma bddAbove_setOf_infinite_setOf_apply_eq : BddAbove {m | {i | a i = m}.Infinite} := by
refine ⟨M a N, fun x hi ↦ ?_⟩
by_contra hx
exact hi (hc.card_lt_M_of_M_le (not_le.mp hx).le).1
lemma infinite_setOf_apply_eq_anti {j k : ℕ} (hj : 0 < j) (hk : {i | a i = k}.Infinite)
(hjk : j ≤ k) : {i | a i = j}.Infinite := by
have hk' : {i | a (i + 1) = k}.Infinite := by
have hinj : Set.InjOn (· + 1) {i | a (i + 1) = k} := (add_left_injective _).injOn
rw [← Set.infinite_image_iff hinj]
have hk0 : ({i | a i = k} \ {0}).Infinite := hk.diff (Set.finite_singleton _)
convert hk0 using 1
ext i
simp only [Set.mem_image, Set.mem_setOf_eq, Set.mem_diff, Set.mem_singleton_iff]
refine ⟨?_, ?_⟩
· rintro ⟨j, rfl, rfl⟩
simp
· rintro ⟨rfl, h⟩
exact ⟨i - 1, by simp [(by omega : i - 1 + 1 = i)]⟩
have hinj : Set.InjOn (fun x ↦ Nat.nth (a · = a x) (j - 1) + 1)
({i | a (i + 1) = k} \ Set.Ico 0 N) := by
intro x hx y hy h
simp only [Set.mem_diff, Set.mem_setOf_eq, Set.mem_Ico, zero_le, true_and, not_lt] at hx hy
rcases hx with ⟨hxk, hNx⟩
rcases hy with ⟨hyk, hNy⟩
simp only [add_left_inj] at h
have hxk' : Nat.nth (a · = a x) (k - 1) = x := by rw [← hxk, hc.nth_apply_add_one_eq hNx]
have hyk' : Nat.nth (a · = a y) (k - 1) = y := by rw [← hyk, hc.nth_apply_add_one_eq hNy]
have hjk' : j - 1 ≤ k - 1 := by omega
apply_fun a at hxk' hyk'
have hyj : a (Nat.nth (a · = a y) (j - 1)) = a y :=
Nat.nth_mem_anti (p := (a · = a y)) hjk' hyk'
rw [← h, Nat.nth_mem_anti (p := (a · = a x)) hjk' hxk'] at hyj
by_contra hxy
exact hc.apply_add_one_ne_of_apply_eq hNx hNy hxy hyj (hyk ▸ hxk)
have hk'' : (_ \ Set.Ico 0 (N + 2)).Infinite :=
((Set.infinite_image_iff hinj).mpr (hk'.diff (Set.finite_Ico _ _))).diff (Set.finite_Ico _ _)
refine hk''.mono fun _ hi ↦ ?_
simp only [Set.mem_image, Set.mem_diff, Set.mem_setOf_eq, Set.mem_Ico, zero_le, true_and,
not_lt] at hi
rcases hi with ⟨⟨x, -, rfl⟩, _⟩
rw [Set.mem_setOf_eq, hc.apply_nth_add_one_eq_of_lt (by omega), Nat.sub_add_cancel hj]
/-! ### The definitions of small, medium and big numbers and the eventual alternation -/
variable (a)
/-- The largest number to appear infinitely often. -/
noncomputable def k : ℕ := sSup {m | {i | a i = m}.Infinite}
/-- Small numbers are those that are at most `k` (that is, those that appear infinitely often). -/
def Small (j : ℕ) : Prop := j ≤ k a
variable {a}
lemma infinite_setOf_apply_eq_k : {i | a i = k a}.Infinite :=
Nat.sSup_mem hc.nonempty_setOf_infinite_setOf_apply_eq hc.bddAbove_setOf_infinite_setOf_apply_eq
lemma infinite_setOf_apply_eq_iff_small {j : ℕ} (hj : 0 < j) :
{i | a i = j}.Infinite ↔ Small a j :=
⟨fun h ↦ le_csSup hc.bddAbove_setOf_infinite_setOf_apply_eq h,
fun h ↦ hc.infinite_setOf_apply_eq_anti hj hc.infinite_setOf_apply_eq_k h⟩
lemma finite_setOf_apply_eq_iff_not_small {j : ℕ} (hj : 0 < j) :
{i | a i = j}.Finite ↔ ¬Small a j := by
simpa only [Set.not_infinite] using (hc.infinite_setOf_apply_eq_iff_small hj).not
lemma finite_setOf_apply_eq_k_add_one : {i | a i = k a + 1}.Finite := by
rw [hc.finite_setOf_apply_eq_iff_not_small (by omega), Small]
omega
/-- There are only finitely many `m` that appear more than `k` times. -/
lemma finite_setOf_k_lt_card : {m | ∀ hf : {i | a i = m}.Finite, k a < #hf.toFinset}.Finite := by
rw [← Set.finite_image_iff]
· refine Set.Finite.of_diff (hc.finite_setOf_apply_eq_k_add_one.subset fun i hi ↦ ?_)
(Set.finite_Iic N)
simp only [Set.mem_diff, Set.mem_image, Set.mem_setOf_eq, Set.mem_Iic, not_le] at hi
rcases hi with ⟨⟨j, hjf, rfl⟩, hNi⟩
rw [Set.mem_setOf_eq, hc.apply_nth_add_one_eq hjf (by omega)]
· intro i hi j hj hij
simp only [add_left_inj] at hij
apply_fun a at hij
rwa [Nat.nth_mem _ hi, Nat.nth_mem _ hj] at hij
lemma bddAbove_setOf_k_lt_card : BddAbove {m | ∀ hf : {i | a i = m}.Finite, k a < #hf.toFinset} :=
hc.finite_setOf_k_lt_card.bddAbove
lemma k_pos : 0 < k a := by
by_contra! hn
apply nonpos_iff_eq_zero.mp hn ▸ hc.infinite_setOf_apply_eq_k
convert Set.finite_empty
ext i
simp [(hc.pos i).ne']
lemma small_one : Small a 1 := by
by_contra hns
simp only [Small, not_le, Nat.lt_one_iff, hc.k_pos.ne'] at hns
lemma infinite_setOf_apply_eq_one : {i | a i = 1}.Infinite :=
(hc.infinite_setOf_apply_eq_iff_small (by decide)).mpr hc.small_one
variable (a)
/-- The largest number to appear more than `k` times. -/
noncomputable def l : ℕ := sSup {m | ∀ hf : {i | a i = m}.Finite, k a < #hf.toFinset}
/-- Medium numbers are those that are more than `k` but at most `l` (and include all numbers
appearing finitely often but more than `k` times). -/
def Medium (j : ℕ) : Prop := k a < j ∧ j ≤ l a
/-- Big numbers are those greater than `l` (thus, appear at most `k` times). -/
def Big (j : ℕ) : Prop := l a < j
variable {a}
lemma k_le_l : k a ≤ l a :=
le_csSup hc.bddAbove_setOf_k_lt_card (fun hf ↦ absurd hf hc.infinite_setOf_apply_eq_k)
lemma k_lt_of_big {j : ℕ} (h : Big a j) : k a < j :=
hc.k_le_l.trans_lt h
lemma pos_of_big {j : ℕ} (h : Big a j) : 0 < j :=
(Nat.zero_le _).trans_lt (hc.k_lt_of_big h)
lemma not_small_of_big {j : ℕ} (h : Big a j) : ¬Small a j := by simp [Small, hc.k_lt_of_big h]
lemma exists_card_le_of_big {j : ℕ} (h : Big a j) :
∃ hf : {i | a i = j}.Finite, #hf.toFinset ≤ k a := by
have hns := hc.not_small_of_big h
rw [← hc.finite_setOf_apply_eq_iff_not_small (hc.pos_of_big h)] at hns
use hns
by_contra! hlt
exact notMem_of_csSup_lt h hc.bddAbove_setOf_k_lt_card fun _ ↦ hlt
variable (a N)
/-- `N'aux` is such that, by position `N'aux`, every medium number has made all its appearances
and every small number has appeared more than max(k, N+1) times. -/
noncomputable def N'aux : ℕ :=
sSup {i | Medium a (a i)} ⊔ sSup ((fun i ↦ Nat.nth (a · = i) (k a ⊔ (N + 1))) '' Set.Iic (k a))
/-- `N'` is such that, by position `N'`, every medium number has made all its appearances
and every small number has appeared more than max(k, N+1) times; furthermore, `a N'` is small
(which means that every subsequent big number is preceded by a small number). -/
noncomputable def N' : ℕ := by
classical
exact N'aux a N + (if Small a (a (N'aux a N + 1)) then 1 else 2)
variable {a N}
lemma not_medium_of_N'aux_lt {j : ℕ} (h : N'aux a N < j) : ¬Medium a (a j) := by
let s : Set ℕ := ⋃ i ∈ Set.Ioc (k a) (l a), {j | a j = i}
have hf : s.Finite := by
refine (Set.finite_Ioc _ _).biUnion ?_
rintro i ⟨hk, -⟩
rwa [hc.finite_setOf_apply_eq_iff_not_small (by omega), Small, not_le]
exact fun hm ↦ notMem_of_csSup_lt (le_sup_left.trans_lt h)
(hf.subset fun i hi ↦ (by simpa [s] using hi)).bddAbove hm
lemma small_or_big_of_N'aux_lt {j : ℕ} (h : N'aux a N < j) : Small a (a j) ∨ Big a (a j) := by
have _ := hc.not_medium_of_N'aux_lt h
rw [Small, Medium, Big] at *
omega
lemma small_or_big_of_N'_le {j : ℕ} (h : N' a N ≤ j) : Small a (a j) ∨ Big a (a j) := by
refine hc.small_or_big_of_N'aux_lt ?_
rw [N'] at h
split_ifs at h <;> omega
omit hc
lemma nth_sup_k_N_add_one_le_N'aux_of_small {j : ℕ} (h : Small a j) :
Nat.nth (a · = j) (k a ⊔ (N + 1)) ≤ N'aux a N := by
by_contra! hn
exact notMem_of_csSup_lt (le_sup_right.trans_lt hn) ((Set.finite_Iic _).image _).bddAbove
⟨j, h, rfl⟩
include hc
lemma nth_sup_k_le_N'aux_of_small {j : ℕ} (h : Small a j) :
Nat.nth (a · = j) (k a) ≤ N'aux a N :=
match j with
| 0 => by simp only [hc.nth_apply_eq_zero, zero_le]
| j + 1 => ((Nat.nth_le_nth ((hc.infinite_setOf_apply_eq_iff_small (Nat.zero_lt_succ j)).mpr h)).2
le_sup_left).trans (nth_sup_k_N_add_one_le_N'aux_of_small h)
lemma nth_sup_N_add_one_le_N'aux_of_small {j : ℕ} (h : Small a j) :
Nat.nth (a · = j) (N + 1) ≤ N'aux a N :=
match j with
| 0 => by simp only [hc.nth_apply_eq_zero, zero_le]
| j + 1 => ((Nat.nth_le_nth ((hc.infinite_setOf_apply_eq_iff_small (Nat.zero_lt_succ j)).mpr h)).2
le_sup_right).trans (nth_sup_k_N_add_one_le_N'aux_of_small h)
lemma N_lt_N'aux : N < N'aux a N :=
Nat.add_one_le_iff.mp ((Nat.le_nth fun hf ↦ absurd hf hc.infinite_setOf_apply_eq_one).trans
(hc.nth_sup_N_add_one_le_N'aux_of_small hc.small_one))
/-- `N` is less than `N'`. -/
lemma N_lt_N' : N < N' a N := hc.N_lt_N'aux.trans_le (Nat.le_add_right _ _)
lemma lt_card_filter_eq_of_small_nth_lt {i j t : ℕ} (hj0 : 0 < j) (h : Small a j)
(ht : Nat.nth (a · = j) t < i) : t < #{m ∈ Finset.range i | a m = j} := by
rw [← hc.infinite_setOf_apply_eq_iff_small hj0] at h
rw [← Nat.count_eq_card_filter_range]
exact (Nat.nth_lt_nth h).mp (ht.trans_le (Nat.le_nth_count h _))
lemma k_lt_card_filter_eq_of_small_of_N'aux_le {i j : ℕ} (hj0 : 0 < j) (h : Small a j)
(hN'aux : N'aux a N < i) : k a < #{m ∈ Finset.range i | a m = j} :=
hc.lt_card_filter_eq_of_small_nth_lt hj0 h ((hc.nth_sup_k_le_N'aux_of_small h).trans_lt hN'aux)
lemma N_add_one_lt_card_filter_eq_of_small_of_N'aux_le {i j : ℕ} (hj0 : 0 < j) (h : Small a j)
(hN'aux : N'aux a N < i) : N + 1 < #{m ∈ Finset.range i | a m = j} :=
hc.lt_card_filter_eq_of_small_nth_lt hj0 h
((hc.nth_sup_N_add_one_le_N'aux_of_small h).trans_lt hN'aux)
lemma N_add_one_lt_card_filter_eq_of_small_of_N'_le {i j : ℕ} (hj0 : 0 < j) (h : Small a j)
(hN' : N' a N < i) : N + 1 < #{m ∈ Finset.range i | a m = j} := by
refine hc.N_add_one_lt_card_filter_eq_of_small_of_N'aux_le hj0 h ?_
rw [N'] at hN'
split_ifs at hN' <;> omega
lemma apply_add_one_big_of_apply_small_of_N'aux_le {i : ℕ} (h : Small a (a i))
(hN'aux : N'aux a N ≤ i) : Big a (a (i + 1)) := by
have hN'' : N'aux a N < i + 1 := by omega
suffices ¬Small a (a (i + 1)) by simpa [this] using hc.small_or_big_of_N'aux_lt hN''
rw [hc.apply_add_one_eq_card (hc.N_lt_N'aux.le.trans hN'aux), Small, not_le]
exact hc.k_lt_card_filter_eq_of_small_of_N'aux_le (hc.pos _) h hN''
lemma apply_add_one_big_of_apply_small_of_N'_le {i : ℕ} (h : Small a (a i)) (hN' : N' a N ≤ i) :
Big a (a (i + 1)) :=
hc.apply_add_one_big_of_apply_small_of_N'aux_le h ((Nat.le_add_right _ _).trans hN')
lemma apply_add_one_small_of_apply_big_of_N'aux_le {i : ℕ} (h : Big a (a i))
(hN'aux : N'aux a N ≤ i) : Small a (a (i + 1)) := by
obtain ⟨hf, hfc⟩ := hc.exists_card_le_of_big h
rw [hc.apply_add_one_eq_card (hc.N_lt_N'aux.le.trans hN'aux)]
exact (Finset.card_le_card (by simp)).trans hfc
lemma apply_add_one_small_of_apply_big_of_N'_le {i : ℕ} (h : Big a (a i)) (hN' : N' a N ≤ i) :
Small a (a (i + 1)) :=
hc.apply_add_one_small_of_apply_big_of_N'aux_le h ((Nat.le_add_right _ _).trans hN')
lemma apply_add_two_small_of_apply_small_of_N'_le {i : ℕ} (h : Small a (a i)) (hN' : N' a N ≤ i) :
Small a (a (i + 2)) :=
hc.apply_add_one_small_of_apply_big_of_N'_le (hc.apply_add_one_big_of_apply_small_of_N'_le h hN')
(by omega)
/-- `a (N' a N)` is a small number. -/
lemma small_apply_N' : Small a (a (N' a N)) := by
rw [N']
split_ifs with hi
· exact hi
· have hb : Big a (a (N'aux a N + 1)) := by
simpa [hi] using hc.small_or_big_of_N'aux_lt (Nat.lt_add_one (N'aux a N))
exact hc.apply_add_one_small_of_apply_big_of_N'aux_le hb (by omega)
lemma small_apply_N'_add_iff_even {n : ℕ} : Small a (a (N' a N + n)) ↔ Even n := by
induction n with
| zero => simpa using hc.small_apply_N'
| succ n ih =>
by_cases he : Even n <;> rw [← add_assoc] <;> simp only [he, iff_true, iff_false] at ih
· have hne : ¬ Even (n + 1) := by simp [Nat.not_even_iff_odd, he]
simp only [hne, iff_false]
exact hc.not_small_of_big (hc.apply_add_one_big_of_apply_small_of_N'_le ih (by omega))
· have hb : Big a (a (N' a N + n)) := by
simpa [ih] using hc.small_or_big_of_N'_le (j := N' a N + n) (by omega)
simp [hc.apply_add_one_small_of_apply_big_of_N'_le hb (by omega), Nat.not_even_iff_odd.mp he]
lemma small_apply_add_two_mul_iff_small {n : ℕ} (m : ℕ) (hN' : N' a N ≤ n) :
Small a (a (n + 2 * m)) ↔ Small a (a n) := by
rw [show n = N' a N + (n - N' a N) by omega, add_assoc, hc.small_apply_N'_add_iff_even,
hc.small_apply_N'_add_iff_even]
simp [Nat.even_add]
lemma apply_sub_one_small_of_apply_big_of_N'_le {i : ℕ} (h : Big a (a i)) (hN' : N' a N ≤ i) :
Small a (a (i - 1)) := by
have h0i : 1 ≤ i := by
have := hc.N_lt_N'
omega
have h' : N' a N ≤ i - 1 := by
by_contra hi
have hi' : i = N' a N := by omega
exact hc.not_small_of_big (hi' ▸ h) hc.small_apply_N'
exact (hc.small_or_big_of_N'_le h').elim id fun hb ↦
False.elim (hc.not_small_of_big h (Nat.sub_add_cancel h0i ▸
(hc.apply_add_one_small_of_apply_big_of_N'_le hb h')))
lemma apply_sub_one_big_of_apply_small_of_N'_lt {i : ℕ} (h : Small a (a i)) (hN' : N' a N < i) :
Big a (a (i - 1)) := by
have h0i : 1 ≤ i := by omega
have h' : N' a N ≤ i - 1 := by omega
exact (hc.small_or_big_of_N'_le h').elim (fun hs ↦ False.elim (hc.not_small_of_big
(Nat.sub_add_cancel h0i ▸ hc.apply_add_one_big_of_apply_small_of_N'_le hs h') h)) id
lemma apply_sub_two_small_of_apply_small_of_N'_lt {i : ℕ} (h : Small a (a i)) (hN' : N' a N < i) :
Small a (a (i - 2)) := by
convert hc.apply_sub_one_small_of_apply_big_of_N'_le
(hc.apply_sub_one_big_of_apply_small_of_N'_lt h hN') (by omega) using 1
lemma N_add_one_lt_apply_of_apply_big_of_N'_le {i : ℕ} (h : Big a (a i)) (hN' : N' a N ≤ i) :
N + 1 < a i := by
refine hc.apply_eq_card (hc.N_lt_N'.trans_le hN') ▸
hc.N_add_one_lt_card_filter_eq_of_small_of_N'_le (hc.pos _)
(hc.apply_sub_one_small_of_apply_big_of_N'_le h hN') ?_
by_contra
exact hc.not_small_of_big ((by omega : i = N' a N) ▸ h) hc.small_apply_N'
lemma setOf_apply_eq_of_apply_big_of_N'_le {i : ℕ} (h : Big a (a i)) (hN' : N' a N ≤ i) :
{j | a j = a i} = {j | N < j ∧ Small a (a (j - 1)) ∧
a i = #{t ∈ Finset.range j | a t = a (j - 1)}} := by
have hs : {j | N < j ∧ Small a (a (j - 1)) ∧ a i = #{t ∈ Finset.range j | a t = a (j - 1)}} ⊆
{j | a j = a i} := by
rintro _ ⟨hNj, -, hj⟩
exact hj ▸ hc.apply_eq_card hNj
rcases hc.exists_card_le_of_big h with ⟨hf, hck⟩
have hf' : {j | N < j ∧ Small a (a (j - 1)) ∧
a i = #{t ∈ Finset.range j | a t = a (j - 1)}}.Finite := hf.subset hs
suffices hf.toFinset = hf'.toFinset by simpa using this
rw [← Set.Finite.toFinset_subset_toFinset (hs := hf') (ht := hf)] at hs
refine (Finset.eq_of_subset_of_card_le hs (hck.trans ?_)).symm
have hs : #((Finset.Icc 1 (k a)).image (fun t ↦ Nat.nth (a · = t) (a i - 1) + 1)) = k a := by
convert Finset.card_image_of_injOn fun t ht u hu htu ↦ ?_
· simp only [Nat.card_Icc, add_tsub_cancel_right]
· simp only [add_left_inj] at htu
simp only [Finset.coe_Icc, Set.mem_Icc] at ht hu
rw [← Small, ← hc.infinite_setOf_apply_eq_iff_small (by omega)] at ht hu
apply_fun a at htu
rwa [Nat.nth_mem_of_infinite ht.2, Nat.nth_mem_of_infinite hu.2] at htu
refine hs ▸ Finset.card_le_card (Finset.subset_iff.2 fun j hj ↦ ?_)
simp only [Set.Finite.mem_toFinset, Set.mem_setOf_eq]
simp only [Finset.mem_image, Finset.mem_Icc] at hj
rcases hj with ⟨t, ⟨ht1, htk⟩, rfl⟩
have hN1 : N < a i - 1 := by
have := hc.N_add_one_lt_apply_of_apply_big_of_N'_le h hN'
omega
simp only [add_tsub_cancel_right]
rw [← Small] at htk
have htki := htk
rw [← hc.infinite_setOf_apply_eq_iff_small (by omega)] at htki
rw [Nat.nth_mem_of_infinite htki]
simp only [htk, true_and]
refine ⟨Nat.lt_add_one_iff.mpr ((Nat.le_nth (fun hf ↦ absurd hf htki)).trans
((Nat.nth_le_nth htki).2 hN1.le)), ?_⟩
rw [← Nat.count_eq_card_filter_range, Nat.count_nth_succ_of_infinite htki]
omega
lemma N_lt_of_apply_eq_of_apply_big_of_N'_le {i j : ℕ} (hj : a j = a i) (h : Big a (a i))
(hN' : N' a N ≤ i) : N < j :=
have hj' : j ∈ {t | a t = a i} := by simpa using hj
(hc.setOf_apply_eq_of_apply_big_of_N'_le h hN' ▸ hj').1
lemma small_apply_sub_one_of_apply_eq_of_apply_big_of_N'_le {i j : ℕ} (hj : a j = a i)
(h : Big a (a i)) (hN' : N' a N ≤ i) : Small a (a (j - 1)) :=
have hj' : j ∈ {t | a t = a i} := by simpa using hj
(hc.setOf_apply_eq_of_apply_big_of_N'_le h hN' ▸ hj').2.1
/-! ### The main lemmas leading to the required result -/
/-- Lemma 1 from the informal solution. -/
lemma apply_add_one_eq_card_small_le_card_eq {i : ℕ} (hi : N' a N < i) (hib : Big a (a i)) :
a (i + 1) = #{m ∈ Finset.range (k a + 1) | a i ≤ #{j ∈ Finset.range i | a j = m}} := by
rw [hc.apply_add_one_eq_card (hc.N_lt_N'.trans hi).le]
convert Finset.card_image_of_injOn (f := fun j ↦ Nat.nth (a · = j) (a i - 1) + 1) ?_ using 1
· congr
ext j
simp only [Finset.mem_filter, Finset.mem_range, Finset.mem_image]
refine ⟨fun ⟨hj, hji⟩ ↦ ⟨a (j - 1), hji ▸ ?_⟩, fun ⟨t, ⟨hts, htr⟩, ht⟩ ↦ ?_⟩
· have hjN : N < j := hc.N_lt_of_apply_eq_of_apply_big_of_N'_le hji hib hi.le
refine ⟨⟨Nat.lt_add_one_iff.mpr (hc.small_apply_sub_one_of_apply_eq_of_apply_big_of_N'_le
hji hib hi.le), ?_⟩, ?_⟩
· rw [hc.apply_eq_card hjN]
have : j ≤ i := by omega
gcongr
· have hj1 : j = j - 1 + 1 := by omega
nth_rw 2 [hj1]
rw [hc.nth_apply_add_one_eq (by omega), hj1.symm]
· subst ht
rw [Nat.lt_add_one_iff, ← Small] at hts
have ht0 : 0 < t := by
by_contra! h0
simp [nonpos_iff_eq_zero.mp h0, hc.apply_ne_zero] at htr
rw [← hc.infinite_setOf_apply_eq_iff_small ht0] at hts
rw [← Nat.count_eq_card_filter_range] at htr
constructor
· rwa [add_lt_add_iff_right, ← Nat.lt_nth_iff_count_lt hts,
Nat.sub_lt_iff_lt_add' (hc.one_le_apply _), Nat.lt_one_add_iff]
· rw [hc.apply_nth_add_one_eq_of_infinite hts]
· exact Nat.sub_add_cancel (hc.one_le_apply _)
· refine (Nat.le_nth fun hf ↦ absurd hf hts).trans ((Nat.nth_le_nth hts).2 ?_)
have := hc.N_add_one_lt_apply_of_apply_big_of_N'_le hib hi.le
omega
· intro t ht u hu htu
simp only [Finset.coe_filter, Finset.mem_range, Set.mem_setOf_eq, Nat.lt_add_one_iff] at ht hu
rw [← Small] at ht hu
have ht0 : 0 < t := by
by_contra! h0
simp only [nonpos_iff_eq_zero] at h0
simp [h0, hc.apply_ne_zero] at ht
have hu0 : 0 < u := by
by_contra! h0
simp only [nonpos_iff_eq_zero] at h0
simp [h0, hc.apply_ne_zero] at hu
rw [← hc.infinite_setOf_apply_eq_iff_small ht0] at ht
rw [← hc.infinite_setOf_apply_eq_iff_small hu0] at hu
simp only [add_left_inj] at htu
apply_fun a at htu
rwa [Nat.nth_mem_of_infinite ht.1, Nat.nth_mem_of_infinite hu.1] at htu
/-- Similar to Lemma 1 from the informal solution, but with a `Small` hypothesis instead of `Big`
and considering a range one larger (the form needed for Lemma 2). -/
lemma apply_eq_card_small_le_card_eq_of_small {i : ℕ} (hi : N' a N + 1 < i)
(his : Small a (a i)) :
a i = #{m ∈ Finset.range (k a + 1) | a (i - 1) ≤ #{j ∈ Finset.range i | a j = m}} := by
have hib : Big a (a (i - 1)) := hc.apply_sub_one_big_of_apply_small_of_N'_lt his (by omega)
nth_rw 1 [show i = i - 1 + 1 by omega]
rw [hc.apply_add_one_eq_card_small_le_card_eq (by omega) hib]
congr 1
ext j
simp only [Finset.mem_filter, Finset.mem_range, and_congr_right_iff]
intro hj
convert Iff.rfl using 2
congr 1
ext t
simp only [Finset.mem_filter, Finset.mem_range]
refine ⟨fun ⟨hti, rfl⟩ ↦ ⟨?_, rfl⟩, fun ⟨_, rfl⟩ ↦ ⟨by omega, rfl⟩⟩
by_contra hti1
have htieq : t = i - 1 := by omega
subst htieq
exact hc.not_small_of_big hib (Nat.lt_add_one_iff.mp hj)
/-- Lemma 2 from the informal solution. -/
lemma exists_apply_sub_two_eq_of_apply_eq {i j : ℕ} (hi : N' a N + 2 < i) (hijlt : i < j)
(his : Small a (a i)) (hijeq : a i = a j)
(hij1 : ∀ t, Small a t → #{x ∈ Finset.Ico i j | a x = t} ≤ 1) :
∃ t, t ∈ Finset.Ico i j ∧ a (i - 2) = a t := by
let I : Finset ℕ := {t ∈ Finset.range (k a + 1) | a (i - 1) ≤ #{u ∈ Finset.range i | a u = t}}
let J : Finset ℕ := {t ∈ Finset.range (k a + 1) | a (j - 1) ≤ #{u ∈ Finset.range j | a u = t}}
have hIc : a i = #I := hc.apply_eq_card_small_le_card_eq_of_small (by omega) his
have hJc : a j = #J := hc.apply_eq_card_small_le_card_eq_of_small (by omega) (hijeq ▸ his)
have hIJc : #I = #J := hIc ▸ hJc ▸ hijeq
have := hc.N_lt_N'
have hiju : Finset.range i ∪ Finset.Ico i j = Finset.range j := by
rw [Finset.range_eq_Ico, Finset.Ico_union_Ico' (by omega) (by omega)]
simp [hijlt.le]
have hi2s : a (i - 2) < k a + 1 :=
Nat.lt_add_one_iff.mpr (hc.apply_sub_two_small_of_apply_small_of_N'_lt his (by omega))
have hiI : a (i - 2) ∈ I := by
simp only [I, Finset.mem_filter, Finset.mem_range, hi2s, true_and]
rw [hc.apply_eq_card (by omega), show i - 1 - 1 = i - 2 by omega]
exact Finset.card_le_card (Finset.filter_subset_filter _ (by simp))
have hj2s : a (j - 2) < k a + 1 :=
Nat.lt_add_one_iff.mpr (hc.apply_sub_two_small_of_apply_small_of_N'_lt (hijeq ▸ his) (by omega))
have hjJ : a (j - 2) ∈ J := by
simp only [J, Finset.mem_filter, Finset.mem_range, hj2s, true_and]
rw [hc.apply_eq_card (by omega), show j - 1 - 1 = j - 2 by omega]
exact Finset.card_le_card (Finset.filter_subset_filter _ (by simp))
have hjI : a (j - 2) ∈ I := by
by_contra hjI
have hjIf := hjI
simp only [Finset.mem_filter, Finset.mem_range, hj2s, true_and, not_le, I,
Nat.lt_iff_add_one_le] at hjIf
have hjI' : a (j - 1) ≤ a (i - 1) := by
calc a (j - 1) ≤ #{u ∈ Finset.range j | a u = a (j - 2)} :=
(Finset.mem_filter.mp hjJ).2
_ = #{u ∈ Finset.range i ∪ Finset.Ico i j | a u = a (j - 2)} := by rw [hiju]
_ ≤ #{u ∈ Finset.range i | a u = a (j - 2)} + #{u ∈ Finset.Ico i j | a u = a (j - 2)} := by
rw [Finset.filter_union]
exact Finset.card_union_le _ _
_ ≤ #{u ∈ Finset.range i | a u = a (j - 2)} + 1 := by
gcongr
exact hij1 _ (by rwa [Nat.lt_add_one_iff, ← Small] at hj2s)
_ ≤ a (i - 1) := hjIf
refine hjI (Finset.eq_of_subset_of_card_le (fun x hxI ↦ ?_) hIJc.symm.le ▸ hjJ)
simp only [Finset.mem_filter, I, J] at *
refine ⟨hxI.1, ?_⟩
calc a (j - 1) ≤ a (i - 1) := hjI'
_ ≤ #{u ∈ Finset.range i | a u = x} := hxI.2
_ ≤ #{u ∈ Finset.range j | a u = x} :=
Finset.card_le_card (Finset.filter_subset_filter _ (by simp [hijlt.le]))
have hi1j1 : a (i - 1) + 1 ≤ a (j - 1) := by
calc a (i - 1) + 1 ≤ #{u ∈ Finset.range i | a u = a (j - 2)} + 1 := by grind
_ ≤ #{u ∈ Finset.range i | a u = a (j - 2)} + #{u ∈ Finset.Ico i j | a u = a (j - 2)} := by
gcongr
simp only [Finset.one_le_card]
refine ⟨j - 2, ?_⟩
simp only [Finset.mem_filter, Finset.mem_Ico, and_true]
refine ⟨?_, by omega⟩
by_contra hj
have hj' : j = i + 1 := by omega
subst hj'
exact hc.not_small_of_big (hc.apply_add_one_big_of_apply_small_of_N'_le his (by omega))
(hijeq ▸ his)
_ = #({u ∈ Finset.range i | a u = a (j - 2)} ∪ {u ∈ Finset.Ico i j | a u = a (j - 2)}) := by
refine (Finset.card_union_of_disjoint ?_).symm
simp only [Finset.disjoint_iff_ne, Finset.mem_filter, Finset.mem_range, Finset.mem_Ico,
and_imp]
rintro t hti - u hiu - -
omega
_ = #{u ∈ Finset.range j | a u = a (j - 2)} := by
rw [← Finset.filter_union, hiju]
_ = a (j - 1) := by
rw [hc.apply_eq_card (show N < j - 1 by omega)]
congr 1
ext t
simp only [Finset.mem_filter, Finset.mem_range]
refine ⟨fun ⟨htj, htj'⟩ ↦ ⟨?_, by convert htj' using 1⟩,
fun ⟨htj, htj'⟩ ↦ ⟨by omega, by convert htj' using 1⟩⟩
by_contra htj''
have ht1 : t = j - 1 := by omega
subst ht1
exact hc.not_small_of_big (htj' ▸ hc.apply_sub_one_big_of_apply_small_of_N'_lt
(hijeq ▸ his) (by omega)) (hc.apply_sub_two_small_of_apply_small_of_N'_lt
(hijeq ▸ his) (by omega))
have hIJ : I = J := by
refine (Finset.eq_of_subset_of_card_le (Finset.subset_iff.mp fun x hxJ ↦ ?_) hIJc.le).symm
simp only [Finset.mem_filter, Finset.mem_range, I, J, Nat.lt_add_one_iff] at *
refine ⟨hxJ.1, (add_le_add_iff_right 1).mp ?_⟩
calc a (i - 1) + 1 ≤ a (j - 1) := hi1j1
_ ≤ #{u ∈ Finset.range j | a u = x} := hxJ.2
_ = #({u ∈ Finset.range i | a u = x} ∪ {u ∈ Finset.Ico i j | a u = x}) := by
rw [← Finset.filter_union, hiju]
_ ≤ #{u ∈ Finset.range i | a u = x} + #{u ∈ Finset.Ico i j | a u = x} :=
Finset.card_union_le _ _
_ ≤ #{u ∈ Finset.range i | a u = x} + 1 := by
gcongr
exact hij1 _ hxJ.1
simp only [hIJ, J, Finset.mem_filter] at hiI
have hiI' := hi1j1.trans hiI.2
rw [hc.apply_eq_card (by omega), show i - 1 - 1 = i - 2 by omega, Nat.add_one_le_iff,
← not_le] at hiI'
rcases Finset.not_subset.mp (mt Finset.card_le_card hiI') with ⟨t, htj, hti⟩
simp only [Finset.mem_filter, Finset.mem_range] at htj hti
simp only [htj.2, and_true, not_lt, tsub_le_iff_right] at hti
refine ⟨t, Finset.mem_Ico.mpr ⟨?_, htj.1⟩, htj.2.symm⟩
by_contra
have hti' : t = i - 1 := by omega
subst hti'
exact hc.not_small_of_big (hc.apply_sub_one_big_of_apply_small_of_N'_lt his (by omega)) (htj.2 ▸
(hc.apply_sub_two_small_of_apply_small_of_N'_lt his (by omega)))
variable (a)
/-- The indices, minus `n`, of small numbers appearing for the second or subsequent time at or
after `a n`. -/
def pSet (n : ℕ) : Set ℕ := {t | ∃ i ∈ Finset.Ico n (n + t), Small a (a i) ∧ a (n + t) = a i}
/-- The index, minus `n`, of the second appearance of the first small number to appear twice at
or after `a n`. This is only used for small `a n` with `N' a N + 2 < n`. -/
noncomputable def p (n : ℕ) : ℕ := sInf (pSet a n)
variable {a}
lemma nonempty_pSet (n : ℕ) : (pSet a n).Nonempty := by
rcases hc.infinite_setOf_apply_eq_one.exists_gt n with ⟨i, hi1, hni⟩
rcases hc.infinite_setOf_apply_eq_one.exists_gt i with ⟨j, hj1, hij⟩
refine ⟨j - n, ?_⟩
simp only [pSet, Finset.mem_Ico, Set.mem_setOf_eq]
exact ⟨i, ⟨hni.le, by omega⟩, hi1 ▸ ⟨hc.small_one, hj1 ▸ (by congr; omega)⟩⟩
lemma exists_mem_Ico_small_and_apply_add_p_eq (n : ℕ) :
∃ i ∈ Finset.Ico n (n + p a n), Small a (a i) ∧ a (n + p a n) = a i :=
csInf_mem (hc.nonempty_pSet _)
lemma p_pos (n : ℕ) : 0 < p a n := by
by_contra! h
have hn := hc.exists_mem_Ico_small_and_apply_add_p_eq n
simp [h] at hn
lemma card_filter_apply_eq_Ico_add_p_le_one (n : ℕ) {j : ℕ} (hjs : Small a j) :
#{i ∈ Finset.Ico n (n + p a n) | a i = j} ≤ 1 := by
have h : IsLeast (pSet a n) (p a n) := isLeast_csInf (hc.nonempty_pSet n)
simp only [IsLeast, pSet, Set.mem_setOf_eq, mem_lowerBounds, forall_exists_index, and_imp,
Finset.mem_Ico] at h
rw [Finset.card_le_one_iff]
intro x y hx hy
simp only [Finset.mem_filter, Finset.mem_Ico] at hx hy
rcases lt_trichotomy x y with hxy | rfl | hxy
· replace h := h.2 (y - n) x hx.1.1 (by omega) (hx.2 ▸ hjs)
rw [show n + (y - n) = y by omega, hx.2, hy.2] at h
omega
· rfl
· replace h := h.2 (x - n) y hy.1.1 (by omega) (hy.2 ▸ hjs)
rw [show n + (x - n) = x by omega, hx.2, hy.2] at h
omega
lemma apply_add_p_eq {n : ℕ} (hn : N' a N + 2 < n) (hs : Small a (a n)) : a (n + p a n) = a n := by
rcases hc.exists_mem_Ico_small_and_apply_add_p_eq n with ⟨i, hiIco, his, hin⟩
suffices i = n by rw [hin, this]
simp only [Finset.mem_Ico] at hiIco
by_contra hin'
have hf (t : ℕ) (hts : Small a t) : #{x ∈ Finset.Ico i (n + p a n) | a x = t} ≤ 1 :=
calc #{x ∈ Finset.Ico i (n + p a n) | a x = t} ≤ #{x ∈ Finset.Ico n (n + p a n) | a x = t} :=
Finset.card_le_card (Finset.filter_subset_filter _ (Finset.Ico_subset_Ico hiIco.1 le_rfl))
_ ≤ 1 := hc.card_filter_apply_eq_Ico_add_p_le_one _ hts
obtain ⟨t, hti, hi2t⟩ := hc.exists_apply_sub_two_eq_of_apply_eq (j := n + p a n) (by omega)
(by omega) his hin.symm hf
have h1 := hc.card_filter_apply_eq_Ico_add_p_le_one n
(hi2t ▸ hc.apply_sub_two_small_of_apply_small_of_N'_lt his (by omega))
revert h1
simp only [imp_false, not_le, Finset.one_lt_card_iff, Finset.mem_filter, Finset.mem_Ico, ne_eq,
exists_and_left]
simp only [Finset.mem_Ico] at hti
refine ⟨i - 2, ⟨⟨?_, by omega⟩, hi2t⟩, t, by omega⟩
by_contra hi2
have hi1 : n = i - 1 := by omega
subst hi1
exact hc.not_small_of_big (hc.apply_sub_one_big_of_apply_small_of_N'_lt his (by omega)) hs
lemma even_p {n : ℕ} (hn : N' a N + 2 < n) (hs : Small a (a n)) : Even (p a n) := by
have hna : n = N' a N + (n - (N' a N)) := by omega
have hs' := hc.apply_add_p_eq hn hs ▸ hs
rw [hna, hc.small_apply_N'_add_iff_even] at hs
nth_rw 1 [hna] at hs'
rw [add_assoc, hc.small_apply_N'_add_iff_even] at hs'
simpa [Nat.even_add, hs] using hs'
lemma p_le_two_mul_k {n : ℕ} (hn : N' a N + 2 < n) (hs : Small a (a n)) : p a n ≤ 2 * k a := by
by_contra hlt
obtain ⟨x, hx, y, hy, hxyne, hxy⟩ : ∃ x ∈ Finset.range (k a + 1), ∃ y ∈ Finset.range (k a + 1),
x ≠ y ∧ a (n + 2 * x) = a (n + 2 * y) := by
convert Finset.exists_ne_map_eq_of_card_lt_of_maps_to (t := Finset.Icc 1 (k a)) ?_ ?_
· simp
· rintro i -
simp only [Finset.coe_Icc, Set.mem_Icc]
rw [← Small, hc.small_apply_add_two_mul_iff_small i (by omega)]
simp [hs, hc.one_le_apply]
have hs' : Small a (a (n + 2 * x)) := by rwa [hc.small_apply_add_two_mul_iff_small x (by omega)]
have hj := hc.card_filter_apply_eq_Ico_add_p_le_one n hs'
revert hj
simp only [imp_false, not_le, Finset.one_lt_card_iff, Finset.mem_filter, Finset.mem_Ico, ne_eq,
exists_and_left]
simp only [Finset.mem_range] at hx hy
exact ⟨n + 2 * x, by omega, n + 2 * y, by omega⟩
lemma p_apply_sub_two_le_p_apply {n : ℕ} (hn : N' a N + 4 < n) (hs : Small a (a n)) :
p a (n - 2) ≤ p a n := by
obtain ⟨t, hti, _⟩ := hc.exists_apply_sub_two_eq_of_apply_eq (j := n + p a n) (by omega)
((lt_add_iff_pos_right n).mpr (hc.p_pos n)) hs
(hc.apply_add_p_eq (by omega) hs).symm (fun _ ↦ hc.card_filter_apply_eq_Ico_add_p_le_one _)
by_contra
have hn2 := (hc.apply_sub_two_small_of_apply_small_of_N'_lt hs (by omega))
have : p a n ≤ p a (n - 2) - 2 := by
obtain ⟨_, _⟩ := hc.even_p (by omega) hs
obtain ⟨_, _⟩ := hc.even_p (by omega) hn2
omega
have h := hc.card_filter_apply_eq_Ico_add_p_le_one (n - 2) hn2
revert h
simp only [imp_false, not_le, Finset.one_lt_card_iff, Finset.mem_filter, Finset.mem_Ico,
ne_eq, exists_and_left]
simp only [Finset.mem_Ico] at hti
exact ⟨n - 2, ⟨⟨le_rfl, by omega⟩, rfl⟩, t, by omega⟩
lemma p_apply_le_p_apply_add_two {n : ℕ} (hn : N' a N + 2 < n) (hs : Small a (a n)) :
p a n ≤ p a (n + 2) :=
hc.p_apply_sub_two_le_p_apply (n := n + 2) (by omega)
(hc.apply_add_two_small_of_apply_small_of_N'_le hs (by omega))
variable (a N)
lemma exists_p_eq : ∃ b c, ∀ n, b < n → p a (N' a N + 2 * n) = c := by
let c : ℕ := sSup (Set.range (fun i ↦ p a (N' a N + 2 * (2 + i))))
have hk : 2 * k a ∈ upperBounds (Set.range (fun i ↦ p a (N' a N + 2 * (2 + i)))) := by
simp only [mem_upperBounds, Set.mem_range, forall_exists_index, forall_apply_eq_imp_iff]
exact fun i ↦ hc.p_le_two_mul_k (by omega) (hc.small_apply_N'_add_iff_even.mpr (by simp))
have hlec : ∀ j ∈ Set.range (fun i ↦ p a (N' a N + 2 * (2 + i))), j ≤ c :=
fun _ hj ↦ le_csSup ⟨_, hk⟩ hj
obtain ⟨t, ht⟩ := Set.Nonempty.csSup_mem (Set.range_nonempty _) (BddAbove.finite ⟨2 * k a, hk⟩)
have heqc (u : ℕ) : p a (N' a N + 2 * (2 + t + u)) = c := by
induction u with
| zero => simpa using ht
| succ u ih =>
refine le_antisymm ?_ (ih ▸ ?_)
· simp only [Set.mem_range, forall_exists_index, forall_apply_eq_imp_iff] at hlec
exact add_assoc _ _ (u + 1) ▸ hlec (t + (u + 1))
· have hs : Small a (a (N' a N + 2 * (2 + t + u))) := by
rw [hc.small_apply_N'_add_iff_even]
simp
convert hc.p_apply_le_p_apply_add_two (by omega) hs using 1
refine ⟨1 + t, c, fun n hn ↦ ?_⟩
rw [show n = 2 + t + (n - (2 + t)) by omega]
exact heqc _
lemma exists_a_apply_add_eq : ∃ b c, 0 < c ∧ ∀ n, b < n →
a (N' a N + 2 * n + 2 * c) = a (N' a N + 2 * n) := by
obtain ⟨b, c', hbc'⟩ := hc.exists_p_eq a N
have hs (n : ℕ) : Small a (a (N' a N + 2 * n)) := hc.small_apply_N'_add_iff_even.mpr (by simp)
refine ⟨b + 2, c' / 2, ?_, fun n hbn ↦ hbc' n (by omega) ▸ ?_⟩
· have := hbc' (b + 2) (by omega)
have := hc.p_pos (N' a N + 2 * (b + 2))
rcases hc.even_p (by omega) (hs (b + 2)) with ⟨_, _⟩
omega
· convert hc.apply_add_p_eq (by omega) (hs n) using 3
rcases hc.even_p (by omega) (hs n) with ⟨_, ht⟩
simp [ht, ← two_mul]
variable {a N}
end Condition
theorem result {a : ℕ → ℕ} {N : ℕ} (h : Condition a N) :
EventuallyPeriodic (fun i ↦ a (2 * i)) ∨ EventuallyPeriodic (fun i ↦ a (2 * i + 1)) := by
obtain ⟨b, c, hc, hbc⟩ := h.exists_a_apply_add_eq a N
obtain ⟨t, _⟩ | ⟨t, _⟩ := Nat.even_or_odd (Condition.N' a N)
· refine .inl ⟨c, Condition.N' a N / 2 + b + 1, hc, fun m hm ↦ ?_⟩
convert hbc (m - t) (by omega) using 1 <;> dsimp only <;> congr <;> omega
· refine .inr ⟨c, Condition.N' a N / 2 + b + 1, hc, fun m hm ↦ ?_⟩
convert hbc (m - t) (by omega) using 1 <;> dsimp only <;> congr 1 <;> omega
end Imo2024Q3 |
.lake/packages/mathlib/Archive/Imo/Imo2006Q5.lean | import Mathlib.Algebra.Polynomial.Roots
import Mathlib.Dynamics.PeriodicPts.Lemmas
/-!
# IMO 2006 Q5
Let $P(x)$ be a polynomial of degree $n>1$ with integer coefficients, and let $k$ be a positive
integer. Consider the polynomial $Q(x) = P(P(\ldots P(P(x))\ldots))$, where $P$ occurs $k$ times.
Prove that there are at most $n$ integers $t$ such that $Q(t)=t$.
## Sketch of solution
The following solution is adapted from
https://artofproblemsolving.com/wiki/index.php/2006_IMO_Problems/Problem_5.
Let $P^k$ denote the polynomial $P$ composed with itself $k$ times. We rely on a key observation: if
$P^k(t)=t$, then $P(P(t))=t$. We prove this by building the cyclic list
$(P(t)-t,P^2(t)-P(t),\ldots)$, and showing that each entry divides the next, which by transitivity
implies they all divide each other, and thus have the same absolute value.
If the entries in this list are all pairwise equal, then we can show inductively that for positive
$n$, $P^n(t)-t$ must always have the same sign as $P(t)-t$. Substituting $n=k$ gives us $P(t)=t$ and
in particular $P(P(t))=t$.
Otherwise, there must be two consecutive entries that are opposites of one another. This means
$P^{n+2}(t)-P^{n+1}(t)=P^n(t)-P^{n+1}(t)$, which implies $P^{n+2}(t)=P^n(t)$ and $P(P(t))=t$.
With this lemma, we can reduce the problem to the case $k=2$. If every root of $P(P(t))-t$ is also a
root of $P(t)-t$, then we're done. Otherwise, there exist $a$ and $b$ with $a\ne b$ and $P(a)=b$,
$P(b)=a$. For any root $t$ of $P(P(t))-t$, defining $u=P(t)$, we easily verify $a-t\mid b-u$,
$b-u\mid a-t$, $a-u\mid b-t$, $b-t\mid a-u$, which imply $|a-t|=|b-u|$ and $|a-u|=|b-t|$. By casing
on these equalities, we deduce $a+b=t+u$. This means that every root of $P(P(t))-t$ is a root of
$P(t)+t-a-b$, and we're again done.
-/
open Function Polynomial
namespace Imo2006Q5
/-- If every entry in a cyclic list of integers divides the next, then they all have the same
absolute value. -/
theorem Int.natAbs_eq_of_chain_dvd {l : Cycle ℤ} {x y : ℤ} (hl : l.Chain (· ∣ ·)) (hx : x ∈ l)
(hy : y ∈ l) : x.natAbs = y.natAbs := by
rw [Cycle.chain_iff_pairwise] at hl
exact Int.natAbs_eq_of_dvd_dvd (hl x hx y hy) (hl y hy x hx)
theorem Int.add_eq_add_of_natAbs_eq_of_natAbs_eq {a b c d : ℤ} (hne : a ≠ b)
(h₁ : (c - a).natAbs = (d - b).natAbs) (h₂ : (c - b).natAbs = (d - a).natAbs) :
a + b = c + d := by
rcases Int.natAbs_eq_natAbs_iff.1 h₁ with h₁ | h₁
· rcases Int.natAbs_eq_natAbs_iff.1 h₂ with h₂ | h₂
· exact (hne <| by linarith).elim
· linarith
· linarith
/-- The main lemma in the proof: if $P^k(t)=t$, then $P(P(t))=t$. -/
theorem Polynomial.isPeriodicPt_eval_two {P : Polynomial ℤ} {t : ℤ}
(ht : t ∈ periodicPts fun x => P.eval x) : IsPeriodicPt (fun x => P.eval x) 2 t := by
-- The cycle [P(t) - t, P(P(t)) - P(t), ...]
let C : Cycle ℤ := (periodicOrbit (fun x => P.eval x) t).map fun x => P.eval x - x
have HC : ∀ {n : ℕ}, (fun x => P.eval x)^[n + 1] t - (fun x => P.eval x)^[n] t ∈ C := by
intro n
rw [Cycle.mem_map, Function.iterate_succ_apply']
exact ⟨_, iterate_mem_periodicOrbit ht n, rfl⟩
-- Elements in C are all divisible by one another.
have Hdvd : C.Chain (· ∣ ·) := by
rw [Cycle.chain_map, periodicOrbit_chain' _ ht]
intro n
convert sub_dvd_eval_sub ((fun x => P.eval x)^[n + 1] t) ((fun x => P.eval x)^[n] t) P <;>
rw [Function.iterate_succ_apply']
-- Any two entries in C have the same absolute value.
have Habs :
∀ m n : ℕ,
((fun x => P.eval x)^[m + 1] t - (fun x => P.eval x)^[m] t).natAbs =
((fun x => P.eval x)^[n + 1] t - (fun x => P.eval x)^[n] t).natAbs :=
fun m n => Int.natAbs_eq_of_chain_dvd Hdvd HC HC
-- We case on whether the elements on C are pairwise equal.
by_cases HC' : C.Chain (· = ·)
· -- Any two entries in C are equal.
have Heq :
∀ m n : ℕ,
(fun x => P.eval x)^[m + 1] t - (fun x => P.eval x)^[m] t =
(fun x => P.eval x)^[n + 1] t - (fun x => P.eval x)^[n] t :=
fun m n => Cycle.chain_iff_pairwise.1 HC' _ HC _ HC
-- The sign of P^n(t) - t is the same as P(t) - t for positive n. Proven by induction on n.
have IH (n : ℕ) : ((fun x => P.eval x)^[n + 1] t - t).sign = (P.eval t - t).sign := by
induction n with
| zero => rfl
| succ n IH =>
apply Eq.trans _ (Int.sign_add_eq_of_sign_eq IH)
have H := Heq n.succ 0
dsimp at H ⊢
rw [← H, sub_add_sub_cancel']
-- This implies that the sign of P(t) - t is the same as the sign of P^k(t) - t, which is 0.
-- Hence P(t) = t and P(P(t)) = P(t).
rcases ht with ⟨_ | k, hk, hk'⟩
· exact (irrefl 0 hk).elim
· have H := IH k
rw [hk'.isFixedPt.eq, sub_self, Int.sign_zero, eq_comm, Int.sign_eq_zero_iff_zero,
sub_eq_zero] at H
simp [IsPeriodicPt, IsFixedPt, H]
· -- We take two nonequal consecutive entries.
rw [Cycle.chain_map, periodicOrbit_chain' _ ht] at HC'
push_neg at HC'
obtain ⟨n, hn⟩ := HC'
-- They must have opposite sign, so that P^{k + 1}(t) - P^k(t) = P^{k + 2}(t) - P^{k + 1}(t).
rcases Int.natAbs_eq_natAbs_iff.1 (Habs n n.succ) with hn' | hn'
· apply (hn _).elim
convert hn' <;> simp only [Function.iterate_succ_apply']
-- We deduce P^{k + 2}(t) = P^k(t) and hence P(P(t)) = t.
· rw [neg_sub, sub_right_inj] at hn'
simp only [Function.iterate_succ_apply'] at hn'
exact isPeriodicPt_of_mem_periodicPts_of_isPeriodicPt_iterate ht hn'.symm
theorem Polynomial.iterate_comp_sub_X_ne {P : Polynomial ℤ} (hP : 1 < P.natDegree) {k : ℕ}
(hk : 0 < k) : P.comp^[k] X - X ≠ 0 := by
rw [sub_ne_zero]
apply_fun natDegree
simpa using (one_lt_pow₀ hP hk.ne').ne'
/-- We solve the problem for the specific case k = 2 first. -/
theorem imo2006_q5' {P : Polynomial ℤ} (hP : 1 < P.natDegree) :
(P.comp P - X).roots.toFinset.card ≤ P.natDegree := by
-- Auxiliary lemmas on degrees.
have hPX : (P - X).natDegree = P.natDegree := by
rw [natDegree_sub_eq_left_of_natDegree_lt]
simpa using hP
have hPX' : P - X ≠ 0 := by
intro h
rw [h, natDegree_zero] at hPX
rw [← hPX] at hP
exact (zero_le_one.not_gt hP).elim
-- If every root of P(P(t)) - t is also a root of P(t) - t, then we're done.
by_cases H : (P.comp P - X).roots.toFinset ⊆ (P - X).roots.toFinset
· exact (Finset.card_le_card H).trans
((Multiset.toFinset_card_le _).trans ((card_roots' _).trans_eq hPX))
-- Otherwise, take a, b with P(a) = b, P(b) = a, a ≠ b.
· rcases Finset.not_subset.1 H with ⟨a, ha, hab⟩
replace ha := isRoot_of_mem_roots (Multiset.mem_toFinset.1 ha)
rw [IsRoot.def, eval_sub, eval_comp, eval_X, sub_eq_zero] at ha
rw [Multiset.mem_toFinset, mem_roots hPX', IsRoot.def, eval_sub, eval_X, sub_eq_zero]
at hab
set b := P.eval a
-- More auxiliary lemmas on degrees.
have hPab : (P + (X : ℤ[X]) - a - b).natDegree = P.natDegree := by
rw [sub_sub, ← Int.cast_add]
have h₁ : (P + X).natDegree = P.natDegree := by
rw [natDegree_add_eq_left_of_natDegree_lt]
simpa using hP
rwa [natDegree_sub_eq_left_of_natDegree_lt]
rw [h₁, natDegree_intCast]
exact zero_lt_one.trans hP
have hPab' : P + (X : ℤ[X]) - a - b ≠ 0 := by
intro h
rw [h, natDegree_zero] at hPab
rw [← hPab] at hP
exact (zero_le_one.not_gt hP).elim
-- We claim that every root of P(P(t)) - t is a root of P(t) + t - a - b. This allows us to
-- conclude the problem.
suffices H' : (P.comp P - X).roots.toFinset ⊆ (P + (X : ℤ[X]) - a - b).roots.toFinset from
(Finset.card_le_card H').trans
((Multiset.toFinset_card_le _).trans <| (card_roots' _).trans_eq hPab)
-- Let t be a root of P(P(t)) - t, define u = P(t).
intro t ht
replace ht := isRoot_of_mem_roots (Multiset.mem_toFinset.1 ht)
rw [IsRoot.def, eval_sub, eval_comp, eval_X, sub_eq_zero] at ht
simp only [mem_roots hPab', sub_eq_iff_eq_add, Multiset.mem_toFinset, IsRoot.def,
eval_sub, eval_add, eval_X, eval_intCast, Int.cast_id, zero_add]
-- An auxiliary lemma proved earlier implies we only need to show |t - a| = |u - b| and
-- |t - b| = |u - a|. We prove this by establishing that each side of either equation divides
-- the other.
apply (Int.add_eq_add_of_natAbs_eq_of_natAbs_eq hab _ _).symm <;>
apply Int.natAbs_eq_of_dvd_dvd <;> set u := P.eval t
· rw [← ha, ← ht]; apply sub_dvd_eval_sub
· apply sub_dvd_eval_sub
· rw [← ht]; apply sub_dvd_eval_sub
· rw [← ha]; apply sub_dvd_eval_sub
end Imo2006Q5
open Imo2006Q5
/-- The general problem follows easily from the k = 2 case. -/
theorem imo2006_q5 {P : Polynomial ℤ} (hP : 1 < P.natDegree) {k : ℕ} (hk : 0 < k) :
(P.comp^[k] X - X).roots.toFinset.card ≤ P.natDegree := by
refine (Finset.card_le_card fun t ht => ?_).trans (imo2006_q5' hP)
have hP' : P.comp P - X ≠ 0 := by
simpa [Nat.iterate] using Polynomial.iterate_comp_sub_X_ne hP zero_lt_two
replace ht := isRoot_of_mem_roots (Multiset.mem_toFinset.1 ht)
rw [IsRoot.def, eval_sub, iterate_comp_eval, eval_X, sub_eq_zero] at ht
rw [Multiset.mem_toFinset, mem_roots hP', IsRoot.def, eval_sub, eval_comp, eval_X,
sub_eq_zero]
exact Polynomial.isPeriodicPt_eval_two ⟨k, hk, ht⟩ |
.lake/packages/mathlib/Archive/Imo/Imo1960Q1.lean | import Mathlib.Data.Nat.Digits.Lemmas
/-!
# IMO 1960 Q1
Determine all three-digit numbers $N$ having the property that $N$ is divisible by 11, and
$\dfrac{N}{11}$ is equal to the sum of the squares of the digits of $N$.
Since Lean doesn't have a way to directly express problem statements of the form
"Determine all X satisfying Y", we express two predicates where proving that one implies the
other is equivalent to solving the problem. A human solver also has to discover the
second predicate.
The strategy here is roughly brute force, checking the possible multiples of 11.
-/
open Nat
namespace Imo1960Q1
def sumOfSquares (L : List ℕ) : ℕ :=
(L.map fun x => x * x).sum
def ProblemPredicate (n : ℕ) : Prop :=
(Nat.digits 10 n).length = 3 ∧ 11 ∣ n ∧ n / 11 = sumOfSquares (Nat.digits 10 n)
def SolutionPredicate (n : ℕ) : Prop :=
n = 550 ∨ n = 803
/-
Proving that three digit numbers are the ones in [100, 1000).
-/
theorem not_zero {n : ℕ} (h1 : ProblemPredicate n) : n ≠ 0 :=
have h2 : Nat.digits 10 n ≠ List.nil := List.ne_nil_of_length_eq_add_one h1.left
digits_ne_nil_iff_ne_zero.mp h2
theorem ge_100 {n : ℕ} (h1 : ProblemPredicate n) : 100 ≤ n := by
have h2 : 10 ^ 3 ≤ 10 * n := by
rw [← h1.left]
refine Nat.base_pow_length_digits_le 10 n ?_ (not_zero h1)
simp
omega
theorem lt_1000 {n : ℕ} (h1 : ProblemPredicate n) : n < 1000 := by
have h2 : n < 10 ^ 3 := by
rw [← h1.left]
refine Nat.lt_base_pow_length_digits ?_
simp
omega
/-
We do an exhaustive search to show that all results are covered by `SolutionPredicate`.
-/
def SearchUpTo (c n : ℕ) : Prop :=
n = c * 11 ∧ ∀ m : ℕ, m < n → ProblemPredicate m → SolutionPredicate m
theorem searchUpTo_start : SearchUpTo 9 99 :=
⟨rfl, fun n h p => by linarith [ge_100 p]⟩
theorem searchUpTo_step {c n} (H : SearchUpTo c n) {c' n'} (ec : c + 1 = c') (en : n + 11 = n') {l}
(el : Nat.digits 10 n = l) (H' : c = sumOfSquares l → c = 50 ∨ c = 73) : SearchUpTo c' n' := by
subst ec; subst en; subst el
obtain ⟨rfl, H⟩ := H
refine ⟨by ring, fun m l p => ?_⟩
obtain ⟨h₁, ⟨m, rfl⟩, h₂⟩ := id p
by_cases h : 11 * m < c * 11; · exact H _ h p
obtain rfl : m = c := by omega
rw [Nat.mul_div_cancel_left _ (by simp : 11 > 0), mul_comm] at h₂
refine (H' h₂).imp ?_ ?_ <;> · rintro rfl; norm_num
theorem searchUpTo_end {c} (H : SearchUpTo c 1001) {n : ℕ} (ppn : ProblemPredicate n) :
SolutionPredicate n :=
H.2 _ (by linarith [lt_1000 ppn]) ppn
theorem right_direction {n : ℕ} : ProblemPredicate n → SolutionPredicate n := by
have := searchUpTo_start
iterate 82
replace :=
searchUpTo_step this (by norm_num1; rfl) (by norm_num1; rfl) rfl
(by simp +decide)
exact searchUpTo_end this
/-
Now we just need to prove the equivalence, for the precise problem statement.
-/
theorem left_direction (n : ℕ) (spn : SolutionPredicate n) : ProblemPredicate n := by
rcases spn with (rfl | rfl) <;> refine ⟨?_, by decide, ?_⟩ <;> norm_num <;> rfl
end Imo1960Q1
open Imo1960Q1
theorem imo1960_q1 (n : ℕ) : ProblemPredicate n ↔ SolutionPredicate n :=
⟨right_direction, left_direction n⟩ |
.lake/packages/mathlib/Archive/Imo/Imo2008Q4.lean | import Mathlib.Data.Real.Basic
import Mathlib.Data.Real.Sqrt
import Mathlib.Data.NNReal.Basic
import Mathlib.Tactic.LinearCombination
/-!
# IMO 2008 Q4
Find all functions `f : (0,∞) → (0,∞)` (so, `f` is a function from the positive real
numbers to the positive real numbers) such that
```
(f(w)^2 + f(x)^2)/(f(y^2) + f(z^2)) = (w^2 + x^2)/(y^2 + z^2)
```
for all positive real numbers `w`, `x`, `y`, `z`, satisfying `wx = yz`.
## Solution
The desired theorem is that either `f = fun x => x` or `f = fun x => 1/x`
-/
open Real
namespace Imo2008Q4
theorem abs_eq_one_of_pow_eq_one (x : ℝ) (n : ℕ) (hn : n ≠ 0) (h : x ^ n = 1) : |x| = 1 := by
rw [← pow_left_inj₀ (abs_nonneg x) zero_le_one hn, one_pow, pow_abs, h, abs_one]
end Imo2008Q4
open Imo2008Q4
theorem imo2008_q4 (f : ℝ → ℝ) (H₁ : ∀ x > 0, f x > 0) :
(∀ w x y z : ℝ, 0 < w → 0 < x → 0 < y → 0 < z → w * x = y * z →
(f w ^ 2 + f x ^ 2) / (f (y ^ 2) + f (z ^ 2)) = (w ^ 2 + x ^ 2) / (y ^ 2 + z ^ 2)) ↔
(∀ x > 0, f x = x) ∨ ∀ x > 0, f x = 1 / x := by
constructor; swap
-- proof that f(x) = x and f(x) = 1/x satisfy the condition
· rintro (h | h)
· intro w x y z hw hx hy hz _
rw [h w hw, h x hx, h (y ^ 2) (pow_pos hy 2), h (z ^ 2) (pow_pos hz 2)]
· intro w x y z hw hx hy hz hprod
rw [h w hw, h x hx, h (y ^ 2) (pow_pos hy 2), h (z ^ 2) (pow_pos hz 2)]
field_simp
linear_combination - (z ^ 2 + y ^ 2) * (w ^ 2 + x ^ 2) * (w * x + y * z) * hprod
-- proof that the only solutions are f(x) = x or f(x) = 1/x
intro H₂
have h₀ : f 1 ≠ 0 := (H₁ 1 zero_lt_one).ne'
have h₁ : f 1 = 1 := by
specialize H₂ 1 1 1 1 zero_lt_one zero_lt_one zero_lt_one
grind
have h₂ : ∀ x > 0, (f x - x) * (f x - 1 / x) = 0 := by
intro x hx
have h1xss : 1 * x = sqrt x * sqrt x := by grind [mul_self_sqrt]
specialize H₂ 1 x (sqrt x) (sqrt x) zero_lt_one
grind [sqrt_pos]
have h₃ : ∀ x > 0, f x = x ∨ f x = 1 / x := by simpa [sub_eq_zero] using h₂
by_contra! h
rcases h with ⟨⟨b, hb, hfb₁⟩, ⟨a, ha, hfa₁⟩⟩
obtain hfa₂ := Or.resolve_right (h₃ a ha) hfa₁
-- f(a) ≠ 1/a, f(a) = a
obtain hfb₂ := Or.resolve_left (h₃ b hb) hfb₁
-- f(b) ≠ b, f(b) = 1/b
have hab : a * b > 0 := mul_pos ha hb
have habss : a * b = sqrt (a * b) * sqrt (a * b) := (mul_self_sqrt (le_of_lt hab)).symm
specialize H₂ a b (sqrt (a * b)) (sqrt (a * b)) ha hb (sqrt_pos.mpr hab) (sqrt_pos.mpr hab) habss
rw [sq_sqrt (le_of_lt hab), ← two_mul (f (a * b)), ← two_mul (a * b)] at H₂
rw [hfa₂, hfb₂] at H₂
have h2ab_ne_0 : 2 * (a * b) ≠ 0 := by positivity
specialize h₃ (a * b) hab
rcases h₃ with hab₁ | hab₂
-- f(ab) = ab → b^4 = 1 → b = 1 → f(b) = b → false
· rw [hab₁] at H₂
field_simp at H₂
obtain hb₂ := abs_eq_one_of_pow_eq_one b 4 (show 4 ≠ 0 by simp) (by grind)
grind [abs_of_pos]
-- f(ab) = 1/ab → a^4 = 1 → a = 1 → f(a) = 1/a → false
· simp only [hab₂, field] at H₂
obtain ha₂ := abs_eq_one_of_pow_eq_one a 4 (show 4 ≠ 0 by simp) (by grind)
grind [abs_of_pos] |
.lake/packages/mathlib/Archive/Imo/Imo1998Q2.lean | import Mathlib.Algebra.Order.BigOperators.Group.Finset
import Mathlib.Algebra.Order.Field.Basic
import Mathlib.Algebra.Order.Field.Rat
import Mathlib.Data.Finite.Prod
import Mathlib.GroupTheory.GroupAction.Ring
import Mathlib.Tactic.NoncommRing
import Mathlib.Tactic.Ring
/-!
# IMO 1998 Q2
In a competition, there are `a` contestants and `b` judges, where `b ≥ 3` is an odd integer. Each
judge rates each contestant as either "pass" or "fail". Suppose `k` is a number such that, for any
two judges, their ratings coincide for at most `k` contestants. Prove that `k / a ≥ (b - 1) / (2b)`.
## Solution
The problem asks us to think about triples consisting of a contestant and two judges whose ratings
agree for that contestant. We thus consider the subset `A ⊆ C × JJ` of all such incidences of
agreement, where `C` and `J` are the sets of contestants and judges, and `JJ = J × J - {(j, j)}`. We
have natural maps: `left : A → C` and `right: A → JJ`. We count the elements of `A` in two ways: as
the sum of the cardinalities of the fibres of `left` and as the sum of the cardinalities of the
fibres of `right`. We obtain an upper bound on the cardinality of `A` from the count for `right`,
and a lower bound from the count for `left`. These two bounds combine to the required result.
First consider the map `right : A → JJ`. Since the size of any fibre over a point in JJ is bounded
by `k` and since `|JJ| = b^2 - b`, we obtain the upper bound: `|A| ≤ k(b^2-b)`.
Now consider the map `left : A → C`. The fibre over a given contestant `c ∈ C` is the set of
ordered pairs of (distinct) judges who agree about `c`. We seek to bound the cardinality of this
fibre from below. Minimum agreement for a contestant occurs when the judges' ratings are split as
evenly as possible. Since `b` is odd, this occurs when they are divided into groups of size
`(b-1)/2` and `(b+1)/2`. This corresponds to a fibre of cardinality `(b-1)^2/2` and so we obtain
the lower bound: `a(b-1)^2/2 ≤ |A|`.
Rearranging gives the result.
-/
variable {C J : Type*} (r : C → J → Prop)
namespace Imo1998Q2
noncomputable section
/-- An ordered pair of judges. -/
abbrev JudgePair (J : Type*) :=
J × J
/-- A triple consisting of contestant together with an ordered pair of judges. -/
abbrev AgreedTriple (C J : Type*) :=
C × JudgePair J
/-- The first judge from an ordered pair of judges. -/
abbrev JudgePair.judge₁ : JudgePair J → J :=
Prod.fst
/-- The second judge from an ordered pair of judges. -/
abbrev JudgePair.judge₂ : JudgePair J → J :=
Prod.snd
/-- The proposition that the judges in an ordered pair are distinct. -/
abbrev JudgePair.Distinct (p : JudgePair J) :=
p.judge₁ ≠ p.judge₂
/-- The proposition that the judges in an ordered pair agree about a contestant's rating. -/
abbrev JudgePair.Agree (p : JudgePair J) (c : C) :=
r c p.judge₁ ↔ r c p.judge₂
/-- The contestant from the triple consisting of a contestant and an ordered pair of judges. -/
abbrev AgreedTriple.contestant : AgreedTriple C J → C :=
Prod.fst
/-- The ordered pair of judges from the triple consisting of a contestant and an ordered pair of
judges. -/
abbrev AgreedTriple.judgePair : AgreedTriple C J → JudgePair J :=
Prod.snd
@[simp]
theorem JudgePair.agree_iff_same_rating (p : JudgePair J) (c : C) :
p.Agree r c ↔ (r c p.judge₁ ↔ r c p.judge₂) :=
Iff.rfl
open scoped Classical in
/-- The set of contestants on which two judges agree. -/
def agreedContestants [Fintype C] (p : JudgePair J) : Finset C :=
Finset.univ.filter fun c => p.Agree r c
section
variable [Fintype J] [Fintype C]
open scoped Classical in
/-- All incidences of agreement. -/
def A : Finset (AgreedTriple C J) :=
Finset.univ.filter @fun (a : AgreedTriple C J) =>
(a.judgePair.Agree r a.contestant ∧ a.judgePair.Distinct)
open scoped Classical in
theorem A_maps_to_offDiag_judgePair (a : AgreedTriple C J) :
a ∈ A r → a.judgePair ∈ Finset.offDiag (@Finset.univ J _) := by simp [A, Finset.mem_offDiag]
open scoped Classical in
theorem A_fibre_over_contestant (c : C) :
(Finset.univ.filter fun p : JudgePair J => p.Agree r c ∧ p.Distinct) =
((A r).filter fun a : AgreedTriple C J => a.contestant = c).image Prod.snd := by
ext p
simp [A]
open scoped Classical in
theorem A_fibre_over_contestant_card (c : C) :
(Finset.univ.filter fun p : JudgePair J => p.Agree r c ∧ p.Distinct).card =
((A r).filter fun a : AgreedTriple C J => a.contestant = c).card := by
rw [A_fibre_over_contestant r]
apply Finset.card_image_of_injOn
unfold Set.InjOn
rintro ⟨a, p⟩ h ⟨a', p'⟩ h' rfl
aesop (add simp AgreedTriple.contestant)
open scoped Classical in
theorem A_fibre_over_judgePair {p : JudgePair J} (h : p.Distinct) :
agreedContestants r p = ((A r).filter fun a : AgreedTriple C J => a.judgePair = p).image
AgreedTriple.contestant := by
dsimp only [A, agreedContestants]; ext c; constructor <;> intro h
· rw [Finset.mem_image]; refine ⟨⟨c, p⟩, ?_⟩; aesop
· aesop
open scoped Classical in
theorem A_fibre_over_judgePair_card {p : JudgePair J} (h : p.Distinct) :
(agreedContestants r p).card =
((A r).filter fun a : AgreedTriple C J => a.judgePair = p).card := by
rw [A_fibre_over_judgePair r h]
apply Finset.card_image_of_injOn
-- `aesop` sees through the abbrev `AgreedTriple C J = C × (J × J)`, but `simp` does not.
-- Tell `simp` to unfold the abbreviations more aggressively, and it works.
-- See also: https://leanprover.zulipchat.com/#narrow/channel/270676-lean4/topic/.60simp.60.20can't.20see.20through.20structure.20abbrevs.3F/with/534442087
aesop (add simp [Set.InjOn, AgreedTriple.contestant, AgreedTriple.judgePair])
theorem A_card_upper_bound {k : ℕ}
(hk : ∀ p : JudgePair J, p.Distinct → (agreedContestants r p).card ≤ k) :
(A r).card ≤ k * (Fintype.card J * Fintype.card J - Fintype.card J) := by
change _ ≤ k * (Finset.card _ * Finset.card _ - Finset.card _)
classical
rw [← Finset.offDiag_card]
apply Finset.card_le_mul_card_image_of_maps_to (A_maps_to_offDiag_judgePair r)
intro p hp
have hp' : p.Distinct := by grind
rw [← A_fibre_over_judgePair_card r hp']; apply hk; exact hp'
end
theorem add_sq_add_sq_sub {α : Type*} [Ring α] (x y : α) :
(x + y) * (x + y) + (x - y) * (x - y) = 2 * x * x + 2 * y * y := by noncomm_ring
theorem norm_bound_of_odd_sum {x y z : ℤ} (h : x + y = 2 * z + 1) :
2 * z * z + 2 * z + 1 ≤ x * x + y * y := by
suffices 4 * z * z + 4 * z + 1 + 1 ≤ 2 * x * x + 2 * y * y by
rw [← mul_le_mul_iff_right₀ (zero_lt_two' ℤ)]; ring_nf at this ⊢; exact this
have h' : (x + y) * (x + y) = 4 * z * z + 4 * z + 1 := by rw [h]; ring
rw [← add_sq_add_sq_sub, h', add_le_add_iff_left]
suffices 0 < (x - y) * (x - y) by apply Int.add_one_le_of_lt this
rw [mul_self_pos, sub_ne_zero]; apply Int.ne_of_odd_add ⟨z, h⟩
section
variable [Fintype J]
open scoped Classical in
theorem judge_pairs_card_lower_bound {z : ℕ} (hJ : Fintype.card J = 2 * z + 1) (c : C) :
2 * z * z + 2 * z + 1 ≤ (Finset.univ.filter fun p : JudgePair J => p.Agree r c).card := by
let x := (Finset.univ.filter fun j => r c j).card
let y := (Finset.univ.filter fun j => ¬r c j).card
have h : (Finset.univ.filter fun p : JudgePair J => p.Agree r c).card = x * x + y * y := by
simp [x, y, ← Finset.filter_product_card]
rw [h]; apply Int.le_of_ofNat_le_ofNat; simp only [Int.natCast_add, Int.natCast_mul]
apply norm_bound_of_odd_sum
suffices x + y = 2 * z + 1 by simp [← Int.natCast_add, this]
rw [Finset.filter_card_add_filter_neg_card_eq_card, ← hJ, Finset.card_univ]
open scoped Classical in
theorem distinct_judge_pairs_card_lower_bound {z : ℕ} (hJ : Fintype.card J = 2 * z + 1) (c : C) :
2 * z * z ≤ (Finset.univ.filter fun p : JudgePair J => p.Agree r c ∧ p.Distinct).card := by
let s := Finset.univ.filter fun p : JudgePair J => p.Agree r c
let t := Finset.univ.filter fun p : JudgePair J => p.Distinct
have hs : 2 * z * z + 2 * z + 1 ≤ s.card := judge_pairs_card_lower_bound r hJ c
have hst : s \ t = Finset.univ.diag := by
ext p; constructor <;> intro hp
· unfold s t at hp
aesop
· unfold s t
suffices p.judge₁ = p.judge₂ by simp [this]
aesop
have hst' : (s \ t).card = 2 * z + 1 := by rw [hst, Finset.diag_card, ← hJ, Finset.card_univ]
rw [Finset.filter_and, ← Finset.sdiff_sdiff_self_left s t, Finset.card_sdiff_of_subset]
· rw [hst']; rw [add_assoc] at hs; apply le_tsub_of_add_le_right hs
· apply Finset.sdiff_subset
theorem A_card_lower_bound [Fintype C] {z : ℕ} (hJ : Fintype.card J = 2 * z + 1) :
2 * z * z * Fintype.card C ≤ (A r).card := by
classical
have h : ∀ a, a ∈ A r → Prod.fst a ∈ @Finset.univ C _ := by intros; apply Finset.mem_univ
apply Finset.mul_card_image_le_card_of_maps_to h
intro c _
rw [← A_fibre_over_contestant_card]
apply distinct_judge_pairs_card_lower_bound r hJ
end
theorem clear_denominators {a b k : ℕ} (ha : 0 < a) (hb : 0 < b) :
(b - 1 : ℚ) / (2 * b) ≤ k / a ↔ ((b : ℕ) - 1) * a ≤ k * (2 * b) := by
rw [div_le_div_iff₀]
on_goal 1 => convert Nat.cast_le (α := ℚ)
all_goals simp [ha, hb]
end
end Imo1998Q2
open Imo1998Q2
theorem imo1998_q2 [Fintype J] [Fintype C] (a b k : ℕ) (hC : Fintype.card C = a)
(hJ : Fintype.card J = b) (ha : 0 < a) (hb : Odd b)
(hk : ∀ p : JudgePair J, p.Distinct → (agreedContestants r p).card ≤ k) :
(b - 1 : ℚ) / (2 * b) ≤ k / a := by
rw [clear_denominators ha hb.pos]
obtain ⟨z, hz⟩ := hb; rw [hz] at hJ; rw [hz]
have h := le_trans (A_card_lower_bound r hJ) (A_card_upper_bound r hk)
rw [hC, hJ] at h
-- We are now essentially done; we just need to bash `h` into exactly the right shape.
have hl : k * ((2 * z + 1) * (2 * z + 1) - (2 * z + 1)) = k * (2 * (2 * z + 1)) * z := by
have : 0 < 2 * z + 1 := by aesop
simp only [mul_comm, add_mul, one_mul, add_tsub_cancel_right]; ring
have hr : 2 * z * z * a = 2 * z * a * z := by ring
rw [hl, hr] at h
rcases z with - | z
· simp
· exact le_of_mul_le_mul_right h z.succ_pos |
.lake/packages/mathlib/Archive/Imo/Imo1962Q1.lean | import Mathlib.Data.Nat.Digits.Lemmas
/-!
# IMO 1962 Q1
Find the smallest natural number $n$ which has the following properties:
(a) Its decimal representation has 6 as the last digit.
(b) If the last digit 6 is erased and placed in front of the remaining digits,
the resulting number is four times as large as the original number $n$.
Since Lean does not explicitly express problems of the form "find the smallest number satisfying X",
we define the problem as a predicate, and then prove a particular number is the smallest member
of a set satisfying it.
-/
namespace Imo1962Q1
open Nat
def ProblemPredicate (n : ℕ) : Prop :=
(digits 10 n).headI = 6 ∧ ofDigits 10 ((digits 10 n).tail.concat 6) = 4 * n
/-!
First, it's inconvenient to work with digits, so let's simplify them out of the problem.
-/
abbrev ProblemPredicate' (c n : ℕ) : Prop :=
n = 10 * c + 6 ∧ 6 * 10 ^ (digits 10 c).length + c = 4 * n
lemma without_digits {n : ℕ} (hn : ProblemPredicate n) : ∃ c : ℕ, ProblemPredicate' c n := by
use n / 10
rcases n with - | n
· have hpp : ¬ProblemPredicate 0 := by simp [ProblemPredicate]
contradiction
· rw [ProblemPredicate, digits_def' (by decide : 2 ≤ 10) n.succ_pos, List.headI, List.tail_cons,
List.concat_eq_append] at hn
constructor
· rw [← hn.left, div_add_mod (n + 1) 10]
· rw [← hn.right, ofDigits_append, ofDigits_digits, ofDigits_singleton, add_comm, mul_comm]
/-!
Now we can eliminate possibilities for `(digits 10 c).length` until we get to the one that works.
-/
lemma case_0_digits {c n : ℕ} (hc : (digits 10 c).length = 0) : ¬ProblemPredicate' c n := by
intro hpp
have hpow : 6 * 10 ^ 0 = 6 * 10 ^ (digits 10 c).length := by rw [hc]
omega
lemma case_1_digits {c n : ℕ} (hc : (digits 10 c).length = 1) : ¬ProblemPredicate' c n := by
intro hpp
have hpow : 6 * 10 ^ 1 = 6 * 10 ^ (digits 10 c).length := by rw [hc]
omega
lemma case_2_digits {c n : ℕ} (hc : (digits 10 c).length = 2) : ¬ProblemPredicate' c n := by
intro hpp
have hpow : 6 * 10 ^ 2 = 6 * 10 ^ (digits 10 c).length := by rw [hc]
omega
lemma case_3_digits {c n : ℕ} (hc : (digits 10 c).length = 3) : ¬ProblemPredicate' c n := by
intro hpp
have hpow : 6 * 10 ^ 3 = 6 * 10 ^ (digits 10 c).length := by rw [hc]
omega
lemma case_4_digits {c n : ℕ} (hc : (digits 10 c).length = 4) : ¬ProblemPredicate' c n := by
intro hpp
have hpow : 6 * 10 ^ 4 = 6 * 10 ^ (digits 10 c).length := by rw [hc]
omega
/-- Putting this inline causes a deep recursion error, so we separate it out. -/
private lemma helper_5_digits {c : ℤ} (hc : 6 * 10 ^ 5 + c = 4 * (10 * c + 6)) : c = 15384 := by
omega
lemma case_5_digits {c n : ℕ} (hc : (digits 10 c).length = 5) (hpp : ProblemPredicate' c n) :
c = 15384 := by
have hpow : 6 * 10 ^ 5 + c = 6 * 10 ^ (digits 10 c).length + c := by rw [hc]
have hmul : 6 * 10 ^ 5 + c = 4 * (10 * c + 6) := by rw [hpow, hpp.right, hpp.left]
zify at *
exact helper_5_digits hmul
/-- `linarith` fails on numbers this large, so this lemma spells out some of the arithmetic
that normally would be automated.
-/
lemma case_more_digits {c n : ℕ} (hc : (digits 10 c).length ≥ 6) (hpp : ProblemPredicate' c n) :
n ≥ 153846 := by
have hnz : c ≠ 0 := by
intro hc0
have hcl : (digits 10 c).length = 0 := by simp [hc0]
exact case_0_digits hcl hpp
calc
n ≥ 10 * c := le.intro hpp.left.symm
_ ≥ 10 ^ (digits 10 c).length := base_pow_length_digits_le 10 c (by decide) hnz
_ ≥ 10 ^ 6 := pow_right_mono₀ (by decide) hc
_ ≥ 153846 := by simp
/-!
Now we combine these cases to show that 153846 is the smallest solution.
-/
lemma satisfied_by_153846 : ProblemPredicate 153846 := by
norm_num [ProblemPredicate]
decide
lemma no_smaller_solutions (n : ℕ) (hn : ProblemPredicate n) : n ≥ 153846 := by
have ⟨c, hcn⟩ := without_digits hn
cases lt_or_ge (digits 10 c).length 6 with
| inl =>
interval_cases hc : (digits 10 c).length
· exfalso; exact case_0_digits hc hcn
· exfalso; exact case_1_digits hc hcn
· exfalso; exact case_2_digits hc hcn
· exfalso; exact case_3_digits hc hcn
· exfalso; exact case_4_digits hc hcn
· exact (case_5_digits hc hcn ▸ hcn.left).ge
| inr hge => exact case_more_digits hge hcn
end Imo1962Q1
open Imo1962Q1
theorem imo1962_q1 : IsLeast {n | ProblemPredicate n} 153846 :=
⟨satisfied_by_153846, no_smaller_solutions⟩ |
.lake/packages/mathlib/Archive/Imo/Imo1963Q5.lean | import Mathlib.Analysis.SpecialFunctions.Trigonometric.Complex
/-!
# IMO 1963 Q5
Prove that `cos (π / 7) - cos (2 * π / 7) + cos (3 * π / 7) = 1 / 2`.
The main idea of the proof is to multiply both sides by `2 * sin (π / 7)`, then the result follows
through basic algebraic manipulations with the use of some trigonometric identities.
-/
open Real
lemma two_sin_pi_div_seven_ne_zero : 2 * sin (π / 7) ≠ 0 := by
apply mul_ne_zero two_ne_zero (Real.sin_pos_of_pos_of_lt_pi _ _).ne' <;> linarith [pi_pos]
lemma sin_pi_mul_neg_div (a b : ℝ) : sin (π * (- a / b)) = - sin (π * (a / b)) := by
ring_nf
exact sin_neg _
theorem imo1963_q5 : cos (π / 7) - cos (2 * π / 7) + cos (3 * π / 7) = 1 / 2 := by
rw [← mul_right_inj' two_sin_pi_div_seven_ne_zero, mul_add, mul_sub, ← sin_two_mul,
two_mul_sin_mul_cos, two_mul_sin_mul_cos]
ring_nf
rw [← sin_pi_sub (π * (3 / 7)), sin_pi_mul_neg_div 2 7, sin_pi_mul_neg_div 1 7]
ring_nf |
.lake/packages/mathlib/Archive/Imo/Imo2001Q6.lean | import Mathlib.Algebra.Ring.Associated
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.LinearCombination
/-!
# IMO 2001 Q6
Let $a$, $b$, $c$, $d$ be integers with $a > b > c > d > 0$. Suppose that
$$ a*c + b*d = (a + b - c + d) * (-a + b + c + d). $$
Prove that $a*b + c*d$ is not prime.
-/
variable {a b c d : ℤ}
theorem imo2001_q6 (hd : 0 < d) (hdc : d < c) (hcb : c < b) (hba : b < a)
(h : a * c + b * d = (a + b - c + d) * (-a + b + c + d)) : ¬Prime (a * b + c * d) := by
intro (h0 : Prime (a * b + c * d))
have ha : 0 < a := by omega
have hb : 0 < b := by omega
have hc : 0 < c := by omega
-- the key step is to show that `a*c + b*d` divides the product `(a*b + c*d) * (a*d + b*c)`
have dvd_mul : a * c + b * d ∣ (a * b + c * d) * (a * d + b * c) := by
use b ^ 2 + b * d + d ^ 2
linear_combination b * d * h
-- since `a*b + c*d` is prime (by assumption), it must divide `a*c + b*d` or `a*d + b*c`
obtain (h1 : a * b + c * d ∣ a * c + b * d) | (h2 : a * c + b * d ∣ a * d + b * c) :=
h0.left_dvd_or_dvd_right_of_dvd_mul dvd_mul
-- in both cases, we derive a contradiction
· have aux : 0 < a * c + b * d := by nlinarith only [ha, hb, hc, hd]
have : a * b + c * d ≤ a * c + b * d := Int.le_of_dvd aux h1
nlinarith only [hba, hcb, hdc, h, this]
· have aux : 0 < a * d + b * c := by nlinarith only [ha, hb, hc, hd]
have : a * c + b * d ≤ a * d + b * c := Int.le_of_dvd aux h2
nlinarith only [hba, hdc, h, this] |
.lake/packages/mathlib/Archive/Imo/Imo2024Q2.lean | import Mathlib.FieldTheory.Finite.Basic
/-!
# IMO 2024 Q2
Determine all pairs $(a,b)$ of positive integers for which there exist positive integers
$g$ and $N$ such that
\[ \gcd(a^n + b, b^n + a) = g \]
holds for all integers $n \ge N$.
We consider the sequence modulo `ab+1`; if the exponent is `-1` modulo `φ(ab+1)`, the terms
are zero modulo `ab+1`, so `ab+1` divides `g`, and all sufficiently large terms, so all terms,
from which we conclude that `a=b=1`.
-/
namespace Imo2024Q2
open scoped Nat
/-- The condition of the problem. -/
def Condition (a b : ℕ) : Prop :=
0 < a ∧ 0 < b ∧ ∃ g N : ℕ, 0 < g ∧ 0 < N ∧ ∀ n : ℕ, N ≤ n → Nat.gcd (a ^ n + b) (b ^ n + a) = g
lemma dvd_pow_iff_of_dvd_sub {a b d n : ℕ} {z : ℤ} (ha : a.Coprime d)
(hd : (φ d : ℤ) ∣ (n : ℤ) - z) :
d ∣ a ^ n + b ↔ (((ZMod.unitOfCoprime _ ha) ^ z : (ZMod d)ˣ) : ZMod d) + b = 0 := by
rcases hd with ⟨k, hk⟩
rw [← ZMod.natCast_eq_zero_iff]
convert Iff.rfl
push_cast
congr
suffices (((ZMod.unitOfCoprime _ ha) ^ z : (ZMod d)ˣ) : ZMod d) =
(((ZMod.unitOfCoprime _ ha) ^ (n : ℤ) : (ZMod d)ˣ) : ZMod d) by
convert this
rw [sub_eq_iff_eq_add] at hk
rw [hk, zpow_add, zpow_mul]
norm_cast
rw [ZMod.pow_totient, one_zpow, one_mul]
namespace Condition
variable {a b : ℕ} (h : Condition a b)
section
include h
lemma a_pos : 0 < a := h.1
lemma b_pos : 0 < b := h.2.1
/-- The value of `g` in the problem (determined by `a` and `b`). -/
noncomputable def g : ℕ := h.2.2.choose
lemma g_spec : ∃ N : ℕ, 0 < h.g ∧ 0 < N ∧ ∀ n : ℕ, N ≤ n → Nat.gcd (a ^ n + b) (b ^ n + a) = h.g :=
h.2.2.choose_spec
/-- The value of `N` in the problem (any sufficiently large value). -/
noncomputable def N : ℕ := h.g_spec.choose
lemma N_spec : 0 < h.g ∧ 0 < h.N ∧ ∀ n : ℕ, h.N ≤ n → Nat.gcd (a ^ n + b) (b ^ n + a) = h.g :=
h.g_spec.choose_spec
lemma g_pos : 0 < h.g := h.N_spec.1
lemma N_pos : 0 < h.N := h.N_spec.2.1
lemma gcd_eq_g {n : ℕ} (hn : h.N ≤ n) : Nat.gcd (a ^ n + b) (b ^ n + a) = h.g := h.N_spec.2.2 n hn
protected lemma symm : Condition b a := by
refine ⟨h.b_pos, h.a_pos, h.g, h.N, h.g_pos, h.N_pos, fun n hn ↦ ?_⟩
rw [Nat.gcd_comm]
exact h.gcd_eq_g hn
lemma dvd_g_of_le_N_of_dvd {n : ℕ} (hn : h.N ≤ n) {d : ℕ} (hab : d ∣ a ^ n + b)
(hba : d ∣ b ^ n + a) : d ∣ h.g := by
rw [← h.gcd_eq_g hn, Nat.dvd_gcd_iff]
exact ⟨hab, hba⟩
end
lemma a_coprime_ab_add_one : a.Coprime (a * b + 1) := by
simp
/-- A sufficiently large value of n, congruent to `-1` mod `φ (a * b + 1)`. -/
noncomputable def large_n : ℕ := (max h.N h.symm.N + 1) * φ (a * b + 1) - 1
lemma symm_large_n : h.symm.large_n = h.large_n := by
simp_rw [large_n]
congr 2
· rw [max_comm]
· rw [mul_comm]
lemma N_le_large_n : h.N ≤ h.large_n := by
have hp : 0 < φ (a * b + 1) := Nat.totient_pos.2 (Nat.add_pos_right _ zero_lt_one)
rw [large_n, add_mul, one_mul, Nat.add_sub_assoc (Nat.one_le_of_lt hp)]
suffices h.N ≤ h.N * φ (a * b + 1) + (φ (a * b + 1) - 1) by
refine this.trans ?_
gcongr
simp
exact Nat.le_add_right_of_le (Nat.le_mul_of_pos_right _ hp)
lemma dvd_large_n_sub_neg_one : (φ (a * b + 1) : ℤ) ∣ (h.large_n : ℤ) - (-1 : ℤ) := by
simp [large_n]
/-- A sufficiently large value of n, congruent to `0` mod `φ (a * b + 1)`. -/
noncomputable def large_n_0 : ℕ := (max h.N h.symm.N) * φ (a * b + 1)
lemma symm_large_n_0 : h.symm.large_n_0 = h.large_n_0 := by
simp_rw [large_n_0]
congr 1
· rw [max_comm]
· rw [mul_comm]
lemma N_le_large_n_0 : h.N ≤ h.large_n_0 := by
have hp : 0 < φ (a * b + 1) := Nat.totient_pos.2 (Nat.add_pos_right _ zero_lt_one)
rw [large_n_0]
suffices h.N ≤ h.N * φ (a * b + 1) by
refine this.trans ?_
gcongr
simp
exact Nat.le_mul_of_pos_right _ hp
lemma dvd_large_n_0_sub_zero : (φ (a * b + 1) : ℤ) ∣ (h.large_n_0 : ℤ) - (0 : ℤ) := by
simp [large_n_0]
lemma ab_add_one_dvd_a_pow_large_n_add_b : a * b + 1 ∣ a ^ h.large_n + b := by
rw [dvd_pow_iff_of_dvd_sub a_coprime_ab_add_one h.dvd_large_n_sub_neg_one, zpow_neg, zpow_one]
suffices ((ZMod.unitOfCoprime _ a_coprime_ab_add_one : (ZMod (a * b + 1))ˣ) : ZMod (a * b + 1)) *
((((ZMod.unitOfCoprime _ a_coprime_ab_add_one)⁻¹ : (ZMod (a * b + 1))ˣ) :
ZMod (a * b + 1)) + (b : ZMod (a * b + 1))) = 0 from
(IsUnit.mul_right_eq_zero (ZMod.unitOfCoprime _ a_coprime_ab_add_one).isUnit).1 this
rw [mul_add]
norm_cast
simp only [mul_inv_cancel, Units.val_one, ZMod.coe_unitOfCoprime]
norm_cast
convert ZMod.natCast_self (a * b + 1) using 2
exact add_comm _ _
lemma ab_add_one_dvd_b_pow_large_n_add_a : a * b + 1 ∣ b ^ h.large_n + a := by
convert h.symm.ab_add_one_dvd_a_pow_large_n_add_b using 1
· rw [mul_comm]
· rw [h.symm_large_n]
lemma ab_add_one_dvd_g : a * b + 1 ∣ h.g :=
h.dvd_g_of_le_N_of_dvd h.N_le_large_n h.ab_add_one_dvd_a_pow_large_n_add_b
h.ab_add_one_dvd_b_pow_large_n_add_a
lemma ab_add_one_dvd_a_pow_large_n_0_add_b : a * b + 1 ∣ a ^ h.large_n_0 + b := by
refine h.ab_add_one_dvd_g.trans ?_
rw [← h.gcd_eq_g h.N_le_large_n_0]
exact Nat.gcd_dvd_left _ _
include h
lemma ab_add_one_dvd_b_add_one : a * b + 1 ∣ b + 1 := by
rw [add_comm b]
suffices a * b + 1 ∣ a ^ h.large_n_0 + b by
rw [dvd_pow_iff_of_dvd_sub a_coprime_ab_add_one h.dvd_large_n_0_sub_zero, zpow_zero] at this
rw [← ZMod.natCast_eq_zero_iff]
push_cast
norm_cast at this
exact h.ab_add_one_dvd_a_pow_large_n_0_add_b
lemma a_eq_one : a = 1 := by
have hle : a * b + 1 ≤ b + 1 := Nat.le_of_dvd (by omega) h.ab_add_one_dvd_b_add_one
rw [add_le_add_iff_right] at hle
suffices a ≤ 1 by
have hp := h.a_pos
omega
have hle' : a * b ≤ 1 * b := by
simpa using hle
exact Nat.le_of_mul_le_mul_right hle' h.b_pos
lemma b_eq_one : b = 1 := h.symm.a_eq_one
end Condition
/-- This is to be determined by the solver of the original problem. -/
def solutionSet : Set (ℕ × ℕ) := {(1, 1)}
theorem result (a b : ℕ) : Condition a b ↔ (a, b) ∈ solutionSet := by
refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩
· simp only [solutionSet, Set.mem_singleton_iff, Prod.mk.injEq]
exact ⟨h.a_eq_one, h.b_eq_one⟩
· simp only [solutionSet, Set.mem_singleton_iff, Prod.mk.injEq] at h
rcases h with ⟨rfl, rfl⟩
rw [Condition]
refine ⟨by decide, by decide, 2, 1, ?_⟩
simp
end Imo2024Q2 |
.lake/packages/mathlib/Archive/Imo/Imo2021Q1.lean | import Mathlib.Order.Interval.Finset.Nat
import Mathlib.Tactic.IntervalCases
import Mathlib.Tactic.Linarith
/-!
# IMO 2021 Q1
Let `n ≥ 100` be an integer. Ivan writes the numbers `n, n+1, ..., 2*n` each on different cards.
He then shuffles these `n+1` cards, and divides them into two piles. Prove that at least one
of the piles contains two cards such that the sum of their numbers is a perfect square.
## Solution
We show there exists a triplet `a, b, c ∈ [n , 2n]` with `a < b < c` and each of the sums `(a + b)`,
`(b + c)`, `(a + c)` being a perfect square. Specifically, we consider the linear system of
equations
a + b = (2 * l - 1) ^ 2
a + c = (2 * l) ^ 2
b + c = (2 * l + 1) ^ 2
which can be solved to give
a = 2 * l ^ 2 - 4 * l
b = 2 * l ^ 2 + 1
c = 2 * l ^ 2 + 4 * l
Therefore, it is enough to show that there exists a natural number `l` such that
`n ≤ 2 * l ^ 2 - 4 * l` and `2 * l ^ 2 + 4 * l ≤ 2 * n` for `n ≥ 100`.
Then, by the Pigeonhole principle, at least two numbers in the triplet must lie in the same pile,
which finishes the proof.
-/
open Finset
namespace Imo2021Q1
-- We will later make use of the fact that there exists `l : ℕ` such that
-- `n ≤ 2 * l ^ 2 - 4 * l` and `2 * l ^ 2 + 4 * l ≤ 2 * n` for `n ≥ 100`.
lemma exists_numbers_in_interval {n : ℕ} (hn : 100 ≤ n) :
∃ l : ℕ, n + 4 * l ≤ 2 * l ^ 2 ∧ 2 * l ^ 2 + 4 * l ≤ 2 * n := by
have hn' : 1 ≤ Nat.sqrt (n + 1) := by
rw [Nat.le_sqrt]
apply Nat.le_add_left
have h₁ := Nat.sqrt_le' (n + 1)
have h₂ := Nat.succ_le_succ_sqrt' (n + 1)
have h₃ : 10 ≤ (n + 1).sqrt := by
rw [Nat.le_sqrt]
omega
rw [← Nat.sub_add_cancel hn'] at h₁ h₂ h₃
set l := (n + 1).sqrt - 1
refine ⟨l, ?_, ?_⟩
· calc n + 4 * l ≤ (l ^ 2 + 4 * l + 2) + 4 * l := by linarith only [h₂]
_ ≤ 2 * l ^ 2 := by nlinarith only [h₃]
· linarith only [h₁]
lemma exists_triplet_summing_to_squares {n : ℕ} (hn : 100 ≤ n) :
∃ a b c : ℕ, n ≤ a ∧ a < b ∧ b < c ∧ c ≤ 2 * n ∧
IsSquare (a + b) ∧ IsSquare (c + a) ∧ IsSquare (b + c) := by
obtain ⟨l, hl1, hl2⟩ := exists_numbers_in_interval hn
have hl : 1 < l := by contrapose! hl1; interval_cases l <;> linarith
have h₁ : 4 * l ≤ 2 * l ^ 2 := by omega
have h₂ : 1 ≤ 2 * l := by omega
refine ⟨2 * l ^ 2 - 4 * l, 2 * l ^ 2 + 1, 2 * l ^ 2 + 4 * l, ?_, ?_, ?_,
⟨?_, ⟨2 * l - 1, ?_⟩, ⟨2 * l, ?_⟩, 2 * l + 1, ?_⟩⟩
all_goals zify [h₁, h₂]; linarith
-- Since it will be more convenient to work with sets later on, we will translate the above claim
-- to state that there always exists a set B ⊆ [n, 2n] of cardinality at least 3, such that each
-- pair of pairwise unequal elements of B sums to a perfect square.
lemma exists_finset_3_le_card_with_pairs_summing_to_squares {n : ℕ} (hn : 100 ≤ n) :
∃ B : Finset ℕ,
2 * 1 + 1 ≤ #B ∧
(∀ a ∈ B, ∀ b ∈ B, a ≠ b → IsSquare (a + b)) ∧
∀ c ∈ B, n ≤ c ∧ c ≤ 2 * n := by
obtain ⟨a, b, c, hna, hab, hbc, hcn, h₁, h₂, h₃⟩ := exists_triplet_summing_to_squares hn
refine ⟨{a, b, c}, ?_, ?_, ?_⟩
· suffices a ∉ {b, c} ∧ b ∉ {c} by
rw [Finset.card_insert_of_notMem this.1, Finset.card_insert_of_notMem this.2,
Finset.card_singleton]
grind
· intro x hx y hy hxy
simp only [Finset.mem_insert, Finset.mem_singleton] at hx hy
rcases hx with (rfl | rfl | rfl) <;> rcases hy with (rfl | rfl | rfl) <;> grind
· grind
end Imo2021Q1
open Imo2021Q1
theorem imo2021_q1 :
∀ n : ℕ, 100 ≤ n → ∀ A ⊆ Finset.Icc n (2 * n),
(∃ a ∈ A, ∃ b ∈ A, a ≠ b ∧ IsSquare (a + b)) ∨
∃ a ∈ Finset.Icc n (2 * n) \ A, ∃ b ∈ Finset.Icc n (2 * n) \ A, a ≠ b ∧ IsSquare (a + b) := by
intro n hn A hA
-- For each n ∈ ℕ such that 100 ≤ n, there exists a pairwise unequal triplet {a, b, c} ⊆ [n, 2n]
-- such that all pairwise sums are perfect squares. In practice, it will be easier to use
-- a finite set B ⊆ [n, 2n] such that all pairwise unequal pairs of B sum to a perfect square
-- noting that B has cardinality greater or equal to 3, by the explicit construction of the
-- triplet {a, b, c} before.
obtain ⟨B, hB, h₁, h₂⟩ := exists_finset_3_le_card_with_pairs_summing_to_squares hn
have hBsub : B ⊆ Finset.Icc n (2 * n) := by
intro c hcB; simpa only [Finset.mem_Icc] using h₂ c hcB
have hB' : 2 * 1 < #(B ∩ (Icc n (2 * n) \ A) ∪ B ∩ A) := by
rwa [← inter_union_distrib_left, sdiff_union_self_eq_union, union_eq_left.2 hA,
inter_eq_left.2 hBsub, ← Nat.succ_le_iff]
-- Since B has cardinality greater or equal to 3, there must exist a subset C ⊆ B such that
-- for any A ⊆ [n, 2n], either C ⊆ A or C ⊆ [n, 2n] \ A and C has cardinality greater
-- or equal to 2.
obtain ⟨C, hC, hCA⟩ := Finset.exists_subset_or_subset_of_two_mul_lt_card hB'
rw [Finset.one_lt_card] at hC
rcases hC with ⟨a, ha, b, hb, hab⟩
simp only [Finset.subset_iff, Finset.mem_inter] at hCA
-- Now we split into the two cases C ⊆ [n, 2n] \ A and C ⊆ A, which can be dealt with identically.
rcases hCA with hCA | hCA <;> [right; left] <;>
exact ⟨a, (hCA ha).2, b, (hCA hb).2, hab, h₁ a (hCA ha).1 b (hCA hb).1 hab⟩ |
.lake/packages/mathlib/Archive/Imo/Imo1986Q5.lean | import Mathlib.Data.NNReal.Basic
/-!
# IMO 1986 Q5
Find all functions `f`, defined on the non-negative real numbers and taking nonnegative real values,
such that:
- $f(xf(y))f(y) = f(x + y)$ for all $x, y \ge 0$,
- $f(2) = 0$,
- $f(x) \ne 0$ for $0 \le x < 2$.
We formalize the assumptions on `f` in `Imo1986Q5.IsGood` predicate,
then prove `Imo1986Q5.IsGood f ↔ f = fun x ↦ 2 / (2 - x)`.
Note that this formalization relies on the fact that Mathlib uses 0 as the "garbage value",
namely for `2 ≤ x` we have `2 - x = 0` and `2 / (2 - x) = 0`.
Formalization is based on
[Art of Problem Solving](https://artofproblemsolving.com/wiki/index.php/1986_IMO_Problems/Problem_5)
with minor modifications.
-/
open NNReal
namespace Imo1986Q5
structure IsGood (f : ℝ≥0 → ℝ≥0) : Prop where
map_add_rev x y : f (x * f y) * f y = f (x + y)
map_two : f 2 = 0
map_ne_zero : ∀ x < 2, f x ≠ 0
namespace IsGood
variable {f : ℝ≥0 → ℝ≥0} (hf : IsGood f) {x y : ℝ≥0}
include hf
theorem map_add (x y : ℝ≥0) : f (x + y) = f (x * f y) * f y :=
(hf.map_add_rev x y).symm
theorem map_eq_zero : f x = 0 ↔ 2 ≤ x := by
refine ⟨fun hx₀ ↦ not_lt.1 fun hlt ↦ hf.map_ne_zero x hlt hx₀, fun hle ↦ ?_⟩
rcases exists_add_of_le hle with ⟨x, rfl⟩
rw [add_comm, hf.map_add, hf.map_two, mul_zero]
theorem map_ne_zero_iff : f x ≠ 0 ↔ x < 2 := by simp [hf.map_eq_zero]
theorem map_of_lt_two (hx : x < 2) : f x = 2 / (2 - x) := by
have hx' : 0 < 2 - x := tsub_pos_of_lt hx
have hfx : f x ≠ 0 := hf.map_ne_zero_iff.2 hx
apply le_antisymm
· rw [le_div_iff₀ hx', ← le_div_iff₀' hfx.bot_lt, tsub_le_iff_right, ← hf.map_eq_zero,
hf.map_add, div_mul_cancel₀ _ hfx, hf.map_two, zero_mul]
· rw [div_le_iff₀' hx', ← hf.map_eq_zero]
refine (mul_eq_zero.1 ?_).resolve_right hfx
rw [hf.map_add_rev, hf.map_eq_zero, tsub_add_cancel_of_le hx.le]
theorem map_eq (x : ℝ≥0) : f x = 2 / (2 - x) :=
match lt_or_ge x 2 with
| .inl hx => hf.map_of_lt_two hx
| .inr hx => by rwa [tsub_eq_zero_of_le hx, div_zero, hf.map_eq_zero]
end IsGood
theorem isGood_iff {f : ℝ≥0 → ℝ≥0} : IsGood f ↔ f = fun x ↦ 2 / (2 - x) := by
refine ⟨fun hf ↦ funext hf.map_eq, ?_⟩
rintro rfl
constructor
case map_two => simp [tsub_self]
case map_ne_zero => intro x hx; simpa [tsub_eq_zero_iff_le]
case map_add_rev =>
intro x y
cases lt_or_ge y 2 with
| inl hy =>
have hy' : 2 - y ≠ 0 := (tsub_pos_of_lt hy).ne'
rw [div_mul_div_comm, tsub_mul, mul_assoc, div_mul_cancel₀ _ hy', mul_comm x,
← mul_tsub, tsub_add_eq_tsub_tsub_swap, mul_div_mul_left _ _ two_ne_zero]
| inr hy =>
have : 2 ≤ x + y := le_add_left hy
simp [tsub_eq_zero_of_le, *]
end Imo1986Q5 |
.lake/packages/mathlib/Archive/Imo/Imo1987Q1.lean | import Mathlib.Data.Fintype.BigOperators
import Mathlib.Data.Fintype.Perm
import Mathlib.Dynamics.FixedPoints.Basic
/-!
# Formalization of IMO 1987, Q1
Let $p_{n, k}$ be the number of permutations of a set of cardinality `n ≥ 1` that fix exactly `k`
elements. Prove that $∑_{k=0}^n k p_{n,k}=n!$.
To prove this identity, we show that both sides are equal to the cardinality of the set
`{(x : α, σ : Perm α) | σ x = x}`, regrouping by `card (fixedPoints σ)` for the left-hand side and
by `x` for the right-hand side.
The original problem assumes `n ≥ 1`. It turns out that a version with `n * (n - 1)!` in the RHS
holds true for `n = 0` as well, so we first prove it, then deduce the original version in the case
`n ≥ 1`. -/
variable (α : Type*) [Fintype α] [DecidableEq α]
open scoped Nat
open Equiv Fintype Function
open Finset (range sum_const)
open Set (Iic)
namespace Imo1987Q1
/-- The set of pairs `(x : α, σ : Perm α)` such that `σ x = x` is equivalent to the set of pairs
`(x : α, σ : Perm {x}ᶜ)`. -/
def fixedPointsEquiv : { σx : α × Perm α // σx.2 σx.1 = σx.1 } ≃ Σ x : α, Perm ({x}ᶜ : Set α) :=
calc
{ σx : α × Perm α // σx.2 σx.1 = σx.1 } ≃ Σ x : α, { σ : Perm α // σ x = x } :=
setProdEquivSigma _
_ ≃ Σ x : α, { σ : Perm α // ∀ y : ({x} : Set α), σ y = Equiv.refl (↥({x} : Set α)) y } :=
(sigmaCongrRight fun x => Equiv.setCongr <| by simp only [SetCoe.forall]; simp)
_ ≃ Σ x : α, Perm ({x}ᶜ : Set α) := sigmaCongrRight fun x => by apply Equiv.Set.compl
theorem card_fixed_points :
card { σx : α × Perm α // σx.2 σx.1 = σx.1 } = card α * (card α - 1)! := by
simp only [card_congr (fixedPointsEquiv α), card_sigma, card_perm]
have (x : _) : ({x}ᶜ : Set α) = Finset.filter (· ≠ x) Finset.univ := by
ext; simp
simp [this]
/-- Given `α : Type*` and `k : ℕ`, `fiber α k` is the set of permutations of `α` with exactly `k`
fixed points. -/
def fiber (k : ℕ) : Set (Perm α) :=
{σ : Perm α | card (fixedPoints σ) = k}
instance {k : ℕ} : Fintype (fiber α k) := by unfold fiber; infer_instance
@[simp]
theorem mem_fiber {σ : Perm α} {k : ℕ} : σ ∈ fiber α k ↔ card (fixedPoints σ) = k :=
Iff.rfl
/-- `p α k` is the number of permutations of `α` with exactly `k` fixed points. -/
def p (k : ℕ) :=
card (fiber α k)
/-- The set of triples `(k ≤ card α, σ ∈ fiber α k, x ∈ fixedPoints σ)` is equivalent
to the set of pairs `(x : α, σ : Perm α)` such that `σ x = x`. The equivalence sends
`(k, σ, x)` to `(x, σ)` and `(x, σ)` to `(card (fixedPoints σ), σ, x)`.
It is easy to see that the cardinality of the LHS is given by
`∑ k : Fin (card α + 1), k * p α k`. -/
def fixedPointsEquiv' :
(Σ (k : Fin (card α + 1)) (σ : fiber α k), fixedPoints σ.1) ≃
{ σx : α × Perm α // σx.2 σx.1 = σx.1 } where
toFun p := ⟨⟨p.2.2, p.2.1⟩, p.2.2.2⟩
invFun p :=
⟨⟨card (fixedPoints p.1.2), (card_subtype_le _).trans_lt (Nat.lt_succ_self _)⟩, ⟨p.1.2, rfl⟩,
⟨p.1.1, p.2⟩⟩
left_inv := fun ⟨⟨k, hk⟩, ⟨σ, hσ⟩, ⟨x, hx⟩⟩ => by
simp only [mem_fiber] at hσ
subst k; rfl
right_inv := fun ⟨⟨x, σ⟩, h⟩ => rfl
/-- Main statement for any `(α : Type*) [Fintype α]`. -/
theorem main_fintype : ∑ k ∈ range (card α + 1), k * p α k = card α * (card α - 1)! := by
have A : ∀ (k) (σ : fiber α k), card (fixedPoints (↑σ : Perm α)) = k := fun k σ => σ.2
simpa [A, ← Fin.sum_univ_eq_sum_range, -card_ofFinset, Finset.card_univ, card_fixed_points,
mul_comm] using card_congr (fixedPointsEquiv' α)
/-- Main statement for permutations of `Fin n`, a version that works for `n = 0`. -/
theorem main₀ (n : ℕ) : ∑ k ∈ range (n + 1), k * p (Fin n) k = n * (n - 1)! := by
simpa using main_fintype (Fin n)
/-- Main statement for permutations of `Fin n`. -/
theorem main {n : ℕ} (hn : 1 ≤ n) : ∑ k ∈ range (n + 1), k * p (Fin n) k = n ! := by
rw [main₀, Nat.mul_factorial_pred (Nat.one_le_iff_ne_zero.mp hn)]
end Imo1987Q1 |
.lake/packages/mathlib/Archive/Imo/Imo1959Q2.lean | import Mathlib.Data.Real.Sqrt
/-!
# IMO 1959 Q2
For what real values of $x$ is
$\sqrt{x+\sqrt{2x-1}} + \sqrt{x-\sqrt{2x-1}} = A,$
given (a) $A=\sqrt{2}$, (b) $A=1$, (c) $A=2$,
where only non-negative real numbers are admitted for square roots?
We encode the equation as a predicate saying both that the equation holds
and that all arguments of square roots are nonnegative.
Then we follow second solution from the
[Art of Problem Solving](https://artofproblemsolving.com/wiki/index.php/1959_IMO_Problems/Problem_2)
website.
Namely, we rewrite the equation as $\sqrt{2x-1}+1+|\sqrt{2x-1}-1|=A\sqrt{2}$,
then consider the cases $\sqrt{2x-1}\le 1$ and $1 < \sqrt{2x-1}$ separately.
-/
open Set Real
namespace Imo1959Q2
def IsGood (x A : ℝ) : Prop :=
sqrt (x + sqrt (2 * x - 1)) + sqrt (x - sqrt (2 * x - 1)) = A ∧ 0 ≤ 2 * x - 1 ∧
0 ≤ x + sqrt (2 * x - 1) ∧ 0 ≤ x - sqrt (2 * x - 1)
variable {x A : ℝ}
theorem isGood_iff : IsGood x A ↔
sqrt (2 * x - 1) + 1 + |sqrt (2 * x - 1) - 1| = A * sqrt 2 ∧ 1 / 2 ≤ x := by
cases le_or_gt (1 / 2) x with
| inl hx =>
have hx' : 0 ≤ 2 * x - 1 := by linarith
have h₁ : x + sqrt (2 * x - 1) = (sqrt (2 * x - 1) + 1) ^ 2 / 2 := by
rw [add_sq, sq_sqrt hx']; field
have h₂ : x - sqrt (2 * x - 1) = (sqrt (2 * x - 1) - 1) ^ 2 / 2 := by
rw [sub_sq, sq_sqrt hx']; field
simp only [IsGood, *, div_nonneg (sq_nonneg _) (zero_le_two (α := ℝ)), sqrt_div (sq_nonneg _),
and_true]
rw [sqrt_sq, sqrt_sq_eq_abs] <;> [skip; positivity]
field_simp
| inr hx =>
have : 2 * x - 1 < 0 := by linarith
simp only [IsGood, this.not_ge, hx.not_ge]; simp
theorem IsGood.one_half_le (h : IsGood x A) : 1 / 2 ≤ x := (isGood_iff.1 h).2
theorem sqrt_two_mul_sub_one_le_one : sqrt (2 * x - 1) ≤ 1 ↔ x ≤ 1 := by
simp [sqrt_le_iff, ← two_mul]
theorem isGood_iff_eq_sqrt_two (hx : x ∈ Icc (1 / 2) 1) : IsGood x A ↔ A = sqrt 2 := by
have : sqrt (2 * x - 1) ≤ 1 := sqrt_two_mul_sub_one_le_one.2 hx.2
simp only [isGood_iff, hx.1, abs_sub_comm _ (1 : ℝ), abs_of_nonneg (sub_nonneg.2 this), and_true]
suffices 2 = A * sqrt 2 ↔ A = sqrt 2 by convert this using 2; ring
rw [← div_eq_iff, div_sqrt, eq_comm]
positivity
theorem isGood_iff_eq_sqrt (hx : 1 < x) : IsGood x A ↔ A = sqrt (4 * x - 2) := by
have h₁ : 1 < sqrt (2 * x - 1) := by simpa only [← not_le, sqrt_two_mul_sub_one_le_one] using hx
have h₂ : 1 / 2 ≤ x := by linarith
simp only [isGood_iff, h₂, abs_of_pos (sub_pos.2 h₁), add_add_sub_cancel, and_true]
rw [← mul_two, ← div_eq_iff (by positivity), mul_div_assoc, div_sqrt, ← sqrt_mul' _ zero_le_two,
eq_comm]
ring_nf
theorem IsGood.sqrt_two_lt_of_one_lt (h : IsGood x A) (hx : 1 < x) : sqrt 2 < A := by
rw [(isGood_iff_eq_sqrt hx).1 h]
refine sqrt_lt_sqrt zero_le_two ?_
linarith
theorem IsGood.eq_sqrt_two_iff_le_one (h : IsGood x A) : A = sqrt 2 ↔ x ≤ 1 :=
⟨fun hA ↦ not_lt.1 fun hx ↦ (h.sqrt_two_lt_of_one_lt hx).ne' hA, fun hx ↦
(isGood_iff_eq_sqrt_two ⟨h.one_half_le, hx⟩).1 h⟩
theorem IsGood.sqrt_two_lt_iff_one_lt (h : IsGood x A) : sqrt 2 < A ↔ 1 < x :=
⟨fun hA ↦ not_le.1 fun hx ↦ hA.ne' <| h.eq_sqrt_two_iff_le_one.2 hx, h.sqrt_two_lt_of_one_lt⟩
theorem IsGood.sqrt_two_le (h : IsGood x A) : sqrt 2 ≤ A :=
(le_or_gt x 1).elim (fun hx ↦ (h.eq_sqrt_two_iff_le_one.2 hx).ge) fun hx ↦
(h.sqrt_two_lt_of_one_lt hx).le
theorem isGood_iff_of_sqrt_two_lt (hA : sqrt 2 < A) : IsGood x A ↔ x = (A / 2) ^ 2 + 1 / 2 := by
have : 0 < A := lt_trans (by simp) hA
constructor
· intro h
have hx : 1 < x := by rwa [h.sqrt_two_lt_iff_one_lt] at hA
rw [isGood_iff_eq_sqrt hx, eq_comm, sqrt_eq_iff_eq_sq] at h <;> linarith
· rintro rfl
rw [isGood_iff_eq_sqrt]
· conv_lhs => rw [← sqrt_sq this.le]
ring_nf
· rw [sqrt_lt' this] at hA
linarith
theorem isGood_sqrt2_iff : IsGood x (sqrt 2) ↔ x ∈ Icc (1 / 2) 1 := by
refine ⟨fun h ↦ ?_, fun h ↦ (isGood_iff_eq_sqrt_two h).2 rfl⟩
exact ⟨h.one_half_le, not_lt.1 fun h₁ ↦ (h.sqrt_two_lt_of_one_lt h₁).false⟩
theorem not_isGood_one : ¬IsGood x 1 := fun h ↦
h.sqrt_two_le.not_gt <| (lt_sqrt zero_le_one).2 (by simp)
theorem isGood_two_iff : IsGood x 2 ↔ x = 3 / 2 :=
(isGood_iff_of_sqrt_two_lt <| (sqrt_lt' two_pos).2 (by norm_num)).trans <| by norm_num
end Imo1959Q2 |
.lake/packages/mathlib/Archive/Imo/Imo1961Q3.lean | import Mathlib.Analysis.SpecialFunctions.Trigonometric.Complex
/-!
# IMO 1961 Q3
Solve the equation
$\cos^n x - \sin^n x = 1$,
where $n$ is a given positive integer.
The solution is based on the one at the
[Art of Problem Solving](https://artofproblemsolving.com/wiki/index.php/1961_IMO_Problems/Problem_3)
website.
-/
open Real
theorem Imo1961Q3 {n : ℕ} {x : ℝ} (h₀ : n ≠ 0) :
(cos x) ^ n - (sin x) ^ n = 1 ↔
(∃ k : ℤ, k * π = x) ∧ Even n ∨ (∃ k : ℤ, k * (2 * π) = x) ∧ Odd n ∨
(∃ k : ℤ, -(π / 2) + k * (2 * π) = x) ∧ Odd n := by
constructor
· intro h
rcases eq_or_ne (sin x) 0 with hsinx | hsinx
· rw [hsinx, zero_pow h₀, sub_zero, pow_eq_one_iff_of_ne_zero h₀, cos_eq_one_iff,
cos_eq_neg_one_iff] at h
rcases h with ⟨k, rfl⟩ | ⟨⟨k, rfl⟩, hn⟩
· cases n.even_or_odd with
| inl hn => refine .inl ⟨⟨k * 2, ?_⟩, hn⟩; simp [mul_assoc]
| inr hn => exact .inr <| .inl ⟨⟨_, rfl⟩, hn⟩
· exact .inl ⟨⟨2 * k + 1, by push_cast; ring⟩, hn⟩
· rcases eq_or_ne (cos x) 0 with hcosx | hcosx
· right; right
rw [hcosx, zero_pow h₀, zero_sub, ← neg_inj, neg_neg, pow_eq_neg_one_iff,
sin_eq_neg_one_iff] at h
simpa only [eq_comm] using h
· have hcos1 : |cos x| < 1 := by
rw [abs_cos_eq_sqrt_one_sub_sin_sq, sqrt_lt' one_pos]
simp [sq_pos_of_ne_zero hsinx]
have hsin1 : |sin x| < 1 := by
rw [abs_sin_eq_sqrt_one_sub_cos_sq, sqrt_lt' one_pos]
simp [sq_pos_of_ne_zero hcosx]
match n with
| 1 =>
rw [pow_one, pow_one, sub_eq_iff_eq_add] at h
have : 2 * sin x * cos x = 0 := by
simpa [h, add_sq, add_assoc, ← two_mul, mul_add, mul_assoc, ← sq]
using cos_sq_add_sin_sq x
simp [hsinx, hcosx] at this
| 2 =>
rw [← cos_sq_add_sin_sq x, sub_eq_add_neg, add_right_inj, neg_eq_self] at h
exact absurd (eq_zero_of_pow_eq_zero h) hsinx
| (n + 1 + 2) =>
set m := n + 1
refine absurd ?_ h.not_lt
calc
(cos x) ^ (m + 2) - (sin x) ^ (m + 2) ≤ |cos x| ^ (m + 2) + |sin x| ^ (m + 2) := by
simp only [← abs_pow, sub_eq_add_neg]
gcongr
exacts [le_abs_self _, neg_le_abs _]
_ = |cos x| ^ m * cos x ^ 2 + |sin x| ^ m * sin x ^ 2 := by simp [pow_add]
_ < 1 ^ m * cos x ^ 2 + 1 ^ m * sin x ^ 2 := by gcongr
_ = 1 := by simp
· rintro (⟨⟨k, rfl⟩, hn⟩ | ⟨⟨k, rfl⟩, -⟩ | ⟨⟨k, rfl⟩, hn⟩)
· rw [sin_int_mul_pi, zero_pow h₀, sub_zero, ← hn.pow_abs, abs_cos_int_mul_pi, one_pow]
· have : sin (k * (2 * π)) = 0 := by simpa [mul_assoc] using sin_int_mul_pi (k * 2)
simp [h₀, this]
· simp [hn.neg_pow, h₀] |
.lake/packages/mathlib/Archive/Imo/Imo2024Q5.lean | import Mathlib.Data.Fin.VecNotation
import Mathlib.Data.List.ChainOfFn
import Mathlib.Data.List.TakeWhile
import Mathlib.Data.Nat.Dist
import Mathlib.Order.Fin.Basic
import Mathlib.Tactic.IntervalCases
/-!
# IMO 2024 Q5
Turbo the snail plays a game on a board with $2024$ rows and $2023$ columns. There are hidden
monsters in $2022$ of the cells. Initially, Turbo does not know where any of the monsters are,
but he knows that there is exactly one monster in each row except the first row and the last
row, and that each column contains at most one monster.
Turbo makes a series of attempts to go from the first row to the last row. On each attempt,
he chooses to start on any cell in the first row, then repeatedly moves to an adjacent cell
sharing a common side. (He is allowed to return to a previously visited cell.) If he reaches a
cell with a monster, his attempt ends and he is transported back to the first row to start a
new attempt. The monsters do not move, and Turbo remembers whether or not each cell he has
visited contains a monster. If he reaches any cell in the last row, his attempt ends and the
game is over.
Determine the minimum value of $n$ for which Turbo has a strategy that guarantees reaching
the last row on the $n$th attempt or earlier, regardless of the locations of the monsters.
We follow the solution from the
[official solutions](https://www.imo2024.uk/s/IMO2024-solutions-updated.pdf). To show that $n$
is at least $3$, it is possible that the first cell Turbo encounters in the second row on his
first attempt contains a monster, and also possible that the first cell Turbo encounters in the
third row on his second attempt contains a monster. To show that $3$ attempts suffice, the first
attempt can be used to locate the monster in the second row; if this is not at either side of
the board, two more attempts suffice to pass behind that monster and from there go along its
column to the last row, while if it is at one side of the board, the second attempt follows a
zigzag path such that if it encounters a monster the third attempt can avoid all monsters.
-/
namespace Imo2024Q5
/-! ### Definitions for setting up the problem -/
-- There are N monsters, N+1 columns and N+2 rows.
variable {N : ℕ}
/-- A cell on the board for the game. -/
abbrev Cell (N : ℕ) : Type := Fin (N + 2) × Fin (N + 1)
/-- A row that is neither the first nor the last (and thus contains a monster). -/
abbrev InteriorRow (N : ℕ) : Type := (Set.Icc 1 ⟨N, by omega⟩ : Set (Fin (N + 2)))
/-- Data for valid positions of the monsters. -/
abbrev MonsterData (N : ℕ) : Type := InteriorRow N ↪ Fin (N + 1)
/-- The cells with monsters as a Set, given an injection from rows to columns. -/
def MonsterData.monsterCells (m : MonsterData N) :
Set (Cell N) :=
Set.range (fun x : InteriorRow N ↦ ((x : Fin (N + 2)), m x))
/-- Whether two cells are adjacent. -/
def Adjacent (x y : Cell N) : Prop :=
Nat.dist x.1 y.1 + Nat.dist x.2 y.2 = 1
/-- A valid path from the first to the last row. -/
structure Path (N : ℕ) where
/-- The cells on the path. -/
cells : List (Cell N)
nonempty : cells ≠ []
head_first_row : (cells.head nonempty).1 = 0
last_last_row : (cells.getLast nonempty).1 = Fin.last (N + 1)
valid_move_seq : cells.IsChain Adjacent
/-- The first monster on a path, or `none`. -/
noncomputable def Path.firstMonster (p : Path N) (m : MonsterData N) : Option (Cell N) :=
letI := Classical.propDecidable
p.cells.find? (fun x ↦ (x ∈ m.monsterCells : Bool))
/-- A strategy, given the results of initial attempts, returns a path for the next attempt. -/
abbrev Strategy (N : ℕ) : Type := ⦃k : ℕ⦄ → (Fin k → Option (Cell N)) → Path N
/-- Playing a strategy, k attempts. -/
noncomputable def Strategy.play (s : Strategy N) (m : MonsterData N) :
(k : ℕ) → Fin k → Option (Cell N)
| 0 => Fin.elim0
| k + 1 => Fin.snoc (s.play m k) ((s (s.play m k)).firstMonster m)
/-- The predicate for a strategy winning within the given number of attempts. -/
def Strategy.WinsIn (s : Strategy N) (m : MonsterData N) (k : ℕ) : Prop :=
none ∈ Set.range (s.play m k)
/-- Whether a strategy forces a win within the given number of attempts. -/
def Strategy.ForcesWinIn (s : Strategy N) (k : ℕ) : Prop :=
∀ m, s.WinsIn m k
/-! ### API definitions and lemmas about `Cell` -/
/-- Reflecting a cell of the board (swapping left and right sides of the board). -/
def Cell.reflect (c : Cell N) : Cell N := (c.1, c.2.rev)
/-! ### API definitions and lemmas about `MonsterData` -/
/-- The row 1, in the form required for MonsterData. -/
def row1 (hN : 2 ≤ N) : InteriorRow N :=
⟨1, ⟨by omega, by
rw [Fin.le_def]
simp
omega⟩⟩
lemma coe_coe_row1 (hN : 2 ≤ N) : (((row1 hN) : Fin (N + 2)) : ℕ) = 1 :=
rfl
/-- The row 2, in the form required for MonsterData. -/
def row2 (hN : 2 ≤ N) : InteriorRow N :=
⟨⟨2, by omega⟩, ⟨by
simp only [Fin.le_def, Fin.val_one]
omega, by
simp only [Fin.le_def]
omega⟩⟩
/-- Reflecting monster data. -/
def MonsterData.reflect (m : MonsterData N) : MonsterData N where
toFun := Fin.rev ∘ m
inj' := fun i j hij ↦ by simpa using hij
lemma MonsterData.reflect_reflect (m : MonsterData N) : m.reflect.reflect = m := by
ext i
simp [MonsterData.reflect]
lemma MonsterData.notMem_monsterCells_of_fst_eq_zero (m : MonsterData N)
{c : Cell N} (hc : c.1 = 0) : c ∉ m.monsterCells := by
simp [monsterCells, Prod.ext_iff, hc]
@[deprecated (since := "2025-05-23")]
alias MonsterData.not_mem_monsterCells_of_fst_eq_zero :=
MonsterData.notMem_monsterCells_of_fst_eq_zero
lemma MonsterData.le_N_of_mem_monsterCells {m : MonsterData N} {c : Cell N}
(hc : c ∈ m.monsterCells) : (c.1 : ℕ) ≤ N := by
simp only [monsterCells, Set.mem_range, Subtype.exists, Set.mem_Icc] at hc
rcases hc with ⟨r, ⟨h1, hN⟩, rfl⟩
rw [Fin.le_def] at hN
exact hN
lemma MonsterData.mk_mem_monsterCells_iff_of_le {m : MonsterData N} {r : Fin (N + 2)}
(hr1 : 1 ≤ r) (hrN : r ≤ ⟨N, by omega⟩) {c : Fin (N + 1)} :
(r, c) ∈ m.monsterCells ↔ m ⟨r, hr1, hrN⟩ = c := by
simp only [monsterCells, Set.mem_range, Prod.mk.injEq]
refine ⟨?_, ?_⟩
· rintro ⟨r', rfl, rfl⟩
simp only [Subtype.coe_eta]
· rintro rfl
exact ⟨⟨r, hr1, hrN⟩, rfl, rfl⟩
lemma MonsterData.mem_monsterCells_iff_of_le {m : MonsterData N} {x : Cell N}
(hr1 : 1 ≤ x.1) (hrN : x.1 ≤ ⟨N, by omega⟩) :
x ∈ m.monsterCells ↔ m ⟨x.1, hr1, hrN⟩ = x.2 :=
MonsterData.mk_mem_monsterCells_iff_of_le hr1 hrN
lemma MonsterData.mk_mem_monsterCells_iff {m : MonsterData N} {r : Fin (N + 2)}
{c : Fin (N + 1)} :
(r, c) ∈ m.monsterCells ↔ ∃ (hr1 : 1 ≤ r) (hrN : r ≤ ⟨N, by omega⟩), m ⟨r, hr1, hrN⟩ = c := by
refine ⟨fun h ↦ ?_, fun ⟨hr1, hrN, h⟩ ↦ (mem_monsterCells_iff_of_le hr1 hrN).2 h⟩
rcases h with ⟨⟨mr, hr1, hrN⟩, h⟩
simp only [Prod.mk.injEq] at h
rcases h with ⟨rfl, rfl⟩
exact ⟨hr1, hrN, rfl⟩
/-! ### API definitions and lemmas about `Adjacent` -/
lemma Adjacent.le_of_lt {x y : Cell N} (ha : Adjacent x y) {r : Fin (N + 2)} (hr : r < y.1) :
r ≤ x.1 := by
rw [Adjacent, Nat.dist] at ha
omega
/-! ### API definitions and lemmas about `Path` -/
lemma Path.exists_mem_fst_eq (p : Path N) (r : Fin (N + 2)) : ∃ c ∈ p.cells, c.1 = r := by
let i : ℕ := p.cells.findIdx fun c ↦ r ≤ c.1
have hi : i < p.cells.length := by
refine List.findIdx_lt_length_of_exists ⟨p.cells.getLast p.nonempty, ?_⟩
simp only [List.getLast_mem, p.last_last_row, decide_eq_true_eq, true_and, Fin.last]
rw [Fin.le_def]
have h := r.isLt
rw [Nat.lt_succ_iff] at h
convert h
have hig : r ≤ (p.cells[i]).1 := of_decide_eq_true (List.findIdx_getElem (w := hi))
refine ⟨p.cells[i], List.getElem_mem _, ?_⟩
refine (hig.lt_or_eq.resolve_left fun h => ?_).symm
rcases Nat.eq_zero_or_pos i with hi | hi
· simp only [hi, List.getElem_zero, p.head_first_row, Fin.not_lt_zero] at h
· suffices r ≤ p.cells[i - 1].1 by
have hi' : i - 1 < i := by omega
exact of_decide_eq_false (List.not_of_lt_findIdx hi') this
have ha : Adjacent p.cells[i - 1] p.cells[i] := by
convert List.isChain_iff_get.1 p.valid_move_seq (i - 1) ?_
· simp [Nat.sub_add_cancel hi]
· omega
exact ha.le_of_lt h
lemma Path.exists_mem_le_fst (p : Path N) (r : Fin (N + 2)) : ∃ c ∈ p.cells, r ≤ c.1 := by
rcases p.exists_mem_fst_eq r with ⟨c, hc, he⟩
exact ⟨c, hc, he.symm.le⟩
/-- The first path element on a row. -/
def Path.findFstEq (p : Path N) (r : Fin (N + 2)) : Cell N :=
(p.cells.find? (fun c ↦ c.1 = r)).get (List.find?_isSome.2 (by simpa using p.exists_mem_fst_eq r))
lemma Path.find_eq_some_findFstEq (p : Path N) (r : Fin (N + 2)) :
p.cells.find? (fun c ↦ c.1 = r) = some (p.findFstEq r) := by
rw [Option.eq_some_iff_get_eq]
exact ⟨_, rfl⟩
lemma Path.findFstEq_mem_cells (p : Path N) (r : Fin (N + 2)) : p.findFstEq r ∈ p.cells :=
List.mem_of_find?_eq_some (p.find_eq_some_findFstEq r)
lemma Path.findFstEq_fst (p : Path N) (r : Fin (N + 2)) : (p.findFstEq r).1 = r := by
have h := List.find?_some (p.find_eq_some_findFstEq r)
simpa using h
lemma find?_eq_eq_find?_le {l : List (Cell N)} {r : Fin (N + 2)} (hne : l ≠ [])
(hf : (l.head hne).1 ≤ r) (ha : l.IsChain Adjacent) :
l.find? (fun c ↦ c.1 = r) = l.find? (fun c ↦ r ≤ c.1) := by
induction l
case nil => simp at hne
case cons head tail hi =>
by_cases h : head.1 = r
· simp [h]
· have h' : ¬(r ≤ head.1) := fun hr' ↦ h (le_antisymm hf hr')
simp only [h, decide_false, Bool.false_eq_true, not_false_eq_true, List.find?_cons_of_neg, h']
rcases tail with ⟨⟩ | ⟨htail, ttail⟩
· simp
· simp only [List.isChain_cons_cons] at ha
rcases ha with ⟨ha1, ha2⟩
simp only [List.head_cons] at hf
simp only [ne_eq, reduceCtorEq, not_false_eq_true, List.head_cons, ha2, true_implies] at hi
refine hi ?_
simp only [Adjacent, Nat.dist] at ha1
omega
lemma Path.findFstEq_eq_find?_le (p : Path N) (r : Fin (N + 2)) : p.findFstEq r =
(p.cells.find? (fun c ↦ r ≤ c.1)).get
(List.find?_isSome.2 (by simpa using p.exists_mem_le_fst r)) := by
rw [findFstEq]
convert rfl using 2
refine (find?_eq_eq_find?_le p.nonempty ?_ p.valid_move_seq).symm
simp [p.head_first_row]
lemma Path.firstMonster_isSome {p : Path N} {m : MonsterData N} :
(p.firstMonster m).isSome = true ↔ ∃ x, x ∈ p.cells ∧ x ∈ m.monsterCells := by
convert List.find?_isSome
simp
lemma Path.firstMonster_eq_none {p : Path N} {m : MonsterData N} :
(p.firstMonster m) = none ↔ ∀ x, x ∈ p.cells → x ∉ m.monsterCells := by
convert List.find?_eq_none
simp
lemma Path.one_lt_length_cells (p : Path N) : 1 < p.cells.length := by
by_contra hl
have h : p.cells.length = 0 ∨ p.cells.length = 1 := by omega
rcases h with h | h
· rw [List.length_eq_zero_iff] at h
exact p.nonempty h
· rw [List.length_eq_one_iff] at h
rcases h with ⟨c, hc⟩
have h1 := p.head_first_row
simp_rw [hc, List.head_cons] at h1
have h2 := p.last_last_row
simp [hc, List.getLast_singleton, h1] at h2
/-- Remove the first cell from a path, if the second cell is also on the first row. -/
def Path.tail (p : Path N) : Path N where
cells := if (p.cells[1]'p.one_lt_length_cells).1 = 0 then p.cells.tail else p.cells
nonempty := by
split_ifs
· rw [← List.length_pos_iff_ne_nil, List.length_tail, Nat.sub_pos_iff_lt]
exact p.one_lt_length_cells
· exact p.nonempty
head_first_row := by
split_ifs with h
· convert h
rw [List.head_tail]
· exact p.head_first_row
last_last_row := by
split_ifs
· rw [← p.last_last_row, List.getLast_tail]
· exact p.last_last_row
valid_move_seq := by
split_ifs
· exact List.IsChain.tail p.valid_move_seq
· exact p.valid_move_seq
lemma Path.tail_induction {motive : Path N → Prop} (ind : ∀ p, motive p.tail → motive p)
(base : ∀ p, (p.cells[1]'p.one_lt_length_cells).1 ≠ 0 → motive p) (p : Path N) : motive p := by
rcases p with ⟨cells, nonempty, head_first_row, last_last_row, valid_move_seq⟩
let p' : Path N := ⟨cells, nonempty, head_first_row, last_last_row, valid_move_seq⟩
induction cells
case nil => simp at nonempty
case cons head tail hi =>
by_cases h : (p'.cells[1]'p'.one_lt_length_cells).1 = 0
· refine ind p' ?_
simp_rw [Path.tail, if_pos h, p', List.tail_cons]
exact hi _ _ _ _
· exact base p' h
lemma Path.tail_findFstEq (p : Path N) {r : Fin (N + 2)} (hr : r ≠ 0) :
p.tail.findFstEq r = p.findFstEq r := by
by_cases h : (p.cells[1]'p.one_lt_length_cells).1 = 0
· simp_rw [Path.tail, if_pos h]
nth_rw 2 [Path.findFstEq]
rcases p with ⟨cells, nonempty, head_first_row, last_last_row, valid_move_seq⟩
rcases cells with ⟨⟩ | ⟨head, tail⟩
· simp at nonempty
· simp only [List.head_cons] at head_first_row
simp only [List.find?_cons, head_first_row, hr.symm, decide_false]
rfl
· simp_rw [Path.tail, if_neg h]
lemma Path.tail_firstMonster (p : Path N) (m : MonsterData N) :
p.tail.firstMonster m = p.firstMonster m := by
by_cases h : (p.cells[1]'p.one_lt_length_cells).1 = 0
· simp_rw [Path.tail, if_pos h]
nth_rw 2 [Path.firstMonster]
rcases p with ⟨cells, nonempty, head_first_row, last_last_row, valid_move_seq⟩
rcases cells with ⟨⟩ | ⟨head, tail⟩
· simp at nonempty
· simp only [List.head_cons] at head_first_row
simp [m.notMem_monsterCells_of_fst_eq_zero head_first_row, firstMonster]
· simp_rw [Path.tail, if_neg h]
lemma Path.firstMonster_eq_of_findFstEq_mem {p : Path N} {m : MonsterData N}
(h : p.findFstEq 1 ∈ m.monsterCells) : p.firstMonster m = some (p.findFstEq 1) := by
induction p using Path.tail_induction
case base p h0 =>
have hl := p.one_lt_length_cells
have adj : Adjacent p.cells[0] p.cells[1] :=
List.isChain_iff_get.1 p.valid_move_seq 0 (by omega)
simp_rw [Adjacent, Nat.dist] at adj
have hc0 : (p.cells[0].1 : ℕ) = 0 := by
convert Fin.ext_iff.1 p.head_first_row
exact List.getElem_zero _
have hc1 : (p.cells[1].1 : ℕ) ≠ 0 := Fin.val_ne_iff.2 h0
have h1 : (p.cells[1].1 : ℕ) = 1 := by omega
simp_rw [firstMonster, findFstEq]
rcases p with ⟨cells, nonempty, head_first_row, last_last_row, valid_move_seq⟩
rcases cells with ⟨⟩ | ⟨head, tail⟩
· simp at nonempty
· simp only [List.head_cons] at head_first_row
simp only [List.getElem_cons_succ] at h1
simp only [List.length_cons, lt_add_iff_pos_left, List.length_pos_iff_ne_nil] at hl
simp only [m.notMem_monsterCells_of_fst_eq_zero head_first_row, decide_false,
Bool.false_eq_true, not_false_eq_true, List.find?_cons_of_neg, head_first_row,
Fin.zero_eq_one_iff, Nat.reduceEqDiff, Option.some_get]
simp only [findFstEq, head_first_row, Fin.zero_eq_one_iff, Nat.reduceEqDiff, decide_false,
Bool.false_eq_true, not_false_eq_true, List.find?_cons_of_neg] at h
rcases tail with ⟨⟩ | ⟨htail, ttail⟩
· simp at hl
· simp only [List.getElem_cons_zero] at h1
have h1' : htail.1 = 1 := by simp [Fin.ext_iff, h1]
simp only [h1', decide_true, List.find?_cons_of_pos, Option.get_some] at h
simp only [h1', h, decide_true, List.find?_cons_of_pos]
case ind p ht =>
have h1 : (1 : Fin (N + 2)) ≠ 0 := by simp
rw [p.tail_findFstEq h1, p.tail_firstMonster m] at ht
exact ht h
lemma Path.findFstEq_fst_sub_one_mem (p : Path N) {r : Fin (N + 2)} (hr : r ≠ 0) :
(⟨(r : ℕ) - 1, by omega⟩, (p.findFstEq r).2) ∈ p.cells := by
rw [findFstEq_eq_find?_le]
have h1 := p.one_lt_length_cells
obtain ⟨cr, hcrc, hcrr⟩ := p.exists_mem_fst_eq r
rcases p with ⟨cells, nonempty, head_first_row, last_last_row, valid_move_seq⟩
dsimp only at h1 hcrc ⊢
have hd : ∃ c ∈ cells, decide (r ≤ c.1) = true := ⟨cr, hcrc, by simpa using hcrr.symm.le⟩
have hd' : cells.dropWhile (fun c ↦ ! decide (r ≤ c.1)) ≠ [] := by simpa using hd
have ht : cells.takeWhile (fun c ↦ ! decide (r ≤ c.1)) ≠ [] := by
intro h
rw [List.takeWhile_eq_nil_iff] at h
replace h := h (by omega)
simp [List.getElem_zero, head_first_row, hr] at h
simp_rw [cells.find?_eq_head_dropWhile_not hd, Option.get_some]
rw [← cells.takeWhile_append_dropWhile (p := fun c ↦ ! decide (r ≤ c.1)),
List.isChain_append] at valid_move_seq
have ha := valid_move_seq.2.2
simp only [List.head?_eq_head hd', List.getLast?_eq_getLast ht, Option.mem_def,
Option.some.injEq, forall_eq'] at ha
nth_rw 1 [← cells.takeWhile_append_dropWhile (p := fun c ↦ ! decide (r ≤ c.1))]
refine List.mem_append_left _ ?_
convert List.getLast_mem ht using 1
have htr : ((List.takeWhile (fun c ↦ !decide (r ≤ c.1)) cells).getLast ht).1 < r := by
simpa using List.mem_takeWhile_imp (List.getLast_mem ht)
have hdr : r ≤ ((List.dropWhile (fun c ↦ !decide (r ≤ c.1)) cells).head hd').1 := by
simpa using cells.head_dropWhile_not (fun c ↦ !decide (r ≤ c.1)) hd'
simp only [Adjacent, Nat.dist] at ha
have hrm : N + 1 + (r : ℕ) = N + 2 + (r - 1) := by omega
simp only [Prod.ext_iff, Fin.ext_iff]
omega
lemma Path.mem_of_firstMonster_eq_some {p : Path N} {m : MonsterData N} {c : Cell N}
(h : p.firstMonster m = some c) : c ∈ p.cells ∧ c ∈ m.monsterCells := by
simp_rw [firstMonster] at h
have h₁ := List.mem_of_find?_eq_some h
have h₂ := List.find?_some h
simp only [decide_eq_true_eq] at h₂
exact ⟨h₁, h₂⟩
/-- Convert a function giving the cells of a path to a `Path`. -/
def Path.ofFn {m : ℕ} (f : Fin m → Cell N) (hm : m ≠ 0)
(hf : (f ⟨0, Nat.pos_of_ne_zero hm⟩).1 = 0)
(hl : (f ⟨m - 1, Nat.sub_one_lt hm⟩).1 = ⟨N + 1, by omega⟩)
(ha : ∀ (i : ℕ) (hi : i + 1 < m), Adjacent (f ⟨i, Nat.lt_of_succ_lt hi⟩) (f ⟨i + 1, hi⟩)) :
Path N where
cells := List.ofFn f
nonempty := mt List.ofFn_eq_nil_iff.1 hm
head_first_row := by
rw [List.head_ofFn, hf]
last_last_row := by
simp [Fin.last, List.getLast_ofFn, hl]
valid_move_seq := by
rwa [List.isChain_ofFn]
lemma Path.ofFn_cells {m : ℕ} (f : Fin m → Cell N) (hm : m ≠ 0)
(hf : (f ⟨0, Nat.pos_of_ne_zero hm⟩).1 = 0)
(hl : (f ⟨m - 1, Nat.sub_one_lt hm⟩).1 = ⟨N + 1, by omega⟩)
(ha : ∀ (i : ℕ) (hi : i + 1 < m), Adjacent (f ⟨i, Nat.lt_of_succ_lt hi⟩) (f ⟨i + 1, hi⟩)) :
(Path.ofFn f hm hf hl ha).cells = List.ofFn f :=
rfl
lemma Path.ofFn_firstMonster_eq_none {m : ℕ} (f : Fin m → Cell N) (hm hf hl ha)
(m : MonsterData N) :
((Path.ofFn f hm hf hl ha).firstMonster m) = none ↔ ∀ i, f i ∉ m.monsterCells := by
simp [firstMonster_eq_none, ofFn_cells, List.mem_ofFn]
/-- Reflecting a path. -/
def Path.reflect (p : Path N) : Path N where
cells := p.cells.map Cell.reflect
nonempty := mt List.map_eq_nil_iff.1 p.nonempty
head_first_row := by
rw [List.head_map]
exact p.head_first_row
last_last_row := by
rw [List.getLast_map]
exact p.last_last_row
valid_move_seq := by
refine List.isChain_map_of_isChain _ ?_ p.valid_move_seq
intro x y h
simp_rw [Adjacent, Nat.dist, Cell.reflect, Fin.rev] at h ⊢
omega
lemma Path.firstMonster_reflect (p : Path N) (m : MonsterData N) :
p.reflect.firstMonster m.reflect = (p.firstMonster m).map Cell.reflect := by
simp_rw [firstMonster, reflect, List.find?_map]
convert rfl
simp only [Function.comp_apply, decide_eq_decide, MonsterData.monsterCells]
refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩
· rcases h with ⟨i, hi⟩
refine ⟨i, ?_⟩
simpa [MonsterData.reflect, Cell.reflect, Prod.ext_iff] using hi
· rcases h with ⟨i, hi⟩
refine ⟨i, ?_⟩
simpa [MonsterData.reflect, Cell.reflect, Prod.ext_iff] using hi
/-! ### API definitions and lemmas about `Strategy` -/
lemma Strategy.play_comp_castLE (s : Strategy N) (m : MonsterData N) {k₁ k₂ : ℕ} (hk : k₁ ≤ k₂) :
s.play m k₂ ∘ Fin.castLE hk = s.play m k₁ := by
induction hk
case refl => rfl
case step k' hk' hki =>
rw [← hki, ← Fin.castLE_comp_castLE hk' (Nat.le_succ k'), ← Function.comp_assoc]
convert rfl
exact Fin.snoc_comp_castSucc.symm
lemma Strategy.play_apply_of_le (s : Strategy N) (m : MonsterData N) {i k₁ k₂ : ℕ} (hi : i < k₁)
(hk : k₁ ≤ k₂) : s.play m k₂ ⟨i, hi.trans_le hk⟩ = s.play m k₁ ⟨i, hi⟩ := by
rw [← s.play_comp_castLE m hk]
rfl
lemma Strategy.play_zero (s : Strategy N) (m : MonsterData N) {k : ℕ} (hk : 0 < k) :
s.play m k ⟨0, hk⟩ = (s Fin.elim0).firstMonster m := by
have hk' : 1 ≤ k := by omega
rw [s.play_apply_of_le m zero_lt_one hk']
rfl
lemma Strategy.play_one (s : Strategy N) (m : MonsterData N) {k : ℕ} (hk : 1 < k) :
s.play m k ⟨1, hk⟩ = (s ![(s Fin.elim0).firstMonster m]).firstMonster m := by
have hk' : 2 ≤ k := by omega
rw [s.play_apply_of_le m one_lt_two hk']
simp only [play, Fin.snoc, lt_self_iff_false, ↓reduceDIte, Nat.reduceAdd,
Fin.mk_one, Fin.isValue, cast_eq, Nat.succ_eq_add_one]
congr
refine funext fun i ↦ ?_
simp_rw [Fin.fin_one_eq_zero]
rfl
lemma Strategy.play_two (s : Strategy N) (m : MonsterData N) {k : ℕ} (hk : 2 < k) :
s.play m k ⟨2, hk⟩ = (s ![(s Fin.elim0).firstMonster m,
(s ![(s Fin.elim0).firstMonster m]).firstMonster m]).firstMonster m := by
have hk' : 3 ≤ k := by omega
rw [s.play_apply_of_le m (by simp : 2 < 3) hk']
simp only [play, Fin.snoc, lt_self_iff_false, ↓reduceDIte, Nat.reduceAdd, cast_eq,
Nat.succ_eq_add_one]
congr
refine funext fun i ↦ ?_
fin_cases i
· rfl
· have h : (1 : Fin 2) = Fin.last 1 := rfl
simp only [Fin.snoc_zero, Nat.reduceAdd, Fin.mk_one, Fin.isValue, Matrix.cons_val]
simp only [h, Fin.snoc_last]
convert rfl
simp_rw [Fin.fin_one_eq_zero, Matrix.cons_val]
lemma Strategy.WinsIn.mono (s : Strategy N) (m : MonsterData N) {k₁ k₂ : ℕ} (h : s.WinsIn m k₁)
(hk : k₁ ≤ k₂) : s.WinsIn m k₂ := by
refine Set.mem_of_mem_of_subset h ?_
rw [Set.range_subset_range_iff_exists_comp]
exact ⟨Fin.castLE hk, (s.play_comp_castLE m hk).symm⟩
lemma Strategy.ForcesWinIn.mono (s : Strategy N) {k₁ k₂ : ℕ} (h : s.ForcesWinIn k₁)
(hk : k₁ ≤ k₂) : s.ForcesWinIn k₂ :=
fun _ ↦ ((h _).mono) hk
/-! ### Proof of lower bound with constructions used therein -/
/-- An arbitrary choice of monster positions, which is modified to put selected monsters in
desired places. -/
def baseMonsterData (N : ℕ) : MonsterData N where
toFun := fun ⟨r, _, hrN⟩ ↦ ⟨↑r, by
rw [Fin.le_def] at hrN
rw [Nat.lt_add_one_iff]
exact hrN⟩
inj' := fun ⟨⟨x, hx⟩, hx1, hxN⟩ ⟨⟨y, hy⟩, hy1, hyN⟩ h ↦ by
simp only [Fin.mk.injEq] at h
simpa using h
/-- Positions for monsters with specified columns in the second and third rows (rows 1 and 2). -/
def monsterData12 (hN : 2 ≤ N) (c₁ c₂ : Fin (N + 1)) : MonsterData N :=
((baseMonsterData N).setValue (row2 hN) c₂).setValue (row1 hN) c₁
lemma monsterData12_apply_row2 (hN : 2 ≤ N) {c₁ c₂ : Fin (N + 1)} (h : c₁ ≠ c₂) :
monsterData12 hN c₁ c₂ (row2 hN) = c₂ := by
rw [monsterData12, Function.Embedding.setValue_eq_of_ne]
· exact Function.Embedding.setValue_eq _ _ _
· simp only [row1, row2, ne_eq, Subtype.mk.injEq]
simp only [Fin.ext_iff, Fin.val_one]
omega
· rw [Function.Embedding.setValue_eq]
exact h.symm
lemma row1_mem_monsterCells_monsterData12 (hN : 2 ≤ N) (c₁ c₂ : Fin (N + 1)) :
(1, c₁) ∈ (monsterData12 hN c₁ c₂).monsterCells := by
exact Set.mem_range_self (row1 hN)
lemma row2_mem_monsterCells_monsterData12 (hN : 2 ≤ N) {c₁ c₂ : Fin (N + 1)} (h : c₁ ≠ c₂) :
(⟨2, by omega⟩, c₂) ∈ (monsterData12 hN c₁ c₂).monsterCells := by
convert Set.mem_range_self (row2 hN)
exact (monsterData12_apply_row2 hN h).symm
lemma Strategy.not_forcesWinIn_two (s : Strategy N) (hN : 2 ≤ N) : ¬ s.ForcesWinIn 2 := by
have : NeZero N := ⟨by omega⟩
have : 0 < N := by omega
simp only [ForcesWinIn, WinsIn, Set.mem_range, not_forall, not_exists, Option.ne_none_iff_isSome]
let m1 : Cell N := (s Fin.elim0).findFstEq 1
let m2 : Cell N := (s ![m1]).findFstEq 2
let m : MonsterData N := monsterData12 hN m1.2 m2.2
have h1r : m1.1 = 1 := Path.findFstEq_fst _ _
have h2r : m2.1 = 2 := Path.findFstEq_fst _ _
have h1 : m1 ∈ m.monsterCells := by
convert row1_mem_monsterCells_monsterData12 hN m1.2 m2.2
refine ⟨m, fun i ↦ ?_⟩
fin_cases i
· simp only [Strategy.play_zero, Path.firstMonster_eq_of_findFstEq_mem h1, Option.isSome_some]
· simp only [Strategy.play_one]
suffices ((s ![some m1]).firstMonster m).isSome = true by
rwa [Path.firstMonster_eq_of_findFstEq_mem h1]
simp_rw [m]
by_cases h : m1.2 = m2.2
· rw [Path.firstMonster_isSome]
refine ⟨m1, ?_, h1⟩
have h' : m1 = (⟨(((2 : Fin (N + 2)) : ℕ) - 1 : ℕ), by omega⟩, m2.2) := by
simpa [Prod.ext_iff, h1r, h2r, h]
nth_rw 2 [h']
exact Path.findFstEq_fst_sub_one_mem _ two_ne_zero
· rw [Path.firstMonster_isSome]
refine ⟨m2, Path.findFstEq_mem_cells _ _, ?_⟩
convert row2_mem_monsterCells_monsterData12 hN h using 1
simpa [Prod.ext_iff, h2r, Fin.ext_iff]
lemma Strategy.ForcesWinIn.three_le {s : Strategy N} {k : ℕ} (hf : s.ForcesWinIn k)
(hN : 2 ≤ N) : 3 ≤ k := by
by_contra hk
exact s.not_forcesWinIn_two hN (Strategy.ForcesWinIn.mono s hf (by omega))
/-! ### Proof of upper bound and constructions used therein -/
/-- The first attempt in a winning strategy, as a function: first pass along the second row to
locate the monster there. -/
def fn0 (N : ℕ) : Fin (2 * N + 2) → Cell N :=
fun i ↦ if i = 0 then (0, 0) else
if h : (i : ℕ) < N + 2 then (1, ⟨(i : ℕ) - 1, by omega⟩) else
(⟨i - N, by omega⟩, ⟨N, by omega⟩)
lemma injective_fn0 (N : ℕ) : Function.Injective (fn0 N) := by
intro ⟨a₁, _⟩ ⟨a₂, _⟩
simp_rw [fn0]
split_ifs <;> simp [Prod.ext_iff] at * <;> omega
/-- The first attempt in a winning strategy, as a `Path`. -/
def path0 (hN : 2 ≤ N) : Path N := Path.ofFn (fn0 N) (by omega) (by simp [fn0])
(by simp only [fn0]; split_ifs with h <;> simp at h ⊢ <;> omega)
(by
simp only [fn0]
intro i hi
split_ifs <;> simp [Adjacent, Nat.dist] at * <;> omega)
/-- The second attempt in a winning strategy, as a function, if the monster in the second row
is not at an edge: pass to the left of that monster then along its column. -/
def fn1OfNotEdge {c₁ : Fin (N + 1)} (hc₁ : c₁ ≠ 0) : Fin (N + 3) → Cell N :=
fun i ↦ if h : (i : ℕ) ≤ 2 then (⟨(i : ℕ), by omega⟩, ⟨(c₁ : ℕ) - 1, by omega⟩) else
(⟨(i : ℕ) - 1, by omega⟩, c₁)
/-- The second attempt in a winning strategy, as a function, if the monster in the second row
is not at an edge. -/
def path1OfNotEdge {c₁ : Fin (N + 1)} (hc₁ : c₁ ≠ 0) : Path N := Path.ofFn (fn1OfNotEdge hc₁)
(by omega) (by simp [fn1OfNotEdge])
(by simp only [fn1OfNotEdge]; split_ifs <;> simp; omega)
(by
simp only [fn1OfNotEdge]
intro i hi
rcases c₁ with ⟨c₁, hc₁N⟩
rw [← Fin.val_ne_iff] at hc₁
split_ifs <;> simp [Adjacent, Nat.dist] at * <;> omega)
/-- The third attempt in a winning strategy, as a function, if the monster in the second row
is not at an edge: pass to the right of that monster then along its column. -/
def fn2OfNotEdge {c₁ : Fin (N + 1)} (hc₁ : (c₁ : ℕ) ≠ N) : Fin (N + 3) → Cell N :=
fun i ↦ if h : (i : ℕ) ≤ 2 then (⟨(i : ℕ), by omega⟩, ⟨(c₁ : ℕ) + 1, by omega⟩) else
(⟨(i : ℕ) - 1, by omega⟩, c₁)
/-- The third attempt in a winning strategy, as a function, if the monster in the second row
is not at an edge. -/
def path2OfNotEdge {c₁ : Fin (N + 1)} (hc₁ : (c₁ : ℕ) ≠ N) : Path N := Path.ofFn (fn2OfNotEdge hc₁)
(by omega) (by simp [fn2OfNotEdge])
(by simp only [fn2OfNotEdge]; split_ifs <;> simp; omega)
(by
simp only [fn2OfNotEdge]
intro i hi
split_ifs <;> simp [Adjacent, Nat.dist] at * <;> omega)
/-- The second attempt in a winning strategy, as a function, if the monster in the second row
is at the left edge: zigzag across the board so that, if we encounter a monster, we have a third
path we know will not encounter a monster. -/
def fn1OfEdge0 (N : ℕ) : Fin (2 * N + 1) → Cell N :=
fun i ↦ if h : (i : ℕ) = 2 * N then (⟨N + 1, by omega⟩, ⟨N, by omega⟩) else
(⟨((i : ℕ) + 1) / 2, by omega⟩, ⟨(i : ℕ) / 2 + 1, by omega⟩)
/-- The second attempt in a winning strategy, as a `Path`, if the monster in the second row
is at the left edge. -/
def path1OfEdge0 (hN : 2 ≤ N) : Path N := Path.ofFn (fn1OfEdge0 N) (by omega)
(by simp only [fn1OfEdge0]; split_ifs <;> simp; omega)
(by simp [fn1OfEdge0])
(by
simp only [fn1OfEdge0]
intro i hi
split_ifs <;> simp [Adjacent, Nat.dist] at * <;> omega)
/-- The second attempt in a winning strategy, as a `Path`, if the monster in the second row
is at the right edge. -/
def path1OfEdgeN (hN : 2 ≤ N) : Path N := (path1OfEdge0 hN).reflect
/-- The third attempt in a winning strategy, as a function, if the monster in the second row
is at the left edge and the second (zigzag) attempt encountered a monster: on the row before
the monster was encountered, move to the following row one place earlier, proceed to the left
edge and then along that column. -/
def fn2OfEdge0 {r : Fin (N + 2)} (hr : (r : ℕ) ≤ N) : Fin (N + 2 * r - 1) → Cell N :=
fun i ↦ if h₁ : (i : ℕ) + 2 < 2 * (r : ℕ) then
(⟨((i : ℕ) + 1) / 2, by omega⟩, ⟨(i : ℕ) / 2 + 1, by omega⟩) else
if h₂ : (i : ℕ) + 2 < 3 * (r : ℕ) then (r, ⟨3 * (r : ℕ) - 3 - (i : ℕ), by omega⟩) else
(⟨i + 3 - 2 * r, by omega⟩, 0)
lemma fn2OfEdge0_apply_eq_fn1OfEdge0_apply_of_lt {r : Fin (N + 2)} (hr : (r : ℕ) ≤ N) {i : ℕ}
(h : i + 2 < 2 * (r : ℕ)) : fn2OfEdge0 hr ⟨i, by omega⟩ = fn1OfEdge0 N ⟨i, by omega⟩ := by
rw [fn1OfEdge0, fn2OfEdge0]
split_ifs with h₁ h₂ <;> simp [Prod.ext_iff] at * <;> omega
/-- The third attempt in a winning strategy, as a `Path`, if the monster in the second row
is at the left edge and the second (zigzag) attempt encountered a monster. -/
def path2OfEdge0 (hN : 2 ≤ N) {r : Fin (N + 2)} (hr2 : 2 ≤ (r : ℕ)) (hrN : (r : ℕ) ≤ N) : Path N :=
Path.ofFn (fn2OfEdge0 hrN) (by omega)
(by simp only [fn2OfEdge0]; split_ifs <;> simp <;> omega)
(by simp only [fn2OfEdge0]; split_ifs <;> simp <;> omega)
(by
simp only [fn2OfEdge0]
intro i hi
split_ifs <;> simp [Adjacent, Nat.dist] at * <;> omega)
/-- The third attempt in a winning strategy, as a `Path`, if the monster in the second row
is at the left edge and the second (zigzag) attempt encountered a monster, version that works
with junk values of `r` for convenience in defining the strategy before needing to prove things
about exactly where it can encounter monsters. -/
def path2OfEdge0Def (hN : 2 ≤ N) (r : Fin (N + 2)) : Path N :=
if h : 2 ≤ (r : ℕ) ∧ (r : ℕ) ≤ N then path2OfEdge0 hN h.1 h.2 else
path2OfEdge0 hN (r := ⟨2, by omega⟩) (le_refl _) hN
/-- The third attempt in a winning strategy, as a `Path`, if the monster in the second row
is at the right edge and the second (zigzag) attempt encountered a monster. -/
def path2OfEdgeNDef (hN : 2 ≤ N) (r : Fin (N + 2)) : Path N :=
(path2OfEdge0Def hN r).reflect
/-- The second attempt in a winning strategy, given the column of the monster in the second row,
as a `Path`. -/
def path1 (hN : 2 ≤ N) (c₁ : Fin (N + 1)) : Path N :=
if hc₁ : c₁ = 0 then path1OfEdge0 hN else
if (c₁ : ℕ) = N then path1OfEdgeN hN else
path1OfNotEdge hc₁
/-- The third attempt in a winning strategy, given the column of the monster in the second row
and the row of the monster (if any) found in the second attempt, as a `Path`. -/
def path2 (hN : 2 ≤ N) (c₁ : Fin (N + 1)) (r : Fin (N + 2)) : Path N :=
if c₁ = 0 then path2OfEdge0Def hN r else
if hc₁N : (c₁ : ℕ) = N then path2OfEdgeNDef hN r else
path2OfNotEdge hc₁N
/-- A strategy that wins in three attempts. -/
def winningStrategy (hN : 2 ≤ N) : Strategy N
| 0 => fun _ ↦ path0 hN
| 1 => fun r => path1 hN ((r 0).getD 0).2
| _ + 2 => fun r => path2 hN ((r 0).getD 0).2 ((r 1).getD 0).1
lemma path0_firstMonster_eq_apply_row1 (hN : 2 ≤ N) (m : MonsterData N) :
(path0 hN).firstMonster m = some (1, m (row1 hN)) := by
simp_rw [path0, Path.firstMonster, Path.ofFn]
have h : (1, m (row1 hN)) = fn0 N ⟨(m (row1 hN) : ℕ) + 1, by omega⟩ := by
simp_rw [fn0]
split_ifs <;> simp [Prod.ext_iff] at *; omega
rw [h, List.find?_ofFn_eq_some_of_injective (injective_fn0 N)]
refine ⟨?_, fun j hj ↦ ?_⟩
· rw [fn0]
split_ifs
· simp [Prod.ext_iff] at *
· have hm1 : (1, m (row1 hN)) ∈ m.monsterCells := Set.mem_range_self (row1 hN)
simpa [Prod.ext_iff] using hm1
· rw [fn0]
split_ifs with h₁
· simp [h₁, MonsterData.monsterCells]
· have hjN2 : (j : ℕ) < N + 2 := by
rw [Fin.lt_def] at hj
refine hj.trans ?_
simp
simp only [MonsterData.monsterCells, h₁, ↓reduceIte, hjN2, ↓reduceDIte, Set.mem_range,
Prod.mk.injEq, Fin.ext_iff, Fin.val_one, Subtype.exists, Set.mem_Icc, exists_and_left,
decide_eq_true_eq, not_exists, not_and]
rintro i hi hix hij
simp only [Fin.ext_iff, Fin.val_zero] at h₁
rw [eq_comm, Nat.sub_eq_iff_eq_add (by omega)] at hij
have hr : row1 hN = ⟨↑i, hix⟩ := by
simp_rw [Subtype.ext_iff, Fin.ext_iff, hi]
rfl
rw [Fin.lt_def, hij, add_lt_add_iff_right, Fin.val_fin_lt, hr] at hj
exact Nat.lt_irrefl _ hj
lemma winningStrategy_play_one (hN : 2 ≤ N) (m : MonsterData N) :
(winningStrategy hN).play m 3 ⟨1, by simp⟩ =
(path1 hN (m (row1 hN))).firstMonster m := by
simp_rw [Strategy.play_one, winningStrategy, path0_firstMonster_eq_apply_row1]
rfl
lemma winningStrategy_play_two (hN : 2 ≤ N) (m : MonsterData N) :
(winningStrategy hN).play m 3 ⟨2, by simp⟩ =
(path2 hN (m (row1 hN))
(((path1 hN (m (row1 hN))).firstMonster m).getD 0).1).firstMonster m := by
simp_rw [Strategy.play_two, winningStrategy, path0_firstMonster_eq_apply_row1]
rfl
lemma path1_firstMonster_of_not_edge (hN : 2 ≤ N) {m : MonsterData N} (hc₁0 : m (row1 hN) ≠ 0)
(hc₁N : (m (row1 hN) : ℕ) ≠ N) :
(path1 hN (m (row1 hN))).firstMonster m = none ∨
(path1 hN (m (row1 hN))).firstMonster m =
some (⟨2, by omega⟩, ⟨(m (row1 hN) : ℕ) - 1, by omega⟩) := by
suffices h : ∀ c ∈ (path1 hN (m (row1 hN))).cells, c ∉ m.monsterCells ∨
c = (⟨2, by omega⟩, ⟨(m (row1 hN) : ℕ) - 1, by omega⟩) by
simp only [Path.firstMonster]
by_cases hn : List.find? (fun x ↦ decide (x ∈ m.monsterCells))
(path1 hN (m (row1 hN))).cells = none
· exact .inl hn
· rw [← ne_eq, Option.ne_none_iff_exists'] at hn
rcases hn with ⟨x, hx⟩
have hxm := List.find?_some hx
have hx' := h _ (List.mem_of_find?_eq_some hx)
simp only [decide_eq_true_eq] at hxm
simp only [hxm, not_true_eq_false, false_or] at hx'
rw [hx'] at hx
exact .inr hx
simp only [path1, hc₁0, ↓reduceDIte, hc₁N, ↓reduceIte, path1OfNotEdge, Path.ofFn_cells,
List.forall_mem_ofFn_iff, fn1OfNotEdge]
intro j
split_ifs with h
· rcases j with ⟨j, hj⟩
simp only at h
interval_cases j
· exact .inl (m.notMem_monsterCells_of_fst_eq_zero rfl)
· simp only [Fin.mk_one, Prod.mk.injEq, Fin.ext_iff, Fin.val_one, OfNat.one_ne_ofNat,
and_true, or_false]
have hN' : 1 ≤ N := by omega
rw [m.mk_mem_monsterCells_iff_of_le (le_refl _) hN', ← ne_eq, ← Fin.val_ne_iff]
rw [← Fin.val_ne_iff] at hc₁0
exact (Nat.sub_one_lt hc₁0).ne'
· exact .inr rfl
· refine .inl ?_
simp only [MonsterData.monsterCells, Set.mem_range, Prod.mk.injEq, Fin.ext_iff,
EmbeddingLike.apply_eq_iff_eq, exists_eq_right, coe_coe_row1]
omega
lemma path2_firstMonster_of_not_edge (hN : 2 ≤ N) {m : MonsterData N} (hc₁0 : m (row1 hN) ≠ 0)
(hc₁N : (m (row1 hN) : ℕ) ≠ N) (r : Fin (N + 2)) :
(path2 hN (m (row1 hN)) r).firstMonster m = none ∨
(path2 hN (m (row1 hN)) r).firstMonster m =
some (⟨2, by omega⟩, ⟨(m (row1 hN) : ℕ) + 1, by omega⟩) := by
suffices h : ∀ c ∈ (path2 hN (m (row1 hN)) r).cells, c ∉ m.monsterCells ∨
c = (⟨2, by omega⟩, ⟨(m (row1 hN) : ℕ) + 1, by omega⟩) by
simp only [Path.firstMonster]
by_cases hn : List.find? (fun x ↦ decide (x ∈ m.monsterCells))
(path2 hN (m (row1 hN)) r).cells = none
· exact .inl hn
· rw [← ne_eq, Option.ne_none_iff_exists'] at hn
rcases hn with ⟨x, hx⟩
have hxm := List.find?_some hx
have hx' := h _ (List.mem_of_find?_eq_some hx)
simp only [decide_eq_true_eq] at hxm
simp only [hxm, not_true_eq_false, false_or] at hx'
rw [hx'] at hx
exact .inr hx
simp only [path2, hc₁0, ↓reduceDIte, hc₁N, ↓reduceIte, path2OfNotEdge, Path.ofFn_cells,
List.forall_mem_ofFn_iff, fn2OfNotEdge]
intro j
split_ifs with h
· rcases j with ⟨j, hj⟩
simp only at h
interval_cases j
· exact .inl (m.notMem_monsterCells_of_fst_eq_zero rfl)
· simp only [Fin.mk_one, Prod.mk.injEq, Fin.ext_iff, Fin.val_one, OfNat.one_ne_ofNat,
and_true, or_false]
have hN' : 1 ≤ N := by omega
rw [m.mk_mem_monsterCells_iff_of_le (le_refl _) hN', ← ne_eq, ← Fin.val_ne_iff]
exact Nat.ne_add_one _
· exact .inr rfl
· refine .inl ?_
simp only [MonsterData.monsterCells, Set.mem_range, Prod.mk.injEq, Fin.ext_iff,
EmbeddingLike.apply_eq_iff_eq, exists_eq_right, coe_coe_row1]
omega
lemma winningStrategy_play_one_eq_none_or_play_two_eq_none_of_not_edge (hN : 2 ≤ N)
{m : MonsterData N} (hc₁0 : m (row1 hN) ≠ 0) (hc₁N : (m (row1 hN) : ℕ) ≠ N) :
(winningStrategy hN).play m 3 ⟨1, by simp⟩ = none ∨
(winningStrategy hN).play m 3 ⟨2, by simp⟩ = none := by
rw [winningStrategy_play_one, winningStrategy_play_two]
have h1 := path1_firstMonster_of_not_edge hN hc₁0 hc₁N
rcases h1 with h1 | h1
· exact .inl h1
· refine .inr ?_
have h2 := path2_firstMonster_of_not_edge hN hc₁0 hc₁N
rcases h2 (((path1 hN (m (row1 hN))).firstMonster m).getD 0).1 with h2r | h2r
· exact h2r
· have h1' := (Path.mem_of_firstMonster_eq_some h1).2
have h2' := (Path.mem_of_firstMonster_eq_some h2r).2
have h12 : 1 ≤ (⟨2, by omega⟩ : Fin (N + 2)) := by
rw [Fin.le_def]
norm_num
rw [m.mk_mem_monsterCells_iff_of_le h12 hN] at h1' h2'
rw [h1'] at h2'
simp at h2'
lemma path2OfEdge0_firstMonster_eq_none_of_path1OfEdge0_firstMonster_eq_some (hN : 2 ≤ N)
{x : Cell N} (hx2 : 2 ≤ (x.1 : ℕ)) (hxN : (x.1 : ℕ) ≤ N) {m : MonsterData N}
(hc₁0 : m (row1 hN) = 0) (hx : (path1OfEdge0 hN).firstMonster m = some x) :
(path2OfEdge0 hN hx2 hxN).firstMonster m = none := by
rw [path2OfEdge0, Path.ofFn_firstMonster_eq_none]
rw [path1OfEdge0, Path.firstMonster, Path.ofFn_cells, List.find?_ofFn_eq_some] at hx
simp only [decide_eq_true_eq] at hx
rcases hx with ⟨hx, i, hix, hnm⟩
have hi : (x.1 : ℕ) = ((i : ℕ) + 1) / 2 := by
rw [fn1OfEdge0] at hix
split_ifs at hix <;> simp [Prod.ext_iff, Fin.ext_iff] at hix <;> omega
have hi' : (i : ℕ) ≠ 2 * N := by
intro h
rw [← hix, fn1OfEdge0, dif_pos h] at hx
have h' := MonsterData.le_N_of_mem_monsterCells hx
simp at h'
intro j
by_cases h : (j : ℕ) + 2 < 2 * (x.1 : ℕ)
· rw [fn2OfEdge0_apply_eq_fn1OfEdge0_apply_of_lt hxN h]
simp_rw [Fin.lt_def] at hnm
refine hnm _ ?_
simp only
omega
· rw [fn2OfEdge0, dif_neg h]
split_ifs with h'
· have hx1 : 1 ≤ x.1 := by
rw [Fin.le_def, Fin.val_one]
omega
rw [MonsterData.mk_mem_monsterCells_iff_of_le hx1 hxN]
rw [MonsterData.mem_monsterCells_iff_of_le hx1 hxN] at hx
simp_rw [hx, ← hix, fn1OfEdge0]
split_ifs <;> simp <;> omega
· rw [MonsterData.mk_mem_monsterCells_iff]
simp only [not_exists]
intro h1 hN'
rw [← hc₁0]
refine m.injective.ne ?_
rw [← Subtype.coe_ne_coe, ← Fin.val_ne_iff, coe_coe_row1]
simp only
omega
lemma winningStrategy_play_one_eq_none_or_play_two_eq_none_of_edge_zero (hN : 2 ≤ N)
{m : MonsterData N} (hc₁0 : m (row1 hN) = 0) :
(winningStrategy hN).play m 3 ⟨1, by simp⟩ = none ∨
(winningStrategy hN).play m 3 ⟨2, by simp⟩ = none := by
rw [or_iff_not_imp_left]
intro h
rw [← ne_eq, Option.ne_none_iff_exists] at h
rcases h with ⟨x, hx⟩
rw [winningStrategy_play_one] at hx
rw [winningStrategy_play_two, ← hx, Option.getD_some]
rw [path1, dif_pos hc₁0] at hx
have h1 := Path.mem_of_firstMonster_eq_some (hx.symm)
have hx2N : 2 ≤ (x.1 : ℕ) ∧ (x.1 : ℕ) ≤ N := by
rw [path1OfEdge0, Path.ofFn_cells, List.mem_ofFn] at h1
rcases h1 with ⟨⟨i, rfl⟩, hm⟩
refine ⟨?_, m.le_N_of_mem_monsterCells hm⟩
rcases i with ⟨i, hi⟩
have hi : 3 ≤ i := by
by_contra hi
interval_cases i <;> rw [fn1OfEdge0] at hm <;> split_ifs at hm with h
· simp at h
omega
· simp at hm
exact m.notMem_monsterCells_of_fst_eq_zero rfl hm
· simp at h
omega
· dsimp only [Nat.reduceAdd, Nat.reduceDiv, Fin.mk_one] at hm
have h1N : 1 ≤ N := by omega
rw [m.mk_mem_monsterCells_iff_of_le (le_refl _) h1N] at hm
rw [row1, hm, Fin.ext_iff] at hc₁0
simp at hc₁0
· simp at h
omega
· simp only at hm
norm_num at hm
have h1N : 1 ≤ N := by omega
rw [m.mk_mem_monsterCells_iff_of_le (le_refl _) h1N] at hm
rw [row1, hm] at hc₁0
simp at hc₁0
rw [fn1OfEdge0]
split_ifs <;> simp <;> omega
rw [path2, if_pos hc₁0, path2OfEdge0Def, dif_pos hx2N]
exact path2OfEdge0_firstMonster_eq_none_of_path1OfEdge0_firstMonster_eq_some hN hx2N.1
hx2N.2 hc₁0 hx.symm
lemma winningStrategy_play_one_of_edge_N (hN : 2 ≤ N) {m : MonsterData N}
(hc₁N : (m (row1 hN) : ℕ) = N) : (winningStrategy hN).play m 3 ⟨1, by simp⟩ =
((winningStrategy hN).play m.reflect 3 ⟨1, by simp⟩).map Cell.reflect := by
have hc₁0 : m (row1 hN) ≠ 0 := by
rw [← Fin.val_ne_iff, hc₁N, Fin.val_zero]
omega
have hc₁r0 : m.reflect (row1 hN) = 0 := by
simp only [MonsterData.reflect, Function.Embedding.coeFn_mk, Function.comp_apply,
← Fin.rev_last, Fin.rev_inj]
rw [Fin.ext_iff]
exact hc₁N
simp_rw [winningStrategy_play_one hN, path1, path1OfEdgeN, dif_neg hc₁0, if_pos hc₁N,
dif_pos hc₁r0, ← Path.firstMonster_reflect, MonsterData.reflect_reflect]
lemma winningStrategy_play_two_of_edge_N (hN : 2 ≤ N) {m : MonsterData N}
(hc₁N : (m (row1 hN) : ℕ) = N) : (winningStrategy hN).play m 3 ⟨2, by simp⟩ =
((winningStrategy hN).play m.reflect 3 ⟨2, by simp⟩).map Cell.reflect := by
have hc₁0 : m (row1 hN) ≠ 0 := by
rw [← Fin.val_ne_iff, hc₁N, Fin.val_zero]
omega
have hc₁r0 : m.reflect (row1 hN) = 0 := by
simp only [MonsterData.reflect, Function.Embedding.coeFn_mk, Function.comp_apply,
← Fin.rev_last, Fin.rev_inj]
rw [Fin.ext_iff]
exact hc₁N
simp_rw [winningStrategy_play_two hN, path1, path1OfEdgeN, path2, path2OfEdgeNDef, if_neg hc₁0,
dif_neg hc₁0, if_pos hc₁N, dif_pos hc₁N, if_pos hc₁r0, dif_pos hc₁r0,
← Path.firstMonster_reflect, MonsterData.reflect_reflect]
convert rfl using 4
nth_rw 2 [← m.reflect_reflect]
rw [Path.firstMonster_reflect]
rcases ((path1OfEdge0 hN).firstMonster m.reflect).eq_none_or_eq_some with h | h
· simp [h]
· rcases h with ⟨x, hx⟩
simp [hx, Cell.reflect]
lemma winningStrategy_play_one_eq_none_or_play_two_eq_none_of_edge_N (hN : 2 ≤ N)
{m : MonsterData N} (hc₁N : (m (row1 hN) : ℕ) = N) :
(winningStrategy hN).play m 3 ⟨1, by simp⟩ = none ∨
(winningStrategy hN).play m 3 ⟨2, by simp⟩ = none := by
simp_rw [winningStrategy_play_one_of_edge_N hN hc₁N, winningStrategy_play_two_of_edge_N hN hc₁N,
Option.map_eq_none_iff]
have hc₁r0 : m.reflect (row1 hN) = 0 := by
simp only [MonsterData.reflect, Function.Embedding.coeFn_mk, Function.comp_apply,
← Fin.rev_last, Fin.rev_inj]
rw [Fin.ext_iff]
exact hc₁N
exact winningStrategy_play_one_eq_none_or_play_two_eq_none_of_edge_zero hN hc₁r0
lemma winningStrategy_play_one_eq_none_or_play_two_eq_none (hN : 2 ≤ N) (m : MonsterData N) :
(winningStrategy hN).play m 3 ⟨1, by simp⟩ = none ∨
(winningStrategy hN).play m 3 ⟨2, by simp⟩ = none := by
by_cases hc₁0 : m (row1 hN) = 0
· exact winningStrategy_play_one_eq_none_or_play_two_eq_none_of_edge_zero hN hc₁0
· by_cases hc₁N : (m (row1 hN) : ℕ) = N
· exact winningStrategy_play_one_eq_none_or_play_two_eq_none_of_edge_N hN hc₁N
· exact winningStrategy_play_one_eq_none_or_play_two_eq_none_of_not_edge hN hc₁0 hc₁N
lemma winningStrategy_forcesWinIn_three (hN : 2 ≤ N) :
(winningStrategy hN).ForcesWinIn 3 := by
intro m
rcases winningStrategy_play_one_eq_none_or_play_two_eq_none hN m with h | h
· rw [Strategy.WinsIn]
convert Set.mem_range_self (⟨1, by simp⟩ : Fin 3)
exact h.symm
· rw [Strategy.WinsIn]
convert Set.mem_range_self (⟨2, by simp⟩ : Fin 3)
exact h.symm
/-- This is to be determined by the solver of the original problem (and much of the difficulty
for contestants is in finding this answer rather than spending time attempting to prove a
conjectured answer around log₂ 2023). -/
def answer : ℕ := 3
/-- The final result, combining upper and lower bounds. -/
theorem result : IsLeast {k | ∃ s : Strategy 2022, s.ForcesWinIn k} answer := by
simp_rw [IsLeast, mem_lowerBounds, Set.mem_setOf, forall_exists_index]
exact ⟨⟨winningStrategy (by simp), winningStrategy_forcesWinIn_three (by simp)⟩,
fun k s h ↦ h.three_le (by simp)⟩
end Imo2024Q5 |
.lake/packages/mathlib/Archive/Imo/Imo2006Q3.lean | import Mathlib.Analysis.SpecialFunctions.Sqrt
/-!
# IMO 2006 Q3
Determine the least real number $M$ such that
$$
\left| ab(a^2 - b^2) + bc(b^2 - c^2) + ca(c^2 - a^2) \right|
≤ M (a^2 + b^2 + c^2)^2
$$
for all real numbers $a$, $b$, $c$.
## Solution
The answer is $M = \frac{9 \sqrt 2}{32}$.
This is essentially a translation of the solution in
https://web.evanchen.cc/exams/IMO-2006-notes.pdf.
It involves making the substitution
`x = a - b`, `y = b - c`, `z = c - a`, `s = a + b + c`.
-/
open Real
namespace Imo2006Q3
/-- Replacing `x` and `y` with their average increases the left side. -/
theorem lhs_ineq {x y : ℝ} (hxy : 0 ≤ x * y) :
16 * x ^ 2 * y ^ 2 * (x + y) ^ 2 ≤ ((x + y) ^ 2) ^ 3 := by
have : (x - y) ^ 2 * ((x + y) ^ 2 + 4 * (x * y)) ≥ 0 := by positivity
calc 16 * x ^ 2 * y ^ 2 * (x + y) ^ 2 ≤ ((x + y) ^ 2) ^ 2 * (x + y) ^ 2 := by gcongr; linarith
_ = ((x + y) ^ 2) ^ 3 := by ring
theorem four_pow_four_pos : (0 : ℝ) < 4 ^ 4 := by simp
theorem mid_ineq {s t : ℝ} : s * t ^ 3 ≤ (3 * t + s) ^ 4 / 4 ^ 4 := by
rw [le_div_iff₀ four_pow_four_pos]
have : 0 ≤ (s - t) ^ 2 * ((s + 7 * t) ^ 2 + 2 * (4 * t) ^ 2) := by positivity
linarith
/-- Replacing `x` and `y` with their average decreases the right side. -/
theorem rhs_ineq {x y : ℝ} : 3 * (x + y) ^ 2 ≤ 2 * (x ^ 2 + y ^ 2 + (x + y) ^ 2) := by
have : 0 ≤ (x - y) ^ 2 := by positivity
linarith
theorem zero_lt_32 : (0 : ℝ) < 32 := by simp
theorem subst_wlog {x y z s : ℝ} (hxy : 0 ≤ x * y) (hxyz : x + y + z = 0) :
32 * |x * y * z * s| ≤ sqrt 2 * (x ^ 2 + y ^ 2 + z ^ 2 + s ^ 2) ^ 2 := by
have hz : (x + y) ^ 2 = z ^ 2 := by linear_combination (x + y - z) * hxyz
have this :=
calc
2 * s ^ 2 * (16 * x ^ 2 * y ^ 2 * (x + y) ^ 2)
≤ _ * _ ^ 3 := by gcongr; exact lhs_ineq hxy
_ ≤ (3 * (x + y) ^ 2 + 2 * s ^ 2) ^ 4 / 4 ^ 4 := mid_ineq
_ ≤ (2 * (x ^ 2 + y ^ 2 + (x + y) ^ 2) + 2 * s ^ 2) ^ 4 / 4 ^ 4 := by
gcongr (?_ + _) ^ 4 / _
apply rhs_ineq
refine le_of_pow_le_pow_left₀ two_ne_zero (by positivity) ?_
calc
(32 * |x * y * z * s|) ^ 2 = 32 * (2 * s ^ 2 * (16 * x ^ 2 * y ^ 2 * (x + y) ^ 2)) := by
rw [mul_pow, sq_abs, hz]; ring
_ ≤ 32 * ((2 * (x ^ 2 + y ^ 2 + (x + y) ^ 2) + 2 * s ^ 2) ^ 4 / 4 ^ 4) := by gcongr
_ = (sqrt 2 * (x ^ 2 + y ^ 2 + z ^ 2 + s ^ 2) ^ 2) ^ 2 := by
simp [field, hz]
ring
/-- Proof that `M = 9 * sqrt 2 / 32` works with the substitution. -/
theorem subst_proof₁ (x y z s : ℝ) (hxyz : x + y + z = 0) :
|x * y * z * s| ≤ sqrt 2 / 32 * (x ^ 2 + y ^ 2 + z ^ 2 + s ^ 2) ^ 2 := by
wlog h' : 0 ≤ x * y generalizing x y z; swap
· rw [div_mul_eq_mul_div, le_div_iff₀' zero_lt_32]
exact subst_wlog h' hxyz
rcases (mul_nonneg_of_three x y z).resolve_left h' with h | h
· convert this y z x _ h using 2 <;> linarith
· convert this z x y _ h using 2 <;> linarith
theorem proof₁ {a b c : ℝ} :
|a * b * (a ^ 2 - b ^ 2) + b * c * (b ^ 2 - c ^ 2) + c * a * (c ^ 2 - a ^ 2)| ≤
9 * sqrt 2 / 32 * (a ^ 2 + b ^ 2 + c ^ 2) ^ 2 :=
calc
_ = |(a - b) * (b - c) * (c - a) * -(a + b + c)| := by ring_nf
_ ≤ _ := subst_proof₁ (a - b) (b - c) (c - a) (-(a + b + c)) (by ring)
_ = _ := by ring
theorem proof₂ (M : ℝ)
(h : ∀ a b c : ℝ,
|a * b * (a ^ 2 - b ^ 2) + b * c * (b ^ 2 - c ^ 2) + c * a * (c ^ 2 - a ^ 2)| ≤
M * (a ^ 2 + b ^ 2 + c ^ 2) ^ 2) :
9 * sqrt 2 / 32 ≤ M := by
set α := sqrt (2:ℝ)
have hα : α ^ 2 = 2 := sq_sqrt (by simp)
let a := 2 - 3 * α
let c := 2 + 3 * α
calc _ = 18 ^ 2 * 2 * α / 48 ^ 2 := by ring
_ ≤ M := ?_
rw [div_le_iff₀ (by positivity)]
calc 18 ^ 2 * 2 * α
= 18 ^ 2 * α ^ 2 * α := by linear_combination -324 * α * hα
_ = abs (-(18 ^ 2 * α ^ 2 * α)) := by rw [abs_neg, abs_of_nonneg]; positivity
_ = |a * 2 * (a ^ 2 - 2 ^ 2) + 2 * c * (2 ^ 2 - c ^ 2) + c * a * (c ^ 2 - a ^ 2)| := by ring_nf!
_ ≤ M * (a ^ 2 + 2 ^ 2 + c ^ 2) ^ 2 := by apply h
_ = M * 48 ^ 2 := by linear_combination (324 * α ^ 2 + 1080) * M * hα
end Imo2006Q3
open Imo2006Q3
theorem imo2006_q3 (M : ℝ) :
(∀ a b c : ℝ,
|a * b * (a ^ 2 - b ^ 2) + b * c * (b ^ 2 - c ^ 2) + c * a * (c ^ 2 - a ^ 2)| ≤
M * (a ^ 2 + b ^ 2 + c ^ 2) ^ 2) ↔
9 * sqrt 2 / 32 ≤ M :=
⟨proof₂ M, fun h _ _ _ => proof₁.trans (by gcongr)⟩ |
.lake/packages/mathlib/Archive/Imo/Imo2020Q2.lean | import Mathlib.Analysis.MeanInequalities
/-!
# IMO 2020 Q2
The real numbers `a`, `b`, `c`, `d` are such that `a ≥ b ≥ c ≥ d > 0` and `a + b + c + d = 1`.
Prove that `(a + 2b + 3c + 4d) a^a b^b c^c d^d < 1`.
A solution is to eliminate the powers using weighted AM-GM and replace
`1` by `(a+b+c+d)^3`, leaving a homogeneous inequality that can be
proved in many ways by expanding, rearranging and comparing individual
terms. The version here using factors such as `a+3b+3c+3d` is from
the official solutions.
-/
open Real
theorem imo2020_q2 (a b c d : ℝ) (hd0 : 0 < d) (hdc : d ≤ c) (hcb : c ≤ b) (hba : b ≤ a)
(h1 : a + b + c + d = 1) : (a + 2 * b + 3 * c + 4 * d) * a ^ a * b ^ b * c ^ c * d ^ d < 1 := by
have hp : a ^ a * b ^ b * c ^ c * d ^ d ≤ a * a + b * b + c * c + d * d := by
refine geom_mean_le_arith_mean4_weighted ?_ ?_ ?_ ?_ ?_ ?_ ?_ ?_ h1 <;> linarith
calc
(a + 2 * b + 3 * c + 4 * d) * a ^ a * b ^ b * c ^ c * d ^ d =
(a + 2 * b + 3 * c + 4 * d) * (a ^ a * b ^ b * c ^ c * d ^ d) := by ac_rfl
_ ≤ (a + 2 * b + 3 * c + 4 * d) * (a * a + b * b + c * c + d * d) := by gcongr; linarith
_ = (a + 2 * b + 3 * c + 4 * d) * a ^ 2 + (a + 2 * b + 3 * c + 4 * d) * b ^ 2
+ (a + 2 * b + 3 * c + 4 * d) * c ^ 2 + (a + 2 * b + 3 * c + 4 * d) * d ^ 2 := by ring
_ ≤ (a + 3 * b + 3 * c + 3 * d) * a ^ 2 + (3 * a + b + 3 * c + 3 * d) * b ^ 2
+ (3 * a + 3 * b + c + 3 * d) * c ^ 2 + (3 * a + 3 * b + 3 * c + d) * d ^ 2 := by
gcongr ?_ * _ + ?_ * _ + ?_ * _ + ?_ * _ <;> linarith
_ < (a + 3 * b + 3 * c + 3 * d) * a ^ 2 + (3 * a + b + 3 * c + 3 * d) * b ^ 2
+ (3 * a + 3 * b + c + 3 * d) * c ^ 2 + (3 * a + 3 * b + 3 * c + d) * d ^ 2
+ (6 * a * b * c + 6 * a * b * d + 6 * a * c * d + 6 * b * c * d) :=
(lt_add_of_pos_right _ (by apply_rules [add_pos, mul_pos, zero_lt_one] <;> linarith))
_ = (a + b + c + d) ^ 3 := by ring
_ = 1 := by simp [h1] |
.lake/packages/mathlib/Archive/Imo/Imo2008Q2.lean | import Mathlib.Data.Real.Basic
import Mathlib.Data.Set.Finite.Lattice
import Mathlib.Tactic.Abel
import Mathlib.Tactic.Field
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.Ring
/-!
# IMO 2008 Q2
(a) Prove that
```
x^2 / (x-1)^2 + y^2 / (y-1)^2 + z^2 / (z-1)^2 ≥ 1
```
for all real numbers `x`,`y`, `z`, each different from 1, and satisfying `xyz = 1`.
(b) Prove that equality holds above for infinitely many triples of rational numbers `x`, `y`, `z`,
each different from 1, and satisfying `xyz = 1`.
## Solution
(a) Since `xyz = 1`, we can apply the substitution `x = a/b`, `y = b/c`, `z = c/a`.
Then we define `m = c-b`, `n = b-a` and rewrite the inequality as `LHS - 1 ≥ 0`
using `c`, `m` and `n`. We factor `LHS - 1` as a square, which finishes the proof.
(b) We present a set `W` of rational triples. We prove that `W` is a subset of the
set of rational solutions to the equation, and that `W` is infinite.
-/
namespace Imo2008Q2
theorem subst_abc {x y z : ℝ} (h : x * y * z = 1) :
∃ a b c : ℝ, a ≠ 0 ∧ b ≠ 0 ∧ c ≠ 0 ∧ x = a / b ∧ y = b / c ∧ z = c / a := by
use x, 1, 1 / y
obtain ⟨⟨hx, hy⟩, _⟩ : (x ≠ 0 ∧ y ≠ 0) ∧ z ≠ 0 := by
have := h.symm ▸ one_ne_zero
simpa [not_or] using this
have : z * (y * x) = 1 := by rw [← h]; ac_rfl
simp [field, mul_assoc, *]
theorem imo2008_q2a (x y z : ℝ) (h : x * y * z = 1) (hx : x ≠ 1) (hy : y ≠ 1) (hz : z ≠ 1) :
x ^ 2 / (x - 1) ^ 2 + y ^ 2 / (y - 1) ^ 2 + z ^ 2 / (z - 1) ^ 2 ≥ 1 := by
obtain ⟨a, b, c, ha, hb, hc, rfl, rfl, rfl⟩ := subst_abc h
obtain ⟨m, n, rfl, rfl⟩ : ∃ m n, b = c - m ∧ a = c - m - n := by use c - b, b - a; simp
have hm_ne_zero : m ≠ 0 := by contrapose! hy; simpa [field]
have hn_ne_zero : n ≠ 0 := by contrapose! hx; simpa [field]
have hmn_ne_zero : m + n ≠ 0 := by contrapose! hz; field_simp; linarith
have hc_sub_sub : c - (c - m - n) = m + n := by abel
rw [ge_iff_le, ← sub_nonneg]
convert sq_nonneg ((c * (m ^ 2 + n ^ 2 + m * n) - m * (m + n) ^ 2) / (m * n * (m + n)))
simp [field, hc_sub_sub]; ring
def rationalSolutions :=
{s : ℚ × ℚ × ℚ | ∃ x y z : ℚ, s = (x, y, z) ∧ x ≠ 1 ∧ y ≠ 1 ∧ z ≠ 1 ∧ x * y * z = 1 ∧
x ^ 2 / (x - 1) ^ 2 + y ^ 2 / (y - 1) ^ 2 + z ^ 2 / (z - 1) ^ 2 = 1}
theorem imo2008_q2b : Set.Infinite rationalSolutions := by
let W := {s : ℚ × ℚ × ℚ | ∃ x y z : ℚ, s = (x, y, z) ∧
∃ t : ℚ, t > 0 ∧ x = -(t + 1) / t ^ 2 ∧ y = t / (t + 1) ^ 2 ∧ z = -t * (t + 1)}
have hW_sub_S : W ⊆ rationalSolutions := by
intro s hs_in_W
rw [rationalSolutions]
simp only [Set.mem_setOf_eq] at hs_in_W ⊢
rcases hs_in_W with ⟨x, y, z, h₁, t, ht_gt_zero, hx_t, hy_t, hz_t⟩
use x, y, z
have key_gt_zero : t ^ 2 + t + 1 > 0 := by linarith [pow_pos ht_gt_zero 2, ht_gt_zero]
have h₂ : x ≠ 1 := by rw [hx_t]; simp [field]; linarith [key_gt_zero]
have h₃ : y ≠ 1 := by rw [hy_t]; simp [field]; linarith [key_gt_zero]
have h₄ : z ≠ 1 := by rw [hz_t]; linarith [key_gt_zero]
have h₅ : x * y * z = 1 := by rw [hx_t, hy_t, hz_t]; field
have h₆ : x ^ 2 / (x - 1) ^ 2 + y ^ 2 / (y - 1) ^ 2 + z ^ 2 / (z - 1) ^ 2 = 1 := by
have hx1 : (x - 1) ^ 2 = (t ^ 2 + t + 1) ^ 2 / t ^ 4 := by
rw [hx_t]; field
have hy1 : (y - 1) ^ 2 = (t ^ 2 + t + 1) ^ 2 / (t + 1) ^ 4 := by
rw [hy_t]; field
have hz1 : (z - 1) ^ 2 = (t ^ 2 + t + 1) ^ 2 := by rw [hz_t]; ring
calc
x ^ 2 / (x - 1) ^ 2 + y ^ 2 / (y - 1) ^ 2 + z ^ 2 / (z - 1) ^ 2 =
(x ^ 2 * t ^ 4 + y ^ 2 * (t + 1) ^ 4 + z ^ 2) / (t ^ 2 + t + 1) ^ 2 := by
rw [hx1, hy1, hz1]; field
_ = 1 := by rw [hx_t, hy_t, hz_t]; field
exact ⟨h₁, h₂, h₃, h₄, h₅, h₆⟩
have hW_inf : Set.Infinite W := by
let g : ℚ × ℚ × ℚ → ℚ := fun s => -s.2.2
let K := g '' W
have hK_not_bdd : ¬BddAbove K := by
rw [not_bddAbove_iff]
intro q
let t : ℚ := max (q + 1) 1
use t * (t + 1)
have h₁ : t * (t + 1) ∈ K := by
let x : ℚ := -(t + 1) / t ^ 2
let y : ℚ := t / (t + 1) ^ 2
set z : ℚ := -t * (t + 1) with hz_def
simp only [t, W, K, g, Set.mem_image, Prod.exists]
use x, y, z; constructor
· simp only [Set.mem_setOf_eq]
use x, y, z; constructor
· rfl
· use t; constructor
· simp only [t, gt_iff_lt, lt_max_iff]; right; trivial
exact ⟨rfl, rfl, rfl⟩
· have hg : -z = g (x, y, z) := rfl
rw [hg, hz_def]; ring
have h₂ : q < t * (t + 1) := by linarith [sq_nonneg t, le_max_left (q + 1) 1]
exact ⟨h₁, h₂⟩
have hK_inf : Set.Infinite K := by intro h; apply hK_not_bdd; exact Set.Finite.bddAbove h
exact hK_inf.of_image g
exact hW_inf.mono hW_sub_S
end Imo2008Q2 |
.lake/packages/mathlib/Archive/Imo/Imo2013Q1.lean | import Mathlib.Algebra.BigOperators.Group.Finset.Powerset
import Mathlib.Algebra.Order.Field.Rat
import Mathlib.Tactic.FieldSimp
import Mathlib.Tactic.Positivity.Basic
import Mathlib.Tactic.Ring
/-!
# IMO 2013 Q1
Prove that for any pair of positive integers k and n, there exist k positive integers
m₁, m₂, ..., mₖ (not necessarily different) such that
1 + (2ᵏ - 1)/ n = (1 + 1/m₁) * (1 + 1/m₂) * ... * (1 + 1/mₖ).
## Solution
Adaptation of the solution found in https://www.imo-official.org/problems/IMO2013SL.pdf
We prove a slightly more general version where k does not need to be strictly positive.
-/
namespace Imo2013Q1
theorem arith_lemma (k n : ℕ) : 0 < 2 * n + 2 ^ k.succ := by positivity
theorem prod_lemma (m : ℕ → ℕ+) (k : ℕ) (nm : ℕ+) :
∏ i ∈ Finset.range k, ((1 : ℚ) + 1 / ↑(if i < k then m i else nm)) =
∏ i ∈ Finset.range k, (1 + 1 / (m i : ℚ)) := by
suffices ∀ i, i ∈ Finset.range k → (1 : ℚ) + 1 / ↑(if i < k then m i else nm) = 1 + 1 / m i from
Finset.prod_congr rfl this
grind
end Imo2013Q1
open Imo2013Q1
theorem imo2013_q1 (n : ℕ+) (k : ℕ) :
∃ m : ℕ → ℕ+, (1 : ℚ) + (2 ^ k - 1) / n = ∏ i ∈ Finset.range k, (1 + 1 / (m i : ℚ)) := by
induction k generalizing n with
| zero => use fun (_ : ℕ) => (1 : ℕ+); simp -- For the base case, any m works.
| succ pk hpk =>
obtain ⟨t, ht : ↑n = t + t⟩ | ⟨t, ht : ↑n = 2 * t + 1⟩ := (n : ℕ).even_or_odd
· -- even case
rw [← two_mul] at ht
-- Eliminate the zero case to simplify later calculations.
obtain ⟨t, rfl⟩ := Nat.exists_eq_succ_of_ne_zero <| by
rintro (rfl : t = 0)
rw [Nat.mul_zero] at ht; exact PNat.ne_zero n ht
-- Now we have ht : ↑n = 2 * (t + 1).
let t_succ : ℕ+ := ⟨t + 1, t.succ_pos⟩
obtain ⟨pm, hpm⟩ := hpk t_succ
let m i := if i < pk then pm i else ⟨2 * t + 2 ^ pk.succ, arith_lemma pk t⟩
use m
have hmpk : (m pk : ℚ) = 2 * t + 2 ^ pk.succ := by
have : m pk = ⟨2 * t + 2 ^ pk.succ, _⟩ := if_neg (irrefl pk); simp [this]
calc
((1 : ℚ) + (2 ^ pk.succ - 1) / (n : ℚ) : ℚ)= 1 + (2 * 2 ^ pk - 1) / (2 * (t + 1) : ℕ) := by
rw [ht, pow_succ']
_ = (1 + 1 / (2 * t + 2 * 2 ^ pk)) * (1 + (2 ^ pk - 1) / (↑t + 1)) := by
simp [field, -mul_eq_mul_right_iff]
ring
_ = (1 + 1 / (2 * t + 2 ^ pk.succ)) * (1 + (2 ^ pk - 1) / t_succ) := by
simp [pow_succ', PNat.mk_coe, t_succ]
_ = (∏ i ∈ Finset.range pk, (1 + 1 / (m i : ℚ))) * (1 + 1 / m pk) := by
rw [prod_lemma, hpm, ← hmpk, mul_comm]
_ = ∏ i ∈ Finset.range pk.succ, (1 + 1 / (m i : ℚ)) := by rw [← Finset.prod_range_succ _ pk]
· -- odd case
let t_succ : ℕ+ := ⟨t + 1, t.succ_pos⟩
obtain ⟨pm, hpm⟩ := hpk t_succ
let m i := if i < pk then pm i else ⟨2 * t + 1, Nat.succ_pos _⟩
use m
have hmpk : (m pk : ℚ) = 2 * t + 1 := by
have : m pk = ⟨2 * t + 1, _⟩ := if_neg (irrefl pk)
simp [this]
calc
((1 : ℚ) + (2 ^ pk.succ - 1) / ↑n : ℚ) = 1 + (2 * 2 ^ pk - 1) / (2 * t + 1 : ℕ) := by
rw [ht, pow_succ']
_ = (1 + 1 / (2 * t + 1)) * (1 + (2 ^ pk - 1) / (t + 1)) := by
simp [field]
ring
_ = (1 + 1 / (2 * t + 1)) * (1 + (2 ^ pk - 1) / t_succ) := by norm_cast
_ = (∏ i ∈ Finset.range pk, (1 + 1 / (m i : ℚ))) * (1 + 1 / ↑(m pk)) := by
rw [prod_lemma, hpm, ← hmpk, mul_comm]
_ = ∏ i ∈ Finset.range pk.succ, (1 + 1 / (m i : ℚ)) := by rw [← Finset.prod_range_succ _ pk] |
.lake/packages/mathlib/Archive/Imo/Imo2008Q3.lean | import Mathlib.Data.Real.Basic
import Mathlib.Data.Real.Sqrt
import Mathlib.Data.Nat.Prime.Defs
import Mathlib.NumberTheory.PrimesCongruentOne
import Mathlib.NumberTheory.LegendreSymbol.QuadraticReciprocity
import Mathlib.Tactic.LinearCombination
/-!
# IMO 2008 Q3
Prove that there exist infinitely many positive integers `n` such that `n^2 + 1` has a prime
divisor which is greater than `2n + √(2n)`.
## Solution
We first prove the following lemma: for every prime `p > 20`, satisfying `p ≡ 1 [MOD 4]`,
there exists `n ∈ ℕ` such that `p ∣ n^2 + 1` and `p > 2n + √(2n)`. Then the statement of the
problem follows from the fact that there exist infinitely many primes `p ≡ 1 [MOD 4]`.
To prove the lemma, notice that `p ≡ 1 [MOD 4]` implies `∃ n ∈ ℕ` such that `n^2 ≡ -1 [MOD p]`
and we can take this `n` such that `n ≤ p/2`. Let `k = p - 2n ≥ 0`. Then we have:
`k^2 + 4 = (p - 2n)^2 + 4 ≣ 4n^2 + 4 ≡ 0 [MOD p]`. Then `k^2 + 4 ≥ p` and so `k ≥ √(p - 4) > 4`.
Then `p = 2n + k ≥ 2n + √(p - 4) = 2n + √(2n + k - 4) > √(2n)` and we are done.
-/
open Real
namespace Imo2008Q3
theorem p_lemma (p : ℕ) (hpp : Nat.Prime p) (hp_mod_4_eq_1 : p ≡ 1 [MOD 4]) (hp_gt_20 : p > 20) :
∃ n : ℕ, p ∣ n ^ 2 + 1 ∧ (p : ℝ) > 2 * n + sqrt (2 * n) := by
haveI := Fact.mk hpp
have hp_mod_4_ne_3 : p % 4 ≠ 3 := by linarith [show p % 4 = 1 from hp_mod_4_eq_1]
obtain ⟨y, hy⟩ := ZMod.exists_sq_eq_neg_one_iff.mpr hp_mod_4_ne_3
let m := ZMod.valMinAbs y
let n := Int.natAbs m
have hnat₁ : p ∣ n ^ 2 + 1 := by
refine Int.natCast_dvd_natCast.mp ?_
simp only [n, Int.natAbs_sq, Int.natCast_pow, Int.natCast_succ]
refine (ZMod.intCast_zmod_eq_zero_iff_dvd (m ^ 2 + 1) p).mp ?_
simp only [m, Int.cast_pow, Int.cast_add, Int.cast_one, ZMod.coe_valMinAbs]
rw [pow_two, ← hy]; exact neg_add_cancel 1
have hnat₂ : n ≤ p / 2 := ZMod.natAbs_valMinAbs_le y
have hnat₃ : p ≥ 2 * n := by omega
set k : ℕ := p - 2 * n with hnat₄
have hnat₅ : p ∣ k ^ 2 + 4 := by
obtain ⟨x, hx⟩ := hnat₁
have : (p : ℤ) ∣ (k : ℤ) ^ 2 + 4 := by
use (p : ℤ) - 4 * n + 4 * x
have hcast₁ : (k : ℤ) = p - 2 * n := by assumption_mod_cast
have hcast₂ : (n : ℤ) ^ 2 + 1 = p * x := by assumption_mod_cast
linear_combination ((k : ℤ) + p - 2 * n) * hcast₁ + 4 * hcast₂
assumption_mod_cast
have hnat₆ : k ^ 2 + 4 ≥ p := Nat.le_of_dvd (k ^ 2 + 3).succ_pos hnat₅
have hreal₁ : (k : ℝ) = p - 2 * n := by assumption_mod_cast
have hreal₂ : (p : ℝ) > 20 := by assumption_mod_cast
have hreal₃ : (k : ℝ) ^ 2 + 4 ≥ p := by assumption_mod_cast
have hreal₅ : (k : ℝ) > 4 := by
refine lt_of_pow_lt_pow_left₀ 2 k.cast_nonneg ?_
linarith only [hreal₂, hreal₃]
have hreal₆ : (k : ℝ) > sqrt (2 * n) := by
refine lt_of_pow_lt_pow_left₀ 2 k.cast_nonneg ?_
rw [sq_sqrt (mul_nonneg zero_le_two n.cast_nonneg)]
linarith only [hreal₁, hreal₃, hreal₅]
exact ⟨n, hnat₁, by linarith only [hreal₆, hreal₁]⟩
end Imo2008Q3
open Imo2008Q3
theorem imo2008_q3 : ∀ N : ℕ, ∃ n : ℕ, n ≥ N ∧
∃ p : ℕ, Nat.Prime p ∧ p ∣ n ^ 2 + 1 ∧ (p : ℝ) > 2 * n + sqrt (2 * n) := by
intro N
obtain ⟨p, hpp, hineq₁, hpmod4⟩ := Nat.exists_prime_gt_modEq_one (N ^ 2 + 20) four_ne_zero
obtain ⟨n, hnat, hreal⟩ := p_lemma p hpp hpmod4 (by linarith [hineq₁, Nat.zero_le (N ^ 2)])
have hineq₂ : n ^ 2 + 1 ≥ p := Nat.le_of_dvd (n ^ 2).succ_pos hnat
have hineq₃ : n * n ≥ N * N := by linarith [hineq₁, hineq₂]
have hn_ge_N : n ≥ N := Nat.mul_self_le_mul_self_iff.1 hineq₃
exact ⟨n, hn_ge_N, p, hpp, hnat, hreal⟩ |
.lake/packages/mathlib/Archive/Imo/Imo2015Q6.lean | import Mathlib.Algebra.BigOperators.Intervals
import Mathlib.Algebra.Order.Group.Abs
import Mathlib.Algebra.Order.Group.Int.Sum
import Mathlib.Algebra.Order.Ring.Int
/-!
# IMO 2015 Q6
The sequence $a_1, a_2, \dots$ of integers satisfies the conditions
1. $1 ≤ a_j ≤ 2015$ for all $j ≥ 1$,
2. $k + a_k ≠ l + a_l$ for all $1 ≤ k < l$.
Prove that there exist two positive integers $b$ and $N$ for which
$$\left|\sum_{j=m+1}^n (a_j-b)\right| ≤ 1007^2$$
for all integers $m,n$ such that $N ≤ m < n$.
## Solution
We follow solution 2 ("juggling") from https://web.evanchen.cc/exams/IMO-2015-notes.pdf.
Consider a collection of balls at different integer heights that starts out empty at time 0
and is modified at each succeeding integer time `t` as follows:
* If there is a ball at height 0 it is removed (caught)
* Then a ball is added at height $a_t$
* Then all balls have their height decreased by 1
Condition 1 ensures that all heights stay in [0, 2014]. Condition 2 ensures that the heights at any
point in time are distinct, so we can model the collection as a finset of heights of monotonically
increasing, bounded cardinality. So there is a time where the cardinality reaches a maximum;
we take `N` to be that time and `b` to be that maximum cardinality. $1 ≤ b ≤ 2015$.
Let $S_t$ be the sum of heights at time $t$. The key observation is that for all $t ≥ N$
$$S_{t+1} = S_t + a_{t+1} - b$$
because 0 must be in the set of heights at time $t$ (otherwise the cardinality will increase);
this height is replaced by $a_{t+1}$ and then all $b$ balls have their height decreased by 1. Thus
$$\left|\sum_{j=m+1}^n (a_j-b)\right| = |S_n - S_m|.$$
Now for all $t ≥ N$,
$$\sum_{i=0}^{b-1} i ≤ S_t ≤ 0 + \sum_{i=0}^{b-2} (2014-i),$$
so the absolute difference is upper-bounded by
$$\sum_{i=0}^{b-2} (2014-i) - (b-1) - \sum_{i=0}^{b-2} (b-2-i) = (b-1)(2015-b) ≤ 1007^2.$$
-/
namespace Imo2015Q6
open Finset
/-- The conditions on `a` in the problem. We reindex `a` to start from 0 rather than 1;
`N` then only has to be nonnegative rather than positive, and the sum in the problem statement
is over `Ico m n` rather than `Ioc m n`. -/
def Condition (a : ℕ → ℤ) : Prop := (∀ i, a i ∈ Icc 1 2015) ∧ Function.Injective fun i ↦ i + a i
/-- The collection of ball heights in the solution. -/
def pool (a : ℕ → ℤ) : ℕ → Finset ℤ
| 0 => ∅
| t + 1 => (insert (a t) ((pool a t).erase 0)).map (Equiv.subRight (1 : ℤ))
variable {a : ℕ → ℤ} (ha : Condition a) {t : ℕ}
section Pool
lemma exists_add_eq_of_mem_pool {z : ℤ} (hz : z ∈ pool a t) : ∃ u < t, u + a u = t + z := by
induction t generalizing z with
| zero => simp only [pool, notMem_empty] at hz
| succ t ih =>
simp_rw [pool, mem_map, Equiv.coe_toEmbedding, Equiv.subRight_apply] at hz
obtain ⟨y, my, ey⟩ := hz
rw [mem_insert, mem_erase] at my; rcases my with h | h
· use t; omega
· obtain ⟨u, lu, hu⟩ := ih h.2
use u; omega
include ha
/-- The ball heights are always within `[0, 2014]`. -/
lemma pool_subset_Icc : ∀ {t}, pool a t ⊆ Icc 0 2014
| 0 => by simp [pool]
| t + 1 => by
intro x hx
simp_rw [pool, mem_map, Equiv.coe_toEmbedding, Equiv.subRight_apply] at hx
obtain ⟨y, my, ey⟩ := hx
suffices y ∈ Icc 1 2015 by rw [mem_Icc] at this ⊢; omega
rw [mem_insert, mem_erase] at my; rcases my with h | ⟨h₁, h₂⟩
· exact h ▸ ha.1 t
· have := pool_subset_Icc h₂; rw [mem_Icc] at this ⊢; omega
lemma notMem_pool_self : a t ∉ pool a t := by
by_contra h
obtain ⟨u, lu, hu⟩ := exists_add_eq_of_mem_pool h
exact lu.ne (ha.2 hu)
@[deprecated (since := "2025-05-23")] alias not_mem_pool_self := notMem_pool_self
/-- The number of balls stays unchanged if there is a ball with height 0 and increases by 1
otherwise. -/
lemma card_pool_succ : #(pool a (t + 1)) = #(pool a t) + if 0 ∈ pool a t then 0 else 1 := by
have nms : a t ∉ (pool a t).erase 0 := by
rw [mem_erase, not_and_or]; exact .inr (notMem_pool_self ha)
rw [pool, card_map, card_insert_of_notMem nms, card_erase_eq_ite]
split_ifs with h
· have := card_pos.mpr ⟨0, h⟩; omega
· rfl
lemma monotone_card_pool : Monotone fun t ↦ #(pool a t) := by
refine monotone_nat_of_le_succ fun t ↦ ?_
have := card_pool_succ (t := t) ha; omega
/-- There exists a point where the number of balls reaches a maximum (which follows from its
monotonicity and boundedness). We take its coordinates for the problem's `b` and `N`. -/
lemma exists_max_card_pool : ∃ b N, ∀ t ≥ N, #(pool a t) = b :=
converges_of_monotone_of_bounded (monotone_card_pool ha)
(fun t ↦ by simpa using card_le_card (pool_subset_Icc ha))
end Pool
section Sums
variable {b N : ℕ} (hbN : ∀ t ≥ N, #(pool a t) = b) (ht : t ≥ N)
include ha hbN
lemma b_pos : 0 < b := by
by_contra! h; rw [nonpos_iff_eq_zero] at h; subst h
replace hbN : ∀ t, #(pool a t) = 0 := fun t ↦ by
obtain h | h := le_or_gt t N
· have : #(pool a t) ≤ #(pool a N) := monotone_card_pool ha h
rwa [hbN _ le_rfl, nonpos_iff_eq_zero] at this
· exact hbN _ h.le
have cp1 : #(pool a 1) = 1 := by
simp_rw [card_pool_succ ha, pool, card_empty, notMem_empty, ite_false]
apply absurd (hbN 1); omega
include ht in
lemma zero_mem_pool : 0 ∈ pool a t := by
have := card_pool_succ (t := t) ha
have := hbN (t + 1) (by omega)
simp_all
include ht in
/-- The key observation, one term of the telescoping sum for the problem's expression. -/
lemma sum_sub_sum_eq_sub : ∑ x ∈ pool a (t + 1), x - ∑ x ∈ pool a t, x = a t - b := by
simp_rw [pool, sum_map, Equiv.coe_toEmbedding, Equiv.subRight_apply]
have nms : a t ∉ (pool a t).erase 0 := by
rw [mem_erase, not_and_or]; exact .inr (notMem_pool_self ha)
rw [sum_insert nms, sum_erase_eq_sub (h := zero_mem_pool ha hbN ht), sum_sub_distrib, sum_const,
nsmul_one, hbN _ ht]
omega
/-- The telescoping sum giving the part of the problem's expression within the modulus signs. -/
lemma sum_telescope {m n : ℕ} (hm : N ≤ m) (hn : m < n) :
∑ j ∈ Ico m n, (a j - b) = ∑ x ∈ pool a n, x - ∑ x ∈ pool a m, x :=
calc
_ = ∑ j ∈ Ico m n, (∑ x ∈ pool a (j + 1), x - ∑ x ∈ pool a j, x) := by
congr! 1 with j hj; rw [sum_sub_sum_eq_sub ha hbN]; simp at hj; omega
_ = _ := sum_Ico_sub (∑ x ∈ pool a ·, x) hn.le
include ht in
lemma le_sum_pool : ∑ i ∈ range b, (i : ℤ) ≤ ∑ x ∈ pool a t, x := by
convert sum_range_le_sum fun x mx ↦ (mem_Icc.mp ((pool_subset_Icc ha) mx)).1
· rw [hbN _ ht]
· rw [zero_add]
include ht in
lemma sum_pool_le : ∑ x ∈ pool a t, x ≤ ∑ i ∈ range (b - 1), (2014 - i : ℤ) := by
have zmp := zero_mem_pool ha hbN ht
rw [← insert_erase zmp, sum_insert (notMem_erase _ _), zero_add]
convert sum_le_sum_range fun x mx ↦ ?_
· rw [card_erase_of_mem zmp, hbN _ ht]
· exact (mem_Icc.mp ((pool_subset_Icc ha) (mem_erase.mp mx).2)).2
end Sums
theorem result (ha : Condition a) :
∃ b > 0, ∃ N, ∀ m ≥ N, ∀ n > m, |∑ j ∈ Ico m n, (a j - b)| ≤ 1007 ^ 2 := by
obtain ⟨b, N, hbN⟩ := exists_max_card_pool ha
have bp := b_pos ha hbN
use b, Int.natCast_pos.mpr bp, N; intro m hm n hn; rw [sum_telescope ha hbN hm hn]
calc
_ ≤ ∑ i ∈ range (b - 1), (2014 - i : ℤ) - ∑ i ∈ range b, (i : ℤ) :=
abs_sub_le_of_le_of_le (le_sum_pool ha hbN (hm.trans hn.le))
(sum_pool_le ha hbN (hm.trans hn.le)) (le_sum_pool ha hbN hm) (sum_pool_le ha hbN hm)
_ = (b - 1) * (2015 - b) := by
nth_rw 2 [← Nat.sub_one_add_one_eq_of_pos bp]
rw [← sum_flip, sum_range_succ, tsub_self, Nat.cast_zero, add_zero, ← sum_sub_distrib]
have sc : ∀ x ∈ range (b - 1), (2014 - x - (b - 1 - x : ℕ)) = (2015 - b : ℤ) := fun x mx ↦ by
rw [mem_range] at mx; omega
rw [sum_congr rfl sc, sum_const, card_range, nsmul_eq_mul, Nat.cast_pred bp]
_ ≤ _ := by
rw [← mul_le_mul_iff_right₀ zero_lt_four, ← mul_assoc,
show 4 * 1007 ^ 2 = ((b - 1 : ℤ) + (2015 - b)) ^ 2 by simp]
exact four_mul_le_sq_add ..
end Imo2015Q6 |
.lake/packages/mathlib/Archive/Imo/Imo1964Q1.lean | import Mathlib.Tactic.IntervalCases
import Mathlib.Data.Nat.ModEq
import Mathlib.Tactic.Ring
/-!
# IMO 1964 Q1
(a) Find all positive integers $n$ for which $2^n-1$ is divisible by $7$.
(b) Prove that there is no positive integer $n$ for which $2^n+1$ is divisible by $7$.
For (a), we find that the order of $2$ mod $7$ is $3$. Therefore for (b), it suffices to check
$n = 0, 1, 2$.
-/
open Nat
namespace Imo1964Q1
theorem two_pow_mod_seven (n : ℕ) : 2 ^ n ≡ 2 ^ (n % 3) [MOD 7] :=
let t := n % 3
calc 2 ^ n = 2 ^ (3 * (n / 3) + t) := by rw [Nat.div_add_mod]
_ = (2 ^ 3) ^ (n / 3) * 2 ^ t := by rw [pow_add, pow_mul]
_ ≡ 1 ^ (n / 3) * 2 ^ t [MOD 7] := by gcongr; decide
_ = 2 ^ t := by ring
end Imo1964Q1
open Imo1964Q1
theorem imo1964_q1a (n : ℕ) (_ : 0 < n) : 7 ∣ 2 ^ n - 1 ↔ 3 ∣ n := by
let t := n % 3
have : t < 3 := Nat.mod_lt _ (by decide)
calc 7 ∣ 2 ^ n - 1 ↔ 2 ^ n ≡ 1 [MOD 7] := by
rw [Nat.ModEq.comm, Nat.modEq_iff_dvd']
apply Nat.one_le_pow'
_ ↔ 2 ^ t ≡ 1 [MOD 7] := ⟨(two_pow_mod_seven n).symm.trans, (two_pow_mod_seven n).trans⟩
_ ↔ t = 0 := by interval_cases t <;> decide
_ ↔ 3 ∣ n := by rw [dvd_iff_mod_eq_zero]
theorem imo1964_q1b (n : ℕ) : ¬7 ∣ 2 ^ n + 1 := by
intro h
let t := n % 3
have : t < 3 := Nat.mod_lt _ (by decide)
have H : 2 ^ t + 1 ≡ 0 [MOD 7] := calc
2 ^ t + 1 ≡ 2 ^ n + 1 [MOD 7] := by gcongr ?_ + 1; exact (two_pow_mod_seven n).symm
_ ≡ 0 [MOD 7] := h.modEq_zero_nat
interval_cases t <;> contradiction |
.lake/packages/mathlib/Archive/Imo/Imo1982Q3.lean | import Mathlib.Algebra.Order.Field.GeomSum
import Mathlib.Data.NNReal.Basic
/-!
# IMO 1982 Q3
Consider infinite sequences $\{x_n\}$ of positive reals such that $x_0 = 1$ and
$x_0 \ge x_1 \ge x_2 \ge \ldots$
a) Prove that for every such sequence there is an $n \ge 1$ such that:
$$\frac{x_0^2}{x_1} + \ldots + \frac{x_{n-1}^2}{x_n} \ge 3.999$$
b) Find such a sequence such that for all $n$:
$$\frac{x_0^2}{x_1} + \ldots + \frac{x_{n-1}^2}{x_n} < 4$$
The solution is based on Solution 1 from the
[Art of Problem Solving](https://artofproblemsolving.com/wiki/index.php/1982_IMO_Problems/Problem_3)
website. For part a, we use Sedrakyan's lemma to show the sum is bounded below by
$\frac{4n}{n + 1}$, which can be made arbitrarily close to $4$ by taking large $n$. For part b, we
show the sequence $x_n = 2^{-n}$ satisfies the desired inequality.
-/
open Finset NNReal
variable {x : ℕ → ℝ} {n : ℕ} (hn : n ≠ 0) (hx : Antitone x)
namespace Imo1982Q3
include hn hx
/-- `x n` is at most the average of all previous terms in the sequence.
This is expressed here with `∑ k ∈ range n, x k` added to both sides. -/
lemma le_avg : ∑ k ∈ range (n + 1), x k ≤ (∑ k ∈ range n, x k) * (1 + 1 / n) := by
rw [sum_range_succ, mul_one_add, add_le_add_iff_left, mul_one_div,
le_div_iff₀ (mod_cast hn.bot_lt), mul_comm, ← nsmul_eq_mul]
conv_lhs => rw [← card_range n, ← sum_const]
gcongr with i hi
refine hx <| le_of_lt ?_
simpa using hi
/-- The main inequality used for part a. -/
lemma ineq (h0 : x 0 = 1) (hp : ∀ k, 0 < x k) :
4 * n / (n + 1) ≤ ∑ k ∈ range (n + 1), x k ^ 2 / x (k + 1) := by
calc
-- We first use AM-GM.
_ ≤ (∑ k ∈ range n, x (k + 1) + 1) ^ 2 / (∑ k ∈ range n, x (k + 1)) * n / (n + 1) := by
gcongr
rw [le_div_iff₀]
· simpa using four_mul_le_sq_add (∑ k ∈ range n, x (k + 1)) 1
· exact sum_pos (fun k _ ↦ hp _) (nonempty_range_iff.2 hn)
-- We move the fraction into the denominator.
_ = (∑ k ∈ range n, x (k + 1) + 1) ^ 2 / ((∑ k ∈ range n, x (k + 1)) * (1 + 1 / n)) := by
field
-- We make use of the `le_avg` lemma.
_ ≤ (∑ k ∈ range (n + 1), x k) ^ 2 / ∑ k ∈ range (n + 1), x (k + 1) := by
gcongr
· exact sum_pos (fun k _ ↦ hp _) nonempty_range_add_one
· exact add_nonneg (sum_nonneg fun k _ ↦ (hp _).le) zero_le_one
· rw [sum_range_succ', h0]
· exact le_avg hn (hx.comp_monotone @Nat.succ_le_succ)
-- We conclude by Sedrakyan.
_ ≤ _ := sq_sum_div_le_sum_sq_div _ x fun k _ ↦ hp (k + 1)
end Imo1982Q3
/-- Part a of the problem is solved by `n = 4000`. -/
theorem imo1982_q3a (hx : Antitone x) (h0 : x 0 = 1) (hp : ∀ k, 0 < x k) :
∃ n : ℕ, 3.999 ≤ ∑ k ∈ range n, (x k) ^ 2 / x (k + 1) := by
use 4000
convert Imo1982Q3.ineq (Nat.succ_ne_zero 3998) hx h0 hp
norm_num
/-- Part b of the problem is solved by `x k = (1 / 2) ^ k`. -/
theorem imo1982_q3b : ∃ x : ℕ → ℝ, Antitone x ∧ x 0 = 1 ∧ (∀ k, 0 < x k)
∧ ∀ n, ∑ k ∈ range n, x k ^ 2 / x (k + 1) < 4 := by
refine ⟨fun k ↦ 2⁻¹ ^ k, ?_, pow_zero _, ?_, fun n ↦ ?_⟩
· apply (pow_right_strictAnti₀ _ _).antitone <;> norm_num
· simp
· have {k : ℕ} : (2 : ℝ)⁻¹ ^ (k * 2) * ((2 : ℝ)⁻¹ ^ k)⁻¹ = (2 : ℝ)⁻¹ ^ k := by
rw [← pow_sub₀] <;> simp [mul_two]
simp_rw [← pow_mul, pow_succ, ← div_eq_mul_inv, div_div_eq_mul_div, mul_comm, mul_div_assoc,
← mul_sum, div_eq_mul_inv, this, ← two_add_two_eq_four, ← mul_two,
mul_lt_mul_iff_of_pos_left two_pos]
convert NNReal.coe_lt_coe.2 <| geom_sum_lt (inv_ne_zero two_ne_zero) two_inv_lt_one n
· simp
· norm_num |
.lake/packages/mathlib/Archive/Imo/README.md | # IMO problems
We have a collection of solutions to IMO problems in mathlib, stored under `/Archive/Imo/`.
These are part of mathlib for three purposes:
* The [IMO Grand Challenge](https://imo-grand-challenge.github.io/) will need training data, and exemplars,
and this is a reasonable place to collect Lean samples of IMO problems.
* As with the rest of `Archive/`, we want to have high quality examples
covering elementary mathematics, available as learning materials.
* They are popular as a first contribution to mathlib,
and an opportunity to teach new contributors how to write Lean code.
That said, IMO problems also come at a cost:
* reviewing pull requests by first-time contributors can be very time-consuming
* less significantly, there is a certain amount of maintenance work
ensuring they keep up with mathlib.
Thus we'd like authors of IMO pull requests to keep in mind the following points.
* Reviewing may take some time
(because reviewers are motivated more by wanting to teach you how to write good code,
rather than personal enthusiasm for the material).
* It is essential to read the
[style guide](https://leanprover-community.github.io/contribute/style.html)
carefully, and try to follow it very closely.
* Please document your solution thoroughly.
Remember everything in `/Archive/` should be an exemplar of good mathlib style.
There must be a clear human-readable account of the solution at the top of the file
(ideally something that would score 7!) but don't stop there.
Please write doc-strings on most of your lemmas, explaining what they are doing and why,
and in any non-trivial proof include single line comments explaining the significant steps.
* Be nice to your reviewers, and responsive to their suggestions!
You should expect that your first pull request will involve at least as much work
after you open the pull request as before.
Reviewers may ask you to factor out useful lemmas into mathlib,
or to completely restructure your proof.
* Pay forward what you learn from reviewing:
there are often several [open pull requests about IMO problems](https://github.com/leanprover-community/mathlib4/pulls?q=is%3Aopen+is%3Apr+label%3Aimo) (and in [Lean 3](https://github.com/leanprover-community/mathlib/pulls?q=is%3Aopen+is%3Apr+label%3Aimo),
and you should go look at the others and see if you can make helpful suggestions!
* If there is a lemma that can be stated more generally than you need for the actual problem,
but that could be useful for others, be sure to write the more general lemma,
and include it in the appropriate part of mathlib (i.e. not under `/Archive/`).
(We're much more interested if you find ways that mathlib could be improved to
make solving your IMO problem easier, than we are in having another solution.)
* Although this may be hard for first-time contributors,
if you can identify a new tactic that would make your proof work more naturally,
either ask for help on Zulip getting it implemented,
or start reading about [metaprogramming](https://leanprover-community.github.io/learn.html#metaprogramming-and-tactic-writing)
and do it yourself. (A new and useful tactic is worth a hundred lemmas!) |
.lake/packages/mathlib/Archive/Imo/Imo1985Q2.lean | import Mathlib.Algebra.Order.Ring.Canonical
import Mathlib.Algebra.Order.Star.Basic
import Mathlib.Data.Int.NatAbs
import Mathlib.Data.Nat.ModEq
/-!
# IMO 1985 Q2
Fix a natural number $n ≥ 3$ and define $N=\{1, 2, 3, \dots, n-1\}$. Fix another natural number
$j ∈ N$ coprime to $n$. Each number in $N$ is now colored with one of two colors, say red or black,
so that:
1. $i$ and $n-i$ always receive the same color, and
2. $i$ and $|j-i|$ receive the same color for all $i ∈ N, i ≠ j$.
Prove that all numbers in $N$ must receive the same color.
## Solution
Let $a \sim b$ denote that $a$ and $b$ have the same color.
Because $j$ is coprime to $n$, every number in $N$ is of the form $kj\bmod n$ for a unique
$1 ≤ k < n$, so it suffices to show that $kj\bmod n \sim (k-1)j\bmod n$ for $1 < k < n$.
In this range of $k$, $kj\bmod n ≠ j$, so
* if $kj\bmod n > j$, $kj\bmod n \sim kj\bmod n - j = (k-1)j\bmod n$ using rule 2;
* if $kj\bmod n < j$, $kj\bmod n \sim j - kj\bmod n \sim n - j + kj\bmod n = (k-1)j\bmod n$
using rule 2 then rule 1.
-/
namespace Imo1985Q2
open Nat
/-- The conditions on the problem's coloring `C`.
Although its domain is all of `ℕ`, we only care about its values in `Set.Ico 1 n`. -/
def Condition (n j : ℕ) (C : ℕ → Fin 2) : Prop :=
(∀ i ∈ Set.Ico 1 n, C i = C (n - i)) ∧ (∀ i ∈ Set.Ico 1 n, i ≠ j → C i = C (j - i : ℤ).natAbs)
/-- For `1 ≤ k < n`, `k * j % n` has the same color as `j`. -/
lemma C_mul_mod {n j : ℕ} (hn : 3 ≤ n) (hj : j ∈ Set.Ico 1 n) (cpj : Nat.Coprime n j)
{C : ℕ → Fin 2} (hC : Condition n j C) {k : ℕ} (hk : k ∈ Set.Ico 1 n) :
C (k * j % n) = C j := by
induction k, hk.1 using Nat.le_induction with
| base => rw [one_mul, Nat.mod_eq_of_lt hj.2]
| succ k hk₁ ih =>
have nej : (k + 1) * j % n ≠ j := by
by_contra! h; nth_rw 2 [← Nat.mod_eq_of_lt hj.2, ← one_mul j] at h
replace h : (k + 1) % n = 1 % n := Nat.ModEq.cancel_right_of_coprime cpj h
rw [Nat.mod_eq_of_lt hk.2, Nat.mod_eq_of_lt (by omega)] at h
omega
have b₁ : (k + 1) * j % n ∈ Set.Ico 1 n := by
refine ⟨?_, Nat.mod_lt _ (by omega)⟩
by_contra! h; rw [Nat.lt_one_iff, ← Nat.dvd_iff_mod_eq_zero] at h
have ek := Nat.eq_zero_of_dvd_of_lt (cpj.dvd_of_dvd_mul_right h) hk.2
omega
rw [← ih ⟨hk₁, Nat.lt_of_succ_lt hk.2⟩, hC.2 _ b₁ nej]
rcases nej.lt_or_gt with h | h
· rw [Int.natAbs_natCast_sub_natCast_of_ge h.le]
have b₂ : j - (k + 1) * j % n ∈ Set.Ico 1 n :=
⟨Nat.sub_pos_iff_lt.mpr h, (Nat.sub_le ..).trans_lt hj.2⟩
have q : n - (j - (k + 1) * j % n) = (k + 1) * j % n + (n - j) % n := by
rw [tsub_tsub_eq_add_tsub_of_le h.le, add_comm, Nat.add_sub_assoc hj.2.le,
Nat.mod_eq_of_lt (show n - j < n by omega)]
rw [hC.1 _ b₂, q, ← Nat.add_mod_of_add_mod_lt (by omega), ← Nat.add_sub_assoc hj.2.le,
add_comm, Nat.add_sub_assoc (Nat.le_mul_of_pos_left _ hk.1), ← tsub_one_mul,
Nat.add_mod_left, add_tsub_cancel_right]
· rw [Int.natAbs_natCast_sub_natCast_of_le h.le, Nat.mod_sub_of_le h.le]
rw [add_mul, one_mul, add_tsub_cancel_right]
theorem result {n j : ℕ} (hn : 3 ≤ n) (hj : j ∈ Set.Ico 1 n) (cpj : Coprime n j)
{C : ℕ → Fin 2} (hC : Condition n j C) {i : ℕ} (hi : i ∈ Set.Ico 1 n) :
C i = C j := by
obtain ⟨v, hv⟩ := exists_mul_emod_eq_one_of_coprime cpj.symm (by omega)
have hvi : i = (v * i % n) * j % n := by
rw [mod_mul_mod, ← mul_rotate, ← mod_mul_mod, hv, one_mul, mod_eq_of_lt hi.2]
have vib : v * i % n ∈ Set.Ico 1 n := by
refine ⟨(?_ : 0 < _), mod_lt _ (by omega)⟩
by_contra! h; rw [le_zero, ← dvd_iff_mod_eq_zero] at h
rw [mul_comm, ← mod_eq_of_lt (show 1 < n by omega)] at hv
have i0 := eq_zero_of_dvd_of_lt
((coprime_of_mul_modEq_one _ hv).symm.dvd_of_dvd_mul_left h) hi.2
subst i; simp at hi
rw [hvi, C_mul_mod hn hj cpj hC vib]
end Imo1985Q2 |
.lake/packages/mathlib/Archive/Imo/Imo1988Q6.lean | import Mathlib.Data.Nat.Prime.Defs
import Mathlib.Data.Rat.Defs
import Mathlib.Order.WellFounded
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.Ring
import Mathlib.Tactic.WLOG
/-!
# IMO 1988 Q6 and constant descent Vieta jumping
Question 6 of IMO1988 is somewhat (in)famous. Several expert problem solvers
could not tackle the question within the given time limit.
The problem lead to the introduction of a new proof technique,
so called “Vieta jumping”.
In this file we formalise constant descent Vieta jumping,
and apply this to prove Q6 of IMO1988.
To illustrate the technique, we also prove a similar result.
-/
attribute [local simp] sq
namespace Imo1988Q6
/-- Constant descent Vieta jumping.
This proof technique allows one to prove an arbitrary proposition `claim`,
by running a descent argument on a hyperbola `H` in the first quadrant of the plane,
under the following conditions:
* `h₀` : There exists an integral point `(x,y)` on the hyperbola `H`.
* `H_symm` : The hyperbola has a symmetry along the diagonal in the plane.
* `H_zero` : If an integral point `(x,0)` lies on the hyperbola `H`, then `claim` is true.
* `H_diag` : If an integral point `(x,x)` lies on the hyperbola `H`, then `claim` is true.
* `H_desc` : If `(x,y)` is an integral point on the hyperbola `H`,
with `x < y` then there exists a “smaller” point on `H`: a point `(x',y')` with `x' < y' ≤ x`.
For reasons of usability, the hyperbola `H` is implemented as an arbitrary predicate.
(In question 6 of IMO1988, where this proof technique was first developed,
the predicate `claim` would be `∃ (d : ℕ), d ^ 2 = k` for some natural number `k`,
and the predicate `H` would be `fun a b ↦ a * a + b * b = (a * b + 1) * k`.)
To ensure that the predicate `H` actually describes a hyperbola,
the user must provide arguments `B` and `C` that are used as coefficients for a quadratic equation.
Finally, `H_quad` is the proof obligation that the quadratic equation
`(y:ℤ) * y - B x * y + C x = 0`
describes the same hyperbola as the predicate `H`.
For extra flexibility, one must provide a predicate `base` on the integral points in the plane.
In the descent step `H_desc` this will give the user the additional assumption that
the point `(x,y)` does not lie in this base locus.
The user must provide a proof that the proposition `claim` is true
if there exists an integral point `(x,y)` on the hyperbola `H` that lies in the base locus.
If such a base locus is not necessary, once can simply let it be `fun x y ↦ False`.
-/
theorem constant_descent_vieta_jumping (x y : ℕ) {claim : Prop} {H : ℕ → ℕ → Prop} (h₀ : H x y)
(B : ℕ → ℤ) (C : ℕ → ℤ) (base : ℕ → ℕ → Prop)
(H_quad : ∀ {x y}, H x y ↔ (y : ℤ) * y - B x * y + C x = 0) (H_symm : ∀ {x y}, H x y ↔ H y x)
(H_zero : ∀ {x}, H x 0 → claim) (H_diag : ∀ {x}, H x x → claim)
(H_desc : ∀ {x y}, 0 < x → x < y → ¬base x y → H x y →
∀ y', y' * y' - B x * y' + C x = 0 → y' = B x - y → y' * y = C x → 0 ≤ y' ∧ y' ≤ x)
(H_base : ∀ {x y}, H x y → base x y → claim) : claim := by
-- First of all, we may assume that x ≤ y.
-- We justify this using H_symm.
wlog hxy : x ≤ y
· rw [H_symm] at h₀; apply this y x h₀ B C base _ _ _ _ _ _ (le_of_not_ge hxy); assumption'
-- In fact, we can easily deal with the case x = y.
by_cases x_eq_y : x = y
· subst x_eq_y; exact H_diag h₀
-- Hence we may assume that x < y.
replace hxy : x < y := lt_of_le_of_ne hxy x_eq_y
clear x_eq_y
-- Consider the upper branch of the hyperbola defined by H.
let upper_branch : Set (ℕ × ℕ) := {p | H p.1 p.2 ∧ p.1 < p.2}
-- Note that the point p = (x,y) lies on the upper branch.
let p : ℕ × ℕ := ⟨x, y⟩
have hp : p ∈ upper_branch := ⟨h₀, hxy⟩
-- We also consider the exceptional set of solutions (a,b) that satisfy
-- a = 0 or a = b or B a = b or B a = b + a or that lie in the base locus.
let exceptional : Set (ℕ × ℕ) :=
{p | H p.1 p.2 ∧ (base p.1 p.2 ∨ p.1 = 0 ∨ p.1 = p.2 ∨ B p.1 = p.2 ∨ B p.1 = p.2 + p.1)}
-- Let S be the projection of the upper branch on to the y-axis
-- after removing the exceptional locus.
let S : Set ℕ := Prod.snd '' (upper_branch \ exceptional)
-- The strategy is to show that the exceptional locus in nonempty
-- by running a descent argument that starts with the given point p = (x,y).
-- Our assumptions ensure that we can then prove the claim.
suffices exc : exceptional.Nonempty by
-- Suppose that there exists an element in the exceptional locus.
simp only [Set.Nonempty, Prod.exists, Set.mem_setOf_eq, exceptional] at exc
-- Let (a,b) be such an element, and consider all the possible cases.
rcases exc with ⟨a, b, hH, hb⟩
rcases hb with (_ | rfl | rfl | hB | hB)
-- The first three cases are rather easy to solve.
· solve_by_elim
· rw [H_symm] at hH; solve_by_elim
· solve_by_elim
-- The final two cases are very similar.
all_goals
-- Consider the quadratic equation that (a,b) satisfies.
rw [H_quad] at hH
-- We find the other root of the equation, and Vieta's formulas.
rcases vieta_formula_quadratic hH with ⟨c, h_root, hV₁, hV₂⟩
-- By substitutions we find that b = 0 or b = a.
simp only [hB, add_eq_left, add_right_inj] at hV₁
subst hV₁
rw [← Int.ofNat_zero] at *
rw [← H_quad] at h_root
-- And hence we are done by H_zero and H_diag.
solve_by_elim
-- To finish the main proof, we need to show that the exceptional locus is nonempty.
-- So we assume that the exceptional locus is empty, and work towards deriving a contradiction.
rw [Set.nonempty_iff_ne_empty]
intro exceptional_empty
-- Observe that S is nonempty.
have S_nonempty : S.Nonempty := by
-- It contains the image of p.
use p.2
apply Set.mem_image_of_mem
-- After all, we assumed that the exceptional locus is empty.
rwa [exceptional_empty, Set.diff_empty]
-- We are now set for an infinite descent argument.
-- Let m be the smallest element of the nonempty set S.
let m : ℕ := WellFounded.min Nat.lt_wfRel.wf S S_nonempty
have m_mem : m ∈ S := WellFounded.min_mem Nat.lt_wfRel.wf S S_nonempty
have m_min : ∀ k ∈ S, ¬k < m := fun k hk => WellFounded.not_lt_min Nat.lt_wfRel.wf S S_nonempty hk
-- It suffices to show that there is point (a,b) with b ∈ S and b < m.
rsuffices ⟨p', p'_mem, p'_small⟩ : ∃ p' : ℕ × ℕ, p'.2 ∈ S ∧ p'.2 < m
· solve_by_elim
-- Let (m_x, m_y) be a point on the upper branch that projects to m ∈ S
-- and that does not lie in the exceptional locus.
rcases m_mem with ⟨⟨mx, my⟩, ⟨⟨hHm, mx_lt_my⟩, h_base⟩, m_eq⟩
-- This means that m_y = m,
-- and the conditions H(m_x, m_y) and m_x < m_y are satisfied.
simp only at mx_lt_my hHm m_eq
simp only [exceptional, hHm, Set.mem_setOf_eq, true_and] at h_base
push_neg at h_base
-- Finally, it also means that (m_x, m_y) does not lie in the base locus,
-- that m_x ≠ 0, m_x ≠ m_y, B(m_x) ≠ m_y, and B(m_x) ≠ m_x + m_y.
rcases h_base with ⟨h_base, hmx, hm_diag, hm_B₁, hm_B₂⟩
replace hmx : 0 < mx := pos_iff_ne_zero.mpr hmx
-- Consider the quadratic equation that (m_x, m_y) satisfies.
have h_quad := hHm
rw [H_quad] at h_quad
-- We find the other root of the equation, and Vieta's formulas.
rcases vieta_formula_quadratic h_quad with ⟨c, h_root, hV₁, hV₂⟩
-- Now we rewrite Vietas formulas a bit, and apply the descent step.
replace hV₁ : c = B mx - my := eq_sub_of_add_eq' hV₁
rw [mul_comm] at hV₂
have Hc := H_desc hmx mx_lt_my h_base hHm c h_root hV₁ hV₂
-- This means that we may assume that c ≥ 0 and c ≤ m_x.
obtain ⟨c_nonneg, c_lt⟩ := Hc
-- In other words, c is a natural number.
lift c to ℕ using c_nonneg
-- Recall that we are trying find a point (a,b) such that b ∈ S and b < m.
-- We claim that p' = (c, m_x) does the job.
let p' : ℕ × ℕ := ⟨c, mx⟩
use p'
-- The second condition is rather easy to check, so we do that first.
constructor; swap
· rwa [m_eq] at mx_lt_my
-- Now we need to show that p' projects onto S. In other words, that c ∈ S.
-- We do that, by showing that it lies in the upper branch
-- (which is sufficient, because we assumed that the exceptional locus is empty).
apply Set.mem_image_of_mem
rw [exceptional_empty, Set.diff_empty]
-- Now we are ready to prove that p' = (c, m_x) lies on the upper branch.
-- We need to check two conditions: H(c, m_x) and c < m_x.
constructor <;> dsimp only
· -- The first condition is not so hard. After all, c is the other root of the quadratic equation.
rw [H_symm, H_quad]
simpa using h_root
· -- For the second condition, we note that it suffices to check that c ≠ m_x.
suffices hc : c ≠ mx from lt_of_le_of_ne (mod_cast c_lt) hc
-- However, recall that B(m_x) ≠ m_x + m_y.
-- If c = m_x, we can prove B(m_x) = m_x + m_y.
contrapose! hm_B₂
subst c
simp [hV₁]
-- Hence p' = (c, m_x) lies on the upper branch, and we are done.
end Imo1988Q6
open Imo1988Q6
/-- Question 6 of IMO1988. If a and b are two natural numbers
such that a*b+1 divides a^2 + b^2, show that their quotient is a perfect square. -/
theorem imo1988_q6 {a b : ℕ} (h : a * b + 1 ∣ a ^ 2 + b ^ 2) :
∃ d, d ^ 2 = (a ^ 2 + b ^ 2) / (a * b + 1) := by
rcases h with ⟨k, hk⟩
rw [hk, Nat.mul_div_cancel_left _ (Nat.succ_pos (a * b))]
simp only [sq] at hk
apply constant_descent_vieta_jumping a b (H := fun a b => a * a + b * b = (a * b + 1) * k)
hk (fun x => k * x) (fun x => x * x - k) fun _ _ => False <;>
clear hk a b
· -- We will now show that the fibers of the solution set are described by a quadratic equation.
intro x y
rw [← Int.natCast_inj, ← sub_eq_zero]
apply eq_iff_eq_cancel_right.2
simp; ring
· -- Show that the solution set is symmetric in a and b.
intro x y
simp [add_comm (x * x), mul_comm x]
· -- Show that the claim is true if b = 0.
suffices ∀ a, a * a = k → ∃ d, d * d = k by simpa
rintro x rfl; use x
· -- Show that the claim is true if a = b.
intro x hx
suffices k ≤ 1 by
rw [Nat.le_add_one_iff, Nat.le_zero] at this
rcases this with (rfl | rfl)
· use 0; simp
· use 1; simp
contrapose! hx with k_lt_one
apply ne_of_lt
calc
x * x + x * x = x * x * 2 := by rw [mul_two]
_ ≤ x * x * k := Nat.mul_le_mul_left (x * x) k_lt_one
_ < (x * x + 1) * k := by linarith
· -- Show the descent step.
intro x y hx x_lt_y _ _ z h_root _ hV₀
constructor
· have hpos : z * z + x * x > 0 := by
apply add_pos_of_nonneg_of_pos
· apply mul_self_nonneg
· apply mul_pos <;> exact mod_cast hx
have hzx : z * z + x * x = (z * x + 1) * k := by
rw [← sub_eq_zero, ← h_root]
ring
rw [hzx] at hpos
replace hpos : z * x + 1 > 0 := pos_of_mul_pos_left hpos (Int.ofNat_zero_le k)
replace hpos : z * x ≥ 0 := Int.le_of_lt_add_one hpos
apply nonneg_of_mul_nonneg_left hpos (mod_cast hx)
· contrapose! hV₀ with x_lt_z
apply ne_of_gt
calc
z * y > x * x := by apply mul_lt_mul' <;> omega
_ ≥ x * x - k := sub_le_self _ (Int.ofNat_zero_le k)
· -- There is no base case in this application of Vieta jumping.
simp
/-
The following example illustrates the use of constant descent Vieta jumping
in the presence of a non-trivial base case.
-/
example {a b : ℕ} (h : a * b ∣ a ^ 2 + b ^ 2 + 1) : 3 * a * b = a ^ 2 + b ^ 2 + 1 := by
rcases h with ⟨k, hk⟩
suffices k = 3 by simp_all; ring
simp only [sq] at hk
apply constant_descent_vieta_jumping a b (H := fun a b => a * a + b * b + 1 = a * b * k)
hk (fun x => k * x) (fun x => x * x + 1) fun x _ => x ≤ 1 <;>
clear hk a b
· -- We will now show that the fibers of the solution set are described by a quadratic equation.
intro x y
rw [← Int.natCast_inj, ← sub_eq_zero]
apply eq_iff_eq_cancel_right.2
simp; ring
· -- Show that the solution set is symmetric in a and b.
intro x y; ring_nf
· -- Show that the claim is true if b = 0.
simp
· -- Show that the claim is true if a = b.
intro x hx
have x_sq_dvd : x * x ∣ x * x * k := dvd_mul_right (x * x) k
rw [← hx] at x_sq_dvd
obtain ⟨y, hy⟩ : x * x ∣ 1 := by simpa only [Nat.dvd_add_self_left, add_assoc] using x_sq_dvd
obtain ⟨rfl, rfl⟩ : x = 1 ∧ y = 1 := by simpa [mul_eq_one] using hy.symm
simpa using hx.symm
· -- Show the descent step.
intro x y _ hx h_base _ z _ _ hV₀
constructor
· have zy_pos : z * y ≥ 0 := by rw [hV₀]; exact mod_cast Nat.zero_le _
apply nonneg_of_mul_nonneg_left zy_pos
omega
· contrapose! hV₀ with x_lt_z
apply ne_of_gt
push_neg at h_base
calc
z * y > x * y := by apply mul_lt_mul_of_pos_right <;> omega
_ ≥ x * (x + 1) := by apply mul_le_mul <;> omega
_ > x * x + 1 := by
rw [mul_add]
omega
· -- Show the base case.
intro x y h h_base
obtain rfl | rfl : x = 0 ∨ x = 1 := by rwa [Nat.le_add_one_iff, Nat.le_zero] at h_base
· simp at h
· rw [mul_one, one_mul, add_right_comm] at h
have y_dvd : y ∣ y * k := dvd_mul_right y k
rw [← h, Nat.dvd_add_left (dvd_mul_left y y)] at y_dvd
obtain rfl | rfl := (Nat.dvd_prime Nat.prime_two).mp y_dvd <;> apply mul_left_cancel₀
exacts [one_ne_zero, h.symm, two_ne_zero, h.symm] |
.lake/packages/mathlib/Archive/Imo/Imo1962Q4.lean | import Mathlib.Analysis.SpecialFunctions.Trigonometric.Complex
/-!
# IMO 1962 Q4
Solve the equation `cos x ^ 2 + cos (2 * x) ^ 2 + cos (3 * x) ^ 2 = 1`.
Since Lean does not have a concept of "simplest form", we just express what is
in fact the simplest form of the set of solutions, and then prove it equals the set of solutions.
-/
open Real
open scoped Real
namespace Imo1962Q4
noncomputable section
def ProblemEquation (x : ℝ) : Prop :=
cos x ^ 2 + cos (2 * x) ^ 2 + cos (3 * x) ^ 2 = 1
def solutionSet : Set ℝ :=
{x : ℝ | ∃ k : ℤ, x = (2 * ↑k + 1) * π / 4 ∨ x = (2 * ↑k + 1) * π / 6}
/-
The key to solving this problem simply is that we can rewrite the equation as
a product of terms, shown in `alt_formula`, being equal to zero.
-/
def altFormula (x : ℝ) : ℝ :=
cos x * (cos x ^ 2 - 1 / 2) * cos (3 * x)
theorem cos_sum_equiv {x : ℝ} :
(cos x ^ 2 + cos (2 * x) ^ 2 + cos (3 * x) ^ 2 - 1) / 4 = altFormula x := by
simp only [Real.cos_two_mul, cos_three_mul, altFormula]
ring
theorem alt_equiv {x : ℝ} : ProblemEquation x ↔ altFormula x = 0 := by
rw [ProblemEquation, ← cos_sum_equiv, div_eq_zero_iff, sub_eq_zero]
norm_num
theorem finding_zeros {x : ℝ} : altFormula x = 0 ↔ cos x ^ 2 = 1 / 2 ∨ cos (3 * x) = 0 := by
simp only [altFormula, mul_assoc, mul_eq_zero, sub_eq_zero]
constructor
· rintro (h1 | h2)
· right
rw [cos_three_mul, h1]
ring
· exact h2
· exact Or.inr
/-
Now we can solve for `x` using basic-ish trigonometry.
-/
theorem solve_cos2_half {x : ℝ} : cos x ^ 2 = 1 / 2 ↔ ∃ k : ℤ, x = (2 * ↑k + 1) * π / 4 := by
rw [cos_sq]
simp only [add_eq_left, div_eq_zero_iff]
norm_num
rw [cos_eq_zero_iff]
constructor <;>
· rintro ⟨k, h⟩
use k
linarith
theorem solve_cos3x_0 {x : ℝ} : cos (3 * x) = 0 ↔ ∃ k : ℤ, x = (2 * ↑k + 1) * π / 6 := by
rw [cos_eq_zero_iff]
refine exists_congr fun k => ?_
constructor <;> intro <;> linarith
end
end Imo1962Q4
open Imo1962Q4
/-
The final theorem is now just gluing together our lemmas.
-/
theorem imo1962_q4 {x : ℝ} : ProblemEquation x ↔ x ∈ solutionSet := by
rw [alt_equiv, finding_zeros, solve_cos3x_0, solve_cos2_half]
exact exists_or.symm
namespace Imo1962Q4
/-
We now present a second solution. The key to this solution is that, when the identity is
converted to an identity which is polynomial in `a` := `cos x`, it can be rewritten as a product of
terms, `a ^ 2 * (2 * a ^ 2 - 1) * (4 * a ^ 2 - 3)`, being equal to zero.
-/
theorem formula {R : Type*} [CommRing R] [IsDomain R] [CharZero R] (a : R) :
a ^ 2 + ((2 : R) * a ^ 2 - (1 : R)) ^ 2 + ((4 : R) * a ^ 3 - 3 * a) ^ 2 = 1 ↔
((2 : R) * a ^ 2 - (1 : R)) * ((4 : R) * a ^ 3 - 3 * a) = 0 := by
constructor <;> intro h
· apply eq_zero_of_pow_eq_zero (n := 2)
apply mul_left_injective₀ (b := 2) (by simp)
linear_combination (8 * a ^ 4 - 10 * a ^ 2 + 3) * h
· linear_combination 2 * a * h
/-
Again, we now can solve for `x` using basic-ish trigonometry.
-/
theorem solve_cos2x_0 {x : ℝ} : cos (2 * x) = 0 ↔ ∃ k : ℤ, x = (2 * ↑k + 1) * π / 4 := by
rw [cos_eq_zero_iff]
refine exists_congr fun k => ?_
constructor <;> intro <;> linarith
end Imo1962Q4
open Imo1962Q4
/-
Again, the final theorem is now just gluing together our lemmas.
-/
theorem imo1962_q4' {x : ℝ} : ProblemEquation x ↔ x ∈ solutionSet :=
calc
ProblemEquation x ↔ cos x ^ 2 + cos (2 * x) ^ 2 + cos (3 * x) ^ 2 = 1 := by rfl
_ ↔ cos (2 * x) = 0 ∨ cos (3 * x) = 0 := by simp [cos_two_mul, cos_three_mul, formula]
_ ↔ x ∈ solutionSet := by rw [solve_cos2x_0, solve_cos3x_0, ← exists_or]; rfl |
.lake/packages/mathlib/Archive/Imo/Imo2005Q4.lean | import Mathlib.FieldTheory.Finite.Basic
/-!
# IMO 2005 Q4
Problem: Determine all positive integers relatively prime to all the terms of the infinite sequence
`a n = 2 ^ n + 3 ^ n + 6 ^ n - 1`, for `n ≥ 1`.
This is quite an easy problem, in which the key point is a modular arithmetic calculation with
the sequence `a n` relative to an arbitrary prime.
-/
namespace IMO2005Q4
/-- The sequence considered in the problem, `2 ^ n + 3 ^ n + 6 ^ n - 1`. -/
def a (n : ℕ) : ℤ :=
2 ^ n + 3 ^ n + 6 ^ n - 1
/-- Key lemma (a modular arithmetic calculation): Given a prime `p` other than `2` or `3`, the
`(p - 2)`th term of the sequence has `p` as a factor. -/
theorem find_specified_factor {p : ℕ} (hp : Nat.Prime p) (hp2 : p ≠ 2) (hp3 : p ≠ 3) :
↑p ∣ a (p - 2) := by
-- Since `p` is neither `2` nor `3`, it is coprime with `2`, `3`, and `6`
rw [Ne, ← Nat.prime_dvd_prime_iff_eq hp (by decide), ← Nat.Prime.coprime_iff_not_dvd hp]
at hp2 hp3
have : Int.gcd p 6 = 1 := Nat.coprime_mul_iff_right.2 ⟨hp2, hp3⟩
-- Nat arithmetic needed to deal with powers
have hp' : p - 1 = p - 2 + 1 := Eq.symm <| Nat.succ_pred <| (tsub_pos_of_lt hp.one_lt).ne'
-- Thus it suffices to show that `6 * a (p - 2) ≡ 0 [ZMOD p]`
rw [← Int.modEq_zero_iff_dvd, ← Int.ediv_one p, ← Nat.cast_one, ← this]
refine Int.ModEq.cancel_left_div_gcd (Nat.cast_pos.2 hp.pos) ?_
calc
6 * a (p - 2) = 3 * 2 ^ (p - 1) + 2 * 3 ^ (p - 1) + (2 * 3) ^ (p - 1) - 6 := by
simp only [a, hp', pow_succ']; ring
_ ≡ 3 * 1 + 2 * 1 + 1 - 6 [ZMOD p] := by
gcongr <;> apply Int.ModEq.pow_card_sub_one_eq_one hp <;>
rwa [Int.isCoprime_iff_gcd_eq_one, Int.gcd_comm]
_ = 0 := rfl
end IMO2005Q4
open IMO2005Q4
/-- Main statement: The only positive integer coprime to all terms of the sequence `a` is `1`. -/
theorem imo2005_q4 {k : ℕ} (hk : 0 < k) : (∀ n : ℕ, 1 ≤ n → IsCoprime (a n) k) ↔ k = 1 := by
constructor; rotate_left
· -- The property is clearly true for `k = 1`
rintro rfl n -
exact isCoprime_one_right
intro h
-- Conversely, suppose `k` is a number with the property, and let `p` be `k.minFac` (by
-- definition this is the minimal prime factor of `k` if `k ≠ 1`, and otherwise `1`.
let p := k.minFac
-- Suppose for the sake of contradiction that `k ≠ 1`. Then `p` is genuinely a prime factor of
-- `k`. Hence, it divides none of `a n`, `1 ≤ n`
by_contra hk'
have hp : Nat.Prime p := Nat.minFac_prime hk'
replace h : ∀ n, 1 ≤ n → ¬(p : ℤ) ∣ a n := fun n hn ↦ by
have : IsCoprime (a n) p :=
.of_isCoprime_of_dvd_right (h n hn) (Int.natCast_dvd_natCast.mpr k.minFac_dvd)
rwa [isCoprime_comm,(Nat.prime_iff_prime_int.mp hp).coprime_iff_not_dvd] at this
-- For `p = 2` and `p = 3`, take `n = 1` and `n = 2`, respectively
by_cases hp2 : p = 2
· rw [hp2] at h
apply h 1 <;> decide
by_cases hp3 : p = 3
· rw [hp3] at h
apply h 2 <;> decide
-- Otherwise, take `n = p - 2`
refine h (p - 2) ?_ (find_specified_factor hp hp2 hp3)
calc
1 = 3 - 2 := by simp
_ ≤ p - 2 := tsub_le_tsub_right (Nat.succ_le_of_lt <| hp.two_le.lt_of_ne' hp2) _ |
.lake/packages/mathlib/Archive/Imo/Imo2001Q3.lean | import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise
import Mathlib.Algebra.Group.Action.Defs
import Mathlib.Algebra.Order.BigOperators.Group.Finset
import Mathlib.Data.Fintype.Prod
import Mathlib.Tactic.NormNum.Ineq
/-!
# IMO 2001 Q3
Twenty-one girls and twenty-one boys took part in a mathematical competition. It turned out that
1. each contestant solved at most six problems, and
2. for each pair of a girl and a boy, there was at least one problem that was solved by
both the girl and the boy.
Show that there is a problem that was solved by at least three girls and at least three boys.
## Solution
Note that not all of the problems a girl $g$ solves can be "hard" for boys, in the sense that
at most two boys solved it. If that was true, by condition 1 at most $6 × 2 = 12$ boys solved
some problem $g$, but by condition 2 that property holds for all 21 boys, which is a
contradiction.
Hence there are at most 5 problems $g$ solved that are hard for boys, and the number of girl-boy
pairs who solved some problem in common that was hard for boys is at most $5 × 2 × 21 = 210$.
By the same reasoning this bound holds when "girls" and "boys" are swapped throughout, but there
are $21^2$ girl-boy pairs in all and $21^2 > 210 + 210$, so some girl-boy pairs solved only problems
in common that were not hard for girls or boys. By condition 2 the result follows.
-/
namespace Imo2001Q3
open Finset
/-- The conditions on the problems the girls and boys solved, represented as functions from `Fin 21`
(index in cohort) to the finset of problems they solved (numbered arbitrarily). -/
structure Condition (G B : Fin 21 → Finset ℕ) where
/-- Every girl solved at most six problems. -/
G_le_6 (i) : #(G i) ≤ 6
/-- Every boy solved at most six problems. -/
B_le_6 (j) : #(B j) ≤ 6
/-- Every girl-boy pair solved at least one problem in common. -/
G_inter_B (i j) : ¬Disjoint (G i) (B j)
/-- A problem is easy for a cohort (boys or girls) if at least three of its members solved it. -/
def Easy (F : Fin 21 → Finset ℕ) (p : ℕ) : Prop := 3 ≤ #{i | p ∈ F i}
variable {G B : Fin 21 → Finset ℕ}
open Classical in
/-- Every contestant solved at most five problems that were not easy for the other cohort. -/
lemma card_not_easy_le_five {i : Fin 21} (hG : #(G i) ≤ 6) (hB : ∀ j, ¬Disjoint (G i) (B j)) :
#{p ∈ G i | ¬Easy B p} ≤ 5 := by
by_contra! h
replace h := le_antisymm (card_filter_le ..) (hG.trans h)
simp_rw [card_filter_eq_iff, Easy, not_le] at h
suffices 21 ≤ 12 by norm_num at this
calc
_ = #{j | ¬Disjoint (G i) (B j)} := by simp [filter_true_of_mem fun j _ ↦ hB j]
_ = #((G i).biUnion fun p ↦ {j | p ∈ B j}) := by congr 1; ext j; simp [not_disjoint_iff]
_ ≤ ∑ p ∈ G i, #{j | p ∈ B j} := card_biUnion_le
_ ≤ ∑ p ∈ G i, 2 := sum_le_sum fun p mp ↦ Nat.le_of_lt_succ (h p mp)
_ ≤ _ := by rw [sum_const, smul_eq_mul]; omega
open Classical in
/-- There are at most 210 girl-boy pairs who solved some problem in common that was not easy for
a fixed cohort. -/
lemma card_not_easy_le_210 (hG : ∀ i, #(G i) ≤ 6) (hB : ∀ i j, ¬Disjoint (G i) (B j)) :
#{ij : Fin 21 × Fin 21 | ∃ p, ¬Easy B p ∧ p ∈ G ij.1 ∩ B ij.2} ≤ 210 :=
calc
_ = ∑ i, #{j | ∃ p, ¬Easy B p ∧ p ∈ G i ∩ B j} := by
simp_rw [card_filter, ← univ_product_univ, sum_product]
_ = ∑ i, #({p ∈ G i | ¬Easy B p}.biUnion fun p ↦ {j | p ∈ B j}) := by
congr!; ext
simp_rw [mem_biUnion, mem_inter, mem_filter]
congr! 2; tauto
_ ≤ ∑ i, ∑ p ∈ G i with ¬Easy B p, #{j | p ∈ B j} := sum_le_sum fun _ _ ↦ card_biUnion_le
_ ≤ ∑ i, ∑ p ∈ G i with ¬Easy B p, 2 := by
gcongr with i _ p mp
rw [mem_filter, Easy, not_le] at mp
exact Nat.le_of_lt_succ mp.2
_ ≤ ∑ i : Fin 21, 5 * 2 := by
gcongr with i
grw [sum_const, smul_eq_mul, card_not_easy_le_five (hG _) (hB _)]
_ = _ := by norm_num
theorem result (h : Condition G B) : ∃ p, Easy G p ∧ Easy B p := by
obtain ⟨G_le_6, B_le_6, G_inter_B⟩ := h
have B_inter_G : ∀ i j, ¬Disjoint (B i) (G j) := fun i j ↦ by
rw [disjoint_comm]; exact G_inter_B j i
have cB := card_not_easy_le_210 G_le_6 G_inter_B
have cG := card_not_easy_le_210 B_le_6 B_inter_G
rw [← card_map ⟨_, Prod.swap_injective⟩] at cG
have key := (card_union_le _ _).trans (add_le_add cB cG) |>.trans_lt
(show _ < #(@univ (Fin 21 × Fin 21) _) by simp)
obtain ⟨⟨i, j⟩, -, hij⟩ := exists_mem_notMem_of_card_lt_card key
simp_rw [mem_union, mem_map, mem_filter_univ, Function.Embedding.coeFn_mk, Prod.exists,
Prod.swap_prod_mk, Prod.mk.injEq, existsAndEq, true_and, and_true, not_or, not_exists,
not_and', not_not, mem_inter, and_imp] at hij
obtain ⟨p, pG, pB⟩ := not_disjoint_iff.mp (G_inter_B i j)
use p, hij.2 _ pB pG, hij.1 _ pG pB
end Imo2001Q3 |
.lake/packages/mathlib/Archive/Imo/Imo1977Q6.lean | import Mathlib.Data.PNat.Basic
/-!
# IMO 1977 Q6
Suppose `f : ℕ+ → ℕ+` satisfies `f(f(n)) < f(n + 1)` for all `n`.
Prove that `f(n) = n` for all `n`.
We first prove the problem statement for `f : ℕ → ℕ`
then we use it to prove the statement for positive naturals.
-/
namespace Imo1977Q6
theorem imo1977_q6_nat (f : ℕ → ℕ) (h : ∀ n, f (f n) < f (n + 1)) : ∀ n, f n = n := by
have h' (k n : ℕ) (hk : k ≤ n) : k ≤ f n := by
induction k generalizing n with
| zero => exact Nat.zero_le _
| succ k h_ind =>
apply Nat.succ_le_of_lt
calc
k ≤ f (f (n - 1)) := h_ind _ (h_ind (n - 1) (le_tsub_of_add_le_right hk))
_ < f n := tsub_add_cancel_of_le (le_trans (Nat.succ_le_succ (Nat.zero_le _)) hk) ▸ h _
have hf : ∀ n, n ≤ f n := fun n => h' n n rfl.le
have hf_mono : StrictMono f := strictMono_nat_of_lt_succ fun _ => lt_of_le_of_lt (hf _) (h _)
intro
exact Nat.eq_of_le_of_lt_succ (hf _) (hf_mono.lt_iff_lt.mp (h _))
end Imo1977Q6
open Imo1977Q6
theorem imo1977_q6 (f : ℕ+ → ℕ+) (h : ∀ n, f (f n) < f (n + 1)) : ∀ n, f n = n := by
intro n
have := by
refine imo1977_q6_nat (fun m => if 0 < m then f m.toPNat' else 0) ?_ n
intro x; cases x
· simp
· simpa using h _
simpa |
.lake/packages/mathlib/Archive/Imo/Imo1972Q5.lean | import Mathlib.Data.Real.Basic
import Mathlib.Analysis.Normed.Module.Basic
/-!
# IMO 1972 Q5
Problem: `f` and `g` are real-valued functions defined on the real line. For all `x` and `y`,
`f(x + y) + f(x - y) = 2f(x)g(y)`. `f` is not identically zero and `|f(x)| ≤ 1` for all `x`.
Prove that `|g(x)| ≤ 1` for all `x`.
-/
/--
This proof begins by introducing the supremum of `f`, `k ≤ 1` as well as `k' = k / ‖g y‖`. We then
suppose that the conclusion does not hold (`hneg`) and show that `k ≤ k'` (by
`2 * (‖f x‖ * ‖g y‖) ≤ 2 * k` obtained from the main hypothesis `hf1`) and that `k' < k` (obtained
from `hneg` directly), finally raising a contradiction with `k' < k'`.
(Authored by Stanislas Polu inspired by Ruben Van de Velde).
-/
theorem imo1972_q5 (f g : ℝ → ℝ) (hf1 : ∀ x, ∀ y, f (x + y) + f (x - y) = 2 * f x * g y)
(hf2 : ∀ y, ‖f y‖ ≤ 1) (hf3 : ∃ x, f x ≠ 0) (y : ℝ) : ‖g y‖ ≤ 1 := by
-- Suppose the conclusion does not hold.
by_contra! hneg
set S := Set.range fun x => ‖f x‖
-- Introduce `k`, the supremum of `f`.
let k : ℝ := sSup S
-- Show that `‖f x‖ ≤ k`.
have hk₁ : ∀ x, ‖f x‖ ≤ k := by
have h : BddAbove S := ⟨1, Set.forall_mem_range.mpr hf2⟩
intro x
exact le_csSup h (Set.mem_range_self x)
-- Show that `2 * (‖f x‖ * ‖g y‖) ≤ 2 * k`.
have hk₂ : ∀ x, 2 * (‖f x‖ * ‖g y‖) ≤ 2 * k := fun x ↦
calc
2 * (‖f x‖ * ‖g y‖) = ‖2 * f x * g y‖ := by simp [mul_assoc]
_ = ‖f (x + y) + f (x - y)‖ := by rw [hf1]
_ ≤ ‖f (x + y)‖ + ‖f (x - y)‖ := norm_add_le _ _
_ ≤ k + k := add_le_add (hk₁ _) (hk₁ _)
_ = 2 * k := (two_mul _).symm
set k' := k / ‖g y‖
-- Demonstrate that `k' < k` using `hneg`.
have H₁ : k' < k := by
have h₁ : 0 < k := by
obtain ⟨x, hx⟩ := hf3
calc
0 < ‖f x‖ := norm_pos_iff.mpr hx
_ ≤ k := hk₁ x
rw [div_lt_iff₀]
· apply lt_mul_of_one_lt_right h₁ hneg
· exact zero_lt_one.trans hneg
-- Demonstrate that `k ≤ k'` using `hk₂`.
have H₂ : k ≤ k' := by
have h₁ : ∃ x : ℝ, x ∈ S := by use ‖f 0‖; exact Set.mem_range_self 0
have h₂ : ∀ x, ‖f x‖ ≤ k' := by
intro x
rw [le_div_iff₀]
· apply (mul_le_mul_iff_right₀ zero_lt_two).mp (hk₂ x)
· exact zero_lt_one.trans hneg
apply csSup_le h₁
rintro y' ⟨yy, rfl⟩
exact h₂ yy
-- Conclude by obtaining a contradiction, `k' < k'`.
apply lt_irrefl k'
calc
k' < k := H₁
_ ≤ k' := H₂
/-- IMO 1972 Q5
Problem: `f` and `g` are real-valued functions defined on the real line. For all `x` and `y`,
`f(x + y) + f(x - y) = 2f(x)g(y)`. `f` is not identically zero and `|f(x)| ≤ 1` for all `x`.
Prove that `|g(x)| ≤ 1` for all `x`.
This is a more concise version of the proof proposed by Ruben Van de Velde.
-/
theorem imo1972_q5' (f g : ℝ → ℝ) (hf1 : ∀ x, ∀ y, f (x + y) + f (x - y) = 2 * f x * g y)
(hf2 : BddAbove (Set.range fun x => ‖f x‖)) (hf3 : ∃ x, f x ≠ 0) (y : ℝ) : ‖g y‖ ≤ 1 := by
obtain ⟨x, hx⟩ := hf3
set k := ⨆ x, ‖f x‖
have h : ∀ x, ‖f x‖ ≤ k := le_ciSup hf2
by_contra! H
have hgy : 0 < ‖g y‖ := by linarith
have k_pos : 0 < k := lt_of_lt_of_le (norm_pos_iff.mpr hx) (h x)
have : k / ‖g y‖ < k := (div_lt_iff₀ hgy).mpr (lt_mul_of_one_lt_right k_pos H)
have : k ≤ k / ‖g y‖ := by
suffices ∀ x, ‖f x‖ ≤ k / ‖g y‖ from ciSup_le this
intro x
suffices 2 * (‖f x‖ * ‖g y‖) ≤ 2 * k by
rwa [le_div_iff₀ hgy, ← mul_le_mul_iff_right₀ (zero_lt_two : (0 : ℝ) < 2)]
calc
2 * (‖f x‖ * ‖g y‖) = ‖2 * f x * g y‖ := by simp [mul_assoc]
_ = ‖f (x + y) + f (x - y)‖ := by rw [hf1]
_ ≤ ‖f (x + y)‖ + ‖f (x - y)‖ := abs_add_le _ _
_ ≤ 2 * k := by linarith [h (x + y), h (x - y)]
linarith |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.