source stringlengths 17 118 | lean4 stringlengths 0 335k |
|---|---|
.lake/packages/mathlib/Mathlib/Probability/Process/HittingTime.lean | import Mathlib.Probability.Process.Stopping
import Mathlib.Tactic.AdaptationNote
/-!
# Hitting times
Given a stochastic process, the hitting time provides the first time the process "hits" some
subset of the state space. The hitting time is a stopping time in the case that the time index is
discrete and the process is adapted (this is true in a far more general setting however we have
only proved it for the discrete case so far).
## Main definition
* `MeasureTheory.hittingBtwn u s n m`: the first time a stochastic process `u` enters a set `s`
after time `n` and before time `m`
* `MeasureTheory.hittingAfter u s n`: the first time a stochastic process `u` enters a set `s`
after time `n`
## Main results
* `MeasureTheory.hittingBtwn_isStoppingTime`: a discrete hitting time of an adapted process is a
stopping time
* `MeasureTheory.hittingAfter_isStoppingTime`: a discrete hitting time of an adapted process is a
stopping time
-/
open Filter Order TopologicalSpace
open scoped MeasureTheory NNReal ENNReal Topology
namespace MeasureTheory
variable {Ω β ι : Type*} {m : MeasurableSpace Ω}
open scoped Classical in
/-- Hitting time: given a stochastic process `u` and a set `s`, `hittingBtwn u s n m` is
the first time `u` is in `s` after time `n` and before time `m` (if `u` does not hit `s`
after time `n` and before `m` then the hitting time is simply `m`).
The hitting time is a stopping time if the process is adapted and discrete. -/
noncomputable def hittingBtwn [Preorder ι] [InfSet ι] (u : ι → Ω → β)
(s : Set β) (n m : ι) : Ω → ι :=
fun x => if ∃ j ∈ Set.Icc n m, u j x ∈ s
then sInf (Set.Icc n m ∩ {i : ι | u i x ∈ s}) else m
@[deprecated (since := "2025-10-25")] alias hitting := hittingBtwn
open scoped Classical in
/-- Hitting time: given a stochastic process `u` and a set `s`, `hittingAfter u s n` is
the first time `u` is in `s` after time `n` (if `u` does not hit `s` after time `n` then the
hitting time is `⊤`). -/
noncomputable def hittingAfter [Preorder ι] [InfSet ι] (u : ι → Ω → β) (s : Set β) (n : ι) :
Ω → WithTop ι :=
fun x ↦ if ∃ j, n ≤ j ∧ u j x ∈ s then (sInf {i : ι | n ≤ i ∧ u i x ∈ s} : ι) else ⊤
open scoped Classical in
theorem hittingBtwn_def [Preorder ι] [InfSet ι] (u : ι → Ω → β) (s : Set β) (n m : ι) :
hittingBtwn u s n m =
fun x => if ∃ j ∈ Set.Icc n m, u j x ∈ s then sInf (Set.Icc n m ∩ {i : ι | u i x ∈ s}) else m :=
rfl
@[deprecated (since := "2025-10-25")] alias hitting_def := hittingBtwn_def
open scoped Classical in
lemma hittingAfter_def [Preorder ι] [InfSet ι] (u : ι → Ω → β) (s : Set β) (n : ι) :
hittingAfter u s n =
fun x => if ∃ j, n ≤ j ∧ u j x ∈ s
then ((sInf {i : ι | n ≤ i ∧ u i x ∈ s} : ι) : WithTop ι) else ⊤ := rfl
section Inequalities
variable [ConditionallyCompleteLinearOrder ι] {u : ι → Ω → β} {s : Set β} {n i : ι} {ω : Ω}
/-- This lemma is strictly weaker than `hittingBtwn_of_le`. -/
theorem hittingBtwn_of_lt {m : ι} (h : m < n) : hittingBtwn u s n m ω = m := by
grind [hittingBtwn, not_le, Set.Icc_eq_empty]
@[deprecated (since := "2025-10-25")] alias hitting_of_lt := hittingBtwn_of_lt
theorem hittingBtwn_le {m : ι} (ω : Ω) : hittingBtwn u s n m ω ≤ m := by
simp only [hittingBtwn]
split_ifs with h
· obtain ⟨j, hj₁, hj₂⟩ := h
change j ∈ {i | u i ω ∈ s} at hj₂
exact (csInf_le (BddBelow.inter_of_left bddBelow_Icc) (Set.mem_inter hj₁ hj₂)).trans hj₁.2
· exact le_rfl
@[deprecated (since := "2025-10-25")] alias hitting_le := hittingBtwn_le
theorem notMem_of_lt_hittingBtwn {m k : ι} (hk₁ : k < hittingBtwn u s n m ω) (hk₂ : n ≤ k) :
u k ω ∉ s := by
classical
intro h
have hexists : ∃ j ∈ Set.Icc n m, u j ω ∈ s := ⟨k, ⟨hk₂, le_trans hk₁.le <| hittingBtwn_le _⟩, h⟩
refine not_le.2 hk₁ ?_
simp_rw [hittingBtwn, if_pos hexists]
exact csInf_le bddBelow_Icc.inter_of_left ⟨⟨hk₂, le_trans hk₁.le <| hittingBtwn_le _⟩, h⟩
@[deprecated (since := "2025-10-25")] alias notMem_of_lt_hitting := notMem_of_lt_hittingBtwn
@[deprecated (since := "2025-05-23")] alias not_mem_of_lt_hitting := notMem_of_lt_hittingBtwn
theorem notMem_of_lt_hittingAfter {k : ι} (hk₁ : k < hittingAfter u s n ω) (hk₂ : n ≤ k) :
u k ω ∉ s := by
refine fun h ↦ not_le.2 hk₁ ?_
rw [hittingAfter, if_pos ⟨k, hk₂, h⟩]
exact_mod_cast csInf_le bddBelow_Ici.inter_of_left ⟨hk₂, h⟩
theorem hittingBtwn_eq_end_iff {m : ι} : hittingBtwn u s n m ω = m ↔
(∃ j ∈ Set.Icc n m, u j ω ∈ s) → sInf (Set.Icc n m ∩ {i : ι | u i ω ∈ s}) = m := by
classical
rw [hittingBtwn, ite_eq_right_iff]
@[deprecated (since := "2025-10-25")] alias hitting_eq_end_iff := hittingBtwn_eq_end_iff
lemma hittingAfter_eq_top_iff : hittingAfter u s n ω = ⊤ ↔ ∀ j, n ≤ j → u j ω ∉ s := by
simp [hittingAfter]
theorem hittingBtwn_of_le {m : ι} (hmn : m ≤ n) : hittingBtwn u s n m ω = m := by
obtain rfl | h := le_iff_eq_or_lt.1 hmn
· classical
rw [hittingBtwn, ite_eq_right_iff, forall_exists_index]
conv => intro; rw [Set.mem_Icc, Set.Icc_self, and_imp, and_imp]
intro i hi₁ hi₂ hi
rw [Set.inter_eq_left.2, csInf_singleton]
exact Set.singleton_subset_iff.2 (le_antisymm hi₂ hi₁ ▸ hi)
· exact hittingBtwn_of_lt h
@[deprecated (since := "2025-10-25")] alias hitting_of_le := hittingBtwn_of_le
theorem le_hittingBtwn {m : ι} (hnm : n ≤ m) (ω : Ω) : n ≤ hittingBtwn u s n m ω := by
simp only [hittingBtwn]
split_ifs with h
· refine le_csInf ?_ fun b hb => ?_
· obtain ⟨k, hk_Icc, hk_s⟩ := h
exact ⟨k, hk_Icc, hk_s⟩
· rw [Set.mem_inter_iff] at hb
exact hb.1.1
· exact hnm
@[deprecated (since := "2025-10-25")] alias le_hitting := le_hittingBtwn
lemma le_hittingAfter (ω : Ω) : n ≤ hittingAfter u s n ω := by
simp only [hittingAfter]
split_ifs with h
· exact_mod_cast le_csInf h fun b hb => hb.1
· simp
theorem le_hittingBtwn_of_exists {m : ι} (h_exists : ∃ j ∈ Set.Icc n m, u j ω ∈ s) :
n ≤ hittingBtwn u s n m ω := by
refine le_hittingBtwn ?_ ω
by_contra h
rw [Set.Icc_eq_empty_of_lt (not_le.mp h)] at h_exists
simp at h_exists
@[deprecated (since := "2025-10-25")] alias le_hitting_of_exists := le_hittingBtwn_of_exists
theorem hittingBtwn_mem_Icc {m : ι} (hnm : n ≤ m) (ω : Ω) : hittingBtwn u s n m ω ∈ Set.Icc n m :=
⟨le_hittingBtwn hnm ω, hittingBtwn_le ω⟩
@[deprecated (since := "2025-10-25")] alias hitting_mem_Icc := hittingBtwn_mem_Icc
theorem hittingBtwn_mem_set [WellFoundedLT ι] {m : ι} (h_exists : ∃ j ∈ Set.Icc n m, u j ω ∈ s) :
u (hittingBtwn u s n m ω) ω ∈ s := by
simp_rw [hittingBtwn, if_pos h_exists]
have h_nonempty : (Set.Icc n m ∩ {i : ι | u i ω ∈ s}).Nonempty := by
obtain ⟨k, hk₁, hk₂⟩ := h_exists
exact ⟨k, Set.mem_inter hk₁ hk₂⟩
have h_mem := csInf_mem h_nonempty
rw [Set.mem_inter_iff] at h_mem
exact h_mem.2
@[deprecated (since := "2025-10-25")] alias hitting_mem_set := hittingBtwn_mem_set
lemma hittingAfter_mem_set [WellFoundedLT ι] (h_exists : ∃ j, n ≤ j ∧ u j ω ∈ s) :
u (hittingAfter u s n ω).untopA ω ∈ s := by
rw [hittingAfter, if_pos h_exists]
have h_nonempty : {i : ι | n ≤ i ∧ u i ω ∈ s}.Nonempty := by
obtain ⟨k, hk₁, hk₂⟩ := h_exists
exact ⟨k, Set.mem_inter hk₁ hk₂⟩
exact (csInf_mem h_nonempty).2
theorem hittingBtwn_mem_set_of_hittingBtwn_lt [WellFoundedLT ι] {m : ι}
(hl : hittingBtwn u s n m ω < m) :
u (hittingBtwn u s n m ω) ω ∈ s := by
by_cases h : ∃ j ∈ Set.Icc n m, u j ω ∈ s
· exact hittingBtwn_mem_set h
· simp_rw [hittingBtwn, if_neg h] at hl
exact False.elim (hl.ne rfl)
@[deprecated (since := "2025-10-25")] alias hitting_mem_set_of_hitting_lt :=
hittingBtwn_mem_set_of_hittingBtwn_lt
lemma hittingAfter_mem_set_of_ne_top [WellFoundedLT ι] (hl : hittingAfter u s n ω ≠ ⊤) :
u (hittingAfter u s n ω).untopA ω ∈ s := by
simp only [ne_eq, hittingAfter_eq_top_iff, not_forall, not_not] at hl
obtain ⟨j, hj₁, hj₂⟩ := hl
exact hittingAfter_mem_set ⟨j, hj₁, hj₂⟩
theorem hittingBtwn_le_of_mem {m : ι} (hin : n ≤ i) (him : i ≤ m) (his : u i ω ∈ s) :
hittingBtwn u s n m ω ≤ i := by
have h_exists : ∃ k ∈ Set.Icc n m, u k ω ∈ s := ⟨i, ⟨hin, him⟩, his⟩
simp_rw [hittingBtwn, if_pos h_exists]
exact csInf_le (BddBelow.inter_of_left bddBelow_Icc) (Set.mem_inter ⟨hin, him⟩ his)
@[deprecated (since := "2025-10-25")] alias hitting_le_of_mem := hittingBtwn_le_of_mem
lemma hittingAfter_le_of_mem (hin : n ≤ i) (his : u i ω ∈ s) :
hittingAfter u s n ω ≤ i := by
have h_exists : ∃ k, n ≤ k ∧ u k ω ∈ s := ⟨i, hin, his⟩
rw [hittingAfter, if_pos h_exists]
exact_mod_cast csInf_le (BddBelow.inter_of_left bddBelow_Ici) (Set.mem_inter hin his)
theorem hittingBtwn_le_iff_of_exists [WellFoundedLT ι] {m : ι}
(h_exists : ∃ j ∈ Set.Icc n m, u j ω ∈ s) :
hittingBtwn u s n m ω ≤ i ↔ ∃ j ∈ Set.Icc n i, u j ω ∈ s := by
constructor <;> intro h'
· exact ⟨hittingBtwn u s n m ω, ⟨le_hittingBtwn_of_exists h_exists, h'⟩,
hittingBtwn_mem_set h_exists⟩
· have h'' : ∃ k ∈ Set.Icc n (min m i), u k ω ∈ s := by
obtain ⟨k₁, hk₁_mem, hk₁_s⟩ := h_exists
obtain ⟨k₂, hk₂_mem, hk₂_s⟩ := h'
refine ⟨min k₁ k₂, ⟨le_min hk₁_mem.1 hk₂_mem.1, min_le_min hk₁_mem.2 hk₂_mem.2⟩, ?_⟩
exact min_rec' (fun j => u j ω ∈ s) hk₁_s hk₂_s
obtain ⟨k, hk₁, hk₂⟩ := h''
refine le_trans ?_ (hk₁.2.trans (min_le_right _ _))
exact hittingBtwn_le_of_mem hk₁.1 (hk₁.2.trans (min_le_left _ _)) hk₂
@[deprecated (since := "2025-10-25")] alias hitting_le_iff_of_exists :=
hittingBtwn_le_iff_of_exists
lemma hittingAfter_le_iff [WellFoundedLT ι] :
hittingAfter u s n ω ≤ i ↔ ∃ j ∈ Set.Icc n i, u j ω ∈ s := by
constructor <;> intro h'
· have h_top : hittingAfter u s n ω ≠ ⊤ := fun h ↦ by simp [h] at h'
have h_le := le_hittingAfter (u := u) (s := s) (n := n) ω
refine ⟨(hittingAfter u s n ω).untopA, ?_, hittingAfter_mem_set_of_ne_top h_top⟩
lift (hittingAfter u s n ω) to ι using h_top with i'
norm_cast at h' h_le
· obtain ⟨j, hj₁, hj₂⟩ := h'
refine le_trans ?_ (mod_cast hj₁.2 : (j : WithTop ι) ≤ i)
exact hittingAfter_le_of_mem hj₁.1 hj₂
theorem hittingBtwn_le_iff_of_lt [WellFoundedLT ι] {m : ι} (i : ι) (hi : i < m) :
hittingBtwn u s n m ω ≤ i ↔ ∃ j ∈ Set.Icc n i, u j ω ∈ s := by
by_cases h_exists : ∃ j ∈ Set.Icc n m, u j ω ∈ s
· rw [hittingBtwn_le_iff_of_exists h_exists]
· simp_rw [hittingBtwn, if_neg h_exists]
push_neg at h_exists
simp only [not_le.mpr hi, Set.mem_Icc, false_iff, not_exists, not_and, and_imp]
exact fun k hkn hki => h_exists k ⟨hkn, hki.trans hi.le⟩
@[deprecated (since := "2025-10-25")] alias hitting_le_iff_of_lt := hittingBtwn_le_iff_of_lt
theorem hittingBtwn_lt_iff [WellFoundedLT ι] {m : ι} (i : ι) (hi : i ≤ m) :
hittingBtwn u s n m ω < i ↔ ∃ j ∈ Set.Ico n i, u j ω ∈ s := by
constructor <;> intro h'
· have h : ∃ j ∈ Set.Icc n m, u j ω ∈ s := by
by_contra h
simp_rw [hittingBtwn, if_neg h, ← not_le] at h'
exact h' hi
exact ⟨hittingBtwn u s n m ω, ⟨le_hittingBtwn_of_exists h, h'⟩, hittingBtwn_mem_set h⟩
· obtain ⟨k, hk₁, hk₂⟩ := h'
refine lt_of_le_of_lt ?_ hk₁.2
exact hittingBtwn_le_of_mem hk₁.1 (hk₁.2.le.trans hi) hk₂
@[deprecated (since := "2025-10-25")] alias hitting_lt_iff := hittingBtwn_lt_iff
lemma hittingAfter_lt_iff [WellFoundedLT ι] :
hittingAfter u s n ω < i ↔ ∃ j ∈ Set.Ico n i, u j ω ∈ s := by
constructor <;> intro h'
· have h_top : hittingAfter u s n ω ≠ ⊤ := fun h ↦ by simp [h] at h'
have h_le := le_hittingAfter (u := u) (s := s) (n := n) ω
refine ⟨(hittingAfter u s n ω).untopA, ?_, hittingAfter_mem_set_of_ne_top h_top⟩
lift (hittingAfter u s n ω) to ι using h_top with i'
norm_cast at h' h_le
· obtain ⟨j, hj₁, hj₂⟩ := h'
refine lt_of_le_of_lt ?_ (mod_cast hj₁.2 : (j : WithTop ι) < i)
exact hittingAfter_le_of_mem hj₁.1 hj₂
theorem hittingBtwn_eq_hittingBtwn_of_exists {m₁ m₂ : ι} (h : m₁ ≤ m₂)
(h' : ∃ j ∈ Set.Icc n m₁, u j ω ∈ s) : hittingBtwn u s n m₁ ω = hittingBtwn u s n m₂ ω := by
simp only [hittingBtwn, if_pos h']
obtain ⟨j, hj₁, hj₂⟩ := h'
rw [if_pos]
· refine le_antisymm ?_ (by gcongr; exacts [bddBelow_Icc.inter_of_left, ⟨j, hj₁, hj₂⟩])
refine le_csInf ⟨j, Set.Icc_subset_Icc_right h hj₁, hj₂⟩ fun i hi => ?_
by_cases hi' : i ≤ m₁
· exact csInf_le bddBelow_Icc.inter_of_left ⟨⟨hi.1.1, hi'⟩, hi.2⟩
· change j ∈ {i | u i ω ∈ s} at hj₂
exact ((csInf_le bddBelow_Icc.inter_of_left ⟨hj₁, hj₂⟩).trans hj₁.2).trans (le_of_not_ge hi')
exact ⟨j, ⟨hj₁.1, hj₁.2.trans h⟩, hj₂⟩
@[deprecated (since := "2025-10-25")] alias hitting_eq_hitting_of_exists :=
hittingBtwn_eq_hittingBtwn_of_exists
theorem hittingBtwn_mono {m₁ m₂ : ι} (hm : m₁ ≤ m₂) :
hittingBtwn u s n m₁ ω ≤ hittingBtwn u s n m₂ ω := by
by_cases h : ∃ j ∈ Set.Icc n m₁, u j ω ∈ s
· exact (hittingBtwn_eq_hittingBtwn_of_exists hm h).le
· simp_rw [hittingBtwn, if_neg h]
split_ifs with h'
· obtain ⟨j, hj₁, hj₂⟩ := h'
refine le_csInf ⟨j, hj₁, hj₂⟩ ?_
by_contra! hneg
obtain ⟨i, hi₁, hi₂⟩ := hneg
exact h ⟨i, ⟨hi₁.1.1, hi₂.le⟩, hi₁.2⟩
· exact hm
@[deprecated (since := "2025-10-25")] alias hitting_mono := hittingBtwn_mono
end Inequalities
/-- A discrete hitting time is a stopping time. -/
theorem hittingBtwn_isStoppingTime [ConditionallyCompleteLinearOrder ι] [WellFoundedLT ι]
[Countable ι] [TopologicalSpace β] [PseudoMetrizableSpace β] [MeasurableSpace β] [BorelSpace β]
{f : Filtration ι m} {u : ι → Ω → β} {s : Set β} {n n' : ι} (hu : Adapted f u)
(hs : MeasurableSet s) : IsStoppingTime f (fun ω ↦ (hittingBtwn u s n n' ω : ι)) := by
intro i
rcases le_or_gt n' i with hi | hi
· have h_le : ∀ ω, hittingBtwn u s n n' ω ≤ i := fun x => (hittingBtwn_le x).trans hi
simp [h_le]
· have h_set_eq_Union : {ω | hittingBtwn u s n n' ω ≤ i} = ⋃ j ∈ Set.Icc n i, u j ⁻¹' s := by
ext x
rw [Set.mem_setOf_eq, hittingBtwn_le_iff_of_lt _ hi]
simp only [Set.mem_Icc, exists_prop, Set.mem_iUnion, Set.mem_preimage]
simp_rw [WithTop.coe_le_coe, h_set_eq_Union]
exact MeasurableSet.iUnion fun j =>
MeasurableSet.iUnion fun hj => f.mono hj.2 _ ((hu j).measurable hs)
@[deprecated (since := "2025-10-25")] alias hitting_isStoppingTime := hittingBtwn_isStoppingTime
/-- A discrete hitting time is a stopping time. -/
theorem hittingAfter_isStoppingTime [ConditionallyCompleteLinearOrder ι] [WellFoundedLT ι]
[Countable ι] [TopologicalSpace β] [PseudoMetrizableSpace β] [MeasurableSpace β] [BorelSpace β]
{f : Filtration ι m} {u : ι → Ω → β} {s : Set β} {n : ι}
(hu : Adapted f u) (hs : MeasurableSet s) :
IsStoppingTime f (hittingAfter u s n) := by
intro i
have h_set_eq_Union : {ω | hittingAfter u s n ω ≤ i} = ⋃ j ∈ Set.Icc n i, u j ⁻¹' s := by
ext x
rw [Set.mem_setOf_eq, hittingAfter_le_iff]
simp only [Set.mem_Icc, exists_prop, Set.mem_iUnion, Set.mem_preimage]
rw [h_set_eq_Union]
exact MeasurableSet.iUnion fun j =>
MeasurableSet.iUnion fun hj => f.mono hj.2 _ ((hu j).measurable hs)
theorem stoppedValue_hittingBtwn_mem [ConditionallyCompleteLinearOrder ι] [WellFoundedLT ι]
{u : ι → Ω → β} {s : Set β} {n m : ι} {ω : Ω} (h : ∃ j ∈ Set.Icc n m, u j ω ∈ s) :
stoppedValue u (fun ω ↦ (hittingBtwn u s n m ω : ι)) ω ∈ s := by
simp only [stoppedValue, hittingBtwn, if_pos h]
obtain ⟨j, hj₁, hj₂⟩ := h
have : sInf (Set.Icc n m ∩ {i | u i ω ∈ s}) ∈ Set.Icc n m ∩ {i | u i ω ∈ s} :=
csInf_mem (Set.nonempty_of_mem ⟨hj₁, hj₂⟩)
exact this.2
@[deprecated (since := "2025-10-25")] alias stoppedValue_hitting_mem := stoppedValue_hittingBtwn_mem
/-- The hitting time of a discrete process with the starting time indexed by a stopping time
is a stopping time. -/
theorem isStoppingTime_hittingBtwn_isStoppingTime [ConditionallyCompleteLinearOrder ι]
[WellFoundedLT ι] [Countable ι] [TopologicalSpace ι] [OrderTopology ι]
[FirstCountableTopology ι] [TopologicalSpace β] [PseudoMetrizableSpace β] [MeasurableSpace β]
[BorelSpace β] {f : Filtration ι m} {u : ι → Ω → β} {τ : Ω → WithTop ι}
(hτ : IsStoppingTime f τ)
{N : ι} (hτbdd : ∀ x, τ x ≤ N) {s : Set β} (hs : MeasurableSet s) (hf : Adapted f u) :
IsStoppingTime f fun x ↦ (hittingBtwn u s (τ x).untopA N x : ι) := by
intro n
have h₁ : {x | hittingBtwn u s (τ x).untopA N x ≤ n} =
(⋃ i ≤ n, {x | τ x = i} ∩ {x | hittingBtwn u s i N x ≤ n}) ∪
⋃ i > n, {x | τ x = i} ∩ {x | hittingBtwn u s i N x ≤ n} := by
ext x
simp only [Set.mem_setOf_eq, gt_iff_lt, Set.mem_union, Set.mem_iUnion, Set.mem_inter_iff,
exists_and_left, exists_prop]
specialize hτbdd x
have h_top : τ x ≠ ⊤ := fun h => by simp [h] at hτbdd
lift τ x to ι using h_top with t
simp [← or_and_right, le_or_gt]
have h₂ : ⋃ i > n, {x | τ x = i} ∩ {x | hittingBtwn u s i N x ≤ n} = ∅ := by
ext x
simp only [gt_iff_lt, Set.mem_iUnion, Set.mem_inter_iff, Set.mem_setOf_eq, exists_prop,
Set.mem_empty_iff_false, iff_false, not_exists, not_and, not_le]
refine fun m hm hτ ↦ hm.trans_le <| le_hittingBtwn ?_ x
specialize hτbdd x
have h_top : τ x ≠ ⊤ := fun h => by simp [h] at hτbdd
lift τ x to ι using h_top with t
rw [hτ] at hτbdd
exact mod_cast hτbdd
simp only [WithTop.coe_le_coe]
rw [h₁, h₂, Set.union_empty]
refine MeasurableSet.iUnion fun i => MeasurableSet.iUnion fun hi =>
(f.mono hi _ (hτ.measurableSet_eq i)).inter ?_
have h := hittingBtwn_isStoppingTime (n := i) (n' := N) hf hs n
simpa only [WithTop.coe_le_coe] using h
@[deprecated (since := "2025-10-25")] alias isStoppingTime_hitting_isStoppingTime :=
isStoppingTime_hittingBtwn_isStoppingTime
section CompleteLattice
variable [CompleteLattice ι] {u : ι → Ω → β} {s : Set β}
theorem hittingBtwn_eq_sInf (ω : Ω) : hittingBtwn u s ⊥ ⊤ ω = sInf {i : ι | u i ω ∈ s} := by
simp only [hittingBtwn, Set.Icc_bot,
Set.Iic_top, Set.univ_inter, ite_eq_left_iff, not_exists]
intro h_notMem_s
symm
rw [sInf_eq_top]
simp only [Set.mem_univ, true_and] at h_notMem_s
exact fun i hi_mem_s => absurd hi_mem_s (h_notMem_s i)
@[deprecated (since := "2025-10-25")] alias hitting_eq_sInf := hittingBtwn_eq_sInf
lemma hittingAfter_eq_sInf [∀ ω, Decidable (∃ j, u j ω ∈ s)] (ω : Ω) :
hittingAfter u s ⊥ ω
= if ∃ j, u j ω ∈ s then ((sInf {i : ι | u i ω ∈ s} : ι) : WithTop ι)
else (⊤ : WithTop ι) := by
simp [hittingAfter]
end CompleteLattice
section ConditionallyCompleteLinearOrderBot
variable [ConditionallyCompleteLinearOrderBot ι] [WellFoundedLT ι]
variable {u : ι → Ω → β} {s : Set β}
theorem hittingBtwn_bot_le_iff {i n : ι} {ω : Ω} (hx : ∃ j, j ≤ n ∧ u j ω ∈ s) :
hittingBtwn u s ⊥ n ω ≤ i ↔ ∃ j ≤ i, u j ω ∈ s := by
rcases lt_or_ge i n with hi | hi
· rw [hittingBtwn_le_iff_of_lt _ hi]
simp
· simp only [(hittingBtwn_le ω).trans hi, true_iff]
obtain ⟨j, hj₁, hj₂⟩ := hx
exact ⟨j, hj₁.trans hi, hj₂⟩
@[deprecated (since := "2025-10-25")] alias hitting_bot_le_iff := hittingBtwn_bot_le_iff
theorem hittingAfter_bot_le_iff {i : ι} {ω : Ω} :
hittingAfter u s ⊥ ω ≤ i ↔ ∃ j ≤ i, u j ω ∈ s := by
simp [hittingAfter_le_iff]
end ConditionallyCompleteLinearOrderBot
end MeasureTheory |
.lake/packages/mathlib/Mathlib/Probability/Process/FiniteDimensionalLaws.lean | import Mathlib.MeasureTheory.Constructions.Projective
import Mathlib.Probability.IdentDistrib
/-!
# Finite-dimensional distributions of a stochastic process
For a stochastic process `X : T → Ω → 𝓧` and a finite measure `P` on `Ω`, the law of the process is
`P.map (fun ω ↦ (X · ω))`, and its finite-dimensional distributions are
`P.map (fun ω ↦ I.restrict (X · ω))` for `I : Finset T`.
We show that two stochastic processes have the same laws if and only if they have the same
finite-dimensional distributions.
## Main statements
* `map_eq_iff_forall_finset_map_restrict_eq`: two processes have the same law if and only if
their finite-dimensional distributions are equal.
* `identDistrib_iff_forall_finset_identDistrib`: same statement, but stated in terms of
`IdentDistrib`.
* `map_restrict_eq_of_forall_ae_eq`: if two processes are modifications of each other, then
their finite-dimensional distributions are equal.
* `map_eq_of_forall_ae_eq`: if two processes are modifications of each other, then they have the
same law.
-/
open MeasureTheory
namespace ProbabilityTheory
variable {T Ω : Type*} {𝓧 : T → Type*} {mΩ : MeasurableSpace Ω} {mα : ∀ t, MeasurableSpace (𝓧 t)}
{X Y : (t : T) → Ω → 𝓧 t} {P : Measure Ω}
/-- The finite-dimensional distributions of a stochastic process are a projective measure family. -/
lemma isProjectiveMeasureFamily_map_restrict (hX : ∀ t, AEMeasurable (X t) P) :
IsProjectiveMeasureFamily (fun I ↦ P.map (fun ω ↦ I.restrict (X · ω))) := by
intro I J hJI
rw [AEMeasurable.map_map_of_aemeasurable (Finset.measurable_restrict₂ _).aemeasurable]
· simp [Finset.restrict_def, Finset.restrict₂_def, Function.comp_def]
· exact aemeasurable_pi_lambda _ fun _ ↦ hX _
/-- The projective limit of the finite-dimensional distributions of a stochastic process is the law
of the process. -/
lemma isProjectiveLimit_map (hX : AEMeasurable (fun ω ↦ (X · ω)) P) :
IsProjectiveLimit (P.map (fun ω ↦ (X · ω))) (fun I ↦ P.map (fun ω ↦ I.restrict (X · ω))) := by
intro I
rw [AEMeasurable.map_map_of_aemeasurable (Finset.measurable_restrict _).aemeasurable hX,
Function.comp_def]
/-- Two stochastic processes have same law iff they have the same
finite-dimensional distributions. -/
lemma map_eq_iff_forall_finset_map_restrict_eq [IsFiniteMeasure P]
(hX : AEMeasurable (fun ω ↦ (X · ω)) P) (hY : AEMeasurable (fun ω ↦ (Y · ω)) P) :
P.map (fun ω ↦ (X · ω)) = P.map (fun ω ↦ (Y · ω))
↔ ∀ I : Finset T, P.map (fun ω ↦ I.restrict (X · ω)) = P.map (fun ω ↦ I.restrict (Y · ω)) := by
refine ⟨fun h I ↦ ?_, fun h ↦ ?_⟩
· have hX' : P.map (fun ω ↦ I.restrict (X · ω)) = (P.map (fun ω ↦ (X · ω))).map I.restrict := by
rw [AEMeasurable.map_map_of_aemeasurable (by fun_prop) hX, Function.comp_def]
have hY' : P.map (fun ω ↦ I.restrict (Y · ω)) = (P.map (fun ω ↦ (Y · ω))).map I.restrict := by
rw [AEMeasurable.map_map_of_aemeasurable (by fun_prop) hY, Function.comp_def]
rw [hX', hY', h]
· have hX' := isProjectiveLimit_map hX
simp_rw [h] at hX'
exact hX'.unique (isProjectiveLimit_map hY)
/-- Two stochastic processes are identically distributed iff they have the same
finite-dimensional distributions. -/
lemma identDistrib_iff_forall_finset_identDistrib [IsFiniteMeasure P]
(hX : AEMeasurable (fun ω ↦ (X · ω)) P) (hY : AEMeasurable (fun ω ↦ (Y · ω)) P) :
IdentDistrib (fun ω ↦ (X · ω)) (fun ω ↦ (Y · ω)) P P
↔ ∀ I : Finset T,
IdentDistrib (fun ω ↦ I.restrict (X · ω)) (fun ω ↦ I.restrict (Y · ω)) P P := by
refine ⟨fun h I ↦ ⟨?_, ?_, ?_⟩, fun h ↦ ⟨hX, hY, ?_⟩⟩
· exact (Finset.measurable_restrict _).comp_aemeasurable hX
· exact (Finset.measurable_restrict _).comp_aemeasurable hY
· exact (map_eq_iff_forall_finset_map_restrict_eq hX hY).mp h.map_eq I
· exact (map_eq_iff_forall_finset_map_restrict_eq hX hY).mpr (fun I ↦ (h I).map_eq)
/-- If two processes are modifications of each other, then they have the same finite-dimensional
distributions. -/
lemma map_restrict_eq_of_forall_ae_eq (h : ∀ t, X t =ᵐ[P] Y t) (I : Finset T) :
P.map (fun ω ↦ I.restrict (X · ω)) = P.map (fun ω ↦ I.restrict (Y · ω)) := by
have h' : ∀ᵐ ω ∂P, ∀ (i : I), X i ω = Y i ω := by
rw [MeasureTheory.ae_all_iff]
exact fun i ↦ h i
refine Measure.map_congr ?_
filter_upwards [h'] with ω h using funext h
/-- If two processes are modifications of each other, then they have the same distribution. -/
lemma map_eq_of_forall_ae_eq [IsFiniteMeasure P]
(hX : AEMeasurable (fun ω ↦ (X · ω)) P) (hY : AEMeasurable (fun ω ↦ (Y · ω)) P)
(h : ∀ t, X t =ᵐ[P] Y t) :
P.map (fun ω ↦ (X · ω)) = P.map (fun ω ↦ (Y · ω)) := by
rw [map_eq_iff_forall_finset_map_restrict_eq hX hY]
exact fun I ↦ map_restrict_eq_of_forall_ae_eq h I
end ProbabilityTheory |
.lake/packages/mathlib/Mathlib/Util/WhatsNew.lean | import Mathlib.Init
/-!
Defines a command wrapper that prints the changes the command makes to the
environment.
```
whatsnew in
theorem foo : 42 = 6 * 7 := rfl
```
-/
open Lean Elab Command
namespace Mathlib.WhatsNew
private def throwUnknownId (id : Name) : CommandElabM Unit :=
throwError "unknown identifier '{mkConst id}'"
private def levelParamsToMessageData (levelParams : List Name) : MessageData :=
match levelParams with
| [] => ""
| u::us => Id.run <| do
let mut m := m!".\{{u}"
for u in us do
m := m ++ ", " ++ toMessageData u
return m ++ "}"
private def mkHeader (kind : String) (id : Name) (levelParams : List Name) (type : Expr)
(safety : DefinitionSafety) : CoreM MessageData := do
let m : MessageData :=
match safety with
| DefinitionSafety.unsafe => "unsafe "
| DefinitionSafety.partial => "partial "
| DefinitionSafety.safe => ""
let m := if isProtected (← getEnv) id then m ++ "protected " else m
let (m, id) := match privateToUserName? id with
| some id => (m ++ "private ", id)
| none => (m, id)
let m := m ++ kind ++ " " ++ id ++ levelParamsToMessageData levelParams ++ " : " ++ type
pure m
private def mkHeader' (kind : String) (id : Name) (levelParams : List Name) (type : Expr)
(isUnsafe : Bool) : CoreM MessageData :=
mkHeader kind id levelParams type
(if isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe)
private def printDefLike (kind : String) (id : Name) (levelParams : List Name) (type : Expr)
(value : Expr) (safety := DefinitionSafety.safe) : CoreM MessageData :=
return (← mkHeader kind id levelParams type safety) ++ " :=" ++ Format.line ++ value
private def printInduct (id : Name) (levelParams : List Name) (_numParams : Nat) (_numIndices : Nat)
(type : Expr) (ctors : List Name) (isUnsafe : Bool) : CoreM MessageData := do
let mut m ← mkHeader' "inductive" id levelParams type isUnsafe
m := m ++ Format.line ++ "constructors:"
for ctor in ctors do
let cinfo ← getConstInfo ctor
m := m ++ Format.line ++ ctor ++ " : " ++ cinfo.type
pure m
private def printIdCore (id : Name) : ConstantInfo → CoreM MessageData
| ConstantInfo.axiomInfo { levelParams := us, type := t, isUnsafe := u, .. } =>
mkHeader' "axiom" id us t u
| ConstantInfo.defnInfo { levelParams := us, type := t, value := v, safety := s, .. } =>
printDefLike "def" id us t v s
| ConstantInfo.thmInfo { levelParams := us, type := t, value := v, .. } =>
printDefLike "theorem" id us t v
| ConstantInfo.opaqueInfo { levelParams := us, type := t, isUnsafe := u, .. } =>
mkHeader' "constant" id us t u
| ConstantInfo.quotInfo { levelParams := us, type := t, .. } =>
mkHeader' "Quotient primitive" id us t false
| ConstantInfo.ctorInfo { levelParams := us, type := t, isUnsafe := u, .. } =>
mkHeader' "constructor" id us t u
| ConstantInfo.recInfo { levelParams := us, type := t, isUnsafe := u, .. } =>
mkHeader' "recursor" id us t u
| ConstantInfo.inductInfo
{ levelParams := us, numParams, numIndices, type := t, ctors, isUnsafe := u, .. } =>
printInduct id us numParams numIndices t ctors u
def diffExtension (old new : Environment)
(ext : PersistentEnvExtension EnvExtensionEntry EnvExtensionEntry EnvExtensionState) :
CoreM (Option MessageData) := unsafe do
let mut asyncMode := ext.toEnvExtension.asyncMode
if asyncMode matches .async .. then
-- allow for diffing async extensions by bumping mode to sync
asyncMode := .sync
let oldSt := ext.toEnvExtension.getState (asyncMode := asyncMode) old
let newSt := ext.toEnvExtension.getState (asyncMode := asyncMode) new
if ptrAddrUnsafe oldSt == ptrAddrUnsafe newSt then return none
let oldEntries := ext.exportEntriesFn (← getEnv) oldSt.state .private
let newEntries := ext.exportEntriesFn (← getEnv) newSt.state .private
pure m!"-- {ext.name} extension: {(newEntries.size - oldEntries.size : Int)} new entries"
def whatsNew (old new : Environment) : CoreM MessageData := do
let mut diffs := #[]
for (c, i) in new.constants.map₂.toList do
unless old.constants.map₂.contains c do
diffs := diffs.push (← printIdCore c i)
for ext in ← persistentEnvExtensionsRef.get do
if let some diff := ← diffExtension old new ext then
diffs := diffs.push diff
if diffs.isEmpty then return "no new constants"
pure <| MessageData.joinSep diffs.toList "\n\n"
/-- `whatsnew in $command` executes the command and then prints the
declarations that were added to the environment. -/
elab "whatsnew " "in" ppLine cmd:command : command => do
let oldEnv ← getEnv
try
elabCommand cmd
finally
let newEnv ← getEnv
logInfo (← liftCoreM <| whatsNew oldEnv newEnv)
end Mathlib.WhatsNew |
.lake/packages/mathlib/Mathlib/Util/FormatTable.lean | import Mathlib.Data.String.Defs
/-!
# Format Table
This file provides a simple function for formatting a two-dimensional array of `String`s
into a markdown-compliant table.
-/
/-- Possible alignment modes for each table item: left-aligned, right-aligned and centered. -/
inductive Alignment where
| left
| right
| center
deriving Inhabited, BEq
/-- Align a `String` `s` to the left, right, or center within a field of width `width`. -/
def String.justify (s : String) (a : Alignment) (width : Nat) : String :=
match a with
| Alignment.left => s.rightpad width
| Alignment.right => s.leftpad width
| Alignment.center =>
let pad := (width - s.length) / 2
String.replicate pad ' ' ++ s ++ String.replicate (width - s.length - pad) ' '
/--
Render a two-dimensional array of `String`s into a markdown-compliant table.
`headers` is a list of column headers,
`table` is a 2D array of cell contents,
`alignments` describes how to align each table column (default: left-aligned). -/
def formatTable (headers : Array String) (table : Array (Array String))
(alignments : Option (Array Alignment) := none) :
String := Id.run do
-- If no alignments are provided, default to left alignment for all columns.
let alignments := alignments.getD (Array.replicate headers.size Alignment.left)
-- Escape all vertical bar characters inside a table cell,
-- otherwise these could get interpreted as starting a new row or column.
let escapedHeaders := headers.map (fun header => header.replace "|" "\\|")
let escapedTable := table.map (fun row => row.map (fun cell => cell.replace "|" "\\|"))
-- Compute the maximum width of each column.
let mut widths := escapedHeaders.map (·.length)
for row in escapedTable do
for i in [0:widths.size] do
widths := widths.set! i (max widths[i]! ((row[i]?.map (·.length)).getD 0))
-- Pad each cell with spaces to match the column width.
let paddedHeaders := escapedHeaders.mapIdx fun i h => h.rightpad widths[i]!
let paddedTable := escapedTable.map fun row => row.mapIdx fun i cell =>
cell.justify alignments[i]! widths[i]!
-- Construct the lines of the table
let headerLine := "| " ++ String.intercalate " | " (paddedHeaders.toList) ++ " |"
-- Construct the separator line, with colons to indicate alignment
let separatorLine :=
"| "
++ String.intercalate " | "
(((widths.zip alignments).map fun ⟨w, a⟩ =>
match w, a with
| 0, _ => ""
| 1, _ => "-"
| _ + 2, Alignment.left => ":" ++ String.replicate (w-1) '-'
| _ + 2, Alignment.right => String.replicate (w-1) '-' ++ ":"
| _ + 2, Alignment.center => ":" ++ String.replicate (w-2) '-' ++ ":"
).toList)
++ " |"
let rowLines := paddedTable.map (fun row => "| " ++ String.intercalate " | " (row.toList) ++ " |")
-- Return the table
return String.intercalate "\n" (headerLine :: separatorLine :: rowLines.toList) |
.lake/packages/mathlib/Mathlib/Util/TermReduce.lean | import Lean.Meta.Tactic.Delta
import Mathlib.Lean.Expr.Basic
/-!
# Term elaborators for reduction
-/
namespace Mathlib.Util.TermReduce
open Lean Elab Term Meta
/-!
The `beta% f x1 ... xn` term elaborator elaborates the expression
`f x1 ... xn` and then does one level of beta reduction.
That is, if `f` is a lambda then it will substitute its arguments.
The purpose of this is to support substitutions in notations such as
`∀ i, beta% p i` so that `p i` gets beta reduced when `p` is a lambda.
-/
/-- `beta% t` elaborates `t` and then if the result is in the form
`f x1 ... xn` where `f` is a (nested) lambda expression,
it will substitute all of its arguments by beta reduction.
This does not recursively do beta reduction, nor will it do
beta reduction of subexpressions.
In particular, `t` is elaborated, its metavariables are instantiated,
and then `Lean.Expr.headBeta` is applied. -/
syntax (name := betaStx) "beta% " term : term
@[term_elab betaStx, inherit_doc betaStx]
def elabBeta : TermElab := fun stx expectedType? =>
match stx with
| `(beta% $t) => do
let e ← elabTerm t expectedType?
return (← instantiateMVars e).headBeta
| _ => throwUnsupportedSyntax
/-- `delta% t` elaborates to a head-delta reduced version of `t`. -/
syntax (name := deltaStx) "delta% " term : term
@[term_elab deltaStx, inherit_doc deltaStx]
def elabDelta : TermElab := fun stx expectedType? =>
match stx with
| `(delta% $t) => do
let t ← withSynthesize (postpone := .partial) do
elabTerm t expectedType?
synthesizeSyntheticMVars
let t ← instantiateMVars t
let some t ← delta? t | throwError "cannot delta reduce {t}"
pure t
| _ => throwUnsupportedSyntax
/-- `zeta% t` elaborates to a zeta and zeta-delta reduced version of `t`. -/
syntax (name := zetaStx) "zeta% " term : term
@[term_elab zetaStx, inherit_doc zetaStx]
def elabZeta : TermElab := fun stx expectedType? =>
match stx with
| `(zeta% $t) => do
let t ← withSynthesize (postpone := .partial) do
elabTerm t expectedType?
synthesizeSyntheticMVars
let t ← instantiateMVars t
let t ← zetaReduce t
pure t
| _ => throwUnsupportedSyntax
/-- `reduceProj% t` apply `Expr.reduceProjStruct?` to all subexpressions of `t`. -/
syntax (name := reduceProjStx) "reduceProj% " term : term
@[term_elab reduceProjStx, inherit_doc reduceProjStx]
def elabReduceProj : TermElab := fun stx expectedType? =>
match stx with
| `(reduceProj% $t) => do
let t ← withSynthesize (postpone := .partial) do
elabTerm t expectedType?
synthesizeSyntheticMVars
let t ← instantiateMVars t
let t ← Lean.Core.transform t (post := fun e ↦ do
return .continue (← Expr.reduceProjStruct? e))
pure t
| _ => throwUnsupportedSyntax
end Mathlib.Util.TermReduce |
.lake/packages/mathlib/Mathlib/Util/ParseCommand.lean | import Lean.Elab.Command
import Mathlib.Init
/-!
# `#parse` -- a command to parse text and log outputs
-/
namespace Mathlib.GuardExceptions
open Lean Parser Elab Command
/-- `captureException env s input` uses the given `Environment` `env` to parse the `String` `input`
using the `ParserFn` `s`.
This is a variation of `Lean.Parser.runParserCategory`.
-/
def captureException (env : Environment) (s : ParserFn) (input : String) : Except String Syntax :=
let ictx := mkInputContext input "<input>"
let s := s.run ictx { env, options := {} } (getTokenTable env) (mkParserState input)
if !s.allErrors.isEmpty then
.error (s.toErrorMsg ictx)
else if ictx.atEnd s.pos then
.ok s.stxStack.back
else
.error ((s.mkError "end of input").toErrorMsg ictx)
/-- `#parse parserFnId => str` allows to capture parsing exceptions.
`parserFnId` is the identifier of a `ParserFn` and `str` is the string that
`parserFnId` should parse.
If the parse is successful, then the output is logged;
if the parse is successful, then the output is captured in an exception.
In either case, `#guard_msgs` can then be used to capture the resulting parsing errors.
For instance, `#parse` can be used as follows
```lean
/-- error: <input>:1:3: Stacks tags must be exactly 4 characters -/
#guard_msgs in #parse Mathlib.Stacks.stacksTagFn => "A05"
```
-/
syntax (name := parseCmd) "#parse " ident " => " str : command
@[inherit_doc parseCmd]
elab_rules : command
| `(command| #parse $parserFnId => $str) => do
elabCommand <| ← `(command|
run_cmd do
let exc ← Lean.ofExcept <| captureException (← getEnv) $parserFnId $str
logInfo $str)
end Mathlib.GuardExceptions |
.lake/packages/mathlib/Mathlib/Util/Qq.lean | import Mathlib.Init
import Qq
import Lean.Expr
/-!
# Extra `Qq` helpers
This file contains some additional functions for using the quote4 library more conveniently.
-/
open Lean Elab Tactic Meta
namespace Qq
/-- If `e` has type `Sort u` for some level `u`, return `u` and `e : Q(Sort u)`. -/
def getLevelQ (e : Expr) : MetaM (Σ u : Lean.Level, Q(Sort u)) := do
return ⟨← getLevel e, e⟩
/-- If `e` has type `Type u` for some level `u`, return `u` and `e : Q(Type u)`. -/
def getLevelQ' (e : Expr) : MetaM (Σ u : Lean.Level, Q(Type u)) := do
let u ← getLevel e
let some v := (← instantiateLevelMVars u).dec | throwError "not a Type{indentExpr e}"
return ⟨v, e⟩
/-- Variant of `inferTypeQ` that yields a type in `Type u` rather than `Sort u`.
Throws an error if the type is a `Prop` or if it's otherwise not possible to represent
the universe as `Type u` (for example due to universe level metavariables). -/
-- See https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/Using.20.60QQ.60.20when.20you.20only.20have.20an.20.60Expr.60/near/303349037
def inferTypeQ' (e : Expr) : MetaM ((u : Level) × (α : Q(Type $u)) × Q($α)) := do
let α ← inferType e
let ⟨v, α⟩ ← getLevelQ' α
pure ⟨v, α, e⟩
theorem QuotedDefEq.rfl {u : Level} {α : Q(Sort u)} {a : Q($α)} : @QuotedDefEq u α a a := ⟨⟩
/-- Return a local declaration whose type is definitionally equal to `sort`.
This is a Qq version of `Lean.Meta.findLocalDeclWithType?` -/
def findLocalDeclWithTypeQ? {u : Level} (sort : Q(Sort u)) : MetaM (Option Q($sort)) := do
let some fvarId ← findLocalDeclWithType? q($sort) | return none
return some <| .fvar fvarId
/-- Returns a proof of `p : Prop` using `decide p`.
This is a Qq version of `Lean.Meta.mkDecideProof`. -/
def mkDecideProofQ (p : Q(Prop)) : MetaM Q($p) := mkDecideProof p
/-- Join a list of elements of type `α` into a container `β`.
Usually `β` is `q(Multiset α)` or `q(Finset α)` or `q(Set α)`.
As an example
```lean
mkSetLiteralQ q(Finset ℝ) (List.range 4 |>.map fun n : ℕ ↦ q($n•π))
```
produces the expression `{0 • π, 1 • π, 2 • π, 3 • π} : Finset ℝ`.
-/
def mkSetLiteralQ {u v : Level} {α : Q(Type u)} (β : Q(Type v))
(elems : List Q($α))
(_ : Q(EmptyCollection $β) := by exact q(inferInstance))
(_ : Q(Singleton $α $β) := by exact q(inferInstance))
(_ : Q(Insert $α $β) := by exact q(inferInstance)) :
Q($β) :=
match elems with
| [] => q(∅)
| [x] => q({$x})
| x :: xs => q(Insert.insert $x $(mkSetLiteralQ β xs))
/-- Returns the natural number literal `n` as used in the frontend. It is a `OfNat.ofNat`
application. Recall that all theorems and definitions containing numeric literals are encoded using
`OfNat.ofNat` applications in the frontend.
This is a Qq version of `Lean.mkNatLit`. -/
def mkNatLitQ (n : Nat) : Q(Nat) := mkNatLit n
/-- Returns the integer literal `n`.
This is a Qq version of `Lean.mkIntLit`. -/
def mkIntLitQ (n : Int) : Q(Int) := mkIntLit n
end Qq |
.lake/packages/mathlib/Mathlib/Util/TransImports.lean | import Mathlib.Init
/-! # The `#trans_imports` command
`#trans_imports` reports how many transitive imports the current module has.
The command takes an optional string input: `#trans_imports str` also shows the transitively
imported modules whose name begins with `str`.
-/
/--
`#trans_imports` reports how many transitive imports the current module has.
The command takes an optional string input: `#trans_imports str` also shows the transitively
imported modules whose name begins with `str`.
Mostly for the sake of tests, the command also takes an optional `at_most x` input:
if the number of imports does not exceed `x`, then the message involves `x`, rather than the
actual, possibly varying, number of imports.
-/
syntax (name := transImportsStx) "#trans_imports" (ppSpace str)? (&" at_most " num)? : command
open Lean in
@[inherit_doc transImportsStx]
elab_rules : command
| `(command| #trans_imports $(stx)? $[at_most $le:num]?) => do
let imports := (← getEnv).allImportedModuleNames
let currMod := if let mod@(.str _ _) := ← getMainModule then m!"'{mod}' has " else ""
let rest := match stx with
| none => m!""
| some str =>
let imps := imports.filterMap fun (i : Name) =>
if i.toString.startsWith str.getString then some i else none
m!"\n\n{imps.size} starting with {str}:\n{imps.qsort (·.toString < ·.toString)}"
match le with
| none => logInfo m!"{currMod}{imports.size} transitive imports{rest}"
| some bd =>
if imports.size ≤ bd.getNat then
logInfo m!"{currMod}at most {bd} transitive imports{rest}"
else
logWarningAt bd
m!"{currMod}{imports.size} transitive imports, exceeding the expected bound of {bd}{rest}" |
.lake/packages/mathlib/Mathlib/Util/PrintSorries.lean | import Mathlib.Lean.Expr.Basic
/-!
# Tracking uses of `sorry`
This file provides a `#print sorries` command to help find out why a given declaration is not
sorry-free. `#print sorries foo` returns a non-sorry-free declaration `bar` which `foo` depends on,
if such a `bar` exists.
The `#print sorries in CMD` combinator prints all sorries appearing in the declarations defined
by the given command.
## TODO
* Add configuration options. `#print sorries +positions -types` would print file/line/col
information and not print the types.
* Make versions for other axioms/constants.
The `#print sorries` command itself shouldn't be generalized, since `sorry` is a special concept,
representing unfinished proofs, and it has special support for "go to definition", etc.
* Move to ImportGraph?
-/
open Lean Meta Elab Command
namespace Mathlib.PrintSorries
/-- Type of intermediate computation of sorry-tracking. -/
structure State where
/-- The set of already visited declarations. -/
visited : NameSet := {}
/-- The set of `sorry` expressions that have been found.
Note that unlabeled sorries will only be reported in the *first* declaration that uses them,
even if a later definition independently has a direct use of `sorryAx`. -/
sorries : Std.HashSet Expr := {}
/-- The uses of `sorry` that were found. -/
sorryMsgs : Array MessageData := #[]
/--
Collects all uses of `sorry` by the declaration `c`.
It finds all transitive uses as well.
This is a version of `Lean.CollectAxioms.collect` that keeps track of enough information to print
each use of `sorry`.
-/
partial def collect (c : Name) : StateT State MetaM Unit := do
let collectExpr (e : Expr) : StateT State MetaM Unit := do
/-
We assume most declarations do not contain sorry.
The `getUsedConstants` function is very efficient compared to `forEachExpr'`,
since `forEachExpr'` needs to instantiate fvars.
Visiting constants first also guarantees that we attribute sorries to the first
declaration that included it. Recall that `sorry` might appear in the type of a theorem,
which leads to the `sorry` appearing directly in any declarations that use it.
This is one reason we need the `State.sorries` set as well.
The other reason is that we match entire sorry applications,
so `forEachExpr'`'s cache won't prevent over-reporting if `sorry` is a function.
-/
let consts := e.getUsedConstants
consts.forM collect
if consts.contains ``sorryAx then
let visitSorry (e : Expr) : StateT State MetaM Unit := do
unless (← get).sorries.contains e do
let mut msg := m!"{.ofConstName c} has {e}"
if e.isSyntheticSorry then
msg := msg ++ " (from error)"
try
msg := msg ++ " of type" ++ indentExpr (← inferType e)
catch _ => pure ()
msg ← addMessageContext msg
modify fun s =>
{ s with
sorries := s.sorries.insert e
sorryMsgs := s.sorryMsgs.push msg }
Meta.forEachExpr' e fun e => do
if e.isSorry then
if let some _ := isLabeledSorry? e then
visitSorry <| e.getBoundedAppFn (e.getAppNumArgs - 3)
else
visitSorry <| e.getBoundedAppFn (e.getAppNumArgs - 2)
return false
else
-- Otherwise continue visiting subexpressions
return true
let s ← get
unless s.visited.contains c do
modify fun s => { s with visited := s.visited.insert c }
let env ← getEnv
match env.checked.get.find? c with
| some (.axiomInfo v) => collectExpr v.type
| some (.defnInfo v) => collectExpr v.type *> collectExpr v.value
| some (.thmInfo v) => collectExpr v.type *> collectExpr v.value
| some (.opaqueInfo v) => collectExpr v.type *> collectExpr v.value
| some (.quotInfo _) => pure ()
| some (.ctorInfo v) => collectExpr v.type
| some (.recInfo v) => collectExpr v.type
| some (.inductInfo v) => collectExpr v.type *> v.ctors.forM collect
| none => pure ()
/--
Prints all uses of `sorry` inside a list of declarations.
Displayed sorries are hoverable and support "go to definition".
-/
def collectSorries (constNames : Array Name) : MetaM (Array MessageData) := do
let (_, s) ← (constNames.forM collect).run {}
pure s.sorryMsgs
/--
- `#print sorries` prints all sorries that the current module depends on.
- `#print sorries id1 id2 ... idn` prints all sorries that the provided declarations depend on.
- `#print sorries in CMD` prints all the sorries in declarations added by the command.
Displayed sorries are hoverable and support "go to definition".
-/
syntax (name := printSorriesStx) "#print " &"sorries" (ppSpace ident)* : command
/--
Collects sorries in the given constants and logs a message.
-/
def evalCollectSorries (names : Array Name) : CommandElabM Unit := do
let msgs ← liftTermElabM <| collectSorries names
if msgs.isEmpty then
logInfo m!"Declarations are sorry-free!"
else
logInfo <| MessageData.joinSep msgs.toList "\n"
elab_rules : command
| `(#print%$tk1 sorries%$tk2 $idents*) => do
let mut names ← liftCoreM <| idents.flatMapM fun id =>
return (← realizeGlobalConstWithInfos id).toArray
if names.isEmpty then
names ← (← getEnv).checked.get.constants.map₂.foldlM (init := #[]) fun acc name _ =>
return if ← name.isBlackListed then acc else acc.push name
withRef (mkNullNode #[tk1, tk2]) <| evalCollectSorries names
@[inherit_doc printSorriesStx]
syntax "#print " &"sorries" " in " command : command
elab_rules : command
| `(#print%$tk1 sorries%$tk2 in $cmd:command) => do
let oldEnv ← getEnv
try
elabCommand cmd
finally
let newEnv ← getEnv
let names ← newEnv.checked.get.constants.map₂.foldlM (init := #[]) fun acc name _ => do
if oldEnv.constants.map₂.contains name then
return acc
else if ← name.isBlackListed then
return acc
else
return acc.push name
withRef (mkNullNode #[tk1, tk2]) <| evalCollectSorries names
end Mathlib.PrintSorries |
.lake/packages/mathlib/Mathlib/Util/Notation3.lean | import Lean.Elab.BuiltinCommand
import Lean.Elab.MacroArgUtil
import Mathlib.Lean.Elab.Term
import Mathlib.Lean.PrettyPrinter.Delaborator
import Mathlib.Tactic.ScopedNS
import Batteries.Linter.UnreachableTactic
import Batteries.Util.ExtendedBinder
import Batteries.Lean.Syntax
import Lean.Elab.AuxDef
/-!
# The notation3 macro, simulating Lean 3's notation.
-/
-- To fix upstream:
-- * bracketedExplicitBinders doesn't support optional types
namespace Mathlib.Notation3
open Lean Parser Meta Elab Command PrettyPrinter.Delaborator SubExpr
open Batteries.ExtendedBinder
initialize registerTraceClass `notation3
/-! ### Syntaxes supporting `notation3` -/
/--
Expands binders into nested combinators.
For example, the familiar exists is given by:
`expand_binders% (p => Exists p) x y : Nat, x < y`
which expands to the same expression as
`∃ x y : Nat, x < y`
-/
syntax "expand_binders% " "(" ident " => " term ")" extBinders ", " term : term
macro_rules
| `(expand_binders% ($x => $term) $y:extBinder, $res) =>
`(expand_binders% ($x => $term) ($y:extBinder), $res)
| `(expand_binders% ($_ => $_), $res) => pure res
macro_rules
| `(expand_binders% ($x => $term) ($y:ident $[: $ty]?) $binders*, $res) => do
let ty := ty.getD (← `(_))
term.replaceM fun x' ↦ do
unless x == x' do return none
`(fun $y:ident : $ty ↦ expand_binders% ($x => $term) $[$binders]*, $res)
| `(expand_binders% ($x => $term) (_%$ph $[: $ty]?) $binders*, $res) => do
let ty := ty.getD (← `(_))
term.replaceM fun x' ↦ do
unless x == x' do return none
`(fun _%$ph : $ty ↦ expand_binders% ($x => $term) $[$binders]*, $res)
| `(expand_binders% ($x => $term) ($y:binderIdent $pred:binderPred) $binders*, $res) => do
let y ←
match y with
| `(binderIdent| $y:ident) => pure y
| `(binderIdent| _) => Term.mkFreshIdent y
| _ => Macro.throwUnsupported
term.replaceM fun x' ↦ do
unless x == x' do return none
`(fun $y:ident ↦ expand_binders% ($x => $term) (h : satisfies_binder_pred% $y $pred)
$[$binders]*, $res)
macro (name := expandFoldl) "expand_foldl% "
"(" x:ident ppSpace y:ident " => " term:term ") " init:term:max " [" args:term,* "]" : term =>
args.getElems.foldlM (init := init) fun res arg ↦ do
term.replaceM fun e ↦
return if e == x then some res else if e == y then some arg else none
macro (name := expandFoldr) "expand_foldr% "
"(" x:ident ppSpace y:ident " => " term:term ") " init:term:max " [" args:term,* "]" : term =>
args.getElems.foldrM (init := init) fun arg res ↦ do
term.replaceM fun e ↦
return if e == x then some arg else if e == y then some res else none
/-- Keywording indicating whether to use a left- or right-fold. -/
syntax foldKind := &"foldl" <|> &"foldr"
/-- `notation3` argument matching `extBinders`. -/
syntax bindersItem := atomic("(" "..." ")")
/-- `notation3` argument simulating a Lean 3 fold notation. -/
syntax foldAction := "(" ident ppSpace strLit "*" (precedence)? " => " foldKind
" (" ident ppSpace ident " => " term ") " term ")"
/-- `notation3` argument binding a name. -/
syntax identOptScoped :=
ident (notFollowedBy(":" "(" "scoped") precedence)? (":" "(" "scoped " ident " => " term ")")?
/-- `notation3` argument. -/
-- Note: there is deliberately no ppSpace between items
-- so that the space in the literals themselves stands out
syntax notation3Item := strLit <|> bindersItem <|> identOptScoped <|> foldAction
/-! ### Expression matching
A more complicated part of `notation3` is the delaborator generator.
While `notation` relies on generating app unexpanders, we instead generate a
delaborator directly so that we can control how binders are formatted (we want
to be able to know the types of binders, whether a lambda is a constant function,
and whether it is `Prop`-valued, which are not things we can answer once we pass
to app unexpanders).
-/
/-- The dynamic state of a `Matcher`. -/
structure MatchState where
/-- This stores the assignments of variables to subexpressions (and their contexts)
that have been found so far during the course of the matching algorithm.
We store the contexts since we need to delaborate expressions after we leave
scoping constructs. -/
vars : Std.HashMap Name (SubExpr × LocalContext × LocalInstances)
/-- The binders accumulated while matching a `scoped` expression. -/
scopeState : Option (Array (TSyntax ``extBinderParenthesized))
/-- The arrays of delaborated `Term`s accumulated while matching
`foldl` and `foldr` expressions. For `foldl`, the arrays are stored in reverse order. -/
foldState : Std.HashMap Name (Array Term)
/-- A matcher is a delaboration function that transforms `MatchState`s. -/
def Matcher := MatchState → DelabM MatchState
deriving Inhabited
/-- The initial state. -/
def MatchState.empty : MatchState where
vars := {}
scopeState := none
foldState := {}
/-- Evaluate `f` with the given variable's value as the `SubExpr` and within that subexpression's
saved context. Fails if the variable has no value. -/
def MatchState.withVar {α : Type} (s : MatchState) (name : Name)
(m : DelabM α) : DelabM α := do
let some (se, lctx, linsts) := s.vars[name]? | failure
withLCtx lctx linsts <| withTheReader SubExpr (fun _ => se) <| m
/-- Delaborate the given variable's value. Fails if the variable has no value.
If `checkNot` is provided, then checks that the expression being delaborated is not
the given one (this is used to prevent infinite loops). -/
def MatchState.delabVar (s : MatchState) (name : Name) (checkNot? : Option Expr := none) :
DelabM Term :=
s.withVar name do
if let some checkNot := checkNot? then
guard <| checkNot != (← getExpr)
delab
/-- Assign a variable to the current `SubExpr`, capturing the local context. -/
def MatchState.captureSubexpr (s : MatchState) (name : Name) : DelabM MatchState := do
return {s with vars := s.vars.insert name (← readThe SubExpr, ← getLCtx, ← getLocalInstances)}
/-- Get the accumulated array of delaborated terms for a given foldr/foldl.
Returns `#[]` if nothing has been pushed yet. -/
def MatchState.getFoldArray (s : MatchState) (name : Name) : Array Term :=
s.foldState[name]?.getD #[]
/-- Get the accumulated array of delaborated terms for a given foldr/foldl.
Returns `#[]` if nothing has been pushed yet. -/
def MatchState.getBinders (s : MatchState) : Array (TSyntax ``extBinderParenthesized) :=
s.scopeState.getD #[]
/-- Push a delaborated term onto a foldr/foldl array. -/
def MatchState.pushFold (s : MatchState) (name : Name) (t : Term) : MatchState :=
let ts := (s.getFoldArray name).push t
{s with foldState := s.foldState.insert name ts}
/-- Matcher that assigns the current `SubExpr` into the match state;
if a value already exists, then it checks for equality. -/
def matchVar (c : Name) : Matcher := fun s => do
if let some (se, _, _) := s.vars[c]? then
guard <| se.expr == (← getExpr)
return s
else
s.captureSubexpr c
/-- Matcher for an expression satisfying a given predicate. -/
def matchExpr (p : Expr → Bool) : Matcher := fun s => do
guard <| p (← getExpr)
return s
/-- Matcher for `Expr.fvar`.
It checks that the user name agrees and that the type of the expression is matched by `matchTy`. -/
def matchFVar (userName : Name) (matchTy : Matcher) : Matcher := fun s => do
let .fvar fvarId ← getExpr | failure
guard <| userName == (← fvarId.getUserName)
withType (matchTy s)
/-- Matcher that checks that the type of the expression is matched by `matchTy`. -/
def matchTypeOf (matchTy : Matcher) : Matcher := fun s => do
withType (matchTy s)
/-- Matches raw `Nat` literals. -/
def natLitMatcher (n : Nat) : Matcher := fun s => do
guard <| (← getExpr).rawNatLit? == n
return s
/-- Matches applications. -/
def matchApp (matchFun matchArg : Matcher) : Matcher := fun s => do
guard <| (← getExpr).isApp
let s ← withAppFn <| matchFun s
let s ← withAppArg <| matchArg s
return s
/-- Matches pi types. The name `n` should be unique, and `matchBody` should use `n`
as the `userName` of its fvar. -/
def matchForall (matchDom : Matcher) (matchBody : Expr → Matcher) : Matcher := fun s => do
guard <| (← getExpr).isForall
let s ← withBindingDomain <| matchDom s
let s ← withBindingBodyUnusedName' fun _ arg => matchBody arg s
return s
/-- Matches lambdas. The `matchBody` takes the fvar introduced when visiting the body. -/
def matchLambda (matchDom : Matcher) (matchBody : Expr → Matcher) : Matcher := fun s => do
guard <| (← getExpr).isLambda
let s ← withBindingDomain <| matchDom s
let s ← withBindingBodyUnusedName' fun _ arg => matchBody arg s
return s
/-- Adds all the names in `boundNames` to the local context
with types that are fresh metavariables.
This is used for example when initializing `p` in `(scoped p => ...)` when elaborating `...`. -/
def setupLCtx (lctx : LocalContext) (boundNames : Array Name) :
MetaM (LocalContext × Std.HashMap FVarId Name) := do
let mut lctx := lctx
let mut boundFVars := {}
for name in boundNames do
let fvarId ← mkFreshFVarId
lctx := lctx.mkLocalDecl fvarId name (← withLCtx lctx (← getLocalInstances) mkFreshTypeMVar)
boundFVars := boundFVars.insert fvarId name
return (lctx, boundFVars)
/--
Like `Expr.isType`, but uses logic that normalizes the universe level.
Mirrors the core `Sort` delaborator logic.
-/
def isType' : Expr → Bool
| .sort u => u.dec.isSome
| _ => false
/--
Represents a key to use when registering the `delab` attribute for a delaborator.
We use this to handle overapplication.
-/
inductive DelabKey where
/-- The key `app.const` or `app` with a specific arity. -/
| app (const : Option Name) (arity : Nat)
| other (key : Name)
deriving Repr
/--
Turns the `DelabKey` into a key that the `delab` attribute accepts.
-/
def DelabKey.key : DelabKey → Name
| .app none _ => `app
| .app (some n) _ => `app ++ n
| .other key => key
/-- Given an expression, generate a matcher for it.
The `boundFVars` hash map records which state variables certain fvars correspond to.
The `localFVars` hash map records which local variable the matcher should use for an exact
expression match.
If it succeeds generating a matcher, returns
1. a list of keys that should be used for the `delab` attribute
when defining the elaborator
2. a `Term` that represents a `Matcher` for the given expression `e`. -/
partial def exprToMatcher (boundFVars : Std.HashMap FVarId Name)
(localFVars : Std.HashMap FVarId Term) (e : Expr) :
OptionT TermElabM (List DelabKey × Term) := do
match e with
| .mvar .. => return ([], ← `(pure))
| .const n _ => return ([.app n 0], ← ``(matchExpr (Expr.isConstOf · $(quote n))))
| .sort u =>
/-
We should try being more accurate here.
Prop / Type / Type _ / Sort _ is at least an OK approximation.
We mimic the core Sort delaborator `Lean.PrettyPrinter.Delaborator.delabSort`.
-/
let matcher ←
if u.isZero then
``(matchExpr Expr.isProp)
else if e.isType0 then
``(matchExpr Expr.isType0)
else if u.dec.isSome then
``(matchExpr isType')
else
``(matchExpr Expr.isSort)
return ([.other `sort], matcher)
| .fvar fvarId =>
if let some n := boundFVars[fvarId]? then
-- This fvar is a pattern variable.
return ([], ← ``(matchVar $(quote n)))
else if let some s := localFVars[fvarId]? then
-- This fvar is bound by a lambda or forall expression in the pattern itself
return ([], ← ``(matchExpr (· == $s)))
else
let n ← fvarId.getUserName
if n.hasMacroScopes then
-- Match by just the type; this is likely an unnamed instance for example
let (_, m) ← exprToMatcher boundFVars localFVars (← instantiateMVars (← inferType e))
return ([.other `fvar], ← ``(matchTypeOf $m))
else
-- This is an fvar from a `variable`. Match by name and type.
let (_, m) ← exprToMatcher boundFVars localFVars (← instantiateMVars (← inferType e))
return ([.other `fvar], ← ``(matchFVar $(quote n) $m))
| .app .. =>
e.withApp fun f args => do
let (keys, matchF) ←
if let .const n _ := f then
pure ([.app n args.size], ← ``(matchExpr (Expr.isConstOf · $(quote n))))
else
let (_, matchF) ← exprToMatcher boundFVars localFVars f
pure ([.app none args.size], matchF)
let mut fty ← inferType f
let mut matcher := matchF
for arg in args do
fty ← whnf fty
guard fty.isForall
let bi := fty.bindingInfo!
fty := fty.bindingBody!.instantiate1 arg
if bi.isInstImplicit then
-- Assumption: elaborated instances are canonical, so no need to match.
-- The type of the instance is already accounted for by the previous arguments
-- and the type of `f`.
matcher ← ``(matchApp $matcher pure)
else
let (_, matchArg) ← exprToMatcher boundFVars localFVars arg
matcher ← ``(matchApp $matcher $matchArg)
return (keys, matcher)
| .lit (.natVal n) => return ([.other `lit], ← ``(natLitMatcher $(quote n)))
| .forallE n t b bi =>
let (_, matchDom) ← exprToMatcher boundFVars localFVars t
withLocalDecl n bi t fun arg => withFreshMacroScope do
let n' ← `(n)
let body := b.instantiate1 arg
let localFVars' := localFVars.insert arg.fvarId! n'
let (_, matchBody) ← exprToMatcher boundFVars localFVars' body
return ([.other `forallE], ← ``(matchForall $matchDom (fun $n' => $matchBody)))
| .lam n t b bi =>
let (_, matchDom) ← exprToMatcher boundFVars localFVars t
withLocalDecl n bi t fun arg => withFreshMacroScope do
let n' ← `(n)
let body := b.instantiate1 arg
let localFVars' := localFVars.insert arg.fvarId! n'
let (_, matchBody) ← exprToMatcher boundFVars localFVars' body
return ([.other `lam], ← ``(matchLambda $matchDom (fun $n' => $matchBody)))
| _ =>
trace[notation3] "can't generate matcher for {e}"
failure
/-- Returns a `Term` that represents a `Matcher` for the given pattern `stx`.
The `boundNames` set determines which identifiers are variables in the pattern.
Fails in the `OptionT` sense if it comes across something it's unable to handle.
Also returns constant names that could serve as a key for a delaborator.
For example, if it's for a function `f`, then `app.f`. -/
partial def mkExprMatcher (stx : Term) (boundNames : Array Name) :
OptionT TermElabM (List DelabKey × Term) := do
let (lctx, boundFVars) ← setupLCtx (← getLCtx) boundNames
withLCtx lctx (← getLocalInstances) do
let patt ←
try
Term.elabPattern stx none
catch e =>
logException e
trace[notation3] "Could not elaborate pattern{indentD stx}\nError: {e.toMessageData}"
-- Convert the exception into an `OptionT` failure so that the `(prettyPrint := false)`
-- suggestion appears.
failure
trace[notation3] "Generating matcher for pattern {patt}"
exprToMatcher boundFVars {} patt
/-- Matcher for processing `scoped` syntax. Assumes the expression to be matched
against is in the `lit` variable.
Runs `smatcher`, extracts the resulting `scopeId` variable, processes this value
(which must be a lambda) to produce a binder, and loops. -/
partial def matchScoped (lit scopeId : Name) (smatcher : Matcher) : Matcher := go #[] where
/-- Variant of `matchScoped` after some number of `binders` have already been captured. -/
go (binders : Array (TSyntax ``extBinderParenthesized)) : Matcher := fun s => do
-- `lit` is bound to the SubExpr that the `scoped` syntax produced
s.withVar lit do
try
-- Run `smatcher` at `lit`, clearing the `scopeId` variable so that it can get a fresh value
let s ← smatcher {s with vars := s.vars.erase scopeId}
s.withVar scopeId do
guard (← getExpr).isLambda
let prop ← try Meta.isProp (← getExpr).bindingDomain! catch _ => pure false
let isDep := (← getExpr).bindingBody!.hasLooseBVar 0
let ppTypes ← getPPOption getPPPiBinderTypes -- the same option controlling ∀
let dom ← withBindingDomain delab
withBindingBodyUnusedName fun x => do
let x : Ident := ⟨x⟩
let binder ←
if prop && !isDep then
-- this underscore is used to support binder predicates, since it indicates
-- the variable is unused and this binder is safe to merge into another
`(extBinderParenthesized|(_ : $dom))
else if prop || ppTypes then
`(extBinderParenthesized|($x:ident : $dom))
else
`(extBinderParenthesized|($x:ident))
-- Now use the body of the lambda for `lit` for the next iteration
let s ← s.captureSubexpr lit
-- TODO merge binders as an inverse to `satisfies_binder_pred%`
let binders := binders.push binder
go binders s
catch _ =>
guard <| !binders.isEmpty
if let some binders₂ := s.scopeState then
guard <| binders == binders₂ -- TODO: this might be a bit too strict, but it seems to work
return s
else
return {s with scopeState := binders}
/-- Create a `Term` that represents a matcher for `scoped` notation.
Fails in the `OptionT` sense if a matcher couldn't be constructed.
Also returns a delaborator key like in `mkExprMatcher`.
Reminder: `$lit:ident : (scoped $scopedId:ident => $scopedTerm:Term)` -/
partial def mkScopedMatcher (lit scopeId : Name) (scopedTerm : Term) (boundNames : Array Name) :
OptionT TermElabM (List DelabKey × Term) := do
-- Build the matcher for `scopedTerm` with `scopeId` as an additional variable
let (keys, smatcher) ← mkExprMatcher scopedTerm (boundNames.push scopeId)
return (keys, ← ``(matchScoped $(quote lit) $(quote scopeId) $smatcher))
/-- Matcher for expressions produced by `foldl`. -/
partial def matchFoldl (lit x y : Name) (smatcher : Matcher) (sinit : Matcher) :
Matcher := fun s => do
s.withVar lit do
let expr ← getExpr
-- Clear x and y state before running smatcher so it can store new values
let s := {s with vars := s.vars |>.erase x |>.erase y}
let some s ← try some <$> smatcher s catch _ => pure none
| -- We put this here rather than using a big try block to prevent backtracking.
-- We have `smatcher` match greedily, and then require that `sinit` *must* succeed
sinit s
-- y gives the next element of the list
let s := s.pushFold lit (← s.delabVar y expr)
-- x gives the next lit
let some newLit := s.vars[x]? | failure
-- If progress was not made, fail
if newLit.1.expr == expr then failure
-- Progress was made, so recurse
let s := {s with vars := s.vars.insert lit newLit}
matchFoldl lit x y smatcher sinit s
/-- Create a `Term` that represents a matcher for `foldl` notation.
Reminder: `( lit ","* => foldl (x y => scopedTerm) init)` -/
partial def mkFoldlMatcher (lit x y : Name) (scopedTerm init : Term) (boundNames : Array Name) :
OptionT TermElabM (List DelabKey × Term) := do
-- Build the `scopedTerm` matcher with `x` and `y` as additional variables
let boundNames' := boundNames |>.push x |>.push y
let (keys, smatcher) ← mkExprMatcher scopedTerm boundNames'
let (keys', sinit) ← mkExprMatcher init boundNames
return (keys ++ keys', ← ``(matchFoldl $(quote lit) $(quote x) $(quote y) $smatcher $sinit))
/-- Create a `Term` that represents a matcher for `foldr` notation.
Reminder: `( lit ","* => foldr (x y => scopedTerm) init)` -/
partial def mkFoldrMatcher (lit x y : Name) (scopedTerm init : Term) (boundNames : Array Name) :
OptionT TermElabM (List DelabKey × Term) := do
-- Build the `scopedTerm` matcher with `x` and `y` as additional variables
let boundNames' := boundNames |>.push x |>.push y
let (keys, smatcher) ← mkExprMatcher scopedTerm boundNames'
let (keys', sinit) ← mkExprMatcher init boundNames
-- N.B. by swapping `x` and `y` we can just use the foldl matcher
return (keys ++ keys', ← ``(matchFoldl $(quote lit) $(quote y) $(quote x) $smatcher $sinit))
/-! ### The `notation3` command -/
/-- Used when processing different kinds of variables when building the
final delaborator. -/
inductive BoundValueType
/-- A normal variable, delaborate its expression. -/
| normal
/-- A fold variable, use the fold state (but reverse the array). -/
| foldl
/-- A fold variable, use the fold state (do not reverse the array). -/
| foldr
syntax prettyPrintOpt := "(" &"prettyPrint" " := " (&"true" <|> &"false") ")"
/-- Interpret a `prettyPrintOpt`. The default value is `true`. -/
def getPrettyPrintOpt (opt? : Option (TSyntax ``prettyPrintOpt)) : Bool :=
if let some opt := opt? then
match opt with
| `(prettyPrintOpt| (prettyPrint := false)) => false
| _ => true
else
true
/--
If `pp.tagAppFns` is true and the head of the current expression is a constant,
then delaborates the head and uses it for the ref.
This causes tokens inside the syntax to refer to this constant.
A consequence is that docgen will linkify the tokens.
-/
def withHeadRefIfTagAppFns (d : Delab) : Delab := do
let tagAppFns ← getPPOption getPPTagAppFns
if tagAppFns && (← getExpr).getAppFn.consumeMData.isConst then
-- Delaborate the head to register term info and get a syntax we can use for the ref.
-- The syntax `f` itself is thrown away.
let f ← withNaryFn <| withOptionAtCurrPos `pp.tagAppFns true delab
let stx ← withRef f d
-- Annotate to ensure that the full syntax still refers to the whole expression.
annotateTermInfo stx
else
d
/--
`notation3` declares notation using Lean-3-style syntax.
Examples:
```
notation3 "∀ᶠ " (...) " in " f ", " r:(scoped p => Filter.eventually p f) => r
notation3 "MyList[" (x", "* => foldr (a b => MyList.cons a b) MyList.nil) "]" => x
```
By default notation is unable to mention any variables defined using `variable`, but
`local notation3` is able to use such local variables.
Use `notation3 (prettyPrint := false)` to keep the command from generating a pretty printer
for the notation.
This command can be used in mathlib4 but it has an uncertain future and was created primarily
for backward compatibility.
-/
elab (name := notation3) doc:(docComment)? attrs?:(Parser.Term.attributes)? attrKind:Term.attrKind
"notation3" prec?:(precedence)? name?:(namedName)? prio?:(namedPrio)?
pp?:(ppSpace prettyPrintOpt)? items:(ppSpace notation3Item)+ " => " val:term : command => do
-- We use raw `Name`s for variables. This maps variable names back to the
-- identifiers that appear in `items`
let mut boundIdents : Std.HashMap Name Ident := {}
-- Replacements to use for the `macro`
let mut boundValues : Std.HashMap Name Syntax := {}
-- The names of the bound names in order, used when constructing patterns for delaboration.
let mut boundNames : Array Name := #[]
-- The normal/foldl/foldr type of each variable (for delaborator)
let mut boundType : Std.HashMap Name BoundValueType := {}
-- Function to update `syntaxArgs` and `pattArgs` using `macroArg` syntax
let pushMacro (syntaxArgs : Array (TSyntax `stx)) (pattArgs : Array Syntax)
(mac : TSyntax ``macroArg) := do
let (syntaxArg, pattArg) ← expandMacroArg mac
return (syntaxArgs.push syntaxArg, pattArgs.push pattArg)
-- Arguments for the `syntax` command
let mut syntaxArgs := #[]
-- Arguments for the LHS pattern in the `macro`. Also used to construct the syntax
-- when delaborating
let mut pattArgs := #[]
-- The matchers to assemble into a delaborator
let mut matchers := #[]
-- Whether we've seen a `(...)` item
let mut hasBindersItem := false
-- Whether we've seen a `scoped` item
let mut hasScoped := false
for item in items do
match item with
| `(notation3Item| $lit:str) =>
-- Can't use `pushMacro` since it inserts an extra variable into the pattern for `str`, which
-- breaks our delaborator
syntaxArgs := syntaxArgs.push (← `(stx| $lit:str))
pattArgs := pattArgs.push <| mkAtomFrom lit lit.1.isStrLit?.get!
| `(notation3Item| $_:bindersItem) =>
if hasBindersItem then
throwErrorAt item "Cannot have more than one `(...)` item."
hasBindersItem := true
-- HACK: Lean 3 traditionally puts a space after the main binder atom, resulting in
-- notation3 "∑ "(...)", "r:(scoped f => sum f) => r
-- but extBinders already has a space before it so we strip the trailing space of "∑ "
if let `(stx| $lit:str) := syntaxArgs.back! then
syntaxArgs := syntaxArgs.pop.push (← `(stx| $(quote lit.getString.trimRight):str))
(syntaxArgs, pattArgs) ← pushMacro syntaxArgs pattArgs (← `(macroArg| binders:extBinders))
| `(notation3Item| ($id:ident $sep:str* $(prec?)? => $kind ($x $y => $scopedTerm) $init)) =>
(syntaxArgs, pattArgs) ← pushMacro syntaxArgs pattArgs <| ←
`(macroArg| $id:ident:sepBy(term $(prec?)?, $sep:str))
-- N.B. `Syntax.getId` returns `.anonymous` for non-idents
let scopedTerm' ← scopedTerm.replaceM fun s => pure boundValues[s.getId]?
let init' ← init.replaceM fun s => pure boundValues[s.getId]?
boundIdents := boundIdents.insert id.getId id
match kind with
| `(foldKind| foldl) =>
boundValues := boundValues.insert id.getId <| ←
`(expand_foldl% ($x $y => $scopedTerm') $init' [$$(.ofElems $id),*])
boundNames := boundNames.push id.getId
boundType := boundType.insert id.getId .foldl
matchers := matchers.push <|
mkFoldlMatcher id.getId x.getId y.getId scopedTerm init boundNames
| `(foldKind| foldr) =>
boundValues := boundValues.insert id.getId <| ←
`(expand_foldr% ($x $y => $scopedTerm') $init' [$$(.ofElems $id),*])
boundNames := boundNames.push id.getId
boundType := boundType.insert id.getId .foldr
matchers := matchers.push <|
mkFoldrMatcher id.getId x.getId y.getId scopedTerm init boundNames
| _ => throwUnsupportedSyntax
| `(notation3Item| $lit:ident $(prec?)? : (scoped $scopedId:ident => $scopedTerm)) =>
hasScoped := true
(syntaxArgs, pattArgs) ← pushMacro syntaxArgs pattArgs <|←
`(macroArg| $lit:ident:term $(prec?)?)
matchers := matchers.push <|
mkScopedMatcher lit.getId scopedId.getId scopedTerm boundNames
let scopedTerm' ← scopedTerm.replaceM fun s => pure boundValues[s.getId]?
boundIdents := boundIdents.insert lit.getId lit
boundValues := boundValues.insert lit.getId <| ←
`(expand_binders% ($scopedId => $scopedTerm') $$binders:extBinders,
$(⟨lit.1.mkAntiquotNode `term⟩):term)
boundNames := boundNames.push lit.getId
| `(notation3Item| $lit:ident $(prec?)?) =>
(syntaxArgs, pattArgs) ← pushMacro syntaxArgs pattArgs <|←
`(macroArg| $lit:ident:term $(prec?)?)
boundIdents := boundIdents.insert lit.getId lit
boundValues := boundValues.insert lit.getId <| lit.1.mkAntiquotNode `term
boundNames := boundNames.push lit.getId
| _stx => throwUnsupportedSyntax
if hasScoped && !hasBindersItem then
throwError "If there is a `scoped` item then there must be a `(...)` item for binders."
-- 1. The `syntax` command
let fullName ← elabSyntax (← `(command|
$[$doc]? $(attrs?)? $attrKind
syntax $(prec?)? $[$name?:namedName]? $(prio?)? $[$syntaxArgs]* : term))
-- 2. The `macro_rules`
trace[notation3] "syntax declaration has name {fullName}"
let pat : Term := ⟨mkNode fullName pattArgs⟩
let val' ← val.replaceM fun s => pure boundValues[s.getId]?
let mut macroDecl ← `(macro_rules | `($pat) => `($val'))
if isLocalAttrKind attrKind then
-- For local notation, take section variables into account
macroDecl ← `(section set_option quotPrecheck.allowSectionVars true $macroDecl end)
elabCommand macroDecl
-- 3. Create a delaborator
if getPrettyPrintOpt pp? then
matchers := matchers.push <| Mathlib.Notation3.mkExprMatcher val boundNames
-- The matchers need to run in reverse order, so may as well reverse them here.
let matchersM? := (matchers.reverse.mapM id).run
-- We let local notations have access to `variable` declarations
let matchers? ← if isLocalAttrKind attrKind then
runTermElabM fun _ => matchersM?
else
liftTermElabM matchersM?
if let some ms := matchers? then
trace[notation3] "Matcher creation succeeded; assembling delaborator"
let matcher ← ms.foldrM (fun m t => `($(m.2) >=> $t)) (← `(pure))
trace[notation3] "matcher:{indentD matcher}"
let mut result ← `(withHeadRefIfTagAppFns `($pat))
for (name, id) in boundIdents.toArray do
match boundType.getD name .normal with
| .normal => result ← `(MatchState.delabVar s $(quote name) (some e) >>= fun $id => $result)
| .foldl => result ←
`(let $id := (MatchState.getFoldArray s $(quote name)).reverse; $result)
| .foldr => result ←
`(let $id := MatchState.getFoldArray s $(quote name); $result)
if hasBindersItem then
result ← `(`(extBinders| $$(MatchState.getBinders s)*) >>= fun binders => $result)
let delabKeys : List DelabKey := ms.foldr (·.1 ++ ·) []
for key in delabKeys do
trace[notation3] "Creating delaborator for key {repr key}"
let bodyCore ← `(getExpr >>= fun e => $matcher MatchState.empty >>= fun s => $result)
let body ←
match key with
| .app _ arity => ``(withOverApp $(quote arity) $bodyCore)
| _ => pure bodyCore
elabCommand <| ← `(
/-- Pretty printer defined by `notation3` command. -/
@[$attrKind delab $(mkIdent key.key)]
public aux_def delab_app $(mkIdent fullName) : Delab :=
whenPPOption getPPNotation <| whenNotPPOption getPPExplicit <| $body)
else
logWarning s!"\
Was not able to generate a pretty printer for this notation. \
If you do not expect it to be pretty printable, then you can use \
`notation3 (prettyPrint := false)`. \
If the notation expansion refers to section variables, be sure to do `local notation3`. \
Otherwise, you might be able to adjust the notation expansion to make it matchable; \
pretty printing relies on deriving an expression matcher from the expansion. \
(Use `set_option trace.notation3 true` to get some debug information.)"
initialize Batteries.Linter.UnreachableTactic.addIgnoreTacticKind ``«notation3»
/-! `scoped[ns]` support -/
macro_rules
| `($[$doc]? $(attr)? scoped[$ns] notation3 $(prec)? $(n)? $(prio)? $(pp)? $items* => $t) =>
`(with_weak_namespace $(mkIdentFrom ns <| rootNamespace ++ ns.getId)
$[$doc]? $(attr)? scoped notation3 $(prec)? $(n)? $(prio)? $(pp)? $items* => $t)
end Notation3
end Mathlib |
.lake/packages/mathlib/Mathlib/Util/AtLocation.lean | import Mathlib.Init
import Lean.Elab.Tactic.Location
import Lean.Meta.Tactic.Simp.Main
/-!
# Rewriting at specified locations
Many metaprograms have the following general structure: the input is an expression `e` and the
output is a new expression `e'`, together with a proof that `e = e'`.
This file provides convenience functions to turn such a metaprogram into a variety of tactics:
using the metaprogram to modify the goal, a specified hypothesis, or (via `Tactic.Location`) a
combination of these.
-/
/-- Runs the given `atLocal` and `atTarget` methods on each of the locations selected by the given
`loc`.
* If `loc` is a list of locations, runs at each specified hypothesis (and finally the goal if `⊢` is
included), and fails if any of the tactic applications fail.
* If `loc` is `*`, runs at the nondependent `Prop` hypotheses (those produced by
`Lean.MVarId.getNondepPropHyps`) and then at the target.
This is a variant of `Lean.Elab.Tactic.withLocation`. -/
def Lean.Elab.Tactic.withNondepPropLocation (loc : Location) (atLocal : FVarId → TacticM Unit)
(atTarget : TacticM Unit) (failed : MVarId → TacticM Unit) : TacticM Unit := do
match loc with
| Location.targets hyps target => do
(← getFVarIds hyps).forM atLocal
if target then atTarget
| Location.wildcard => do
let mut worked := false
for hyp in ← (← getMainGoal).getNondepPropHyps do
worked := worked || (← tryTactic <| atLocal hyp)
unless worked || (← tryTactic atTarget) do
failed (← getMainGoal)
namespace Mathlib.Tactic
open Lean Meta Elab.Tactic
/-- Use the procedure `m` to rewrite the provided goal. -/
def transformAtTarget (m : Expr → ReaderT Simp.Context MetaM Simp.Result) (proc : String)
(failIfUnchanged : Bool) (goal : MVarId) :
ReaderT Simp.Context MetaM (Option MVarId) := do
let tgt ← instantiateMVars (← goal.getType)
let r ← m tgt
-- we use expression equality here (rather than defeq) to be consistent with, e.g.,
-- `applySimpResultToTarget`
let unchanged := tgt.cleanupAnnotations == r.expr.cleanupAnnotations
if failIfUnchanged && unchanged then throwError "{proc} made no progress on goal"
if r.expr.isTrue then
goal.assign (← mkOfEqTrue (← r.getProof))
pure none
else
-- this ensures that we really get the same goal as an `MVarId`,
-- not a different `MVarId` for which `MVarId.getType` is the same
if unchanged then return goal
applySimpResultToTarget goal tgt r
/-- Use the procedure `m` to rewrite hypothesis `fvarId`.
The `simpTheorems` of the simp-context carried with `m` will be modified to remove `fvarId`;
this ensures that if the procedure `m` involves rewriting by this `SimpTheoremsArray`, then, e.g.,
`h : x = y` is not transformed (by rewriting `h`) to `True`. -/
def transformAtLocalDecl (m : Expr → ReaderT Simp.Context MetaM Simp.Result) (proc : String)
(failIfUnchanged : Bool) (mayCloseGoal : Bool) (fvarId : FVarId) (goal : MVarId) :
ReaderT Simp.Context MetaM (Option MVarId) := do
let ldecl ← fvarId.getDecl
if ldecl.isImplementationDetail then
throwError "cannot run {proc} at {ldecl.userName}, it is an implementation detail"
let tgt ← instantiateMVars (← fvarId.getType)
let eraseFVarId (ctx : Simp.Context) :=
ctx.setSimpTheorems <| ctx.simpTheorems.eraseTheorem (.fvar fvarId)
let r ← withReader eraseFVarId <| m tgt
-- we use expression equality here (rather than defeq) to be consistent with, e.g.,
-- `applySimpResultToLocalDeclCore`
if failIfUnchanged && tgt.cleanupAnnotations == r.expr.cleanupAnnotations then
throwError "{proc} made no progress at {ldecl.userName}"
return (← applySimpResultToLocalDecl goal fvarId r mayCloseGoal).map Prod.snd
/-- Use the procedure `m` to transform at specified locations (hypotheses and/or goal). -/
def transformAtLocation (m : Expr → ReaderT Simp.Context MetaM Simp.Result) (proc : String)
(loc : Location) (failIfUnchanged : Bool := true) (mayCloseGoalFromHyp : Bool := false)
-- streamline the most common use case, in which the procedure `m`'s implementation is not
-- simp-based and its `Simp.Context` is ignored
(ctx : Simp.Context := default) :
TacticM Unit :=
withLocation loc
(liftMetaTactic1 ∘ (transformAtLocalDecl m proc failIfUnchanged mayCloseGoalFromHyp · · ctx))
(liftMetaTactic1 (transformAtTarget m proc failIfUnchanged · ctx))
fun _ ↦ throwError "{proc} made no progress anywhere"
/-- Use the procedure `m` to transform at specified locations (hypotheses and/or goal).
In the wildcard case (`*`), filter out all dependent and/or non-Prop hypotheses. -/
def transformAtNondepPropLocation (m : Expr → ReaderT Simp.Context MetaM Simp.Result)
(proc : String) (loc : Location) (failIfUnchanged : Bool := true)
(mayCloseGoalFromHyp : Bool := false)
-- streamline the most common use case, in which the procedure `m`'s implementation is not
-- simp-based and its `Simp.Context` is ignored
(ctx : Simp.Context := default) :
TacticM Unit :=
withNondepPropLocation loc
(liftMetaTactic1 ∘ (transformAtLocalDecl m proc failIfUnchanged mayCloseGoalFromHyp · · ctx))
(liftMetaTactic1 (transformAtTarget m proc failIfUnchanged · ctx))
fun _ ↦ throwError "{proc} made no progress anywhere"
end Mathlib.Tactic |
.lake/packages/mathlib/Mathlib/Util/PPOptions.lean | import Mathlib.Init
/-!
Mathlib-specific pretty printer options.
-/
namespace Mathlib
open Lean
/--
The `pp.mathlib.binderPredicates` option is used to control whether mathlib pretty printers
should use binder predicate notation (such as `∀ x < 2, p x`).
-/
register_option pp.mathlib.binderPredicates : Bool := {
defValue := true
group := "pp"
descr := "(pretty printer) pretty prints binders such as \
`∀ (x : α) (x < 2), p x` as `∀ x < 2, p x`"
}
/-- Gets whether `pp.mathlib.binderPredicates` is enabled. -/
def getPPBinderPredicates (o : Options) : Bool :=
o.get pp.mathlib.binderPredicates.name (!getPPAll o)
end Mathlib |
.lake/packages/mathlib/Mathlib/Util/GetAllModules.lean | import Mathlib.Init
import Lean.Util.Path
/-!
# Utility functions for finding all `.lean` files or modules in a project.
TODO:
`getLeanLibs` contains a hard-coded choice of which dependencies should be built and which ones
should not. Could this be made more structural and robust, possibly with extra `Lake` support?
-/
open Lean System.FilePath
/-- `getAllFiles git ml` takes all `.lean` files in the directory `ml`
(recursing into sub-directories) and returns the `Array` of `String`s
```
#[file₁, ..., fileₙ]
```
of all their file names. These are not sorted in general.
The input `git` is a `Bool`ean flag:
* `true` means that the command uses `git ls-files` to find the relevant files;
* `false` means that the command recursively scans all dirs searching for `.lean` files.
-/
def getAllFiles (git : Bool) (ml : String) : IO (Array System.FilePath) := do
let ml.lean := addExtension ⟨ml⟩ "lean" -- for example, `Mathlib.lean`
let allModules : Array System.FilePath ← (do
if git then
let mlDir := ml.push pathSeparator -- for example, `Mathlib/`
let allLean ← IO.Process.run { cmd := "git", args := #["ls-files", mlDir ++ "*.lean"] }
return (((allLean.dropRightWhile (· == '\n')).splitOn "\n").map (⟨·⟩)).toArray
else do
let all ← walkDir ml
return all.filter (·.extension == some "lean"))
-- Filter out all files which do not exist.
-- This check is helpful in case the `git` option is on and a local file has been removed.
return ← (allModules.erase ml.lean).filterMapM (fun f ↦ do
if ← pathExists f then pure (some f) else pure none
)
/-- Like `getAllFiles`, but return an array of *module* names instead,
i.e. names of the form `Mathlib/Algebra/Algebra/Basic.lean`.
In addition, these names are sorted in a platform-independent order. -/
def getAllModulesSorted (git : Bool) (ml : String) : IO (Array String) := do
let files ← getAllFiles git ml
let names := ← files.mapM fun f => do
return (← moduleNameOfFileName f none).toString
return names.qsort (· < ·) |
.lake/packages/mathlib/Mathlib/Util/AtomM.lean | import Mathlib.Init
import Lean.Meta.Tactic.Simp.Types
import Qq
/-!
# A monad for tracking and deduplicating atoms
This monad is used by tactics like `ring` and `abel` to keep uninterpreted atoms in a consistent
order, and also to allow unifying atoms up to a specified transparency mode.
Note: this can become very expensive because it is using `isDefEq`.
For performance reasons, consider whether `Lean.Meta.Canonicalizer.canon` can be used instead.
After canonicalizing, a `HashMap Expr Nat` suffices to keep track of previously seen atoms,
and is much faster as it uses `Expr` equality rather than `isDefEq`.
-/
namespace Mathlib.Tactic
open Lean Meta
/-- The context (read-only state) of the `AtomM` monad. -/
structure AtomM.Context where
/-- The reducibility setting for definitional equality of atoms -/
red : TransparencyMode
/-- A simplification to apply to atomic expressions when they are encountered,
before interning them in the atom list. -/
evalAtom : Expr → MetaM Simp.Result := fun e ↦ pure { expr := e }
deriving Inhabited
/-- The mutable state of the `AtomM` monad. -/
structure AtomM.State where
/-- The list of atoms-up-to-defeq encountered thus far, used for atom sorting. -/
atoms : Array Expr := #[]
/-- The monad that `ring` works in. This is only used for collecting atoms. -/
abbrev AtomM := ReaderT AtomM.Context <| StateRefT AtomM.State MetaM
/-- Run a computation in the `AtomM` monad. -/
def AtomM.run {α : Type} (red : TransparencyMode) (m : AtomM α)
(evalAtom : Expr → MetaM Simp.Result := fun e ↦ pure { expr := e }) :
MetaM α :=
(m { red, evalAtom }).run' {}
/-- A safe version of `isDefEq` that doesn't throw errors. We use it to avoid
"unknown free variable '_fvar.102937'" errors when there may be out-of-scope free variables.
TODO: don't catch any other errors
-/
def isDefEqSafe (a b : Expr) : MetaM Bool :=
try isDefEq a b catch _ => pure false
/-- If an atomic expression has already been encountered, get the index and the stored form of the
atom (which will be defeq at the specified transparency, but not necessarily syntactically equal).
If the atomic expression has *not* already been encountered, store it in the list of atoms, and
return the new index (and the stored form of the atom, which will be itself).
In a normalizing tactic, the expression returned by `addAtom` should be considered the normal form.
-/
def AtomM.addAtom (e : Expr) : AtomM (Nat × Expr) := do
let c ← get
for h : i in [:c.atoms.size] do
if ← withTransparency (← read).red <| isDefEqSafe e c.atoms[i] then
return (i, c.atoms[i])
modifyGet fun c ↦ ((c.atoms.size, e), { c with atoms := c.atoms.push e })
open Qq in
/-- If an atomic expression has already been encountered, get the index and the stored form of the
atom (which will be defeq at the specified transparency, but not necessarily syntactically equal).
If the atomic expression has *not* already been encountered, store it in the list of atoms, and
return the new index (and the stored form of the atom, which will be itself).
In a normalizing tactic, the expression returned by `addAtomQ` should be considered the normal form.
This is a strongly-typed version of `AtomM.addAtom` for code using `Qq`.
-/
def AtomM.addAtomQ {u : Level} {α : Q(Type u)} (e : Q($α)) :
AtomM (Nat × {e' : Q($α) // $e =Q $e'}) := do
let (n, e') ← AtomM.addAtom e
return (n, ⟨e', ⟨⟩⟩)
end Mathlib.Tactic |
.lake/packages/mathlib/Mathlib/Util/SleepHeartbeats.lean | import Mathlib.Init
import Lean.Elab.Tactic.Basic
/-!
# Defines `sleep_heartbeats` tactic.
This is useful for testing / debugging long running commands or elaboration in a somewhat precise
manner.
-/
open Lean Elab
/-- A low level command to sleep for at least a given number of heartbeats by running in a loop
until the desired number of heartbeats is hit.
Warning: this function relies on interpreter / compiler
behaviour that is not guaranteed to function in the way that is relied upon here.
As such this function is not to be considered reliable, especially after future updates to Lean.
This should be used with caution and basically only for demo / testing purposes
and not in compiled code without further testing. -/
def sleepAtLeastHeartbeats (n : Nat) : IO Unit := do
let i ← IO.getNumHeartbeats
while (← IO.getNumHeartbeats) < i + n do
continue
/-- do nothing for at least n heartbeats -/
elab "sleep_heartbeats " n:num : tactic => do
match Syntax.isNatLit? n with
| none => throwIllFormedSyntax
/-
We multiply by `1000` to convert the user-facing heartbeat count to the
internal heartbeat counter used by `IO.getNumHeartbeats`.
-/
| some m => sleepAtLeastHeartbeats (m * 1000)
example : 1 = 1 := by
sleep_heartbeats 1000
rfl |
.lake/packages/mathlib/Mathlib/Util/WithWeakNamespace.lean | import Mathlib.Init
/-!
# Defines `with_weak_namespace` command.
Changes the current namespace without causing scoped things to go out of scope.
-/
namespace Lean.Elab.Command
/-- Adds the name to the namespace, `_root_`-aware.
```
resolveNamespace `A `B.b == `A.B.b
resolveNamespace `A `_root_.B.c == `B.c
```
-/
def resolveNamespace (ns : Name) : Name → Name
| `_root_ => Name.anonymous
| Name.str n s .. => Name.mkStr (resolveNamespace ns n) s
| Name.num n i .. => Name.mkNum (resolveNamespace ns n) i
| Name.anonymous => ns
/-- Changes the current namespace without causing scoped things to go out of scope -/
def withWeakNamespace {α : Type} (ns : Name) (m : CommandElabM α) : CommandElabM α := do
let old ← getCurrNamespace
let ns := resolveNamespace old ns
modify fun s ↦ { s with env := s.env.registerNamespace ns }
modifyScope ({ · with currNamespace := ns })
try m finally modifyScope ({ · with currNamespace := old })
/-- Changes the current namespace without causing scoped things to go out of scope -/
elab "with_weak_namespace " ns:ident cmd:command : command =>
withWeakNamespace ns.getId (elabCommand cmd)
end Lean.Elab.Command |
.lake/packages/mathlib/Mathlib/Util/CountHeartbeats.lean | import Mathlib.Init
import Lean.Util.Heartbeats
import Lean.Meta.Tactic.TryThis
/-!
Defines a command wrapper that prints the number of heartbeats used in the enclosed command.
For example
```
#count_heartbeats in
theorem foo : 42 = 6 * 7 := rfl
```
will produce an info message containing a number around 51.
If this number is above the current `maxHeartbeats`, we also print a `Try this:` suggestion.
-/
open Lean Elab Command Meta Linter
namespace Mathlib.CountHeartbeats
-- This file mentions bare `set_option maxHeartbeats` by design: do not warn about this.
set_option linter.style.setOption false
open Tactic
/--
Run a tactic, optionally restoring the original state, and report just the number of heartbeats.
-/
def runTacForHeartbeats (tac : TSyntax `Lean.Parser.Tactic.tacticSeq) (revert : Bool := true) :
TacticM Nat := do
let start ← IO.getNumHeartbeats
let s ← saveState
withOptions (fun opts => opts.set ``Elab.async false) do
evalTactic tac
if revert then restoreState s
return (← IO.getNumHeartbeats) - start
/--
Given a `List Nat`, return the minimum, maximum, and standard deviation.
-/
def variation (counts : List Nat) : List Nat :=
let min := counts.min?.getD 0
let max := counts.max?.getD 0
let toFloat (n : Nat) := n.toUInt64.toFloat
let toNat (f : Float) := f.toUInt64.toNat
let counts' := counts.map toFloat
let μ : Float := counts'.foldl (· + ·) 0 / toFloat counts.length
let stddev : Float := Float.sqrt <|
((counts'.map fun i => (i - μ)^2).foldl (· + ·) 0) / toFloat counts.length
[min, max, toNat stddev]
/--
Given a `List Nat`, log an info message with the minimum, maximum, and standard deviation.
-/
def logVariation {m} [Monad m] [MonadLog m] [AddMessageContext m] [MonadOptions m]
(counts : List Nat) : m Unit := do
if let [min, max, stddev] := variation counts then
-- convert `[min, max, stddev]` to user-facing heartbeats
logInfo s!"Min: {min / 1000} Max: {max / 1000} StdDev: {stddev / 10}%"
/-- Count the heartbeats used by a tactic, e.g.: `#count_heartbeats simp`. -/
elab "#count_heartbeats " tac:tacticSeq : tactic => do
logInfo s!"{← runTacForHeartbeats tac (revert := false)}"
/--
`#count_heartbeats! in tac` runs a tactic 10 times, counting the heartbeats used, and logs the range
and standard deviation. The tactic `#count_heartbeats! n in tac` runs it `n` times instead.
-/
elab "#count_heartbeats! " n:(num)? "in" ppLine tac:tacticSeq : tactic => do
let n := match n with
| some j => j.getNat
| none => 10
-- First run the tactic `n-1` times, reverting the state.
let counts ← (List.range (n - 1)).mapM fun _ => runTacForHeartbeats tac
-- Then run once more, keeping the state.
let counts := (← runTacForHeartbeats tac (revert := false)) :: counts
logVariation counts
/--
Round down the number `n` to the nearest thousand, if `approx` is `true`.
-/
def roundDownIf (n : Nat) (approx : Bool) : String :=
if approx then s!"approximately {(n / 1000) * 1000}" else s!"{n}"
set_option linter.style.maxHeartbeats false in
/--
`#count_heartbeats in cmd` counts the heartbeats used in the enclosed command `cmd`.
Use `#count_heartbeats` to count the heartbeats in *all* the following declarations.
This is most useful for setting sufficient but reasonable limits via `set_option maxHeartbeats`
for long-running declarations.
If you do so, please resist the temptation to set the limit as low as possible.
As the `simp` set and other features of the library evolve,
other contributors will find that their (likely unrelated) changes
have pushed the declaration over the limit.
`count_heartbeats in` will automatically suggest a `set_option maxHeartbeats` via "Try this:"
using the least number of the form `2^k * 200000` that suffices.
Note that the internal heartbeat counter accessible via `IO.getNumHeartbeats`
has granularity 1000 times finer than the limits set by `set_option maxHeartbeats`.
As this is intended as a user command, we divide by 1000.
The optional `approximately` keyword rounds down the heartbeats to the nearest thousand.
This helps make the tests more stable to small changes in heartbeats.
To use this functionality, use `#count_heartbeats approximately in cmd`.
-/
elab "#count_heartbeats " approx:(&"approximately ")? "in" ppLine cmd:command : command => do
let start ← IO.getNumHeartbeats
try
elabCommand (← `(command| set_option maxHeartbeats 0 in $cmd))
finally
let finish ← IO.getNumHeartbeats
let elapsed := (finish - start) / 1000
let roundElapsed := roundDownIf elapsed approx.isSome
let max := (← Command.liftCoreM getMaxHeartbeats) / 1000
if elapsed < max then
logInfo
m!"Used {roundElapsed} heartbeats, which is less than the current maximum of {max}."
else
let mut max' := max
while max' < elapsed do
max' := 2 * max'
logInfo
m!"Used {roundElapsed} heartbeats, which is greater than the current maximum of {max}."
let m : TSyntax `num := quote max'
Command.liftCoreM <| MetaM.run' do
Lean.Meta.Tactic.TryThis.addSuggestion (← getRef)
(← set_option hygiene false in `(command| set_option maxHeartbeats $m in $cmd))
set_option linter.style.maxHeartbeats false in
/--
Guard the minimal number of heartbeats used in the enclosed command.
This is most useful in the context of debugging and minimizing an example of a slow declaration.
By guarding the number of heartbeats used in the slow declaration,
an error message will be generated if a minimization step makes the slow behaviour go away.
The default number of minimal heartbeats is the value of `maxHeartbeats` (typically 200000).
Alternatively, you can specify a number of heartbeats to guard against,
using the syntax `guard_min_heartbeats n in cmd`.
The optional `approximately` keyword rounds down the heartbeats to the nearest thousand.
This helps make the tests more stable to small changes in heartbeats.
To use this functionality, use `guard_min_heartbeats approximately (n)? in cmd`.
-/
elab "guard_min_heartbeats " approx:(&"approximately ")? n:(num)? "in" ppLine cmd:command :
command => do
let max := (← Command.liftCoreM getMaxHeartbeats) / 1000
let n := match n with
| some j => j.getNat
| none => max
let start ← IO.getNumHeartbeats
try
elabCommand (← `(command| set_option Elab.async false in set_option maxHeartbeats 0 in $cmd))
finally
let finish ← IO.getNumHeartbeats
let elapsed := (finish - start) / 1000
if elapsed < n then
logInfo m!"Used {roundDownIf elapsed approx.isSome} heartbeats, \
which is less than the minimum of {n}."
set_option linter.style.maxHeartbeats false in
/--
Run a command, optionally restoring the original state, and report just the number of heartbeats.
-/
def elabForHeartbeats (cmd : TSyntax `command) (revert : Bool := true) : CommandElabM Nat := do
let start ← IO.getNumHeartbeats
let s ← get
elabCommand (← `(command| set_option maxHeartbeats 0 in $cmd))
if revert then set s
return (← IO.getNumHeartbeats) - start
/--
`#count_heartbeats! in cmd` runs a command `10` times, reporting the range in heartbeats, and the
standard deviation. The command `#count_heartbeats! n in cmd` runs it `n` times instead.
Example usage:
```
#count_heartbeats! in
def f := 37
```
displays the info message `Min: 7 Max: 8 StdDev: 14%`.
-/
elab "#count_heartbeats! " n:(num)? "in" ppLine cmd:command : command => do
let n := match n with
| some j => j.getNat
| none => 10
-- First run the command `n-1` times, reverting the state.
let counts ← (List.range (n - 1)).mapM fun _ => elabForHeartbeats cmd
-- Then run once more, keeping the state.
let counts := (← elabForHeartbeats cmd (revert := false)) :: counts
logVariation counts
end CountHeartbeats
end Mathlib
/-!
# The "countHeartbeats" linter
The "countHeartbeats" linter counts the heartbeats of every declaration.
-/
namespace Mathlib.Linter
/--
The "countHeartbeats" linter counts the heartbeats of every declaration.
The effect of the linter is similar to `#count_heartbeats in xxx`, except that it applies
to all declarations.
Note that the linter only counts heartbeats in "top-level" declarations:
it looks inside `set_option ... in`, but not, for instance, inside `mutual` blocks.
There is a convenience notation `#count_heartbeats` that simply sets the linter option to true.
-/
register_option linter.countHeartbeats : Bool := {
defValue := false
descr := "enable the countHeartbeats linter"
}
/--
An option used by the `countHeartbeats` linter: if set to `true`, then the countHeartbeats linter
rounds down to the nearest 1000 the heartbeat count.
-/
register_option linter.countHeartbeatsApprox : Bool := {
defValue := false
descr := "if set to `true`, then the countHeartbeats linter rounds down \
to the nearest 1000 the heartbeat count"
}
namespace CountHeartbeats
@[inherit_doc Mathlib.Linter.linter.countHeartbeats]
def countHeartbeatsLinter : Linter where run := withSetOptionIn fun stx ↦ do
unless getLinterValue linter.countHeartbeats (← getLinterOptions) do
return
if (← get).messages.hasErrors then
return
let mut msgs := #[]
if [``Lean.Parser.Command.declaration, `lemma].contains stx.getKind then
let s ← get
if getLinterValue linter.countHeartbeatsApprox (← getLinterOptions) then
elabCommand (← `(command| #count_heartbeats approximately in $(⟨stx⟩)))
else
elabCommand (← `(command| #count_heartbeats in $(⟨stx⟩)))
msgs := (← get).messages.unreported.toArray.filter (·.severity != .error)
set s
match stx.find? (·.isOfKind ``Parser.Command.declId) with
| some decl =>
for msg in msgs do logInfoAt decl m!"'{decl[0].getId}' {(← msg.toString).decapitalize}"
| none =>
for msg in msgs do logInfoAt stx m!"{← msg.toString}"
initialize addLinter countHeartbeatsLinter
@[inherit_doc Mathlib.Linter.linter.countHeartbeats]
macro "#count_heartbeats" approx:(&" approximately")? : command => do
let approx ←
if approx.isSome then
`(set_option linter.countHeartbeatsApprox true) else
`(set_option linter.countHeartbeatsApprox false)
return ⟨mkNullNode
#[← `(command| set_option linter.countHeartbeats true),
approx]⟩
end CountHeartbeats
end Mathlib.Linter |
.lake/packages/mathlib/Mathlib/Util/AssertExists.lean | import Mathlib.Init
import Lean.Elab.Command
import Mathlib.Util.AssertExistsExt
/-!
# User commands to assert the (non-)existence of declarations or instances.
These commands are used to enforce the independence of different parts of mathlib.
## TODO
Potentially reimplement the mathlib 3 linters to check that declarations asserted
not to exist do eventually exist.
Implement `assert_instance` and `assert_no_instance`.
-/
section
open Lean Elab Meta Command
namespace Mathlib.AssertNotExist
/-- `#check_assertions` retrieves all declarations and all imports that were declared
not to exist so far (including in transitively imported files) and reports their current
status:
* ✓ means the declaration or import exists,
* × means the declaration or import does not exist.
This means that the expectation is that all checks *succeed* by the time `#check_assertions`
is used, typically once all of `Mathlib` has been built.
If all declarations and imports are available when `#check_assertions` is used,
then the command logs an info message. Otherwise, it emits a warning.
The variant `#check_assertions!` only prints declarations/imports that are not present in the
environment. In particular, it is silent if everything is imported, making it useful for testing.
-/
elab "#check_assertions" tk:("!")? : command => do
let env ← getEnv
let entries := env.getSortedAssertExists
if entries.isEmpty && tk.isNone then logInfo "No assertions made." else
let allMods := env.allImportedModuleNames
let mut msgs := #[m!""]
let mut outcome := m!""
let mut allExist? := true
for d in entries do
let type := if d.isDecl then "declaration" else "module"
let cond := if d.isDecl then env.contains d.givenName else allMods.contains d.givenName
outcome := if cond then m!"{checkEmoji}" else m!"{crossEmoji}"
allExist? := allExist? && cond
if tk.isNone || !cond then
msgs := msgs.push m!"{outcome} '{d.givenName}' ({type}) asserted in '{d.modName}'."
msgs := msgs.push m!"---"
|>.push m!"{checkEmoji} means the declaration or import exists."
|>.push m!"{crossEmoji} means the declaration or import does not exist."
let msg := MessageData.joinSep msgs.toList "\n"
if allExist? && tk.isNone then
logInfo msg
if !allExist? then
logWarning msg
end Mathlib.AssertNotExist
/--
`assert_exists n` is a user command that asserts that a declaration named `n` exists
in the current import scope.
Be careful to use names (e.g. `Rat`) rather than notations (e.g. `ℚ`).
-/
elab "assert_exists " n:ident : command => do
-- this throws an error if the user types something ambiguous or
-- something that doesn't exist, otherwise succeeds
let _ ← liftCoreM <| realizeGlobalConstNoOverloadWithInfo n
/-- `importPathMessage env idx` produces a message laying out an import chain from `idx` to the
current module. The output is of the form
```
Mathlib.Init,
which is imported by Mathlib.Util.AssertExistsExt,
which is imported by Mathlib.Util.AssertExists,
which is imported by this file.
```
if `env` is an `Environment` and `idx` is the module index of `Mathlib.Init`.
-/
def importPathMessage (env : Environment) (idx : ModuleIdx) : MessageData :=
let modNames := env.header.moduleNames
let msg := (env.importPath modNames[idx]!).foldl (init := m!"{modNames[idx]!},")
(· ++ m!"\n which is imported by {·},")
msg ++ m!"\n which is imported by this file."
/--
`assert_not_exists d₁ d₂ ... dₙ` is a user command that asserts that the declarations named
`d₁ d₂ ... dₙ` *do not exist* in the current import scope.
Be careful to use names (e.g. `Rat`) rather than notations (e.g. `ℚ`).
It may be used (sparingly!) in mathlib to enforce plans that certain files
are independent of each other.
If you encounter an error on an `assert_not_exists` command while developing mathlib,
it is probably because you have introduced new import dependencies to a file.
In this case, you should refactor your work
(for example by creating new files rather than adding imports to existing files).
You should *not* delete the `assert_not_exists` statement without careful discussion ahead of time.
`assert_not_exists` statements should generally live at the top of the file, after the module doc.
-/
elab "assert_not_exists " ns:ident+ : command => do
let env ← getEnv
for n in ns do
let decl ←
try liftCoreM <| realizeGlobalConstNoOverloadWithInfo n
catch _ =>
Mathlib.AssertNotExist.addDeclEntry true n.getId (← getMainModule)
continue
let c ← mkConstWithLevelParams decl
let msg ← (do
let mut some idx := env.getModuleIdxFor? decl
| pure m!"Declaration {c} is defined in this file."
pure m!"Declaration {c} is not allowed to be imported by this file.\n\
It is defined in {importPathMessage env idx}")
logErrorAt n m!"{msg}\n\n\
These invariants are maintained by `assert_not_exists` statements, \
and exist in order to ensure that \"complicated\" parts of the library \
are not accidentally introduced as dependencies of \"simple\" parts of the library."
/-- `assert_not_imported m₁ m₂ ... mₙ` checks that each one of the modules `m₁ m₂ ... mₙ` is not
among the transitive imports of the current file.
The command does not currently check whether the modules `m₁ m₂ ... mₙ` actually exist.
-/
-- TODO: make sure that each one of `m₁ m₂ ... mₙ` is the name of an actually existing module!
elab "assert_not_imported " ids:ident+ : command => do
let env ← getEnv
for id in ids do
if let some idx := env.getModuleIdx? id.getId then
logWarningAt id
m!"the module '{id}' is (transitively) imported via\n{importPathMessage env idx}"
else
Mathlib.AssertNotExist.addDeclEntry false id.getId (← getMainModule)
end |
.lake/packages/mathlib/Mathlib/Util/Superscript.lean | import Mathlib.Init
import Batteries.Tactic.Lint
/-!
# A parser for superscripts and subscripts
This is intended for use in local notations. Basic usage is:
```
local syntax:arg term:max superscript(term) : term
local macro_rules | `($a:term $b:superscript) => `($a ^ $b)
```
where `superscript(term)` indicates that it will parse a superscript, and the `$b:superscript`
antiquotation binds the `term` argument of the superscript. Given a notation like this,
the expression `2⁶⁴` parses and expands to `2 ^ 64`.
The superscript body is considered to be the longest contiguous sequence of superscript tokens and
whitespace, so no additional bracketing is required (unless you want to separate two superscripts).
However, note that Unicode has a rather restricted character set for superscripts and subscripts
(see `Mapping.superscript` and `Mapping.subscript` in this file), so you should not use this
parser for complex expressions.
-/
universe u
namespace Mathlib.Tactic
open Lean Parser PrettyPrinter Delaborator Std
namespace Superscript
instance : Hashable Char := ⟨fun c => hash c.1⟩
/-- A bidirectional character mapping. -/
structure Mapping where
/-- Map from "special" (e.g. superscript) characters to "normal" characters. -/
toNormal : Std.HashMap Char Char := {}
/-- Map from "normal" text to "special" (e.g. superscript) characters. -/
toSpecial : Std.HashMap Char Char := {}
deriving Inhabited
/-- Constructs a mapping (intended for compile time use). Panics on violated invariants. -/
def mkMapping (s₁ s₂ : String) : Mapping := Id.run do
let mut toNormal := {}
let mut toSpecial := {}
assert! s₁.length == s₂.length
for sp in s₁.toSubstring, nm in s₂ do
assert! !toNormal.contains sp
assert! !toSpecial.contains nm
toNormal := toNormal.insert sp nm
toSpecial := toSpecial.insert nm sp
pure { toNormal, toSpecial }
/-- A mapping from superscripts to and from regular text. -/
def Mapping.superscript := mkMapping
"⁰¹²³⁴⁵⁶⁷⁸⁹ᵃᵇᶜᵈᵉᶠᵍʰⁱʲᵏˡᵐⁿᵒᵖ𐞥ʳˢᵗᵘᵛʷˣʸᶻᴬᴮᴰᴱᴳᴴᴵᴶᴷᴸᴹᴺᴼᴾꟴᴿᵀᵁⱽᵂᵝᵞᵟᵋᶿᶥᶹᵠᵡ⁺⁻⁼⁽⁾"
"0123456789abcdefghijklmnopqrstuvwxyzABDEGHIJKLMNOPQRTUVWβγδεθιυφχ+-=()"
/-- A mapping from subscripts to and from regular text. -/
def Mapping.subscript := mkMapping
"₀₁₂₃₄₅₆₇₈₉ₐₑₕᵢⱼₖₗₘₙₒₚᵣₛₜᵤᵥₓᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘꞯʀꜱᴛᴜᴠᴡʏᴢᵦᵧᵨᵩᵪ₊₋₌₍₎"
"0123456789aehijklmnoprstuvxABCDEFGHIJKLMNOPQRSTUVWYZβγρφχ+-=()"
/-- Collects runs of text satisfying `p` followed by whitespace. Fails if the first character does
not satisfy `p`. If `many` is true, it will parse 1 or more many whitespace-separated runs,
otherwise it will parse only 1. If successful, it passes the result to `k` as an array `(a, b, c)`
where `a..b` is a token and `b..c` is whitespace.
-/
partial def satisfyTokensFn (p : Char → Bool) (errorMsg : String) (many := true)
(k : Array (String.Pos.Raw × String.Pos.Raw × String.Pos.Raw) → ParserState → ParserState) :
ParserFn := fun c s =>
let start := s.pos
let s := takeWhile1Fn p errorMsg c s
if s.hasError then s else
let stop := s.pos
let s := whitespace c s
let toks := #[(start, stop, s.pos)]
if many then
let rec /-- Loop body of `satisfyTokensFn` -/
loop (toks) (s : ParserState) : ParserState :=
let start := s.pos
let s := takeWhileFn p c s
if s.pos == start then k toks s else
let stop := s.pos
let s := whitespace c s
let toks := toks.push (start, stop, s.pos)
loop toks s
loop toks s
else k toks s
variable {α : Type u} [Inhabited α] (as : Array α) (leftOfPartition : α → Bool) in
/-- Given a predicate `leftOfPartition` which is true for indexes `< i` and false for `≥ i`,
returns `i`, by binary search. -/
@[specialize]
def partitionPoint (lo := 0) (hi := as.size) : Nat :=
if lo < hi then
let m := (lo + hi)/2
let a := as[m]!
if leftOfPartition a then
partitionPoint (m+1) hi
else
partitionPoint lo m
else lo
termination_by hi - lo
/-- The core function for super/subscript parsing. It consists of three stages:
1. Parse a run of superscripted characters, skipping whitespace and stopping when we hit a
non-superscript character.
2. Un-superscript the text and pass the body to the inner parser (usually `term`).
3. Take the resulting `Syntax` object and align all the positions to fit back into the original
text (which as a side effect also rewrites all the substrings to be in subscript text).
If `many` is false, then whitespace (and comments) are not allowed inside the superscript.
-/
partial def scriptFnNoAntiquot (m : Mapping) (errorMsg : String) (p : ParserFn)
(many := true) : ParserFn := fun c s =>
let start := s.pos
satisfyTokensFn m.toNormal.contains errorMsg many c s (k := fun toks s => Id.run do
let mut newStr := ""
-- This consists of a sorted array of `(from, to)` pairs, where indexes `from+i` in `newStr`
-- such that `from+i < from'` for the next element of the array, are mapped to `to+i`.
let mut aligns := #[((0 : String.Pos.Raw), start)]
for (start, stopTk, stopWs) in toks do
let mut pos := start
while pos < stopTk do
let ch := c.get pos
let ch' := m.toNormal[ch]!
newStr := newStr.push ch'
pos := pos + ch
if ch.utf8Size != ch'.utf8Size then
aligns := aligns.push (newStr.endPos, pos)
newStr := newStr.push ' '
if stopWs.1 - stopTk.1 != 1 then
aligns := aligns.push (newStr.endPos, stopWs)
let ictx := mkInputContext newStr "<superscript>"
let s' := p.run ictx c.toParserModuleContext c.tokens (mkParserState newStr)
let rec /-- Applies the alignment mapping to a position. -/
align (pos : String.Pos.Raw) :=
let i := partitionPoint aligns (·.1 ≤ pos)
let (a, b) := aligns[i - 1]!
pos.unoffsetBy a |>.offsetBy b
let s := { s with pos := align s'.pos, errorMsg := s'.errorMsg }
if s.hasError then return s
let rec
/-- Applies the alignment mapping to a `Substring`. -/
alignSubstr : Substring → Substring
| ⟨_newStr, start, stop⟩ => c.substring (align start) (align stop),
/-- Applies the alignment mapping to a `SourceInfo`. -/
alignInfo : SourceInfo → SourceInfo
| .original leading pos trailing endPos =>
-- Marking these as original breaks semantic highlighting,
-- marking them as canonical breaks the unused variables linter. :(
.original (alignSubstr leading) (align pos) (alignSubstr trailing) (align endPos)
| .synthetic pos endPos canonical =>
.synthetic (align pos) (align endPos) canonical
| .none => .none,
/-- Applies the alignment mapping to a `Syntax`. -/
alignSyntax : Syntax → Syntax
| .missing => .missing
| .node info kind args => .node (alignInfo info) kind (args.map alignSyntax)
| .atom info val =>
-- We have to preserve the unsubscripted `val` even though it breaks `Syntax.reprint`
-- because basic parsers like `num` read the `val` directly
.atom (alignInfo info) val
| .ident info rawVal val preresolved =>
.ident (alignInfo info) (alignSubstr rawVal) val preresolved
s.pushSyntax (alignSyntax s'.stxStack.back)
)
/-- The super/subscript parser.
* `m`: the character mapping
* `antiquotName`: the name to use for antiquotation bindings `$a:antiquotName`.
Note that the actual syntax kind bound will be the body kind (parsed by `p`), not `kind`.
* `errorMsg`: shown when the parser does not match
* `p`: the inner parser (usually `term`), to be called on the body of the superscript
* `many`: if false, whitespace is not allowed inside the superscript
* `kind`: the term will be wrapped in a node with this kind;
generally this is a name of the parser declaration itself.
-/
def scriptParser (m : Mapping) (antiquotName errorMsg : String) (p : Parser)
(many := true) (kind : SyntaxNodeKind := by exact decl_name%) : Parser :=
let tokens := "$" :: (m.toNormal.toArray.map (·.1.toString) |>.qsort (·<·)).toList
let antiquotP := mkAntiquot antiquotName `term (isPseudoKind := true)
let p := Superscript.scriptFnNoAntiquot m errorMsg p.fn many
node kind {
info.firstTokens := .tokens tokens
info.collectTokens := (tokens ++ ·)
fn := withAntiquotFn antiquotP.fn p (isCatAntiquot := true)
}
/-- Parenthesizer for the script parser. -/
def scriptParser.parenthesizer (k : SyntaxNodeKind) (p : Parenthesizer) : Parenthesizer :=
Parenthesizer.node.parenthesizer k p
/-- Map over the strings in a `Format`. -/
def _root_.Std.Format.mapStringsM {m} [Monad m] (f : Format) (f' : String → m String) : m Format :=
match f with
| .group f b => (.group · b) <$> Std.Format.mapStringsM f f'
| .tag t g => .tag t <$> Std.Format.mapStringsM g f'
| .append f g => .append <$> Std.Format.mapStringsM f f' <*> Std.Format.mapStringsM g f'
| .nest n f => .nest n <$> Std.Format.mapStringsM f f'
| .text s => .text <$> f' s
| .align _ | .line | .nil => pure f
/-- Formatter for the script parser. -/
def scriptParser.formatter (name : String) (m : Mapping) (k : SyntaxNodeKind) (p : Formatter) :
Formatter := do
let stack ← modifyGet fun s => (s.stack, {s with stack := #[]})
Formatter.node.formatter k p
let st ← get
let transformed : Except String _ := st.stack.mapM (·.mapStringsM fun s => do
let some s := s.toList.mapM (m.toSpecial.insert ' ' ' ').get? | .error s
.ok s.asString)
match transformed with
| .error err =>
-- TODO: this only appears if the caller explicitly calls the pretty-printer
Lean.logErrorAt (← get).stxTrav.cur s!"Not a {name}: '{err}'"
set { st with stack := stack ++ st.stack }
| .ok newStack =>
set { st with stack := stack ++ newStack }
end Superscript
/--
The parser `superscript(term)` parses a superscript. Basic usage is:
```
local syntax:arg term:max superscript(term) : term
local macro_rules | `($a:term $b:superscript) => `($a ^ $b)
```
Given a notation like this, the expression `2⁶⁴` parses and expands to `2 ^ 64`.
Note that because of Unicode limitations, not many characters can actually be typed inside the
superscript, so this should not be used for complex expressions. Legal superscript characters:
```
⁰¹²³⁴⁵⁶⁷⁸⁹ᵃᵇᶜᵈᵉᶠᵍʰⁱʲᵏˡᵐⁿᵒᵖ𐞥ʳˢᵗᵘᵛʷˣʸᶻᴬᴮᴰᴱᴳᴴᴵᴶᴷᴸᴹᴺᴼᴾꟴᴿᵀᵁⱽᵂᵝᵞᵟᵋᶿᶥᶹᵠᵡ⁺⁻⁼⁽⁾
```
-/
def superscript (p : Parser) : Parser :=
Superscript.scriptParser .superscript "superscript" "expected superscript character" p
/-- Formatter for the superscript parser. -/
@[combinator_parenthesizer superscript]
def superscript.parenthesizer := Superscript.scriptParser.parenthesizer ``superscript
/-- Formatter for the superscript parser. -/
@[combinator_formatter superscript]
def superscript.formatter :=
Superscript.scriptParser.formatter "superscript" .superscript ``superscript
/-- Shorthand for `superscript(term)`.
This is needed because the initializer below does not always run, and if it has not run then
downstream parsers using the combinators will crash.
See https://leanprover.zulipchat.com/#narrow/channel/270676-lean4/topic/Non-builtin.20parser.20aliases/near/365125476
for some context. -/
@[term_parser]
def superscriptTerm := leading_parser (withAnonymousAntiquot := false) superscript termParser
initialize register_parser_alias superscript
/--
The parser `subscript(term)` parses a subscript. Basic usage is:
```
local syntax:arg term:max subscript(term) : term
local macro_rules | `($a:term $i:subscript) => `($a $i)
```
Given a notation like this, the expression `(a)ᵢ` parses and expands to `a i`. (Either parentheses
or a whitespace as in `a ᵢ` is required, because `aᵢ` is considered as an identifier.)
Note that because of Unicode limitations, not many characters can actually be typed inside the
subscript, so this should not be used for complex expressions. Legal subscript characters:
```
₀₁₂₃₄₅₆₇₈₉ₐₑₕᵢⱼₖₗₘₙₒₚᵣₛₜᵤᵥₓᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘꞯʀꜱᴛᴜᴠᴡʏᴢᵦᵧᵨᵩᵪ₊₋₌₍₎
```
-/
def subscript (p : Parser) : Parser :=
Superscript.scriptParser .subscript "subscript" "expected subscript character" p
/-- Formatter for the subscript parser. -/
@[combinator_parenthesizer subscript]
def subscript.parenthesizer := Superscript.scriptParser.parenthesizer ``subscript
/-- Formatter for the subscript parser. -/
@[combinator_formatter subscript]
def subscript.formatter := Superscript.scriptParser.formatter "subscript" .subscript ``subscript
/-- Shorthand for `subscript(term)`.
This is needed because the initializer below does not always run, and if it has not run then
downstream parsers using the combinators will crash.
See https://leanprover.zulipchat.com/#narrow/channel/270676-lean4/topic/Non-builtin.20parser.20aliases/near/365125476
for some context. -/
@[term_parser]
def subscriptTerm := leading_parser (withAnonymousAntiquot := false) subscript termParser
initialize register_parser_alias subscript
/-- Returns true if every character in `stx : Syntax` can be superscripted
(or subscripted). -/
private partial def Superscript.isValid (m : Mapping) : Syntax → Bool
| .node _ kind args => kind == hygieneInfoKind || (!(scripted kind) && args.all (isValid m))
| .atom _ s => valid s
| .ident _ _ s _ => valid s.toString
| _ => false
where
valid (s : String) : Bool :=
s.all ((m.toSpecial.insert ' ' ' ').contains ·)
scripted : SyntaxNodeKind → Bool :=
#[``subscript, ``superscript].contains
/-- Successfully delaborates only if the resulting expression can be superscripted.
See `Mapping.superscript` in this file for legal superscript characters. -/
def delabSuperscript : Delab := do
let stx ← delab
if Superscript.isValid .superscript stx.raw then pure stx else failure
/-- Successfully delaborates only if the resulting expression can be subscripted.
See `Mapping.subscript` in this file for legal subscript characters. -/
def delabSubscript : Delab := do
let stx ← delab
if Superscript.isValid .subscript stx.raw then pure stx else failure
end Mathlib.Tactic |
.lake/packages/mathlib/Mathlib/Util/Delaborators.lean | import Mathlib.Init
import Mathlib.Util.PPOptions
import Lean.PrettyPrinter.Delaborator.Builtins
/-! # Pi type notation
Provides the `Π x : α, β x` notation as an alternative to Lean 4's built-in
`(x : α) → β x` notation. To get all non-`∀` pi types to pretty print this way
then do `open scoped PiNotation`.
The notation also accepts extended binders, like `Π x ∈ s, β x` for `Π x, x ∈ s → β x`.
This can be disabled with the `pp.mathlib.binderPredicates` option.
-/
namespace PiNotation
open Lean hiding binderIdent
open Lean.Parser Term
open Lean.PrettyPrinter.Delaborator
open Mathlib
/-- Dependent function type (a "pi type"). The notation `Π x : α, β x` can
also be written as `(x : α) → β x`. -/
-- A direct copy of forall notation but with `Π`/`Pi` instead of `∀`/`Forall`.
@[term_parser]
def piNotation := leading_parser:leadPrec
unicodeSymbol "Π" "PiType" >>
many1 (ppSpace >> (binderIdent <|> bracketedBinder)) >>
optType >> ", " >> termParser
/-- Dependent function type (a "pi type"). The notation `Π x ∈ s, β x` is
short for `Π x, x ∈ s → β x`. -/
-- A copy of forall notation from `Batteries.Util.ExtendedBinder` for pi notation
syntax "Π " binderIdent binderPred ", " term : term
macro_rules
| `(Π $x:ident $pred:binderPred, $p) => `(Π $x:ident, satisfies_binder_pred% $x $pred → $p)
| `(Π _ $pred:binderPred, $p) => `(Π x, satisfies_binder_pred% x $pred → $p)
/-- Since pi notation and forall notation are interchangeable, we can
parse it by simply using the pre-existing forall parser. -/
@[macro PiNotation.piNotation] def replacePiNotation : Lean.Macro
| .node info _ args => return .node info ``Lean.Parser.Term.forall args
| _ => Lean.Macro.throwUnsupported
/-- Override the Lean 4 pi notation delaborator with one that prints cute binders
such as `∀ ε > 0`. -/
@[delab forallE]
def delabPi : Delab := whenPPOption getPPBinderPredicates <| whenPPOption Lean.getPPNotation do
let stx ← delabForall
match stx with
| `(∀ ($i:ident : $_), $j:ident ∈ $s → $body) =>
if i == j then `(∀ $i:ident ∈ $s, $body) else pure stx
| `(∀ ($x:ident : $_), $y:ident > $z → $body) =>
if x == y then `(∀ $x:ident > $z, $body) else pure stx
| `(∀ ($x:ident : $_), $y:ident < $z → $body) =>
if x == y then `(∀ $x:ident < $z, $body) else pure stx
| `(∀ ($x:ident : $_), $y:ident ≥ $z → $body) =>
if x == y then `(∀ $x:ident ≥ $z, $body) else pure stx
| `(∀ ($x:ident : $_), $y:ident ≤ $z → $body) =>
if x == y then `(∀ $x:ident ≤ $z, $body) else pure stx
| `(Π ($i:ident : $_), $j:ident ∈ $s → $body) =>
if i == j then `(Π $i:ident ∈ $s, $body) else pure stx
| `(∀ ($i:ident : $_), $j:ident ∉ $s → $body) =>
if i == j then `(∀ $i:ident ∉ $s, $body) else pure stx
| `(∀ ($i:ident : $_), $j:ident ⊆ $s → $body) =>
if i == j then `(∀ $i:ident ⊆ $s, $body) else pure stx
| `(∀ ($i:ident : $_), $j:ident ⊂ $s → $body) =>
if i == j then `(∀ $i:ident ⊂ $s, $body) else pure stx
| `(∀ ($i:ident : $_), $j:ident ⊇ $s → $body) =>
if i == j then `(∀ $i:ident ⊇ $s, $body) else pure stx
| `(∀ ($i:ident : $_), $j:ident ⊃ $s → $body) =>
if i == j then `(∀ $i:ident ⊃ $s, $body) else pure stx
| _ => pure stx
/-- Override the Lean 4 pi notation delaborator with one that uses `Π` and prints
cute binders such as `∀ ε > 0`.
Note that this takes advantage of the fact that `(x : α) → p x` notation is
never used for propositions, so we can match on this result and rewrite it. -/
@[scoped delab forallE]
def delabPi' : Delab := whenPPOption Lean.getPPNotation do
-- Use delabForall as a backup if `pp.mathlib.binderPredicates` is false.
let stx ← delabPi <|> delabForall
-- Replacements
let stx : Term ←
match stx with
| `($group:bracketedBinder → $body) => `(Π $group:bracketedBinder, $body)
| _ => pure stx
-- Merging
match stx with
| `(Π $group, Π $groups*, $body) => `(Π $group $groups*, $body)
| _ => pure stx
end PiNotation
section existential
open Lean Parser Term PrettyPrinter Delaborator
/-- Delaborator for existential quantifier, including extended binders. -/
-- TODO: reduce the duplication in this code
@[app_delab Exists]
def exists_delab : Delab := whenPPOption Lean.getPPNotation do
let #[ι, f] := (← SubExpr.getExpr).getAppArgs | failure
unless f.isLambda do failure
let prop ← Meta.isProp ι
let dep := f.bindingBody!.hasLooseBVar 0
let ppTypes ← getPPOption getPPFunBinderTypes
let stx ← SubExpr.withAppArg do
let dom ← SubExpr.withBindingDomain delab
withBindingBodyUnusedName fun x => do
let x : TSyntax `ident := .mk x
let body ← delab
if prop && !dep then
`(∃ (_ : $dom), $body)
else if prop || ppTypes then
`(∃ ($x:ident : $dom), $body)
else
`(∃ $x:ident, $body)
-- Cute binders
let stx : Term ←
if ← getPPOption Mathlib.getPPBinderPredicates then
match stx with
| `(∃ $i:ident, $j:ident ∈ $s ∧ $body)
| `(∃ ($i:ident : $_), $j:ident ∈ $s ∧ $body) =>
if i == j then `(∃ $i:ident ∈ $s, $body) else pure stx
| `(∃ $x:ident, $y:ident > $z ∧ $body)
| `(∃ ($x:ident : $_), $y:ident > $z ∧ $body) =>
if x == y then `(∃ $x:ident > $z, $body) else pure stx
| `(∃ $x:ident, $y:ident < $z ∧ $body)
| `(∃ ($x:ident : $_), $y:ident < $z ∧ $body) =>
if x == y then `(∃ $x:ident < $z, $body) else pure stx
| `(∃ $x:ident, $y:ident ≥ $z ∧ $body)
| `(∃ ($x:ident : $_), $y:ident ≥ $z ∧ $body) =>
if x == y then `(∃ $x:ident ≥ $z, $body) else pure stx
| `(∃ $x:ident, $y:ident ≤ $z ∧ $body)
| `(∃ ($x:ident : $_), $y:ident ≤ $z ∧ $body) =>
if x == y then `(∃ $x:ident ≤ $z, $body) else pure stx
| `(∃ $x:ident, $y:ident ∉ $z ∧ $body)
| `(∃ ($x:ident : $_), $y:ident ∉ $z ∧ $body) => do
if x == y then `(∃ $x:ident ∉ $z, $body) else pure stx
| `(∃ $x:ident, $y:ident ⊆ $z ∧ $body)
| `(∃ ($x:ident : $_), $y:ident ⊆ $z ∧ $body) =>
if x == y then `(∃ $x:ident ⊆ $z, $body) else pure stx
| `(∃ $x:ident, $y:ident ⊂ $z ∧ $body)
| `(∃ ($x:ident : $_), $y:ident ⊂ $z ∧ $body) =>
if x == y then `(∃ $x:ident ⊂ $z, $body) else pure stx
| `(∃ $x:ident, $y:ident ⊇ $z ∧ $body)
| `(∃ ($x:ident : $_), $y:ident ⊇ $z ∧ $body) =>
if x == y then `(∃ $x:ident ⊇ $z, $body) else pure stx
| `(∃ $x:ident, $y:ident ⊃ $z ∧ $body)
| `(∃ ($x:ident : $_), $y:ident ⊃ $z ∧ $body) =>
if x == y then `(∃ $x:ident ⊃ $z, $body) else pure stx
| _ => pure stx
else
pure stx
match stx with
| `(∃ $group:bracketedExplicitBinders, ∃ $[$groups:bracketedExplicitBinders]*, $body) =>
`(∃ $group $groups*, $body)
| `(∃ $b:binderIdent, ∃ $[$bs:binderIdent]*, $body) => `(∃ $b:binderIdent $[$bs]*, $body)
| _ => pure stx
end existential
open Lean Lean.PrettyPrinter.Delaborator
/-- Delaborator for `∉`. -/
@[app_delab Not] def delab_not_in := whenPPOption Lean.getPPNotation do
let #[f] := (← SubExpr.getExpr).getAppArgs | failure
guard <| f.isAppOfArity ``Membership.mem 5
let stx₁ ← SubExpr.withAppArg <| SubExpr.withNaryArg 3 delab
let stx₂ ← SubExpr.withAppArg <| SubExpr.withNaryArg 4 delab
return ← `($stx₂ ∉ $stx₁) |
.lake/packages/mathlib/Mathlib/Util/Simp.lean | import Lean.Meta.Tactic.Simp.Types
import Mathlib.Init
import Qq
/-! # Additional simp utilities
This file adds additional tools for metaprogramming with the `simp` tactic
-/
open Lean Meta Qq
namespace Lean.Meta.Simp
/-- `Qq` version of `Lean.Meta.Simp.Methods.discharge?`, which avoids having to use `~q` matching
on the proof expression returned by `discharge?`
`dischargeQ? (a : Q(Prop))` attempts to prove `a` using the discharger, returning
`some (pf : Q(a))` if a proof is found and `none` otherwise. -/
@[inline]
def Methods.dischargeQ? (M : Methods) (a : Q(Prop)) : SimpM <| Option Q($a) := M.discharge? a
end Lean.Meta.Simp |
.lake/packages/mathlib/Mathlib/Util/Tactic.lean | import Mathlib.Init
import Lean.MetavarContext
/-!
# Miscellaneous helper functions for tactics.
[TODO] Ideally we would find good homes for everything in this file, eventually removing it.
-/
namespace Mathlib.Tactic
open Lean Meta Tactic
variable {m : Type → Type}
/--
`modifyMetavarDecl mvarId f` updates the `MetavarDecl` for `mvarId` with `f`.
Conditions on `f`:
- The target of `f mdecl` is defeq to the target of `mdecl`.
- The local context of `f mdecl` must contain the same fvars as the local
context of `mdecl`. For each fvar in the local context of `f mdecl`, the type
(and value, if any) of the fvar must be defeq to the corresponding fvar in
the local context of `mdecl`.
If `mvarId` does not refer to a declared metavariable, nothing happens.
-/
def modifyMetavarDecl [MonadMCtx m] (mvarId : MVarId)
(f : MetavarDecl → MetavarDecl) : m Unit :=
modifyMCtx fun mctx ↦
match mctx.decls.find? mvarId with
| none => mctx
| some mdecl => { mctx with decls := mctx.decls.insert mvarId (f mdecl) }
/--
`modifyTarget mvarId f` updates the target of the metavariable `mvarId` with
`f`. For any `e`, `f e` must be defeq to `e`. If `mvarId` does not refer to
a declared metavariable, nothing happens.
-/
def modifyTarget [MonadMCtx m] (mvarId : MVarId) (f : Expr → Expr) : m Unit :=
modifyMetavarDecl mvarId fun mdecl ↦
{ mdecl with type := f mdecl.type }
/--
`modifyLocalContext mvarId f` updates the local context of the metavariable
`mvarId` with `f`. The new local context must contain the same fvars as the old
local context and the types (and values, if any) of the fvars in the new local
context must be defeq to their equivalents in the old local context.
If `mvarId` does not refer to a declared metavariable, nothing happens.
-/
def modifyLocalContext [MonadMCtx m] (mvarId : MVarId)
(f : LocalContext → LocalContext) : m Unit :=
modifyMetavarDecl mvarId fun mdecl ↦
{ mdecl with lctx := f mdecl.lctx }
/--
`modifyLocalDecl mvarId fvarId f` updates the local decl `fvarId` in the local
context of `mvarId` with `f`. `f` must leave the `fvarId` and `index` of the
`LocalDecl` unchanged. The type of the new `LocalDecl` must be defeq to the type
of the old `LocalDecl` (and the same applies to the value of the `LocalDecl`, if
any).
If `mvarId` does not refer to a declared metavariable or if `fvarId` does not
exist in the local context of `mvarId`, nothing happens.
-/
def modifyLocalDecl [MonadMCtx m] (mvarId : MVarId) (fvarId : FVarId)
(f : LocalDecl → LocalDecl) : m Unit :=
modifyLocalContext mvarId fun lctx ↦ lctx.modifyLocalDecl fvarId f
end Mathlib.Tactic |
.lake/packages/mathlib/Mathlib/Util/CompileInductive.lean | import Mathlib.Init
import Lean.Elab.Command
import Lean.Compiler.CSimpAttr
import Lean.Util.FoldConsts
import Lean.Data.AssocList
/-!
# Define the `compile_inductive%` command.
The command `compile_inductive% Foo` adds compiled code for the recursor `Foo.rec`,
working around a bug in the core Lean compiler which does not support recursors.
For technical reasons, the recursor code generated by `compile_inductive%`
unfortunately evaluates the base cases eagerly. That is,
`List.rec (unreachable!) (fun _ _ _ => 42) [42]` will panic.
Similarly, `compile_def% Foo.foo` adds compiled code for definitions when missing.
This can be the case for type class projections, or definitions like `List._sizeOf_1`.
-/
namespace Mathlib.Util
open Lean Meta
private def replaceConst (repl : AssocList Name Name) (e : Expr) : Expr :=
e.replace fun | .const n us => repl.find? n |>.map (.const · us) | _ => none
/-- Returns the names of the recursors for a nested or mutual inductive,
using the `all` and `numMotives` arguments from `RecursorVal`. -/
def mkRecNames (all : List Name) (numMotives : Nat) : List Name :=
if numMotives ≤ all.length then
all.map mkRecName
else
let main := all[0]!
all.map mkRecName ++
(List.range (numMotives - all.length)).map (fun i => main.str s!"rec_{i+1}")
private def addAndCompile' (decl : Declaration) : CoreM Unit := do
try addAndCompile decl
catch e =>
match decl with
| .defnDecl val => throwError "while compiling {val.name}: {e.toMessageData}"
| .mutualDefnDecl val => throwError "while compiling {val.map (·.name)}: {e.toMessageData}"
| _ => unreachable!
/--
Compile the definition `dv` by adding a second definition `dv✝` with the same body,
and registering a `csimp`-lemma `dv = dv✝`.
-/
def compileDefn (dv : DefinitionVal) : MetaM Unit := do
if ((← getEnv).getModuleIdxFor? dv.name).isNone then
-- If it's in the same module then we can safely just call `compileDecl`
-- on the original definition
return ← compileDecl <| .defnDecl dv
let name ← mkFreshUserName dv.name
addAndCompile' <| .defnDecl { dv with name }
let levels := dv.levelParams.map .param
let old := .const dv.name levels
let new := .const name levels
let name ← mkFreshUserName <| dv.name.str "eq"
addDecl <| .thmDecl {
name
levelParams := dv.levelParams
type := ← mkEq old new
value := ← mkEqRefl old
}
Compiler.CSimp.add name .global
open Elab
/-- Returns true if the given declaration has a `@[csimp]` lemma. -/
def hasCSimpLemma (env : Environment) (n : Name) : Bool :=
(Compiler.CSimp.ext.getState env).map.contains n
/--
`compile_def% Foo.foo` adds compiled code for the definition `Foo.foo`.
This can be used for type class projections or definitions like `List._sizeOf_1`,
for which Lean does not generate compiled code by default
(since it is not used 99% of the time).
-/
elab tk:"compile_def% " i:ident : command => Command.liftTermElabM do
let n ← realizeGlobalConstNoOverloadWithInfo i
if hasCSimpLemma (← getEnv) n then
logWarningAt tk m!"already compiled {n}"
return
let dv ← withRef i <| getConstInfoDefn n
withRef tk <| compileDefn dv
private def compileStructOnly (iv : InductiveVal) (rv : RecursorVal) : MetaM Unit := do
let value ← forallTelescope rv.type fun xs _ =>
let val := xs[rv.getFirstMinorIdx]!
let val := mkAppN val ⟨.map (xs[rv.getMajorIdx]!.proj iv.name) <| .range rv.rules[0]!.nfields⟩
mkLambdaFVars xs val
go value
where
go value := do
let name ← mkFreshUserName rv.name
addAndCompile' <| .defnDecl { rv with
name
value
hints := .abbrev
safety := .safe
}
let levels := rv.levelParams.map .param
let old := .const rv.name levels
let new := .const name levels
let name ← mkFreshUserName <| rv.name.str "eq"
addDecl <| .mutualDefnDecl [{
name
levelParams := rv.levelParams
type := ← mkEq old new
value := .const name levels
hints := .opaque
safety := .partial
}]
Compiler.CSimp.add name .global
compileDefn <| ← getConstInfoDefn <| mkRecOnName iv.name
/--
Generate compiled code for the recursor for `iv`, excluding the `sizeOf` function.
-/
def compileInductiveOnly (iv : InductiveVal) (rv : RecursorVal) (warn := true) : MetaM Unit := do
if ← isProp rv.type then
if warn then logWarning m!"not compiling {rv.name}"
return
if !iv.isRec && rv.numMotives == 1 && iv.numCtors == 1 && iv.numIndices == 0 then
compileStructOnly iv rv
return
let levels := rv.levelParams.map .param
let rvs ←
if rv.numMotives == 1 then pure [rv]
else mkRecNames iv.all rv.numMotives |>.mapM getConstInfoRec
let rvs ← rvs.mapM fun rv => return (rv, ← mkFreshUserName rv.name)
let repl := rvs.foldl (fun l (rv, name) => .cons rv.name name l) .nil
addAndCompile' <| .mutualDefnDecl <|← rvs.mapM fun (rv, name) => do
pure { rv with
name
value := ← forallTelescope rv.type fun xs body => do
let major := xs[rv.getMajorIdx]!
(← whnfD <| ← inferType major).withApp fun head args => do
let .const iv levels' := head | throwError "not an inductive"
let iv ← getConstInfoInduct iv
let rv' ← getConstInfoRec <| mkRecName iv.name
if !iv.isRec && rv'.numMotives == 1 && iv.numCtors == 1 && iv.numIndices == 0 then
let rule := rv.rules[0]!
let val := .beta (replaceConst repl rule.rhs) xs[:rv.getFirstIndexIdx]
let val := .beta val ⟨.map (major.proj iv.name) <| .range rule.nfields⟩
mkLambdaFVars xs val
else
let val := .const (mkCasesOnName iv.name) (.param rv.levelParams.head! :: levels')
let val := mkAppN val args[:rv'.numParams]
let val := .app val <| ← mkLambdaFVars xs[rv.getFirstIndexIdx:] body
let val := mkAppN val xs[rv.getFirstIndexIdx:]
let val := mkAppN val <| rv.rules.toArray.map fun rule =>
.beta (replaceConst repl rule.rhs) xs[:rv.getFirstIndexIdx]
mkLambdaFVars xs val
hints := .opaque
safety := .partial
}
for (rv, name) in rvs do
let old := .const rv.name levels
let new := .const name levels
let name ← mkFreshUserName <| rv.name.str "eq"
addDecl <| .mutualDefnDecl [{
name
levelParams := rv.levelParams
type := ← mkEq old new
value := .const name levels
hints := .opaque
safety := .partial
}]
Compiler.CSimp.add name .global
for name in iv.all do
for aux in [mkRecOnName name, (mkBRecOnName name).str "go", mkBRecOnName name] do
if let some (.defnInfo dv) := (← getEnv).find? aux then
compileDefn dv
mutual
/--
Generate compiled code for the recursor for `iv`.
-/
partial def compileInductive (iv : InductiveVal) (warn := true) : MetaM Unit := do
let rv ← getConstInfoRec <| mkRecName iv.name
if hasCSimpLemma (← getEnv) rv.name then
if warn then logWarning m!"already compiled {rv.name}"
return
compileInductiveOnly iv rv warn
compileSizeOf iv rv
/--
Compiles the `sizeOf` auxiliary functions. It also recursively compiles any inductives required to
compile the `sizeOf` definition (because `sizeOf` definitions depend on `T.rec`).
-/
partial def compileSizeOf (iv : InductiveVal) (rv : RecursorVal) : MetaM Unit := do
let go aux := do
if let some (.defnInfo dv) := (← getEnv).find? aux then
if !hasCSimpLemma (← getEnv) aux then
let deps : NameSet := dv.value.foldConsts ∅ fun c arr =>
if let .str name "_sizeOf_inst" := c then arr.insert name else arr
for i in deps do
-- We only want to recompile inductives defined in external modules, because attempting
-- to recompile `sizeOf` functions defined in the current module multiple times will lead
-- to errors. An entire mutual block of inductives is compiled when compiling any
-- inductive within it, so every inductive within the same module can be explicitly
-- compiled using `compile_inductive%` if necessary.
if ((← getEnv).getModuleIdxFor? i).isSome then
if let some (.inductInfo iv) := (← getEnv).find? i then
compileInductive iv (warn := false)
compileDefn dv
for name in iv.all do
for i in [:rv.numMotives] do
go <| name.str s!"_sizeOf_{i+1}"
go <| name.str "_sizeOf_inst"
end
/--
`compile_inductive% Foo` creates compiled code for the recursor `Foo.rec`,
so that `Foo.rec` can be used in a definition
without having to mark the definition as `noncomputable`.
-/
elab tk:"compile_inductive% " i:ident : command => Command.liftTermElabM do
let n ← realizeGlobalConstNoOverloadWithInfo i
let iv ← withRef i <| getConstInfoInduct n
withRef tk <| compileInductive iv
end Mathlib.Util
-- `Nat.rec` already has a `@[csimp]` lemma in Lean.
compile_def% Nat.recOn
compile_def% Nat.brecOn.go
compile_def% Nat.brecOn
compile_inductive% Prod
compile_inductive% List
compile_inductive% PUnit
compile_inductive% PEmpty
compile_inductive% Sum
compile_inductive% PSum
compile_inductive% And
compile_inductive% False
compile_inductive% Empty
compile_inductive% Bool
compile_inductive% Sigma
compile_inductive% Option
-- In addition to the manual implementation below, we also have to override the `Float.val` and
-- `Float.mk` functions because these also have no implementation in core lean.
-- Because `floatSpec.float` is an opaque type, the identity function is as good an implementation
-- as any.
private unsafe def Float.valUnsafe : Float → floatSpec.float := unsafeCast
private unsafe def Float.mkUnsafe : floatSpec.float → Float := unsafeCast
@[implemented_by Float.valUnsafe] private def Float.valImpl (x : Float) : floatSpec.float := x.1
@[implemented_by Float.mkUnsafe] private def Float.mkImpl (x : floatSpec.float) : Float := ⟨x⟩
@[csimp] private theorem Float.val_eq : @Float.val = Float.valImpl := rfl
@[csimp] private theorem Float.mk_eq : @Float.mk = Float.mkImpl := rfl
-- These types need manual implementations because the default implementation in `compileStruct`
-- uses `Expr.proj` which has an invalid IR type.
open Lean Meta Elab Mathlib.Util in
run_cmd Command.liftTermElabM do
for n in [``UInt8, ``UInt16, ``UInt32, ``UInt64, ``USize, ``Float] do
let iv ← getConstInfoInduct n
let rv ← getConstInfoRec <| mkRecName n
let value ← Elab.Term.elabTerm (← `(fun H t => H t.1))
(← inferType (.const rv.name (rv.levelParams.map .param)))
compileStructOnly.go iv rv value
compileSizeOf iv rv
-- These need special handling because `Lean.Name.sizeOf` and `Lean.instSizeOfName`
-- were manually implemented as `noncomputable`
compile_inductive% String
compile_inductive% Lean.Name
compile_def% Lean.Name.sizeOf
compile_def% Lean.instSizeOfName |
.lake/packages/mathlib/Mathlib/Util/ElabWithoutMVars.lean | import Mathlib.Init
/-!
# `elabTermWithoutNewMVars`
-/
open Lean Elab Tactic
/-- Elaborates a term with `errToSorry = false` and ensuring it has no metavariables. -/
def elabTermWithoutNewMVars (tactic : Name) (t : Term) : TacticM Expr := Term.withoutErrToSorry do
let (e, mvars) ← elabTermWithHoles t none tactic
unless mvars.isEmpty do
throwErrorAt t "Argument passed to {tactic} has metavariables:{indentD e}"
return e |
.lake/packages/mathlib/Mathlib/Util/DischargerAsTactic.lean | import Mathlib.Init
import Lean.Elab.Tactic.Basic
import Lean.Meta.Tactic.Simp.Rewrite
import Batteries.Tactic.Exact
/-!
## Dischargers for `simp` to tactics
This file defines a wrapper for `Simp.Discharger`s as regular tactics, that allows them to be
used via the tactic frontend of `simp` via `simp (discharger := wrapSimpDischarger my_discharger)`.
-/
open Lean Meta Elab Tactic
/-- Wrap a simp discharger (a function `Expr → SimpM (Option Expr)`) as a tactic,
so that it can be passed as an argument to `simp (discharger := foo)`.
This is inverse to `mkDischargeWrapper`. -/
def wrapSimpDischarger (dis : Simp.Discharge) : TacticM Unit := do
let eS : Lean.Meta.Simp.State := {}
let eC : Lean.Meta.Simp.Context := ← Simp.mkContext {}
let eM : Lean.Meta.Simp.Methods := {}
let (some a, _) ← liftM <| StateRefT'.run (ReaderT.run (ReaderT.run (dis <| ← getMainTarget)
eM.toMethodsRef) eC) eS | failure
(← getMainGoal).assignIfDefEq a |
.lake/packages/mathlib/Mathlib/Util/Export.lean | import Mathlib.Init
import Lean.CoreM
import Lean.Util.FoldConsts
/-!
A rudimentary export format, adapted from
<https://github.com/leanprover-community/lean/blob/master/doc/export_format.md>
with support for Lean 4 kernel primitives.
-/
open Lean
open Std (HashMap HashSet)
namespace Lean
namespace Export
/- References -/
private opaque MethodsRefPointed : NonemptyType.{0}
private def MethodsRef : Type := MethodsRefPointed.type
inductive Entry
| name (n : Name)
| level (n : Level)
| expr (n : Expr)
| defn (n : Name)
deriving Inhabited
instance : Coe Name Entry := ⟨Entry.name⟩
instance : Coe Level Entry := ⟨Entry.level⟩
instance : Coe Expr Entry := ⟨Entry.expr⟩
structure Alloc (α) [BEq α] [Hashable α] where
map : Std.HashMap α Nat
next : Nat
deriving Inhabited
structure State where
names : Alloc Name := ⟨(∅ : Std.HashMap Name Nat).insert Name.anonymous 0, 1⟩
levels : Alloc Level := ⟨(∅ : Std.HashMap Level Nat).insert levelZero 0, 1⟩
exprs : Alloc Expr
defs : Std.HashSet Name
stk : Array (Bool × Entry)
deriving Inhabited
class OfState (α : Type) [BEq α] [Hashable α] where
get : State → Alloc α
modify : (Alloc α → Alloc α) → State → State
instance : OfState Name where
get s := s.names
modify f s := { s with names := f s.names }
instance : OfState Level where
get s := s.levels
modify f s := { s with levels := f s.levels }
instance : OfState Expr where
get s := s.exprs
modify f s := { s with exprs := f s.exprs }
end Export
abbrev ExportM := StateT Export.State CoreM
namespace Export
def alloc {α} [BEq α] [Hashable α] [OfState α] (a : α) : ExportM Nat := do
let n := (OfState.get (α := α) (← get)).next
modify <| OfState.modify (α := α) fun s ↦ {map := s.map.insert a n, next := n + 1}
pure n
def exportName (n : Name) : ExportM Nat := do
match (← get).names.map[n]? with
| some i => pure i
| none => match n with
| .anonymous => pure 0
| .num p a => let i ← alloc n; IO.println s!"{i} #NI {← exportName p} {a}"; pure i
| .str p s => let i ← alloc n; IO.println s!"{i} #NS {← exportName p} {s}"; pure i
def exportLevel (L : Level) : ExportM Nat := do
match (← get).levels.map[L]? with
| some i => pure i
| none => match L with
| .zero => pure 0
| .succ l =>
let i ← alloc L; IO.println s!"{i} #US {← exportLevel l}"; pure i
| .max l₁ l₂ =>
let i ← alloc L; IO.println s!"{i} #UM {← exportLevel l₁} {← exportLevel l₂}"; pure i
| .imax l₁ l₂ =>
let i ← alloc L; IO.println s!"{i} #UIM {← exportLevel l₁} {← exportLevel l₂}"; pure i
| .param n =>
let i ← alloc L; IO.println s!"{i} #UP {← exportName n}"; pure i
| .mvar _ => unreachable!
def biStr : BinderInfo → String
| BinderInfo.default => "#BD"
| BinderInfo.implicit => "#BI"
| BinderInfo.strictImplicit => "#BS"
| BinderInfo.instImplicit => "#BC"
open ConstantInfo in
mutual
partial def exportExpr (E : Expr) : ExportM Nat := do
match (← get).exprs.map[E]? with
| some i => pure i
| none => match E with
| .bvar n => let i ← alloc E; IO.println s!"{i} #EV {n}"; pure i
| .fvar _ => unreachable!
| .mvar _ => unreachable!
| .sort l => let i ← alloc E; IO.println s!"{i} #ES {← exportLevel l}"; pure i
| .const n ls =>
exportDef n
let i ← alloc E
let mut s := s!"{i} #EC {← exportName n}"
for l in ls do s := s ++ s!" {← exportLevel l}"
IO.println s; pure i
| .app e₁ e₂ =>
let i ← alloc E; IO.println s!"{i} #EA {← exportExpr e₁} {← exportExpr e₂}"; pure i
| .lam _ e₁ e₂ d =>
let i ← alloc E
IO.println s!"{i} #EL {biStr d} {← exportExpr e₁} {← exportExpr e₂}"; pure i
| .forallE _ e₁ e₂ d =>
let i ← alloc E
IO.println s!"{i} #EP {biStr d} {← exportExpr e₁} {← exportExpr e₂}"; pure i
| .letE _ e₁ e₂ e₃ _ =>
let i ← alloc E
IO.println s!"{i} #EP {← exportExpr e₁} {← exportExpr e₂} {← exportExpr e₃}"; pure i
| .lit (.natVal n) => let i ← alloc E; IO.println s!"{i} #EN {n}"; pure i
| .lit (.strVal s) => let i ← alloc E; IO.println s!"{i} #ET {s}"; pure i
| .mdata _ _ => unreachable!
| .proj n k e =>
let i ← alloc E; IO.println s!"{i} #EJ {← exportName n} {k} {← exportExpr e}"; pure i
partial def exportDef (n : Name) : ExportM Unit := do
if (← get).defs.contains n then return
let ci ← getConstInfo n
for c in ci.value!.getUsedConstants do
unless (← get).defs.contains c do
exportDef c
match ci with
| axiomInfo val => axdef "#AX" val.name val.type val.levelParams
| defnInfo val => defn "#DEF" val.name val.type val.value val.levelParams
| thmInfo val => defn "#THM" val.name val.type val.value val.levelParams
| opaqueInfo val => defn "#CN" val.name val.type val.value val.levelParams
| quotInfo _ =>
IO.println "#QUOT"
for n in [``Quot, ``Quot.mk, ``Quot.lift, ``Quot.ind] do
insert n
| inductInfo val => ind val.all
| ctorInfo val => ind (← getConstInfoInduct val.induct).all
| recInfo val => ind val.all
where
insert (n : Name) : ExportM Unit :=
modify fun s ↦ { s with defs := s.defs.insert n }
defn (ty : String) (n : Name) (t e : Expr) (ls : List Name) : ExportM Unit := do
let mut s := s!"{ty} {← exportName n} {← exportExpr t} {← exportExpr e}"
for l in ls do s := s ++ s!" {← exportName l}"
IO.println s
insert n
axdef (ty : String) (n : Name) (t : Expr) (ls : List Name) : ExportM Unit := do
let mut s := s!"{ty} {← exportName n} {← exportExpr t}"
for l in ls do s := s ++ s!" {← exportName l}"
IO.println s
insert n
ind : List Name → ExportM Unit
| [] => unreachable!
| is@(i::_) => do
let val ← getConstInfoInduct i
let mut s := match is.length with
| 1 => s!"#IND {val.numParams}"
| n => s!"#MUT {val.numParams} {n}"
for j in is do insert j; insert (mkRecName j)
for j in is do
let val ← getConstInfoInduct j
s := s ++ s!" {← exportName val.name} {← exportExpr val.type} {val.ctors.length}"
for c in val.ctors do
insert c
s := s ++ s!" {← exportName c} {← exportExpr (← getConstInfoCtor c).type}"
for j in is do s ← indbody j s
for l in val.levelParams do s := s ++ s!" {← exportName l}"
IO.println s
indbody (ind : Name) (s : String) : ExportM String := do
let val ← getConstInfoInduct ind
let mut s := s ++ s!" {← exportName ind} {← exportExpr val.type} {val.ctors.length}"
for c in val.ctors do
s := s ++ s!" {← exportName c} {← exportExpr (← getConstInfoCtor c).type}"
pure s
end
def runExportM {α : Type} (m : ExportM α) : CoreM α := m.run' default
-- #eval runExportM (exportDef `Lean.Expr)
end Export
end Lean |
.lake/packages/mathlib/Mathlib/Util/AssertExistsExt.lean | import Lean.Environment
import Mathlib.Init
/-!
# Environment extension for tracking existence of declarations and imports
This is used by the `assert_not_exists` and `assert_not_imported` commands.
-/
open Lean
namespace Mathlib.AssertNotExist
/-- `AssertExists` is the structure that carries the data to check whether a declaration or an
import is meant to exist somewhere in Mathlib. -/
structure AssertExists where
/-- The type of the assertion: `true` means declaration, `false` means import. -/
isDecl : Bool
/-- The fully qualified name of a declaration that is expected to exist. -/
givenName : Name
/-- The name of the module where the assertion was made. -/
modName : Name
deriving BEq, Hashable
/-- Defines the `assertExistsExt` extension for adding a `HashSet` of `AssertExists` entries
to the environment. -/
initialize assertExistsExt : SimplePersistentEnvExtension AssertExists (Std.HashSet AssertExists) ←
registerSimplePersistentEnvExtension {
addImportedFn := fun as => as.foldl Std.HashSet.insertMany {}
addEntryFn := .insert
}
/--
`addDeclEntry isDecl declName mod` takes as input the `Bool`ean `isDecl` and the `Name`s of
a declaration or import, `declName`, and of a module, `mod`.
It extends the `AssertExists` environment extension with the data `isDecl, declName, mod`.
This information is used to capture declarations and modules that are forbidden from
existing/being imported at some point, but should eventually exist/be imported.
-/
def addDeclEntry {m : Type → Type} [MonadEnv m] (isDecl : Bool) (declName mod : Name) : m Unit :=
modifyEnv (assertExistsExt.addEntry · { isDecl := isDecl, givenName := declName, modName := mod })
end Mathlib.AssertNotExist
open Mathlib.AssertNotExist
/-- `getSortedAssertExists env` returns the array of `AssertExists`, placing first all declarations,
in alphabetical order, and then all modules, also in alphabetical order. -/
def Lean.Environment.getSortedAssertExists (env : Environment) : Array AssertExists :=
assertExistsExt.getState env |>.toArray.qsort fun d e => (e.isDecl < d.isDecl) ||
(e.isDecl == d.isDecl && (d.givenName.toString < e.givenName.toString)) |
.lake/packages/mathlib/Mathlib/Util/AssertNoSorry.lean | import Mathlib.Init
import Lean.Util.CollectAxioms
import Lean.Elab.Command
/-!
# Defines the `assert_no_sorry` command.
Throws an error if the given identifier uses sorryAx.
-/
open Lean Meta Elab Command
/-- Throws an error if the given identifier uses sorryAx. -/
elab "assert_no_sorry " n:ident : command => do
let name ← liftCoreM <| Lean.Elab.realizeGlobalConstNoOverloadWithInfo n
let axioms ← Lean.collectAxioms name
if axioms.contains ``sorryAx
then throwError "{n} contains sorry" |
.lake/packages/mathlib/Mathlib/Util/LongNames.lean | import Mathlib.Lean.Name
import Mathlib.Lean.Expr.Basic
import Lean.Elab.Command
/-!
# Commands `#long_names` and `#long_instances`
For finding declarations with excessively long names.
-/
open Lean Meta Elab
/-- Helper function for `#long_names` and `#long_instances`. -/
def printNameHashMap (h : Std.HashMap Name (Array Name)) : IO Unit :=
for (m, names) in h.toList do
IO.println "----"
IO.println <| m.toString ++ ":"
for n in names do
IO.println n
/--
Lists all declarations with a long name, gathered according to the module they are defined in.
Use as `#long_names` or `#long_names 100` to specify the length.
-/
elab "#long_names " N:(num)? : command =>
Command.runTermElabM fun _ => do
let N := N.map TSyntax.getNat |>.getD 50
let namesByModule ← allNamesByModule (fun n => n.toString.length > N)
let namesByModule := namesByModule.filter fun m _ => m.getRoot.toString = "Mathlib"
printNameHashMap namesByModule
/--
Lists all instances with a long name beginning with `inst`,
gathered according to the module they are defined in.
This is useful for finding automatically named instances with absurd names.
Use as `#long_names` or `#long_names 100` to specify the length.
-/
elab "#long_instances " N:(num)?: command =>
Command.runTermElabM fun _ => do
let N := N.map TSyntax.getNat |>.getD 50
let namesByModule ← allNamesByModule
(fun n => n.lastComponentAsString.startsWith "inst" && n.lastComponentAsString.length > N)
let namesByModule := namesByModule.filter fun m _ => m.getRoot.toString = "Mathlib"
printNameHashMap namesByModule |
.lake/packages/mathlib/Mathlib/Util/SynthesizeUsing.lean | import Mathlib.Init
import Lean.Elab.Tactic.Basic
import Qq
/-!
# `SynthesizeUsing`
This is a slight simplification of the `solve_aux` tactic in Lean3.
-/
open Lean Elab Tactic Meta Qq
/--
`synthesizeUsing type tac` synthesizes an element of type `type` using tactic `tac`.
The tactic `tac` is allowed to leave goals open, and these remain as metavariables in the
returned expression.
-/
-- In Lean3 this was called `solve_aux`,
-- and took a `TacticM α` and captured the produced value in `α`.
-- As this was barely used, we've simplified here.
def synthesizeUsing {u : Level} (type : Q(Sort u)) (tac : TacticM Unit) :
MetaM (List MVarId × Q($type)) := do
let m ← mkFreshExprMVar type
let goals ← (Term.withoutErrToSorry <| run m.mvarId! tac).run'
return (goals, ← instantiateMVars m)
/--
`synthesizeUsing type tac` synthesizes an element of type `type` using tactic `tac`.
The tactic must solve for all goals, in contrast to `synthesizeUsing`.
-/
def synthesizeUsing' {u : Level} (type : Q(Sort u)) (tac : TacticM Unit) : MetaM Q($type) := do
let (goals, e) ← synthesizeUsing type tac
-- Note: does not use `tac *> Tactic.done` since that just adds a message
-- rather than raising an error.
unless goals.isEmpty do
throwError m!"synthesizeUsing': unsolved goals\n{goalsToMessageData goals}"
return e
/--
`synthesizeUsing type tacticSyntax` synthesizes an element of type `type` by evaluating the
given tactic syntax.
Example:
```lean
let (gs, e) ← synthesizeUsingTactic ty (← `(tactic| congr!))
```
The tactic `tac` is allowed to leave goals open, and these remain as metavariables in the
returned expression.
-/
def synthesizeUsingTactic {u : Level} (type : Q(Sort u)) (tac : Syntax) :
MetaM (List MVarId × Q($type)) := do
synthesizeUsing type (do evalTactic tac)
/--
`synthesizeUsing' type tacticSyntax` synthesizes an element of type `type` by evaluating the
given tactic syntax.
Example:
```lean
let e ← synthesizeUsingTactic' ty (← `(tactic| norm_num))
```
The tactic must solve for all goals, in contrast to `synthesizeUsingTactic`.
If you need to insert expressions into a tactic proof, then you might use `synthesizeUsing'`
directly, since the `TacticM` monad has access to the `TermElabM` monad. For example, here
is a term elaborator that wraps the `simp at ...` tactic:
```
def simpTerm (e : Expr) : MetaM Expr := do
let mvar ← Meta.mkFreshTypeMVar
let e' ← synthesizeUsing' mvar
(do evalTactic (← `(tactic| have h := $(← Term.exprToSyntax e); simp at h; exact h)))
-- Note: `simp` does not always insert type hints, so to ensure that we get a term
-- with the simplified type (as opposed to one that is merely defeq), we should add
-- a type hint ourselves.
Meta.mkExpectedTypeHint e' mvar
elab "simpTerm% " t:term : term => do simpTerm (← Term.elabTerm t none)
```
-/
def synthesizeUsingTactic' {u : Level} (type : Q(Sort u)) (tac : Syntax) : MetaM Q($type) := do
synthesizeUsing' type (do evalTactic tac) |
.lake/packages/mathlib/Mathlib/Util/AddRelatedDecl.lean | import Mathlib.Init
import Lean.Elab.DeclarationRange
/-!
# `addRelatedDecl`
-/
open Lean Meta Elab
namespace Mathlib.Tactic
/-- A helper function for constructing a related declaration from an existing one.
This is currently used by the attributes `reassoc` and `elementwise`,
and has been factored out to avoid code duplication.
Feel free to add features as needed for other applications.
This helper:
* calls `addDeclarationRangesFromSyntax`, so jump-to-definition works,
* copies the `protected` status of the existing declaration, and
* supports copying attributes.
Arguments:
* `src : Name` is the existing declaration that we are modifying.
* `suffix : String` will be appended to `src` to form the name of the new declaration.
* `ref : Syntax` is the syntax where the user requested the related declaration.
* `construct value levels : MetaM (Expr × List Name)`
given an `Expr.const` referring to the original declaration, and its universe variables,
should construct the value of the new declaration,
along with the names of its universe variables.
* `attrs` is the attributes that should be applied to both the new and the original declaration,
e.g. in the usage `@[reassoc (attr := simp)]`.
We apply it to both declarations, to have the same behavior as `to_additive`, and to shorten some
attribute commands. Note that `@[elementwise (attr := simp), reassoc (attr := simp)]` will try
to apply `simp` twice to the current declaration, but that causes no issues.
-/
def addRelatedDecl (src : Name) (suffix : String) (ref : Syntax)
(attrs? : Option (Syntax.TSepArray `Lean.Parser.Term.attrInstance ","))
(construct : Expr → List Name → MetaM (Expr × List Name)) :
MetaM Unit := do
let tgt := match src with
| Name.str n s => Name.mkStr n <| s ++ suffix
| x => x
addDeclarationRangesFromSyntax tgt (← getRef) ref
let info ← getConstInfo src
let value := .const src (info.levelParams.map mkLevelParam)
let (newValue, newLevels) ← construct value info.levelParams
let newValue ← instantiateMVars newValue
let newType ← instantiateMVars (← inferType newValue)
match info with
| ConstantInfo.thmInfo info =>
addAndCompile <| .thmDecl
{ info with levelParams := newLevels, type := newType, name := tgt, value := newValue }
| ConstantInfo.defnInfo info =>
-- Structure fields are created using `def`, even when they are propositional,
-- so we don't rely on this to decide whether we should be constructing a `theorem` or a `def`.
addAndCompile <| if ← isProp newType then .thmDecl
{ info with levelParams := newLevels, type := newType, name := tgt, value := newValue }
else .defnDecl
{ info with levelParams := newLevels, type := newType, name := tgt, value := newValue }
| _ => throwError "Constant {src} is not a theorem or definition."
if isProtected (← getEnv) src then
setEnv <| addProtected (← getEnv) tgt
inferDefEqAttr tgt
let attrs := match attrs? with | some attrs => attrs | none => #[]
_ ← Term.TermElabM.run' <| do
let attrs ← elabAttrs attrs
Term.applyAttributes src attrs
Term.applyAttributes tgt attrs
end Mathlib.Tactic |
.lake/packages/mathlib/Mathlib/Util/MemoFix.lean | import Std.Data.HashMap.Basic
import Mathlib.Init
/-!
# Fixpoint function with memoisation
-/
universe u v
open ShareCommon Std
private unsafe abbrev ObjectMap := @Std.HashMap Object Object ⟨Object.ptrEq⟩ ⟨Object.hash⟩
@[noinline]
private def injectIntoBaseIO {α : Type} (a : α) : BaseIO α := pure a
private unsafe def memoFixImplObj (f : (Object → Object) → (Object → Object)) (a : Object) :
Object := unsafeBaseIO do
let cache : IO.Ref ObjectMap ← ST.mkRef ∅
let rec fix (a) := unsafeBaseIO do
if let some b := (← cache.get)[a]? then
return b
let b ← injectIntoBaseIO (f fix a)
cache.modify (·.insert a b)
pure b
pure <| fix a
private unsafe def memoFixImpl {α : Type u} {β : Type v} [Nonempty β] :
(f : (α → β) → (α → β)) → (a : α) → β :=
unsafeCast memoFixImplObj
/-- Takes the fixpoint of `f` with caching of values that have been seen before.
Hashing makes use of a pointer hash.
This is useful for implementing tree traversal functions where
subtrees may be referenced in multiple places.
-/
@[implemented_by memoFixImpl]
opaque memoFix {α : Type u} {β : Type v} [Nonempty β] (f : (α → β) → (α → β)) : α → β |
.lake/packages/mathlib/Mathlib/Util/AtomM/Recurse.lean | import Mathlib.Util.AtomM
/-!
# Running `AtomM` metaprograms recursively
Tactics such as `ring` and `abel` are implemented using the `AtomM` monad, which tracks "atoms" --
expressions which cannot be further parsed according to the arithmetic operations they handle --
to allow for consistent normalization relative to these atoms.
This file provides methods to allow for such normalization to run recursively: the atoms themselves
will have the normalization run on any of their subterms for which this makes sense. For example,
given an implementation of ring-normalization, the methods in this file implement the bottom-to-top
recursive ring-normalization in which `sin (x + y) + sin (y + x)` is normalized first to
`sin (x + y) + sin (x + y)` and then to `2 * sin (x + y)`.
## Main declarations
* `Mathlib.Tactic.AtomM.RecurseM.run`: run a metaprogram (in `AtomM` or its slight extension
`AtomM.RecurseM`), with atoms normalized according to a provided normalization operation (in
`AtomM`), run recursively.
* `Mathlib.Tactic.AtomM.recurse`: run a normalization operation (in `AtomM`) recursively on an
expression.
-/
namespace Mathlib.Tactic.AtomM
open Lean Meta
/-- Configuration for `AtomM.Recurse`. -/
structure Recurse.Config where
/-- the reducibility setting to use when comparing atoms for defeq -/
red := TransparencyMode.reducible
/-- if true, local let variables can be unfolded -/
zetaDelta := false
deriving Inhabited, BEq, Repr
-- See https://github.com/leanprover/lean4/issues/10295
attribute [nolint unusedArguments] Mathlib.Tactic.AtomM.Recurse.instReprConfig.repr
/-- The read-only state of the `AtomM.Recurse` monad. -/
structure Recurse.Context where
/-- A basically empty simp context, passed to the `simp` traversal in `AtomM.onSubexpressions`.
-/
ctx : Simp.Context
/-- A cleanup routine, which simplifies evaluation results to a more human-friendly format. -/
simp : Simp.Result → MetaM Simp.Result
/-- The monad for `AtomM.Recurse` contains, in addition to the `AtomM` state,
a simp context for the main traversal and a cleanup function to simplify evaluation results. -/
abbrev RecurseM := ReaderT Recurse.Context AtomM
/--
A tactic in the `AtomM.RecurseM` monad which will simplify expression `parent` to a normal form, by
running a core operation `eval` (in the `AtomM` monad) on the maximal subexpression(s) on which
`eval` does not fail.
There is also a subsequent clean-up operation, governed by the context from the `AtomM.RecurseM`
monad.
* `root`: true if this is a direct call to the function.
`AtomM.RecurseM.run` sets this to `false` in recursive mode.
-/
def onSubexpressions (eval : Expr → AtomM Simp.Result) (parent : Expr) (root := true) :
RecurseM Simp.Result :=
fun nctx rctx s ↦ do
let pre : Simp.Simproc := fun e =>
try
guard <| root || parent != e -- recursion guard
let r' ← eval e rctx s
let r ← nctx.simp r'
if ← withReducible <| isDefEq r.expr e then return .done { expr := r.expr }
pure (.done r)
catch _ => pure <| .continue
let post := Simp.postDefault #[]
(·.1) <$> Simp.main parent nctx.ctx (methods := { pre, post })
/--
Runs a tactic in the `AtomM.RecurseM` monad, given initial data:
* `s`: a reference to the mutable `AtomM` state, for persisting across calls.
This ensures that atom ordering is used consistently.
* `cfg`: the configuration options
* `eval`: a normalization operation which will be run recursively, potentially dependent on a known
atom ordering
* `simp`: a cleanup operation which will be used to post-process expressions
* `x`: the tactic to run
-/
partial def RecurseM.run
{α : Type} (s : IO.Ref State) (cfg : Recurse.Config) (eval : Expr → AtomM Simp.Result)
(simp : Simp.Result → MetaM Simp.Result) (x : RecurseM α) :
MetaM α := do
let ctx ← Simp.mkContext { zetaDelta := cfg.zetaDelta, singlePass := true }
(simpTheorems := #[← Elab.Tactic.simpOnlyBuiltins.foldlM (·.addConst ·) {}])
(congrTheorems := ← getSimpCongrTheorems)
let nctx := { ctx, simp }
let rec
/-- The recursive context. -/
rctx := { red := cfg.red, evalAtom },
/-- The atom evaluator calls `AtomM.onSubexpressions` recursively. -/
evalAtom e := onSubexpressions eval e false nctx rctx s
withConfig ({ · with zetaDelta := cfg.zetaDelta }) <| x nctx rctx s
/--
Normalizes an expression, given initial data:
* `s`: a reference to the mutable `AtomM` state, for persisting across calls.
This ensures that atom ordering is used consistently.
* `cfg`: the configuration options
* `eval`: a normalization operation which will be run recursively, potentially dependent on a known
atom ordering
* `simp`: a cleanup operation which will be used to post-process expressions
* `tgt`: the expression to normalize
-/
def recurse (s : IO.Ref State) (cfg : Recurse.Config)
(eval : Expr → AtomM Simp.Result)
(simp : Simp.Result → MetaM Simp.Result) (tgt : Expr) :
MetaM Simp.Result := do
RecurseM.run s cfg eval simp <| onSubexpressions eval tgt
end Mathlib.Tactic.AtomM |
.lake/packages/mathlib/Mathlib/NumberTheory/Niven.lean | import Mathlib.Analysis.SpecialFunctions.Complex.Log
import Mathlib.RingTheory.Polynomial.RationalRoot
import Mathlib.Tactic.Peel
import Mathlib.Tactic.Rify
/-! # Niven's Theorem
This file proves Niven's theorem, stating that the only rational angles _in degrees_ which
also have rational cosines, are 0, 30 degrees, and 90 degrees - up to reflection and shifts
by π. Equivalently, the only rational numbers that occur as `cos(π * p / q)` are the five
values `{-1, -1/2, 0, 1/2, 1}`.
-/
namespace IsIntegral
variable {α R : Type*} [DivisionRing α] [CharZero α] {q : ℚ} {x : α}
@[simp]
theorem ratCast_iff : IsIntegral ℤ (q : α) ↔ IsIntegral ℤ q :=
isIntegral_algebraMap_iff (FaithfulSMul.algebraMap_injective ℚ α)
theorem exists_int_iff_exists_rat (h₁ : IsIntegral ℤ x) : (∃ q : ℚ, x = q) ↔ ∃ k : ℤ, x = k := by
refine ⟨?_, fun ⟨w, h⟩ ↦ ⟨w, by simp [h]⟩⟩
rintro ⟨q, rfl⟩
rw [ratCast_iff] at h₁
peel IsIntegrallyClosed.algebraMap_eq_of_integral h₁ with h
simp [← h]
end IsIntegral
variable {θ : ℝ}
open Real
theorem isIntegral_two_mul_cos_rat_mul_pi (r : ℚ) :
IsIntegral ℤ (2 * cos (r * π)) := by
let z : ℂ := .exp (.I * r * π)
obtain ⟨p, q, hq_pos, rfl⟩ : ∃ (p : ℤ) (q : ℕ), q ≠ 0 ∧ r = p / q :=
⟨r.num, r.den, r.den_ne_zero, r.num_div_den.symm⟩
-- Let `z = e ^ (i * π * p / q)`, which is a root of unity.
have hz_root : z ^ (2 * q) = 1 := by
rw [← Complex.exp_nat_mul, Complex.exp_eq_one_iff]
use p
push_cast
field [hq_pos]
-- Since z is a root of unity, `2 cos θ = z` and `z⁻¹` are algebraic integers, and their sum.
have h_cos_eq : 2 * cos (p / q * π) = z + z⁻¹ := by
simpa [Complex.cos, Complex.exp_neg, z] using by ring_nf
obtain ⟨f, hf₁, hf₂⟩ : IsIntegral ℤ (z + z⁻¹) := by apply IsIntegral.add <;>
exact ⟨.X ^ (2 * q) - 1, Polynomial.monic_X_pow_sub_C _ (by positivity), by simp [hz_root]⟩
use f, hf₁
simp_all [Polynomial.eval₂_eq_sum_range, ← Complex.ofReal_inj]
/-- **Niven's theorem**: The only rational values of `cos` that occur at rational multiples of π
are `{-1, -1/2, 0, 1/2, 1}`. -/
theorem niven (hθ : ∃ r : ℚ, θ = r * π) (hcos : ∃ q : ℚ, cos θ = q) :
cos θ ∈ ({-1, -1 / 2, 0, 1 / 2, 1} : Set ℝ) := by
-- Since `2 cos θ ` is an algebraic integer and rational, it must be an integer.
-- Hence, `2 cos θ ∈ {-2, -1, 0, 1, 2}`.
obtain ⟨r, rfl⟩ := hθ
obtain ⟨k, hk⟩ : ∃ k : ℤ, 2 * cos (r * π) = k := by
rw [← (isIntegral_two_mul_cos_rat_mul_pi r).exists_int_iff_exists_rat]
exact ⟨2 * hcos.choose, by push_cast; linarith [hcos.choose_spec]⟩
-- Since k is an integer and `2 * cos (w * pi) = k`, we have $k ∈ {-2, -1, 0, 1, 2}$.
have hk_values : k ∈ Finset.Icc (-2 : ℤ) 2 := by
rw [Finset.mem_Icc]
rify
constructor <;> linarith [hk, (r * π).neg_one_le_cos, (r * π).cos_le_one]
rw [show cos (r * π) = k / 2 by grind]
fin_cases hk_values <;> simp
/-- Niven's theorem, but stated for `sin` instead of `cos`. -/
theorem niven_sin (hθ : ∃ r : ℚ, θ = r * π) (hcos : ∃ q : ℚ, sin θ = q) :
sin θ ∈ ({-1, -1 / 2, 0, 1 / 2, 1} : Set ℝ) := by
convert ← niven (θ := θ - π/2) ?_ ?_ using 1
· exact cos_sub_pi_div_two θ
· exact hθ.imp' (· - 1 / 2) (by intros; push_cast; linarith)
· simpa [cos_sub_pi_div_two]
/-- Niven's theorem, giving the possible angles for `θ` in the range `0 .. π`. -/
theorem niven_angle_eq (hθ : ∃ r : ℚ, θ = r * π) (hcos : ∃ q : ℚ, cos θ = q)
(h_bnd : θ ∈ Set.Icc 0 π) : θ ∈ ({0, π / 3, π / 2, π * (2 / 3), π} : Set ℝ) := by
rcases niven hθ hcos with h | h | h | h | h <;>
-- define `h₂` appropriately for each proof branch
[ have h₂ := cos_pi;
have h₂ : cos (π * (2 / 3)) = -1 / 2 := by
have := cos_pi_sub (π / 3)
have := cos_pi_div_three
grind;;
have h₂ := cos_pi_div_two;
have h₂ := cos_pi_div_three;
have h₂ := cos_zero] <;>
simp [injOn_cos h_bnd ⟨by positivity, by linarith [pi_nonneg]⟩ (h₂ ▸ h)] |
.lake/packages/mathlib/Mathlib/NumberTheory/BernoulliPolynomials.lean | import Mathlib.Algebra.Polynomial.AlgebraMap
import Mathlib.Algebra.Polynomial.Derivative
import Mathlib.Data.Nat.Choose.Cast
import Mathlib.NumberTheory.Bernoulli
/-!
# Bernoulli polynomials
The [Bernoulli polynomials](https://en.wikipedia.org/wiki/Bernoulli_polynomials)
are an important tool obtained from Bernoulli numbers.
## Mathematical overview
The $n$-th Bernoulli polynomial is defined as
$$ B_n(X) = ∑_{k = 0}^n {n \choose k} (-1)^k B_k X^{n - k} $$
where $B_k$ is the $k$-th Bernoulli number. The Bernoulli polynomials are generating functions,
$$ \frac{t e^{tX} }{ e^t - 1} = ∑_{n = 0}^{\infty} B_n(X) \frac{t^n}{n!} $$
## Implementation detail
Bernoulli polynomials are defined using `bernoulli`, the Bernoulli numbers.
## Main theorems
- `sum_bernoulli`: The sum of the $k^\mathrm{th}$ Bernoulli polynomial with binomial
coefficients up to `n` is `(n + 1) * X^n`.
- `Polynomial.bernoulli_generating_function`: The Bernoulli polynomials act as generating functions
for the exponential.
## TODO
- `bernoulli_eval_one_neg` : $$ B_n(1 - x) = (-1)^n B_n(x) $$
-/
noncomputable section
open Nat Polynomial
open Nat Finset
namespace Polynomial
/-- The Bernoulli polynomials are defined in terms of the negative Bernoulli numbers. -/
def bernoulli (n : ℕ) : ℚ[X] :=
∑ i ∈ range (n + 1), Polynomial.monomial (n - i) (_root_.bernoulli i * choose n i)
theorem bernoulli_def (n : ℕ) : bernoulli n =
∑ i ∈ range (n + 1), Polynomial.monomial i (_root_.bernoulli (n - i) * choose n i) := by
rw [← sum_range_reflect, add_succ_sub_one, add_zero, bernoulli]
apply sum_congr rfl
rintro x hx
rw [mem_range_succ_iff] at hx
rw [choose_symm hx, tsub_tsub_cancel_of_le hx]
/-
### examples
-/
section Examples
@[simp]
theorem bernoulli_zero : bernoulli 0 = 1 := by simp [bernoulli]
@[simp]
theorem bernoulli_eval_zero (n : ℕ) : (bernoulli n).eval 0 = _root_.bernoulli n := by
rw [bernoulli, eval_finset_sum, sum_range_succ]
have : ∑ x ∈ range n, _root_.bernoulli x * n.choose x * 0 ^ (n - x) = 0 := by
apply sum_eq_zero fun x hx => _
intro x hx
simp [tsub_eq_zero_iff_le, mem_range.1 hx]
simp [this]
@[simp]
theorem bernoulli_eval_one (n : ℕ) : (bernoulli n).eval 1 = bernoulli' n := by
simp only [bernoulli, eval_finset_sum]
simp only [← succ_eq_add_one, sum_range_succ, mul_one, cast_one, choose_self,
(_root_.bernoulli _).mul_comm, sum_bernoulli, one_pow, mul_one, eval_monomial, one_mul]
by_cases h : n = 1
· norm_num [h]
· simp [h, bernoulli_eq_bernoulli'_of_ne_one h]
end Examples
theorem derivative_bernoulli_add_one (k : ℕ) :
Polynomial.derivative (bernoulli (k + 1)) = (k + 1) * bernoulli k := by
simp_rw [bernoulli, derivative_sum, derivative_monomial, Nat.sub_sub, Nat.add_sub_add_right]
-- LHS sum has an extra term, but the coefficient is zero:
rw [range_add_one, sum_insert notMem_range_self, tsub_self, cast_zero, mul_zero,
map_zero, zero_add, mul_sum]
-- the rest of the sum is termwise equal:
refine sum_congr (by rfl) fun m _ => ?_
conv_rhs => rw [← Nat.cast_one, ← Nat.cast_add, ← C_eq_natCast, C_mul_monomial, mul_comm]
rw [mul_assoc, mul_assoc, ← Nat.cast_mul, ← Nat.cast_mul]
congr 3
rw [(choose_mul_succ_eq k m).symm]
theorem derivative_bernoulli (k : ℕ) :
Polynomial.derivative (bernoulli k) = k * bernoulli (k - 1) := by
cases k with
| zero => rw [Nat.cast_zero, zero_mul, bernoulli_zero, derivative_one]
| succ k => exact mod_cast derivative_bernoulli_add_one k
@[simp]
nonrec theorem sum_bernoulli (n : ℕ) :
(∑ k ∈ range (n + 1), ((n + 1).choose k : ℚ) • bernoulli k) = monomial n (n + 1 : ℚ) := by
simp_rw [bernoulli_def, Finset.smul_sum, Finset.range_eq_Ico, ← Finset.sum_Ico_Ico_comm,
Finset.sum_Ico_eq_sum_range]
simp only [add_tsub_cancel_left, tsub_zero, zero_add, map_add]
simp_rw [smul_monomial, mul_comm (_root_.bernoulli _) _, smul_eq_mul, ← mul_assoc]
conv_lhs =>
apply_congr
· skip
· conv =>
apply_congr
· skip
· rw [← Nat.cast_mul, choose_mul ((le_tsub_iff_left <| mem_range_le (by assumption)).1 <|
mem_range_le (by assumption)) (le.intro rfl),
Nat.cast_mul, add_tsub_cancel_left, mul_assoc, mul_comm, ← smul_eq_mul, ←
smul_monomial]
simp_rw [← sum_smul]
rw [sum_range_succ_comm]
simp only [add_eq_left, mul_one, cast_one, cast_add, add_tsub_cancel_left,
choose_succ_self_right, one_smul, _root_.bernoulli_zero, sum_singleton, zero_add,
map_add, range_one, mul_one]
apply sum_eq_zero fun x hx => _
have f : ∀ x ∈ range n, ¬n + 1 - x = 1 := by grind
intro x hx
rw [sum_bernoulli]
have g : ite (n + 1 - x = 1) (1 : ℚ) 0 = 0 := by
simp only [ite_eq_right_iff, one_ne_zero]
intro h₁
exact (f x hx) h₁
rw [g, zero_smul]
/-- Another version of `Polynomial.sum_bernoulli`. -/
theorem bernoulli_eq_sub_sum (n : ℕ) :
(n.succ : ℚ) • bernoulli n =
monomial n (n.succ : ℚ) - ∑ k ∈ Finset.range n, ((n + 1).choose k : ℚ) • bernoulli k := by
rw [Nat.cast_succ, ← sum_bernoulli n, sum_range_succ, add_sub_cancel_left, choose_succ_self_right,
Nat.cast_succ]
/-- Another version of `sum_range_pow`. -/
theorem sum_range_pow_eq_bernoulli_sub (n p : ℕ) :
((p + 1 : ℚ) * ∑ k ∈ range n, (k : ℚ) ^ p) = (bernoulli p.succ).eval (n : ℚ) -
_root_.bernoulli p.succ := by
rw [sum_range_pow, bernoulli_def, eval_finset_sum, ← sum_div, mul_div_cancel₀ _ _]
· simp_rw [eval_monomial]
symm
rw [← sum_flip _, sum_range_succ]
simp only [tsub_self, tsub_zero, choose_zero_right, cast_one, mul_one, _root_.pow_zero,
add_tsub_cancel_right]
apply sum_congr rfl fun x hx => _
intro x hx
apply congr_arg₂ _ (congr_arg₂ _ _ _) rfl
· rw [Nat.sub_sub_self (mem_range_le hx)]
· rw [← choose_symm (mem_range_le hx)]
· norm_cast
/-- Rearrangement of `Polynomial.sum_range_pow_eq_bernoulli_sub`. -/
theorem bernoulli_succ_eval (n p : ℕ) : (bernoulli p.succ).eval (n : ℚ) =
_root_.bernoulli p.succ + (p + 1 : ℚ) * ∑ k ∈ range n, (k : ℚ) ^ p := by
apply eq_add_of_sub_eq'
rw [sum_range_pow_eq_bernoulli_sub]
theorem bernoulli_eval_one_add (n : ℕ) (x : ℚ) :
(bernoulli n).eval (1 + x) = (bernoulli n).eval x + n * x ^ (n - 1) := by
refine Nat.strong_induction_on n fun d hd => ?_
have nz : ((d.succ : ℕ) : ℚ) ≠ 0 := by norm_cast
apply (mul_right_inj' nz).1
rw [← smul_eq_mul, ← eval_smul, bernoulli_eq_sub_sum, mul_add, ← smul_eq_mul, ← eval_smul,
bernoulli_eq_sub_sum, eval_sub, eval_finset_sum]
conv_lhs =>
congr
· skip
· apply_congr
· skip
· rw [eval_smul, hd _ (mem_range.1 (by assumption))]
rw [eval_sub, eval_finset_sum]
simp_rw [eval_smul, smul_add]
rw [sum_add_distrib, sub_add, sub_eq_sub_iff_sub_eq_sub, _root_.add_sub_sub_cancel]
conv_rhs =>
congr
· skip
· congr
rw [succ_eq_add_one, ← choose_succ_self_right d]
rw [Nat.cast_succ, ← smul_eq_mul, ← sum_range_succ _ d, eval_monomial_one_add_sub]
simp_rw [smul_eq_mul]
open PowerSeries
variable {A : Type*} [CommRing A] [Algebra ℚ A]
-- TODO: define exponential generating functions, and use them here
-- This name should probably be updated afterwards
/-- The theorem that $(e^X - 1) * ∑ Bₙ(t)* X^n/n! = Xe^{tX}$ -/
theorem bernoulli_generating_function (t : A) :
(mk fun n => aeval t ((1 / n ! : ℚ) • bernoulli n)) * (exp A - 1) =
PowerSeries.X * rescale t (exp A) := by
-- check equality of power series by checking coefficients of X^n
ext n
-- n = 0 case solved by `simp`
cases n with | zero => simp | succ n =>
-- n ≥ 1, the coefficients is a sum to n+2, so use `sum_range_succ` to write as
-- last term plus sum to n+1
rw [coeff_succ_X_mul, coeff_rescale, coeff_exp, PowerSeries.coeff_mul,
Nat.sum_antidiagonal_eq_sum_range_succ_mk, sum_range_succ]
-- last term is zero so kill with `add_zero`
simp only [RingHom.map_sub, tsub_self, constantCoeff_one, constantCoeff_exp,
coeff_zero_eq_constantCoeff, mul_zero, sub_self, add_zero]
-- Let's multiply both sides by (n+1)! (OK because it's a unit)
have hnp1 : IsUnit ((n + 1)! : ℚ) := IsUnit.mk0 _ (mod_cast factorial_ne_zero (n + 1))
rw [← (hnp1.map (algebraMap ℚ A)).mul_right_inj]
-- do trivial rearrangements to make RHS (n+1)*t^n
rw [mul_left_comm, ← RingHom.map_mul]
change _ = t ^ n * algebraMap ℚ A (((n + 1) * n ! : ℕ) * (1 / n !))
rw [cast_mul, mul_assoc,
mul_one_div_cancel (show (n ! : ℚ) ≠ 0 from cast_ne_zero.2 (factorial_ne_zero n)), mul_one,
mul_comm (t ^ n), ← aeval_monomial, cast_add, cast_one]
-- But this is the RHS of `Polynomial.sum_bernoulli`
rw [← sum_bernoulli, Finset.mul_sum, map_sum]
-- and now we have to prove a sum is a sum, but all the terms are equal.
apply Finset.sum_congr rfl
-- The rest is just trivialities, hampered by the fact that we're coercing
-- factorials and binomial coefficients between ℕ and ℚ and A.
intro i hi
-- deal with coefficients of e^X-1
simp only [Nat.cast_choose ℚ (mem_range_le hi), coeff_mk, if_neg (mem_range_sub_ne_zero hi),
one_div, PowerSeries.coeff_one, coeff_exp, sub_zero, LinearMap.map_sub,
Algebra.smul_def, mul_right_comm _ ((aeval t) _), ← mul_assoc, ←
RingHom.map_mul, ← Polynomial.C_eq_algebraMap, Polynomial.aeval_mul,
Polynomial.aeval_C]
-- finally cancel the Bernoulli polynomial and the algebra_map
field_simp
end Polynomial |
.lake/packages/mathlib/Mathlib/NumberTheory/Bertrand.lean | import Mathlib.Data.Nat.Choose.Factorization
import Mathlib.NumberTheory.Primorial
import Mathlib.Analysis.Convex.SpecificFunctions.Basic
import Mathlib.Analysis.Convex.SpecificFunctions.Deriv
import Mathlib.Tactic.NormNum.Prime
/-!
# Bertrand's Postulate
This file contains a proof of Bertrand's postulate: That between any positive number and its
double there is a prime.
The proof follows the outline of the Erdős proof presented in "Proofs from THE BOOK": One considers
the prime factorization of `(2 * n).choose n`, and splits the constituent primes up into various
groups, then upper bounds the contribution of each group. This upper bounds the central binomial
coefficient, and if the postulate does not hold, this upper bound conflicts with a simple lower
bound for large enough `n`. This proves the result holds for large enough `n`, and for smaller `n`
an explicit list of primes is provided which covers the remaining cases.
As in the [Metamath implementation](carneiro2015arithmetic), we rely on some optimizations from
[Shigenori Tochiori](tochiori_bertrand). In particular we use the cleaner bound on the central
binomial coefficient given in `Nat.four_pow_lt_mul_centralBinom`.
## References
* [M. Aigner and G. M. Ziegler _Proofs from THE BOOK_][aigner1999proofs]
* [S. Tochiori, _Considering the Proof of “There is a Prime between n and 2n”_][tochiori_bertrand]
* [M. Carneiro, _Arithmetic in Metamath, Case Study: Bertrand's Postulate_][carneiro2015arithmetic]
## Tags
Bertrand, prime, binomial coefficients
-/
section Real
open Real
namespace Bertrand
/-- A refined version of the `Bertrand.main_inequality` below.
This is not best possible: it actually holds for 464 ≤ x.
-/
theorem real_main_inequality {x : ℝ} (x_large : (512 : ℝ) ≤ x) :
x * (2 * x) ^ √(2 * x) * 4 ^ (2 * x / 3) ≤ 4 ^ x := by
let f : ℝ → ℝ := fun x => log x + √(2 * x) * log (2 * x) - log 4 / 3 * x
have hf' : ∀ x, 0 < x → 0 < x * (2 * x) ^ √(2 * x) / 4 ^ (x / 3) := fun x h =>
div_pos (mul_pos h (rpow_pos_of_pos (mul_pos two_pos h) _)) (rpow_pos_of_pos four_pos _)
have hf : ∀ x, 0 < x → f x = log (x * (2 * x) ^ √(2 * x) / 4 ^ (x / 3)) := by
intro x h5
have h6 := mul_pos (zero_lt_two' ℝ) h5
have h7 := rpow_pos_of_pos h6 (√(2 * x))
rw [log_div (mul_pos h5 h7).ne' (rpow_pos_of_pos four_pos _).ne', log_mul h5.ne' h7.ne',
log_rpow h6, log_rpow zero_lt_four, ← mul_div_right_comm, ← mul_div, mul_comm x]
have h5 : 0 < x := lt_of_lt_of_le (by norm_num1) x_large
rw [← div_le_one (rpow_pos_of_pos four_pos x), ← div_div_eq_mul_div, ← rpow_sub four_pos, ←
mul_div 2 x, mul_div_left_comm, ← mul_one_sub, (by norm_num1 : (1 : ℝ) - 2 / 3 = 1 / 3),
mul_one_div, ← log_nonpos_iff (hf' x h5).le, ← hf x h5]
-- Porting note (https://github.com/leanprover-community/mathlib4/issues/11083): the proof was rewritten, because it was too slow
-- Original:
/-
have h : ConcaveOn ℝ (Set.Ioi 0.5) f := by
refine ((strictConcaveOn_log_Ioi.concaveOn.subset (Set.Ioi_subset_Ioi _)
(convex_Ioi 0.5)).add ((strictConcaveOn_sqrt_mul_log_Ioi.concaveOn.comp_linearMap
((2 : ℝ) • LinearMap.id)).subset
(fun a ha => lt_of_eq_of_lt _ ((mul_lt_mul_iff_right₀ two_pos).mpr ha)) (convex_Ioi 0.5))).sub
((convex_on_id (convex_Ioi (0.5 : ℝ))).smul (div_nonneg (log_nonneg _) _))
norm_num
-/
have h : ConcaveOn ℝ (Set.Ioi 0.5) f := by
apply ConcaveOn.sub
· apply ConcaveOn.add
· exact strictConcaveOn_log_Ioi.concaveOn.subset
(Set.Ioi_subset_Ioi (by norm_num)) (convex_Ioi 0.5)
convert ((strictConcaveOn_sqrt_mul_log_Ioi.concaveOn.comp_linearMap
((2 : ℝ) • LinearMap.id))) using 1
ext x
simp only [Set.mem_Ioi, Set.mem_preimage, LinearMap.smul_apply,
LinearMap.id_coe, id_eq, smul_eq_mul]
rw [← mul_lt_mul_iff_right₀ (two_pos)]
norm_num1
rfl
apply ConvexOn.smul
· refine div_nonneg (log_nonneg (by norm_num1)) (by norm_num1)
· exact convexOn_id (convex_Ioi (0.5 : ℝ))
suffices ∃ x1 x2, 0.5 < x1 ∧ x1 < x2 ∧ x2 ≤ x ∧ 0 ≤ f x1 ∧ f x2 ≤ 0 by
obtain ⟨x1, x2, h1, h2, h0, h3, h4⟩ := this
exact (h.right_le_of_le_left'' h1 ((h1.trans h2).trans_le h0) h2 h0 (h4.trans h3)).trans h4
refine ⟨18, 512, by norm_num1, by norm_num1, x_large, ?_, ?_⟩
· have : √(2 * 18 : ℝ) = 6 := (sqrt_eq_iff_mul_self_eq_of_pos (by norm_num1)).mpr (by norm_num1)
rw [hf _ (by norm_num1), log_nonneg_iff (by positivity), this, one_le_div (by norm_num1)]
norm_num1
· have : √(2 * 512) = 32 :=
(sqrt_eq_iff_mul_self_eq_of_pos (by norm_num1)).mpr (by norm_num1)
rw [hf _ (by norm_num1), log_nonpos_iff (hf' _ (by norm_num1)).le, this,
div_le_one (by positivity)]
conv in 512 => equals 2 ^ 9 => norm_num1
conv in 2 * 512 => equals 2 ^ 10 => norm_num1
conv in 32 => rw [← Nat.cast_ofNat]
rw [rpow_natCast, ← pow_mul, ← pow_add]
conv in 4 => equals 2 ^ (2 : ℝ) => rw [rpow_two]; norm_num1
rw [← rpow_mul, ← rpow_natCast]
on_goal 1 => apply rpow_le_rpow_of_exponent_le
all_goals norm_num1
end Bertrand
end Real
section Nat
open Nat
/-- The inequality which contradicts Bertrand's postulate, for large enough `n`.
-/
theorem bertrand_main_inequality {n : ℕ} (n_large : 512 ≤ n) :
n * (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) ≤ 4 ^ n := by
rw [← @cast_le ℝ]
simp only [cast_mul, cast_pow, ← Real.rpow_natCast, cast_ofNat]
refine _root_.trans ?_ (Bertrand.real_main_inequality (by exact_mod_cast n_large))
gcongr
· have n2_pos : 0 < 2 * n := by positivity
exact mod_cast n2_pos
· exact_mod_cast Real.nat_sqrt_le_real_sqrt
· norm_num1
· exact cast_div_le.trans (by norm_cast)
/-- A lemma that tells us that, in the case where Bertrand's postulate does not hold, the prime
factorization of the central binomial coefficient only has factors at most `2 * n / 3 + 1`.
-/
theorem centralBinom_factorization_small (n : ℕ) (n_large : 2 < n)
(no_prime : ∀ p : ℕ, p.Prime → n < p → 2 * n < p) :
centralBinom n = ∏ p ∈ Finset.range (2 * n / 3 + 1), p ^ (centralBinom n).factorization p := by
refine (Eq.trans ?_ n.prod_pow_factorization_centralBinom).symm
apply Finset.prod_subset
· grw [Nat.div_le_self]
intro x hx h2x
rw [Finset.mem_range, Nat.lt_succ_iff] at hx h2x
rw [not_le, div_lt_iff_lt_mul three_pos, mul_comm x] at h2x
obtain h | h : ¬ x.Prime ∨ x ≤ n := by simpa [imp_iff_not_or, hx.not_gt] using no_prime x
· rw [factorization_eq_zero_of_not_prime n.centralBinom h, Nat.pow_zero]
· rw [factorization_centralBinom_of_two_mul_self_lt_three_mul n_large h h2x, Nat.pow_zero]
/-- An upper bound on the central binomial coefficient used in the proof of Bertrand's postulate.
The bound splits the prime factors of `centralBinom n` into those
1. At most `sqrt (2 * n)`, which contribute at most `2 * n` for each such prime.
2. Between `sqrt (2 * n)` and `2 * n / 3`, which contribute at most `4^(2 * n / 3)` in total.
3. Between `2 * n / 3` and `n`, which do not exist.
4. Between `n` and `2 * n`, which would not exist in the case where Bertrand's postulate is false.
5. Above `2 * n`, which do not exist.
-/
theorem centralBinom_le_of_no_bertrand_prime (n : ℕ) (n_large : 2 < n)
(no_prime : ∀ p : ℕ, p.Prime → n < p → 2 * n < p) :
centralBinom n ≤ (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) := by
have n_pos : 0 < n := (Nat.zero_le _).trans_lt n_large
have n2_pos : 1 ≤ 2 * n := mul_pos (zero_lt_two' ℕ) n_pos
let S := {p ∈ Finset.range (2 * n / 3 + 1) | Nat.Prime p}
let f x := x ^ n.centralBinom.factorization x
have : ∏ x ∈ S, f x = ∏ x ∈ Finset.range (2 * n / 3 + 1), f x := by
refine Finset.prod_filter_of_ne fun p _ h => ?_
contrapose! h; dsimp only [f]
rw [factorization_eq_zero_of_not_prime n.centralBinom h, _root_.pow_zero]
rw [centralBinom_factorization_small n n_large no_prime, ← this, ←
Finset.prod_filter_mul_prod_filter_not S (· ≤ sqrt (2 * n))]
apply mul_le_mul'
· refine (Finset.prod_le_prod' fun p _ => (?_ : f p ≤ 2 * n)).trans ?_
· exact pow_factorization_choose_le (mul_pos two_pos n_pos)
have : (Finset.Icc 1 (sqrt (2 * n))).card = sqrt (2 * n) := by rw [card_Icc, Nat.add_sub_cancel]
rw [Finset.prod_const]
refine pow_right_mono₀ n2_pos ((Finset.card_le_card fun x hx => ?_).trans this.le)
obtain ⟨h1, h2⟩ := Finset.mem_filter.1 hx
exact Finset.mem_Icc.mpr ⟨(Finset.mem_filter.1 h1).2.one_lt.le, h2⟩
· refine le_trans ?_ (primorial_le_4_pow (2 * n / 3))
refine (Finset.prod_le_prod' fun p hp => (?_ : f p ≤ p)).trans ?_
· obtain ⟨h1, h2⟩ := Finset.mem_filter.1 hp
refine (pow_right_mono₀ (Finset.mem_filter.1 h1).2.one_lt.le ?_).trans (pow_one p).le
exact Nat.factorization_choose_le_one (sqrt_lt'.mp <| not_le.1 h2)
refine Finset.prod_le_prod_of_subset_of_one_le' (Finset.filter_subset _ _) ?_
exact fun p hp _ => (Finset.mem_filter.1 hp).2.one_lt.le
namespace Nat
/-- Proves that **Bertrand's postulate** holds for all sufficiently large `n`.
-/
theorem exists_prime_lt_and_le_two_mul_eventually (n : ℕ) (n_large : 512 ≤ n) :
∃ p : ℕ, p.Prime ∧ n < p ∧ p ≤ 2 * n := by
have no_prime : 4 ^ n < n * n.centralBinom :=
Nat.four_pow_lt_mul_centralBinom n (le_trans (by norm_num1) n_large)
-- Assume there is no prime in the range.
contrapose! no_prime
-- Then we have the above sub-exponential bound on the size of this central binomial coefficient.
-- We now couple this bound with an exponential lower bound on the central binomial coefficient,
-- yielding an inequality which we have seen is false for large enough n.
have : n.centralBinom ≤ (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) :=
centralBinom_le_of_no_bertrand_prime n (lt_of_lt_of_le (by norm_num1) n_large) no_prime
grw [this, ← mul_assoc, bertrand_main_inequality n_large]
/-- Proves that Bertrand's postulate holds over all positive naturals less than n by identifying a
descending list of primes, each no more than twice the next, such that the list contains a witness
for each number ≤ n.
-/
theorem exists_prime_lt_and_le_two_mul_succ {n} (q) {p : ℕ} (prime_p : Nat.Prime p)
(covering : p ≤ 2 * q) (H : n < q → ∃ p : ℕ, p.Prime ∧ n < p ∧ p ≤ 2 * n) (hn : n < p) :
∃ p : ℕ, p.Prime ∧ n < p ∧ p ≤ 2 * n := by
grind
/--
**Bertrand's Postulate**: For any positive natural number, there is a prime which is greater than
it, but no more than twice as large.
-/
theorem exists_prime_lt_and_le_two_mul (n : ℕ) (hn0 : n ≠ 0) :
∃ p, Nat.Prime p ∧ n < p ∧ p ≤ 2 * n := by
-- Split into cases whether `n` is large or small
rcases lt_or_ge 511 n with h | h
-- If `n` is large, apply the lemma derived from the inequalities on the central binomial
-- coefficient.
· exact exists_prime_lt_and_le_two_mul_eventually n h
replace h : n < 521 := h.trans_lt (by norm_num1)
revert h
-- For small `n`, supply a list of primes to cover the initial cases.
open Lean Elab Tactic in
run_tac do
for i in [317, 163, 83, 43, 23, 13, 7, 5, 3, 2] do
let i : Term := quote i
evalTactic <| ←
`(tactic| refine exists_prime_lt_and_le_two_mul_succ $i (by norm_num1) (by norm_num1) ?_)
exact fun h2 => ⟨2, prime_two, h2, Nat.mul_le_mul_left 2 (Nat.pos_of_ne_zero hn0)⟩
alias bertrand := Nat.exists_prime_lt_and_le_two_mul
end Nat
end Nat |
.lake/packages/mathlib/Mathlib/NumberTheory/SiegelsLemma.lean | import Mathlib.Analysis.Matrix.Normed
import Mathlib.Data.Pi.Interval
import Mathlib.Tactic.Rify
/-!
# Siegel's Lemma
In this file we introduce and prove Siegel's Lemma in its most basic version. This is a fundamental
tool in diophantine approximation and transcendence and says that there exists a "small" integral
non-zero solution of a non-trivial underdetermined system of linear equations with integer
coefficients.
## Main results
- `exists_ne_zero_int_vec_norm_le`: Given a non-zero `m × n` matrix `A` with `m < n` the linear
system it determines has a non-zero integer solution `t` with
`‖t‖ ≤ ((n * ‖A‖) ^ ((m : ℝ) / (n - m)))`
## Notation
- `‖_‖ ` : Matrix.seminormedAddCommGroup is the sup norm, the maximum of the absolute values of
the entries of the matrix
## References
See [M. Hindry and J. Silverman, Diophantine Geometry: an Introduction][hindrysilverman00].
-/
/- We set ‖⬝‖ to be Matrix.seminormedAddCommGroup -/
attribute [local instance] Matrix.seminormedAddCommGroup
open Matrix Finset
namespace Int.Matrix
variable {α β : Type*} [Fintype α] [Fintype β] (A : Matrix α β ℤ)
-- Some definitions and relative properties
local notation3 "m" => Fintype.card α
local notation3 "n" => Fintype.card β
local notation3 "e" => m / ((n : ℝ) - m) -- exponent
local notation3 "B" => Nat.floor (((n : ℝ) * max 1 ‖A‖) ^ e)
-- B' is the vector with all components = B
local notation3 "B'" => fun _ : β => (B : ℤ)
-- T is the box [0 B]^n
local notation3 "T" => Finset.Icc 0 B'
local notation3 "P" => fun i : α => ∑ j : β, B * posPart (A i j)
local notation3 "N" => fun i : α => ∑ j : β, B * (-negPart (A i j))
-- S is the box where the image of T goes
local notation3 "S" => Finset.Icc N P
section preparation
/- In order to apply Pigeonhole we need:
# Step 1: ∀ v ∈ T, A *ᵥ v ∈ S
and
# Step 2: #S < #T
Pigeonhole will give different x and y in T with A.mulVec x = A.mulVec y in S
Their difference is the solution we are looking for
-/
-- # Step 1: ∀ v ∈ T, A *ᵥ v ∈ S
private lemma image_T_subset_S [DecidableEq α] [DecidableEq β] (v) (hv : v ∈ T) : A *ᵥ v ∈ S := by
rw [mem_Icc] at hv ⊢
have mulVec_def : A.mulVec v =
fun i ↦ Finset.sum univ fun j : β ↦ A i j * v j := rfl
rw [mulVec_def]
refine ⟨fun i ↦ ?_, fun i ↦ ?_⟩
all_goals
simp only [mul_neg]
gcongr ∑ _ : β, ?_ with j _ -- Get rid of sums
rw [← mul_comm (v j)] -- Move A i j to the right of the products
rcases le_total 0 (A i j) with hsign | hsign-- We have to distinguish cases: we have now 4 goals
· rw [negPart_eq_zero.2 hsign]
exact mul_nonneg (hv.1 j) hsign
· rw [negPart_eq_neg.2 hsign]
simp only [mul_neg, neg_neg]
exact mul_le_mul_of_nonpos_right (hv.2 j) hsign
· rw [posPart_eq_self.2 hsign]
gcongr
apply hv.2
· rw [posPart_eq_zero.2 hsign]
exact mul_nonpos_of_nonneg_of_nonpos (hv.1 j) hsign
-- # Preparation for Step 2
private lemma card_T_eq [DecidableEq β] : #T = (B + 1) ^ n := by
rw [Pi.card_Icc 0 B']
simp only [Pi.zero_apply, card_Icc, sub_zero, toNat_natCast_add_one, prod_const, card_univ]
-- This lemma is necessary to be able to apply the formula #(Icc a b) = b + 1 - a
private lemma N_le_P_add_one (i : α) : N i ≤ P i + 1 := by
calc N i
_ ≤ 0 := by
apply Finset.sum_nonpos
intro j _
simp only [mul_neg, Left.neg_nonpos_iff]
positivity
_ ≤ P i + 1 := by
apply le_trans (Finset.sum_nonneg _) (Int.le_add_one (le_refl P i))
intro j _
positivity
private lemma card_S_eq [DecidableEq α] : #(Finset.Icc N P) = ∏ i : α, (P i - N i + 1) := by
rw [Pi.card_Icc N P, Nat.cast_prod]
congr
ext i
rw [Int.card_Icc_of_le (N i) (P i) (N_le_P_add_one A i)]
exact add_sub_right_comm (P i) 1 (N i)
/-- The sup norm of a non-zero integer matrix is at least one -/
lemma one_le_norm_A_of_ne_zero (hA : A ≠ 0) : 1 ≤ ‖A‖ := by
by_contra! h
apply hA
ext i j
simp only [zero_apply]
rw [norm_lt_iff Real.zero_lt_one] at h
specialize h i j
rw [Int.norm_eq_abs] at h
norm_cast at h
exact Int.abs_lt_one_iff.1 h
-- # Step 2: #S < #T
open Real Nat
private lemma card_S_lt_card_T [DecidableEq α] [DecidableEq β]
(hn : Fintype.card α < Fintype.card β) (hm : 0 < Fintype.card α) :
#S < #T := by
zify -- This is necessary to use card_S_eq
rw [card_T_eq A, card_S_eq]
rify -- This is necessary because ‖A‖ is a real number
calc
∏ x : α, (∑ x_1 : β, ↑B * ↑(A x x_1)⁺ - ∑ x_1 : β, ↑B * -↑(A x x_1)⁻ + 1)
≤ ∏ x : α, (n * max 1 ‖A‖ * B + 1) := by
refine Finset.prod_le_prod (fun i _ ↦ ?_) (fun i _ ↦ ?_)
· have h := N_le_P_add_one A i
rify at h
linarith only [h]
· simp only [mul_neg, sum_neg_distrib, sub_neg_eq_add, add_le_add_iff_right]
have h1 : n * max 1 ‖A‖ * B = ∑ _ : β, max 1 ‖A‖ * B := by
simp
ring
simp_rw [h1, ← Finset.sum_add_distrib, ← mul_add, mul_comm (max 1 ‖A‖), ← Int.cast_add]
gcongr with j _
rw [posPart_add_negPart (A i j), Int.cast_abs]
exact le_trans (norm_entry_le_entrywise_sup_norm A) (le_max_right ..)
_ = (n * max 1 ‖A‖ * B + 1) ^ m := by simp
_ ≤ (n * max 1 ‖A‖) ^ m * (B + 1) ^ m := by
rw [← mul_pow, mul_add, mul_one]
gcongr
have H : 1 ≤ (n : ℝ) := mod_cast (hm.trans hn)
exact one_le_mul_of_one_le_of_one_le H <| le_max_left ..
_ = ((n * max 1 ‖A‖) ^ (m / ((n : ℝ) - m))) ^ ((n : ℝ) - m) * (B + 1) ^ m := by
congr 1
rw [← rpow_mul (mul_nonneg (Nat.cast_nonneg' n) (le_trans zero_le_one (le_max_left ..))),
← Real.rpow_natCast, div_mul_cancel₀]
exact sub_ne_zero_of_ne (mod_cast hn.ne')
_ < (B + 1) ^ ((n : ℝ) - m) * (B + 1) ^ m := by
gcongr
· exact sub_pos.mpr (mod_cast hn)
· exact Nat.lt_floor_add_one ((n * max 1 ‖A‖) ^ e)
_ = (B + 1) ^ n := by
rw [← rpow_natCast, ← rpow_add (Nat.cast_add_one_pos B), ← rpow_natCast, sub_add_cancel]
end preparation
theorem exists_ne_zero_int_vec_norm_le
(hn : Fintype.card α < Fintype.card β) (hm : 0 < Fintype.card α) : ∃ t : β → ℤ, t ≠ 0 ∧
A *ᵥ t = 0 ∧ ‖t‖ ≤ (n * max 1 ‖A‖) ^ ((m : ℝ) / (n - m)) := by
classical
-- Pigeonhole
rcases Finset.exists_ne_map_eq_of_card_lt_of_maps_to
(card_S_lt_card_T A hn hm) (image_T_subset_S A)
with ⟨x, hxT, y, hyT, hneq, hfeq⟩
-- Proofs that x - y ≠ 0 and x - y is a solution
refine ⟨x - y, sub_ne_zero.mpr hneq, by simp only [mulVec_sub, sub_eq_zero, hfeq], ?_⟩
-- Inequality
have n_mul_norm_A_pow_e_nonneg : 0 ≤ (n * max 1 ‖A‖) ^ e := by positivity
rw [← norm_replicateCol (ι := Unit), norm_le_iff n_mul_norm_A_pow_e_nonneg]
intro i j
simp only [replicateCol_apply, Pi.sub_apply]
rw [Int.norm_eq_abs, ← Int.cast_abs]
refine le_trans ?_ (Nat.floor_le n_mul_norm_A_pow_e_nonneg)
norm_cast
rw [abs_le]
rw [Finset.mem_Icc] at hxT hyT
constructor
· simp only [neg_le_sub_iff_le_add]
apply le_trans (hyT.2 i)
norm_cast
simp only [le_add_iff_nonneg_left]
exact hxT.1 i
· simp only [tsub_le_iff_right]
apply le_trans (hxT.2 i)
norm_cast
simp only [le_add_iff_nonneg_right]
exact hyT.1 i
theorem exists_ne_zero_int_vec_norm_le'
(hn : Fintype.card α < Fintype.card β) (hm : 0 < Fintype.card α) (hA : A ≠ 0) :
∃ t : β → ℤ, t ≠ 0 ∧
A *ᵥ t = 0 ∧ ‖t‖ ≤ (n * ‖A‖) ^ ((m : ℝ) / (n - m)) := by
have := exists_ne_zero_int_vec_norm_le A hn hm
rwa [max_eq_right] at this
exact Int.Matrix.one_le_norm_A_of_ne_zero _ hA
end Int.Matrix |
.lake/packages/mathlib/Mathlib/NumberTheory/ZetaValues.lean | import Mathlib.NumberTheory.BernoulliPolynomials
import Mathlib.MeasureTheory.Integral.IntervalIntegral.Basic
import Mathlib.Analysis.Calculus.Deriv.Polynomial
import Mathlib.Analysis.Fourier.AddCircle
import Mathlib.Analysis.PSeries
/-!
# Critical values of the Riemann zeta function
In this file we prove formulae for the critical values of `ζ(s)`, and more generally of Hurwitz
zeta functions, in terms of Bernoulli polynomials.
## Main results:
* `hasSum_zeta_nat`: the final formula for zeta values,
$$\zeta(2k) = \frac{(-1)^{(k + 1)} 2 ^ {2k - 1} \pi^{2k} B_{2 k}}{(2 k)!}.$$
* `hasSum_zeta_two` and `hasSum_zeta_four`: special cases given explicitly.
* `hasSum_one_div_nat_pow_mul_cos`: a formula for the sum `∑ (n : ℕ), cos (2 π i n x) / n ^ k` as
an explicit multiple of `Bₖ(x)`, for any `x ∈ [0, 1]` and `k ≥ 2` even.
* `hasSum_one_div_nat_pow_mul_sin`: a formula for the sum `∑ (n : ℕ), sin (2 π i n x) / n ^ k` as
an explicit multiple of `Bₖ(x)`, for any `x ∈ [0, 1]` and `k ≥ 3` odd.
-/
noncomputable section
open scoped Nat Real Interval
open Complex MeasureTheory Set intervalIntegral
local notation "𝕌" => UnitAddCircle
section BernoulliFunProps
/-! Simple properties of the Bernoulli polynomial, as a function `ℝ → ℝ`. -/
/-- The function `x ↦ Bₖ(x) : ℝ → ℝ`. -/
def bernoulliFun (k : ℕ) (x : ℝ) : ℝ :=
(Polynomial.map (algebraMap ℚ ℝ) (Polynomial.bernoulli k)).eval x
theorem bernoulliFun_eval_zero (k : ℕ) : bernoulliFun k 0 = bernoulli k := by
rw [bernoulliFun, Polynomial.eval_zero_map, Polynomial.bernoulli_eval_zero, eq_ratCast]
theorem bernoulliFun_endpoints_eq_of_ne_one {k : ℕ} (hk : k ≠ 1) :
bernoulliFun k 1 = bernoulliFun k 0 := by
rw [bernoulliFun_eval_zero, bernoulliFun, Polynomial.eval_one_map, Polynomial.bernoulli_eval_one,
bernoulli_eq_bernoulli'_of_ne_one hk, eq_ratCast]
theorem bernoulliFun_eval_one (k : ℕ) : bernoulliFun k 1 = bernoulliFun k 0 + ite (k = 1) 1 0 := by
rw [bernoulliFun, bernoulliFun_eval_zero, Polynomial.eval_one_map, Polynomial.bernoulli_eval_one]
split_ifs with h
· rw [h, bernoulli_one, bernoulli'_one, eq_ratCast]
push_cast; ring
· rw [bernoulli_eq_bernoulli'_of_ne_one h, add_zero, eq_ratCast]
theorem hasDerivAt_bernoulliFun (k : ℕ) (x : ℝ) :
HasDerivAt (bernoulliFun k) (k * bernoulliFun (k - 1) x) x := by
convert ((Polynomial.bernoulli k).map <| algebraMap ℚ ℝ).hasDerivAt x using 1
simp only [bernoulliFun, Polynomial.derivative_map, Polynomial.derivative_bernoulli k,
Polynomial.map_mul, Polynomial.map_natCast, Polynomial.eval_mul, Polynomial.eval_natCast]
theorem antideriv_bernoulliFun (k : ℕ) (x : ℝ) :
HasDerivAt (fun x => bernoulliFun (k + 1) x / (k + 1)) (bernoulliFun k x) x := by
convert (hasDerivAt_bernoulliFun (k + 1) x).div_const _ using 1
simp [Nat.cast_add_one_ne_zero k]
theorem integral_bernoulliFun_eq_zero {k : ℕ} (hk : k ≠ 0) :
∫ x : ℝ in 0..1, bernoulliFun k x = 0 := by
rw [integral_eq_sub_of_hasDerivAt (fun x _ => antideriv_bernoulliFun k x)
((Polynomial.continuous _).intervalIntegrable _ _)]
rw [bernoulliFun_eval_one]
split_ifs with h
· exfalso; exact hk (Nat.succ_inj.mp h)
· simp
end BernoulliFunProps
section BernoulliFourierCoeffs
/-! Compute the Fourier coefficients of the Bernoulli functions via integration by parts. -/
/-- The `n`-th Fourier coefficient of the `k`-th Bernoulli function on the interval `[0, 1]`. -/
def bernoulliFourierCoeff (k : ℕ) (n : ℤ) : ℂ :=
fourierCoeffOn zero_lt_one (fun x => bernoulliFun k x) n
/-- Recurrence relation (in `k`) for the `n`-th Fourier coefficient of `Bₖ`. -/
theorem bernoulliFourierCoeff_recurrence (k : ℕ) {n : ℤ} (hn : n ≠ 0) :
bernoulliFourierCoeff k n =
1 / (-2 * π * I * n) * (ite (k = 1) 1 0 - k * bernoulliFourierCoeff (k - 1) n) := by
unfold bernoulliFourierCoeff
rw [fourierCoeffOn_of_hasDerivAt zero_lt_one hn
(fun x _ => (hasDerivAt_bernoulliFun k x).ofReal_comp)
((continuous_ofReal.comp <|
continuous_const.mul <| Polynomial.continuous _).intervalIntegrable
_ _)]
simp_rw [ofReal_one, ofReal_zero, sub_zero, one_mul]
rw [QuotientAddGroup.mk_zero, fourier_eval_zero, one_mul, ← ofReal_sub, bernoulliFun_eval_one,
add_sub_cancel_left]
congr 2
· split_ifs <;> simp only [ofReal_one, ofReal_zero]
· simp_rw [ofReal_mul, ofReal_natCast, fourierCoeffOn.const_mul]
/-- The Fourier coefficients of `B₀(x) = 1`. -/
theorem bernoulli_zero_fourier_coeff {n : ℤ} (hn : n ≠ 0) : bernoulliFourierCoeff 0 n = 0 := by
simpa using bernoulliFourierCoeff_recurrence 0 hn
/-- The `0`-th Fourier coefficient of `Bₖ(x)`. -/
theorem bernoulliFourierCoeff_zero {k : ℕ} (hk : k ≠ 0) : bernoulliFourierCoeff k 0 = 0 := by
simp_rw [bernoulliFourierCoeff, fourierCoeffOn_eq_integral, neg_zero, fourier_zero, sub_zero,
div_one, one_smul, intervalIntegral.integral_ofReal, integral_bernoulliFun_eq_zero hk,
ofReal_zero]
theorem bernoulliFourierCoeff_eq {k : ℕ} (hk : k ≠ 0) (n : ℤ) :
bernoulliFourierCoeff k n = -k ! / (2 * π * I * n) ^ k := by
rcases eq_or_ne n 0 with (rfl | hn)
· rw [bernoulliFourierCoeff_zero hk, Int.cast_zero, mul_zero, zero_pow hk,
div_zero]
refine Nat.le_induction ?_ (fun k hk h'k => ?_) k (Nat.one_le_iff_ne_zero.mpr hk)
· rw [bernoulliFourierCoeff_recurrence 1 hn]
simp only [Nat.cast_one, tsub_self, neg_mul, one_mul, if_true,
Nat.factorial_one, pow_one]
rw [bernoulli_zero_fourier_coeff hn, sub_zero, mul_one, div_neg, neg_div]
· rw [bernoulliFourierCoeff_recurrence (k + 1) hn, Nat.add_sub_cancel k 1]
split_ifs with h
· exfalso; exact (ne_of_gt (Nat.lt_succ_iff.mpr hk)) h
· rw [h'k, Nat.factorial_succ, zero_sub, Nat.cast_mul, pow_add]
ring
end BernoulliFourierCoeffs
section BernoulliPeriodized
/-! In this section we use the above evaluations of the Fourier coefficients of Bernoulli
polynomials, together with the theorem `has_pointwise_sum_fourier_series_of_summable` from Fourier
theory, to obtain an explicit formula for `∑ (n:ℤ), 1 / n ^ k * fourier n x`. -/
/-- The Bernoulli polynomial, extended from `[0, 1)` to the unit circle. -/
def periodizedBernoulli (k : ℕ) : 𝕌 → ℝ :=
AddCircle.liftIco 1 0 (bernoulliFun k)
theorem periodizedBernoulli.continuous {k : ℕ} (hk : k ≠ 1) : Continuous (periodizedBernoulli k) :=
AddCircle.liftIco_zero_continuous
(mod_cast (bernoulliFun_endpoints_eq_of_ne_one hk).symm)
(Polynomial.continuous _).continuousOn
theorem fourierCoeff_bernoulli_eq {k : ℕ} (hk : k ≠ 0) (n : ℤ) :
fourierCoeff ((↑) ∘ periodizedBernoulli k : 𝕌 → ℂ) n = -k ! / (2 * π * I * n) ^ k := by
have : ((↑) ∘ periodizedBernoulli k : 𝕌 → ℂ) = AddCircle.liftIco 1 0 ((↑) ∘ bernoulliFun k) := by
ext1 x; rfl
rw [this, fourierCoeff_liftIco_eq]
simpa only [zero_add] using bernoulliFourierCoeff_eq hk n
theorem summable_bernoulli_fourier {k : ℕ} (hk : 2 ≤ k) :
Summable (fun n => -k ! / (2 * π * I * n) ^ k : ℤ → ℂ) := by
have :
∀ n : ℤ, -(k ! : ℂ) / (2 * π * I * n) ^ k = -k ! / (2 * π * I) ^ k * (1 / (n : ℂ) ^ k) := by
intro n; rw [mul_one_div, div_div, ← mul_pow]
simp_rw [this]
refine Summable.mul_left _ <| .of_norm ?_
have : (fun x : ℤ => ‖1 / (x : ℂ) ^ k‖) = fun x : ℤ => |1 / (x : ℝ) ^ k| := by
ext1 x
simp only [one_div, norm_inv, norm_pow, norm_intCast, pow_abs, abs_inv]
simp_rw [this]
rwa [summable_abs_iff, Real.summable_one_div_int_pow]
theorem hasSum_one_div_pow_mul_fourier_mul_bernoulliFun {k : ℕ} (hk : 2 ≤ k) {x : ℝ}
(hx : x ∈ Icc (0 : ℝ) 1) :
HasSum (fun n : ℤ => 1 / (n : ℂ) ^ k * fourier n (x : 𝕌))
(-(2 * π * I) ^ k / k ! * bernoulliFun k x) := by
-- first show it suffices to prove result for `Ico 0 1`
suffices ∀ {y : ℝ}, y ∈ Ico (0 : ℝ) 1 →
HasSum (fun (n : ℤ) ↦ 1 / (n : ℂ) ^ k * fourier n y)
(-(2 * (π : ℂ) * I) ^ k / k ! * bernoulliFun k y) by
rw [← Ico_insert_right (zero_le_one' ℝ), mem_insert_iff, or_comm] at hx
rcases hx with (hx | rfl)
· exact this hx
· convert this (left_mem_Ico.mpr zero_lt_one) using 1
· rw [AddCircle.coe_period, QuotientAddGroup.mk_zero]
· rw [bernoulliFun_endpoints_eq_of_ne_one (by cutsat : k ≠ 1)]
intro y hy
let B : C(𝕌, ℂ) :=
ContinuousMap.mk ((↑) ∘ periodizedBernoulli k)
(continuous_ofReal.comp (periodizedBernoulli.continuous (by cutsat)))
have step1 : ∀ n : ℤ, fourierCoeff B n = -k ! / (2 * π * I * n) ^ k := by
rw [ContinuousMap.coe_mk]; exact fourierCoeff_bernoulli_eq (by cutsat : k ≠ 0)
have step2 :=
has_pointwise_sum_fourier_series_of_summable
((summable_bernoulli_fourier hk).congr fun n => (step1 n).symm) y
simp_rw [step1] at step2
convert step2.mul_left (-(2 * ↑π * I) ^ k / (k ! : ℂ)) using 2 with n
· rw [smul_eq_mul, ← mul_assoc, mul_div, mul_neg, div_mul_cancel₀, neg_neg, mul_pow _ (n : ℂ),
← div_div, div_self]
· rw [Ne, pow_eq_zero_iff', not_and_or]
exact Or.inl two_pi_I_ne_zero
· exact Nat.cast_ne_zero.mpr (Nat.factorial_ne_zero _)
· rw [ContinuousMap.coe_mk, Function.comp_apply, ofReal_inj, periodizedBernoulli,
AddCircle.liftIco_coe_apply (show y ∈ Ico 0 (0 + 1) by rwa [zero_add])]
end BernoulliPeriodized
section Cleanup
-- This section is just reformulating the results in a nicer form.
theorem hasSum_one_div_nat_pow_mul_fourier {k : ℕ} (hk : 2 ≤ k) {x : ℝ} (hx : x ∈ Icc (0 : ℝ) 1) :
HasSum
(fun n : ℕ =>
(1 : ℂ) / (n : ℂ) ^ k * (fourier n (x : 𝕌) + (-1 : ℂ) ^ k * fourier (-n) (x : 𝕌)))
(-(2 * π * I) ^ k / k ! * bernoulliFun k x) := by
convert (hasSum_one_div_pow_mul_fourier_mul_bernoulliFun hk hx).nat_add_neg using 1
· ext1 n
rw [Int.cast_neg, mul_add, ← mul_assoc]
conv_rhs => rw [neg_eq_neg_one_mul, mul_pow, ← div_div]
congr 2
rw [div_mul_eq_mul_div₀, one_mul]
congr 1
rw [eq_div_iff, ← mul_pow, ← neg_eq_neg_one_mul, neg_neg, one_pow]
apply pow_ne_zero; rw [neg_ne_zero]; exact one_ne_zero
· rw [Int.cast_zero, zero_pow (by positivity : k ≠ 0), div_zero, zero_mul, add_zero]
theorem hasSum_one_div_nat_pow_mul_cos {k : ℕ} (hk : k ≠ 0) {x : ℝ} (hx : x ∈ Icc (0 : ℝ) 1) :
HasSum (fun n : ℕ => 1 / (n : ℝ) ^ (2 * k) * Real.cos (2 * π * n * x))
((-1 : ℝ) ^ (k + 1) * (2 * π) ^ (2 * k) / 2 / (2 * k)! *
(Polynomial.map (algebraMap ℚ ℝ) (Polynomial.bernoulli (2 * k))).eval x) := by
have :
HasSum (fun n : ℕ => 1 / (n : ℂ) ^ (2 * k) * (fourier n (x : 𝕌) + fourier (-n) (x : 𝕌)))
((-1 : ℂ) ^ (k + 1) * (2 * (π : ℂ)) ^ (2 * k) / (2 * k)! * bernoulliFun (2 * k) x) := by
convert
hasSum_one_div_nat_pow_mul_fourier (by cutsat : 2 ≤ 2 * k)
hx using 3
· rw [pow_mul (-1 : ℂ), neg_one_sq, one_pow, one_mul]
· rw [pow_add, pow_one]
conv_rhs =>
rw [mul_pow]
congr
congr
· skip
· rw [pow_mul, I_sq]
ring
have ofReal_two : ((2 : ℝ) : ℂ) = 2 := by norm_cast
convert ((hasSum_iff _ _).mp (this.div_const 2)).1 with n
· convert (ofReal_re _).symm
rw [ofReal_mul]; rw [← mul_div]; congr
· rw [ofReal_div, ofReal_one, ofReal_pow]; rfl
· rw [ofReal_cos, ofReal_mul, fourier_coe_apply, fourier_coe_apply, cos, ofReal_one, div_one,
div_one, ofReal_mul, ofReal_mul, ofReal_two, Int.cast_neg, Int.cast_natCast,
ofReal_natCast]
congr 3
· ring
· ring
· convert (ofReal_re _).symm
rw [ofReal_mul, ofReal_div, ofReal_div, ofReal_mul, ofReal_pow, ofReal_pow, ofReal_neg,
ofReal_natCast, ofReal_mul, ofReal_two, ofReal_one]
rw [bernoulliFun]
ring
theorem hasSum_one_div_nat_pow_mul_sin {k : ℕ} (hk : k ≠ 0) {x : ℝ} (hx : x ∈ Icc (0 : ℝ) 1) :
HasSum (fun n : ℕ => 1 / (n : ℝ) ^ (2 * k + 1) * Real.sin (2 * π * n * x))
((-1 : ℝ) ^ (k + 1) * (2 * π) ^ (2 * k + 1) / 2 / (2 * k + 1)! *
(Polynomial.map (algebraMap ℚ ℝ) (Polynomial.bernoulli (2 * k + 1))).eval x) := by
have :
HasSum (fun n : ℕ => 1 / (n : ℂ) ^ (2 * k + 1) * (fourier n (x : 𝕌) - fourier (-n) (x : 𝕌)))
((-1 : ℂ) ^ (k + 1) * I * (2 * π : ℂ) ^ (2 * k + 1) / (2 * k + 1)! *
bernoulliFun (2 * k + 1) x) := by
convert
hasSum_one_div_nat_pow_mul_fourier
(by cutsat : 2 ≤ 2 * k + 1) hx using 1
· ext1 n
rw [pow_add (-1 : ℂ), pow_mul (-1 : ℂ), neg_one_sq, one_pow, one_mul, pow_one, ←
neg_eq_neg_one_mul, ← sub_eq_add_neg]
· congr
rw [pow_add, pow_one]
conv_rhs =>
rw [mul_pow]
congr
congr
· skip
· rw [pow_add, pow_one, pow_mul, I_sq]
ring
have ofReal_two : ((2 : ℝ) : ℂ) = 2 := by norm_cast
convert ((hasSum_iff _ _).mp (this.div_const (2 * I))).1
· convert (ofReal_re _).symm
rw [ofReal_mul]; rw [← mul_div]; congr
· rw [ofReal_div, ofReal_one, ofReal_pow]; rfl
· rw [ofReal_sin, ofReal_mul, fourier_coe_apply, fourier_coe_apply, sin, ofReal_one, div_one,
div_one, ofReal_mul, ofReal_mul, ofReal_two, Int.cast_neg, Int.cast_natCast,
ofReal_natCast, ← div_div, div_I, div_mul_eq_mul_div₀, ← neg_div, ← neg_mul, neg_sub]
congr 4
· ring
· ring
· convert (ofReal_re _).symm
rw [ofReal_mul, ofReal_div, ofReal_div, ofReal_mul, ofReal_pow, ofReal_pow, ofReal_neg,
ofReal_natCast, ofReal_mul, ofReal_two, ofReal_one, ← div_div, div_I,
div_mul_eq_mul_div₀]
have : ∀ α β γ δ : ℂ, α * I * β / γ * δ * I = I ^ 2 * α * β / γ * δ := by intros; ring
rw [this, I_sq]
rw [bernoulliFun]
ring
theorem hasSum_zeta_nat {k : ℕ} (hk : k ≠ 0) :
HasSum (fun n : ℕ => 1 / (n : ℝ) ^ (2 * k))
((-1 : ℝ) ^ (k + 1) * (2 : ℝ) ^ (2 * k - 1) * π ^ (2 * k) *
bernoulli (2 * k) / (2 * k)!) := by
convert hasSum_one_div_nat_pow_mul_cos hk (left_mem_Icc.mpr zero_le_one) using 1
· ext1 n; rw [mul_zero, Real.cos_zero, mul_one]
rw [Polynomial.eval_zero_map, Polynomial.bernoulli_eval_zero, eq_ratCast]
have : (2 : ℝ) ^ (2 * k - 1) = (2 : ℝ) ^ (2 * k) / 2 := by
rw [eq_div_iff (two_ne_zero' ℝ)]
conv_lhs =>
congr
· skip
· rw [← pow_one (2 : ℝ)]
rw [← pow_add, Nat.sub_add_cancel]
omega
rw [this, mul_pow]
ring
end Cleanup
section Examples
theorem hasSum_zeta_two : HasSum (fun n : ℕ => (1 : ℝ) / (n : ℝ) ^ 2) (π ^ 2 / 6) := by
convert hasSum_zeta_nat one_ne_zero using 1; rw [mul_one]
rw [bernoulli_eq_bernoulli'_of_ne_one (by decide : 2 ≠ 1), bernoulli'_two]
simp [Nat.factorial]; ring
theorem hasSum_zeta_four : HasSum (fun n : ℕ => (1 : ℝ) / (n : ℝ) ^ 4) (π ^ 4 / 90) := by
convert hasSum_zeta_nat two_ne_zero using 1; norm_num
rw [bernoulli_eq_bernoulli'_of_ne_one, bernoulli'_four]
· simp [Nat.factorial]; ring
· decide
theorem Polynomial.bernoulli_three_eval_one_quarter :
(Polynomial.bernoulli 3).eval (1 / 4) = 3 / 64 := by
simp_rw [Polynomial.bernoulli, Finset.sum_range_succ, Polynomial.eval_add,
Polynomial.eval_monomial]
rw [Finset.sum_range_zero, Polynomial.eval_zero, zero_add, bernoulli_one]
rw [bernoulli_eq_bernoulli'_of_ne_one zero_ne_one, bernoulli'_zero,
bernoulli_eq_bernoulli'_of_ne_one (by decide : 2 ≠ 1), bernoulli'_two,
bernoulli_eq_bernoulli'_of_ne_one (by decide : 3 ≠ 1), bernoulli'_three]
norm_num
/-- Explicit formula for `L(χ, 3)`, where `χ` is the unique nontrivial Dirichlet character modulo 4.
-/
theorem hasSum_L_function_mod_four_eval_three :
HasSum (fun n : ℕ => (1 : ℝ) / (n : ℝ) ^ 3 * Real.sin (π * n / 2)) (π ^ 3 / 32) := by
apply (congr_arg₂ HasSum ?_ ?_).to_iff.mp <|
hasSum_one_div_nat_pow_mul_sin one_ne_zero (?_ : 1 / 4 ∈ Icc (0 : ℝ) 1)
· ext1 n
ring_nf
· have : (1 / 4 : ℝ) = (algebraMap ℚ ℝ) (1 / 4 : ℚ) := by simp
rw [this, mul_pow, Polynomial.eval_map, Polynomial.eval₂_at_apply, (by decide : 2 * 1 + 1 = 3),
Polynomial.bernoulli_three_eval_one_quarter]
simp [Nat.factorial]; ring
· rw [mem_Icc]; constructor
· linarith
· linarith
end Examples |
.lake/packages/mathlib/Mathlib/NumberTheory/SumPrimeReciprocals.lean | import Mathlib.Algebra.Order.Group.Indicator
import Mathlib.Analysis.PSeries
import Mathlib.NumberTheory.SmoothNumbers
/-!
# The sum of the reciprocals of the primes diverges
We show that the sum of `1/p`, where `p` runs through the prime numbers, diverges.
We follow the elementary proof by Erdős that is reproduced in "Proofs from THE BOOK".
There are two versions of the main result: `not_summable_one_div_on_primes`, which
expresses the sum as a sub-sum of the harmonic series, and `Nat.Primes.not_summable_one_div`,
which writes it as a sum over `Nat.Primes`. We also show that the sum of `p^r` for `r : ℝ`
converges if and only if `r < -1`; see `Nat.Primes.summable_rpow`.
## References
See the sixth proof for the infinity of primes in Chapter 1 of [aigner1999proofs].
The proof is due to Erdős.
-/
open Set Nat
open scoped Topology
/-- The cardinality of the set of `k`-rough numbers `≤ N` is bounded by `N` times the sum
of `1/p` over the primes `k ≤ p ≤ N`. -/
-- This needs `Mathlib/Analysis/RCLike/Basic.lean`, so we put it here
-- instead of in `Mathlib/NumberTheory/SmoothNumbers.lean`.
lemma Nat.roughNumbersUpTo_card_le' (N k : ℕ) :
(roughNumbersUpTo N k).card ≤
N * (N.succ.primesBelow \ k.primesBelow).sum (fun p ↦ (1 : ℝ) / p) := by
simp_rw [Finset.mul_sum, mul_one_div]
exact (Nat.cast_le.mpr <| roughNumbersUpTo_card_le N k).trans <|
cast_sum (R := ℝ) .. ▸ Finset.sum_le_sum fun n _ ↦ cast_div_le
/-- The sum over primes `k ≤ p ≤ 4^(π(k-1)+1)` over `1/p` (as a real number) is at least `1/2`. -/
lemma one_half_le_sum_primes_ge_one_div (k : ℕ) :
1 / 2 ≤ ∑ p ∈ (4 ^ (k.primesBelow.card + 1)).succ.primesBelow \ k.primesBelow,
(1 / p : ℝ) := by
set m : ℕ := 2 ^ k.primesBelow.card
set N₀ : ℕ := 2 * m ^ 2 with hN₀
let S : ℝ := ((2 * N₀).succ.primesBelow \ k.primesBelow).sum (fun p ↦ (1 / p : ℝ))
suffices 1 / 2 ≤ S by
convert this using 5
rw [show 4 = 2 ^ 2 by simp, pow_right_comm]
ring
suffices 2 * N₀ ≤ m * (2 * N₀).sqrt + 2 * N₀ * S by
rwa [hN₀, ← mul_assoc, ← pow_two 2, ← mul_pow, sqrt_eq', ← sub_le_iff_le_add',
cast_mul, cast_mul, cast_pow, cast_two,
show (2 * (2 * m ^ 2) - m * (2 * m) : ℝ) = 2 * (2 * m ^ 2) * (1 / 2) by ring,
mul_le_mul_iff_right₀ <| by positivity] at this
calc (2 * N₀ : ℝ)
_ = ((2 * N₀).smoothNumbersUpTo k).card + ((2 * N₀).roughNumbersUpTo k).card := by
exact_mod_cast ((2 * N₀).smoothNumbersUpTo_card_add_roughNumbersUpTo_card k).symm
_ ≤ m * (2 * N₀).sqrt + ((2 * N₀).roughNumbersUpTo k).card := by
exact_mod_cast Nat.add_le_add_right ((2 * N₀).smoothNumbersUpTo_card_le k) _
_ ≤ m * (2 * N₀).sqrt + 2 * N₀ * S := by grw [roughNumbersUpTo_card_le']; norm_cast
/-- The sum over the reciprocals of the primes diverges. -/
theorem not_summable_one_div_on_primes :
¬ Summable (indicator {p | p.Prime} (fun n : ℕ ↦ (1 : ℝ) / n)) := by
intro h
obtain ⟨k, hk⟩ := h.nat_tsum_vanishing (Iio_mem_nhds one_half_pos : Iio (1 / 2 : ℝ) ∈ 𝓝 0)
specialize hk ({p | Nat.Prime p} ∩ {p | k ≤ p}) inter_subset_right
rw [tsum_subtype, indicator_indicator, inter_eq_left.mpr fun n hn ↦ hn.1, mem_Iio] at hk
have h' : Summable (indicator ({p | Nat.Prime p} ∩ {p | k ≤ p}) fun n ↦ (1 : ℝ) / n) := by
convert h.indicator {n : ℕ | k ≤ n} using 1
simp only [indicator_indicator, inter_comm]
refine ((one_half_le_sum_primes_ge_one_div k).trans_lt <| LE.le.trans_lt ?_ hk).false
convert Summable.sum_le_tsum (primesBelow ((4 ^ (k.primesBelow.card + 1)).succ) \ primesBelow k)
(fun n _ ↦ indicator_nonneg (fun p _ ↦ by positivity) _) h' using 2 with p hp
obtain ⟨hp₁, hp₂⟩ := mem_setOf_eq ▸ Finset.mem_sdiff.mp hp
have hpp := prime_of_mem_primesBelow hp₁
refine (indicator_of_mem ?_ fun n : ℕ ↦ (1 / n : ℝ)).symm
exact ⟨hpp, by simpa [primesBelow, hpp] using hp₂⟩
/-- The sum over the reciprocals of the primes diverges. -/
theorem Nat.Primes.not_summable_one_div : ¬ Summable (fun p : Nat.Primes ↦ (1 / p : ℝ)) := by
convert summable_subtype_iff_indicator.mp.mt not_summable_one_div_on_primes
/-- The series over `p^r` for primes `p` converges if and only if `r < -1`. -/
theorem Nat.Primes.summable_rpow {r : ℝ} :
Summable (fun p : Nat.Primes ↦ (p : ℝ) ^ r) ↔ r < -1 := by
by_cases h : r < -1
· -- case `r < -1`
simp only [h, iff_true]
exact (Real.summable_nat_rpow.mpr h).subtype _
· -- case `-1 ≤ r`
simp only [h, iff_false]
refine fun H ↦ Nat.Primes.not_summable_one_div <| H.of_nonneg_of_le (fun _ ↦ by positivity) ?_
intro p
rw [one_div, ← Real.rpow_neg_one]
exact Real.rpow_le_rpow_of_exponent_le (by exact_mod_cast p.prop.one_lt.le) <| not_lt.mp h |
.lake/packages/mathlib/Mathlib/NumberTheory/Dioph.lean | import Mathlib.Data.Fin.Fin2
import Mathlib.Data.PFun
import Mathlib.Data.Vector3
import Mathlib.NumberTheory.PellMatiyasevic
/-!
# Diophantine functions and Matiyasevic's theorem
Hilbert's tenth problem asked whether there exists an algorithm which for a given integer polynomial
determines whether this polynomial has integer solutions. It was answered in the negative in 1970,
the final step being completed by Matiyasevic who showed that the power function is Diophantine.
Here a function is called Diophantine if its graph is Diophantine as a set. A subset `S ⊆ ℕ ^ α` in
turn is called Diophantine if there exists an integer polynomial on `α ⊕ β` such that `v ∈ S` iff
there exists `t : ℕ^β` with `p (v, t) = 0`.
## Main definitions
* `IsPoly`: a predicate stating that a function is a multivariate integer polynomial.
* `Poly`: the type of multivariate integer polynomial functions.
* `Dioph`: a predicate stating that a set is Diophantine, i.e. a set `S ⊆ ℕ^α` is
Diophantine if there exists a polynomial on `α ⊕ β` such that `v ∈ S` iff there
exists `t : ℕ^β` with `p (v, t) = 0`.
* `DiophFn`: a predicate on a function stating that it is Diophantine in the sense that its graph
is Diophantine as a set.
## Main statements
* `pell_dioph` states that solutions to Pell's equation form a Diophantine set.
* `pow_dioph` states that the power function is Diophantine, a version of Matiyasevic's theorem.
## References
* [M. Carneiro, _A Lean formalization of Matiyasevic's theorem_][carneiro2018matiyasevic]
* [M. Davis, _Hilbert's tenth problem is unsolvable_][MR317916]
## Tags
Matiyasevic's theorem, Hilbert's tenth problem
## TODO
* Finish the solution of Hilbert's tenth problem.
* Connect `Poly` to `MvPolynomial`
-/
open Fin2 Function Nat Sum
local infixr:67 " ::ₒ " => Option.elim'
local infixr:65 " ⊗ " => Sum.elim
universe u
/-!
### Multivariate integer polynomials
Note that this duplicates `MvPolynomial`.
-/
section Polynomials
variable {α β : Type*}
/-- A predicate asserting that a function is a multivariate integer polynomial.
(We are being a bit lazy here by allowing many representations for multiplication,
rather than only allowing monomials and addition, but the definition is equivalent
and this is easier to use.) -/
inductive IsPoly : ((α → ℕ) → ℤ) → Prop
| proj : ∀ i, IsPoly fun x : α → ℕ => x i
| const : ∀ n : ℤ, IsPoly fun _ : α → ℕ => n
| sub : ∀ {f g : (α → ℕ) → ℤ}, IsPoly f → IsPoly g → IsPoly fun x => f x - g x
| mul : ∀ {f g : (α → ℕ) → ℤ}, IsPoly f → IsPoly g → IsPoly fun x => f x * g x
theorem IsPoly.neg {f : (α → ℕ) → ℤ} : IsPoly f → IsPoly (-f) := by
rw [← zero_sub]; exact (IsPoly.const 0).sub
theorem IsPoly.add {f g : (α → ℕ) → ℤ} (hf : IsPoly f) (hg : IsPoly g) : IsPoly (f + g) := by
rw [← sub_neg_eq_add]; exact hf.sub hg.neg
/-- The type of multivariate integer polynomials -/
def Poly (α : Type u) := { f : (α → ℕ) → ℤ // IsPoly f }
namespace Poly
section
instance instFunLike : FunLike (Poly α) (α → ℕ) ℤ :=
⟨Subtype.val, Subtype.val_injective⟩
/-- The underlying function of a `Poly` is a polynomial -/
protected theorem isPoly (f : Poly α) : IsPoly f := f.2
/-- Extensionality for `Poly α` -/
@[ext]
theorem ext {f g : Poly α} : (∀ x, f x = g x) → f = g := DFunLike.ext _ _
/-- The `i`th projection function, `x_i`. -/
def proj (i : α) : Poly α := ⟨_, IsPoly.proj i⟩
@[simp]
theorem proj_apply (i : α) (x) : proj i x = x i := rfl
/-- The constant function with value `n : ℤ`. -/
def const (n : ℤ) : Poly α := ⟨_, IsPoly.const n⟩
@[simp]
theorem const_apply (n) (x : α → ℕ) : const n x = n := rfl
instance : Zero (Poly α) := ⟨const 0⟩
instance : One (Poly α) := ⟨const 1⟩
instance : Neg (Poly α) := ⟨fun f => ⟨-f, f.2.neg⟩⟩
instance : Add (Poly α) := ⟨fun f g => ⟨f + g, f.2.add g.2⟩⟩
instance : Sub (Poly α) := ⟨fun f g => ⟨f - g, f.2.sub g.2⟩⟩
instance : Mul (Poly α) := ⟨fun f g => ⟨f * g, f.2.mul g.2⟩⟩
@[simp]
theorem coe_zero : ⇑(0 : Poly α) = const 0 := rfl
@[simp]
theorem coe_one : ⇑(1 : Poly α) = const 1 := rfl
@[simp]
theorem coe_neg (f : Poly α) : ⇑(-f) = -f := rfl
@[simp]
theorem coe_add (f g : Poly α) : ⇑(f + g) = f + g := rfl
@[simp]
theorem coe_sub (f g : Poly α) : ⇑(f - g) = f - g := rfl
@[simp]
theorem coe_mul (f g : Poly α) : ⇑(f * g) = f * g := rfl
@[simp]
theorem zero_apply (x) : (0 : Poly α) x = 0 := rfl
@[simp]
theorem one_apply (x) : (1 : Poly α) x = 1 := rfl
@[simp]
theorem neg_apply (f : Poly α) (x) : (-f) x = -f x := rfl
@[simp]
theorem add_apply (f g : Poly α) (x : α → ℕ) : (f + g) x = f x + g x := rfl
@[simp]
theorem sub_apply (f g : Poly α) (x : α → ℕ) : (f - g) x = f x - g x := rfl
@[simp]
theorem mul_apply (f g : Poly α) (x : α → ℕ) : (f * g) x = f x * g x := rfl
instance (α : Type*) : Inhabited (Poly α) := ⟨0⟩
instance : AddCommGroup (Poly α) where
nsmul := @nsmulRec _ ⟨(0 : Poly α)⟩ ⟨(· + ·)⟩
zsmul := @zsmulRec _ ⟨(0 : Poly α)⟩ ⟨(· + ·)⟩ ⟨Neg.neg⟩ (@nsmulRec _ ⟨(0 : Poly α)⟩ ⟨(· + ·)⟩)
add_zero _ := by ext; simp_rw [add_apply, zero_apply, add_zero]
zero_add _ := by ext; simp_rw [add_apply, zero_apply, zero_add]
add_comm _ _ := by ext; simp_rw [add_apply, add_comm]
add_assoc _ _ _ := by ext; simp_rw [add_apply, ← add_assoc]
neg_add_cancel _ := by ext; simp_rw [add_apply, neg_apply, neg_add_cancel, zero_apply]
instance : AddGroupWithOne (Poly α) where
natCast := fun n => Poly.const n
intCast := Poly.const
instance : CommRing (Poly α) where
__ := (inferInstance : AddCommGroup (Poly α))
__ := (inferInstance : AddGroupWithOne (Poly α))
npow := @npowRec _ ⟨(1 : Poly α)⟩ ⟨(· * ·)⟩
mul_zero _ := by ext; rw [mul_apply, zero_apply, mul_zero]
zero_mul _ := by ext; rw [mul_apply, zero_apply, zero_mul]
mul_one _ := by ext; rw [mul_apply, one_apply, mul_one]
one_mul _ := by ext; rw [mul_apply, one_apply, one_mul]
mul_comm _ _ := by ext; simp_rw [mul_apply, mul_comm]
mul_assoc _ _ _ := by ext; simp_rw [mul_apply, mul_assoc]
left_distrib _ _ _ := by ext; simp_rw [add_apply, mul_apply]; apply mul_add
right_distrib _ _ _ := by ext; simp only [add_apply, mul_apply]; apply add_mul
theorem induction {C : Poly α → Prop} (H1 : ∀ i, C (proj i)) (H2 : ∀ n, C (const n))
(H3 : ∀ f g, C f → C g → C (f - g)) (H4 : ∀ f g, C f → C g → C (f * g)) (f : Poly α) : C f := by
obtain ⟨f, pf⟩ := f
induction pf with
| proj => apply H1
| const => apply H2
| sub _ _ ihf ihg => apply H3 _ _ ihf ihg
| mul _ _ ihf ihg => apply H4 _ _ ihf ihg
/-- The sum of squares of a list of polynomials. This is relevant for
Diophantine equations, because it means that a list of equations
can be encoded as a single equation: `x = 0 ∧ y = 0 ∧ z = 0` is
equivalent to `x^2 + y^2 + z^2 = 0`. -/
def sumsq : List (Poly α) → Poly α
| [] => 0
| p::ps => p * p + sumsq ps
@[simp] theorem sumsq_nonneg (x : α → ℕ) : ∀ l, 0 ≤ sumsq l x
| [] => le_refl 0
| p::ps => by
rw [sumsq]
exact add_nonneg (mul_self_nonneg _) (sumsq_nonneg _ ps)
theorem sumsq_eq_zero (x) : ∀ l, sumsq l x = 0 ↔ l.Forall fun a : Poly α => a x = 0
| [] => eq_self_iff_true _
| p::ps => by simp [sumsq, add_eq_zero_iff_of_nonneg, mul_self_nonneg, sumsq_eq_zero]
end
/-- Map the index set of variables, replacing `x_i` with `x_(f i)`. -/
def map {α β} (f : α → β) (g : Poly α) : Poly β :=
⟨fun v => g <| v ∘ f, Poly.induction (C := fun g => IsPoly (fun v => g (v ∘ f)))
(fun i => by simpa using IsPoly.proj _) (fun n => by simpa using IsPoly.const _)
(fun f g pf pg => by simpa using IsPoly.sub pf pg)
(fun f g pf pg => by simpa using IsPoly.mul pf pg) _⟩
@[simp]
theorem map_apply {α β} (f : α → β) (g : Poly α) (v) : map f g v = g (v ∘ f) := rfl
end Poly
end Polynomials
/-! ### Diophantine sets -/
/-- A set `S ⊆ ℕ^α` is Diophantine if there exists a polynomial on
`α ⊕ β` such that `v ∈ S` iff there exists `t : ℕ^β` with `p (v, t) = 0`. -/
def Dioph {α : Type u} (S : Set (α → ℕ)) : Prop :=
∃ (β : Type u) (p : Poly (α ⊕ β)), ∀ v, S v ↔ ∃ t, p (v ⊗ t) = 0
namespace Dioph
section
variable {α β γ : Type u} {S S' : Set (α → ℕ)}
theorem ext (d : Dioph S) (H : ∀ v, v ∈ S ↔ v ∈ S') : Dioph S' := by rwa [← Set.ext H]
theorem of_no_dummies (S : Set (α → ℕ)) (p : Poly α) (h : ∀ v, S v ↔ p v = 0) : Dioph S :=
⟨PEmpty, ⟨p.map inl, fun v => (h v).trans ⟨fun h => ⟨PEmpty.elim, h⟩, fun ⟨_, ht⟩ => ht⟩⟩⟩
theorem inject_dummies_lem (f : β → γ) (g : γ → Option β) (inv : ∀ x, g (f x) = some x)
(p : Poly (α ⊕ β)) (v : α → ℕ) :
(∃ t, p (v ⊗ t) = 0) ↔ ∃ t, p.map (inl ⊗ inr ∘ f) (v ⊗ t) = 0 := by
dsimp; refine ⟨fun t => ?_, fun t => ?_⟩ <;> obtain ⟨t, ht⟩ := t
· have : (v ⊗ (0 ::ₒ t) ∘ g) ∘ (inl ⊗ inr ∘ f) = v ⊗ t :=
funext fun s => by rcases s with a | b <;> dsimp [(· ∘ ·)]; try rw [inv]; rfl
exact ⟨(0 ::ₒ t) ∘ g, by rwa [this]⟩
· have : v ⊗ t ∘ f = (v ⊗ t) ∘ (inl ⊗ inr ∘ f) := funext fun s => by rcases s with a | b <;> rfl
exact ⟨t ∘ f, by rwa [this]⟩
theorem inject_dummies (f : β → γ) (g : γ → Option β) (inv : ∀ x, g (f x) = some x)
(p : Poly (α ⊕ β)) (h : ∀ v, S v ↔ ∃ t, p (v ⊗ t) = 0) :
∃ q : Poly (α ⊕ γ), ∀ v, S v ↔ ∃ t, q (v ⊗ t) = 0 :=
⟨p.map (inl ⊗ inr ∘ f), fun v => (h v).trans <| inject_dummies_lem f g inv _ _⟩
variable (β) in
theorem reindex_dioph (f : α → β) : Dioph S → Dioph {v | v ∘ f ∈ S}
| ⟨γ, p, pe⟩ => ⟨γ, p.map (inl ∘ f ⊗ inr), fun v =>
(pe _).trans <|
exists_congr fun t =>
suffices v ∘ f ⊗ t = (v ⊗ t) ∘ (inl ∘ f ⊗ inr) by simp [this]
funext fun s => by rcases s with a | b <;> rfl⟩
theorem DiophList.forall (l : List (Set <| α → ℕ)) (d : l.Forall Dioph) :
Dioph {v | l.Forall fun S : Set (α → ℕ) => v ∈ S} := by
suffices ∃ (β : _) (pl : List (Poly (α ⊕ β))), ∀ v, List.Forall (fun S : Set _ => S v) l ↔
∃ t, List.Forall (fun p : Poly (α ⊕ β) => p (v ⊗ t) = 0) pl
from
let ⟨β, pl, h⟩ := this
⟨β, Poly.sumsq pl, fun v => (h v).trans <| exists_congr fun t => (Poly.sumsq_eq_zero _ _).symm⟩
induction l with | nil => exact ⟨ULift Empty, [], fun _ => by simp⟩ | cons S l IH =>
obtain ⟨⟨β, p, pe⟩, dl⟩ := (List.forall_cons _ _ _).mp d
exact
let ⟨γ, pl, ple⟩ := IH dl
⟨β ⊕ γ, p.map (inl ⊗ inr ∘ inl)::pl.map fun q => q.map (inl ⊗ inr ∘ inr),
fun v => by
simpa using
Iff.trans (and_congr (pe v) (ple v))
⟨fun ⟨⟨m, hm⟩, ⟨n, hn⟩⟩ =>
⟨m ⊗ n, by
rw [show (v ⊗ m ⊗ n) ∘ (inl ⊗ inr ∘ inl) = v ⊗ m from
funext fun s => by rcases s with a | b <;> rfl]; exact hm, by
refine List.Forall.imp (fun q hq => ?_) hn; dsimp [Function.comp_def]
rw [show
(fun x : α ⊕ γ => (v ⊗ m ⊗ n) ((inl ⊗ fun x : γ => inr (inr x)) x)) = v ⊗ n
from funext fun s => by rcases s with a | b <;> rfl]; exact hq⟩,
fun ⟨t, hl, hr⟩ =>
⟨⟨t ∘ inl, by
rwa [show (v ⊗ t) ∘ (inl ⊗ inr ∘ inl) = v ⊗ t ∘ inl from
funext fun s => by rcases s with a | b <;> rfl] at hl⟩,
⟨t ∘ inr, by
refine List.Forall.imp (fun q hq => ?_) hr; dsimp [Function.comp_def] at hq
rwa [show
(fun x : α ⊕ γ => (v ⊗ t) ((inl ⊗ fun x : γ => inr (inr x)) x)) =
v ⊗ t ∘ inr
from funext fun s => by rcases s with a | b <;> rfl] at hq ⟩⟩⟩⟩
/-- Diophantine sets are closed under intersection. -/
theorem inter (d : Dioph S) (d' : Dioph S') : Dioph (S ∩ S') := DiophList.forall [S, S'] ⟨d, d'⟩
/-- Diophantine sets are closed under union. -/
theorem union : ∀ (_ : Dioph S) (_ : Dioph S'), Dioph (S ∪ S')
| ⟨β, p, pe⟩, ⟨γ, q, qe⟩ =>
⟨β ⊕ γ, p.map (inl ⊗ inr ∘ inl) * q.map (inl ⊗ inr ∘ inr), fun v => by
refine
Iff.trans (or_congr ((pe v).trans ?_) ((qe v).trans ?_))
(exists_or.symm.trans
(exists_congr fun t =>
(@mul_eq_zero _ _ _ (p ((v ⊗ t) ∘ (inl ⊗ inr ∘ inl)))
(q ((v ⊗ t) ∘ (inl ⊗ inr ∘ inr)))).symm))
· -- Porting note: putting everything on the same line fails
refine inject_dummies_lem _ (some ⊗ fun _ => none) ?_ _ _
exact fun _ => by simp only [elim_inl]
· -- Porting note: putting everything on the same line fails
refine inject_dummies_lem _ ((fun _ => none) ⊗ some) ?_ _ _
exact fun _ => by simp only [elim_inr]⟩
/-- A partial function is Diophantine if its graph is Diophantine. -/
def DiophPFun (f : (α → ℕ) →. ℕ) : Prop :=
Dioph {v : Option α → ℕ | f.graph (v ∘ some, v none)}
/-- A function is Diophantine if its graph is Diophantine. -/
def DiophFn (f : (α → ℕ) → ℕ) : Prop :=
Dioph {v : Option α → ℕ | f (v ∘ some) = v none}
theorem reindex_diophFn {f : (α → ℕ) → ℕ} (g : α → β) (d : DiophFn f) :
DiophFn fun v => f (v ∘ g) := by convert reindex_dioph (Option β) (Option.map g) d
theorem ex_dioph {S : Set (α ⊕ β → ℕ)} : Dioph S → Dioph {v | ∃ x, v ⊗ x ∈ S}
| ⟨γ, p, pe⟩ =>
⟨β ⊕ γ, p.map ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr), fun v =>
⟨fun ⟨x, hx⟩ =>
let ⟨t, ht⟩ := (pe _).1 hx
⟨x ⊗ t, by
simp only [Poly.map_apply]
rw [show (v ⊗ x ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ x) ⊗ t from
funext fun s => by rcases s with a | b <;> try { cases a <;> rfl }; rfl]
exact ht⟩,
fun ⟨t, ht⟩ =>
⟨t ∘ inl,
(pe _).2
⟨t ∘ inr, by
simp only [Poly.map_apply] at ht
rwa [show (v ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ t ∘ inl) ⊗ t ∘ inr from
funext fun s => by rcases s with a | b <;> try { cases a <;> rfl }; rfl] at ht⟩⟩⟩⟩
theorem ex1_dioph {S : Set (Option α → ℕ)} : Dioph S → Dioph {v | ∃ x, x ::ₒ v ∈ S}
| ⟨β, p, pe⟩ =>
⟨Option β, p.map (inr none ::ₒ inl ⊗ inr ∘ some), fun v =>
⟨fun ⟨x, hx⟩ =>
let ⟨t, ht⟩ := (pe _).1 hx
⟨x ::ₒ t, by
simp only [Poly.map_apply]
rw [show (v ⊗ x ::ₒ t) ∘ (inr none ::ₒ inl ⊗ inr ∘ some) = x ::ₒ v ⊗ t from
funext fun s => by rcases s with a | b <;> try { cases a <;> rfl}; rfl]
exact ht⟩,
fun ⟨t, ht⟩ =>
⟨t none,
(pe _).2
⟨t ∘ some, by
simp only [Poly.map_apply] at ht
rwa [show (v ⊗ t) ∘ (inr none ::ₒ inl ⊗ inr ∘ some) = t none ::ₒ v ⊗ t ∘ some from
funext fun s => by rcases s with a | b <;> try { cases a <;> rfl }; rfl] at ht ⟩⟩⟩⟩
theorem dom_dioph {f : (α → ℕ) →. ℕ} (d : DiophPFun f) : Dioph f.Dom :=
cast (congr_arg Dioph <| Set.ext fun _ => (PFun.dom_iff_graph _ _).symm) (ex1_dioph d)
theorem diophFn_iff_pFun (f : (α → ℕ) → ℕ) : DiophFn f = @DiophPFun α f := by
refine congr_arg Dioph (Set.ext fun v => ?_); exact PFun.lift_graph.symm
theorem abs_poly_dioph (p : Poly α) : DiophFn fun v => (p v).natAbs :=
of_no_dummies _ ((p.map some - Poly.proj none) * (p.map some + Poly.proj none))
fun v => (by dsimp; exact Int.natAbs_eq_iff_mul_eq_zero)
theorem proj_dioph (i : α) : DiophFn fun v => v i :=
abs_poly_dioph (Poly.proj i)
theorem diophPFun_comp1 {S : Set (Option α → ℕ)} (d : Dioph S) {f} (df : DiophPFun f) :
Dioph {v : α → ℕ | ∃ h : f.Dom v, f.fn v h ::ₒ v ∈ S} :=
ext (ex1_dioph (d.inter df)) fun v =>
⟨fun ⟨x, hS, (h : Exists _)⟩ => by
rw [show (x ::ₒ v) ∘ some = v from funext fun s => rfl] at h
obtain ⟨hf, h⟩ := h; refine ⟨hf, ?_⟩; rw [PFun.fn, h]; exact hS,
fun ⟨x, hS⟩ =>
⟨f.fn v x, hS, show Exists _ by
rw [show (f.fn v x ::ₒ v) ∘ some = v from funext fun s => rfl]; exact ⟨x, rfl⟩⟩⟩
theorem diophFn_comp1 {S : Set (Option α → ℕ)} (d : Dioph S) {f : (α → ℕ) → ℕ} (df : DiophFn f) :
Dioph {v | f v ::ₒ v ∈ S} :=
ext (diophPFun_comp1 d <| cast (diophFn_iff_pFun f) df)
fun _ => ⟨fun ⟨_, h⟩ => h, fun h => ⟨trivial, h⟩⟩
end
section
variable {α : Type} {n : ℕ}
open Vector3
open scoped Vector3
theorem diophFn_vec_comp1 {S : Set (Vector3 ℕ (succ n))} (d : Dioph S) {f : Vector3 ℕ n → ℕ}
(df : DiophFn f) : Dioph {v : Vector3 ℕ n | (f v::v) ∈ S} :=
Dioph.ext (diophFn_comp1 (reindex_dioph _ (none::some) d) df) (fun v => by
dsimp
-- TODO: `apply iff_of_eq` is required here, even though `congr!` works on iff below.
apply iff_of_eq
congr 1
ext x; cases x <;> rfl)
/-- Deleting the first component preserves the Diophantine property. -/
theorem vec_ex1_dioph (n) {S : Set (Vector3 ℕ (succ n))} (d : Dioph S) :
Dioph {v : Fin2 n → ℕ | ∃ x, (x::v) ∈ S} :=
ext (ex1_dioph <| reindex_dioph _ (none::some) d) fun v =>
exists_congr fun x => by
dsimp
rw [show Option.elim' x v ∘ cons none some = x::v from
funext fun s => by rcases s with a | b <;> rfl]
theorem diophFn_vec (f : Vector3 ℕ n → ℕ) : DiophFn f ↔ Dioph {v | f (v ∘ fs) = v fz} :=
⟨reindex_dioph _ (fz ::ₒ fs), reindex_dioph _ (none::some)⟩
theorem diophPFun_vec (f : Vector3 ℕ n →. ℕ) : DiophPFun f ↔ Dioph {v | f.graph (v ∘ fs, v fz)} :=
⟨reindex_dioph _ (fz ::ₒ fs), reindex_dioph _ (none::some)⟩
theorem diophFn_compn :
∀ {n} {S : Set (α ⊕ (Fin2 n) → ℕ)} (_ : Dioph S) {f : Vector3 ((α → ℕ) → ℕ) n}
(_ : VectorAllP DiophFn f), Dioph {v : α → ℕ | (v ⊗ fun i => f i v) ∈ S}
| 0, S, d, f => fun _ =>
ext (reindex_dioph _ (id ⊗ Fin2.elim0) d) fun v => by
dsimp
-- TODO: `congr! 1; ext` should be equivalent to `congr! 1 with x` but that does not work.
congr! 1
ext x; obtain _ | _ | _ := x; rfl
| succ n, S, d, f =>
f.consElim fun f fl => by
simp only [vectorAllP_cons, and_imp]
exact fun df dfl =>
have : Dioph {v | (v ∘ inl ⊗ f (v ∘ inl)::v ∘ inr) ∈ S} :=
ext (diophFn_comp1 (reindex_dioph _ (some ∘ inl ⊗ none::some ∘ inr) d) <|
reindex_diophFn inl df)
fun v => by
dsimp
-- TODO: `congr! 1; ext` should be equivalent to `congr! 1 with x`
-- but that does not work.
congr! 1
ext x; obtain _ | _ | _ := x <;> rfl
have : Dioph {v | (v ⊗ f v::fun i : Fin2 n => fl i v) ∈ S} :=
@diophFn_compn n (fun v => S (v ∘ inl ⊗ f (v ∘ inl)::v ∘ inr)) this _ dfl
ext this fun v => by
dsimp
congr! 3 with x
obtain _ | _ | _ := x <;> rfl
theorem dioph_comp {S : Set (Vector3 ℕ n)} (d : Dioph S) (f : Vector3 ((α → ℕ) → ℕ) n)
(df : VectorAllP DiophFn f) : Dioph {v | (fun i => f i v) ∈ S} :=
diophFn_compn (reindex_dioph _ inr d) df
theorem diophFn_comp {f : Vector3 ℕ n → ℕ} (df : DiophFn f) (g : Vector3 ((α → ℕ) → ℕ) n)
(dg : VectorAllP DiophFn g) : DiophFn fun v => f fun i => g i v :=
dioph_comp ((diophFn_vec _).1 df) ((fun v => v none)::fun i v => g i (v ∘ some)) <| by
simp only [vectorAllP_cons]
exact ⟨proj_dioph none, (vectorAllP_iff_forall _ _).2 fun i =>
reindex_diophFn _ <| (vectorAllP_iff_forall _ _).1 dg _⟩
@[inherit_doc]
scoped notation:35 x " D∧ " y => Dioph.inter x y
@[inherit_doc]
scoped notation:35 x " D∨ " y => Dioph.union x y
@[inherit_doc]
scoped notation:30 "D∃" => Dioph.vec_ex1_dioph
/-- Local abbreviation for `Fin2.ofNat'` -/
scoped prefix:arg "&" => Fin2.ofNat'
theorem proj_dioph_of_nat {n : ℕ} (m : ℕ) [IsLT m n] : DiophFn fun v : Vector3 ℕ n => v &m :=
proj_dioph &m
/-- Projection preserves Diophantine functions. -/
scoped prefix:100 "D&" => Dioph.proj_dioph_of_nat
theorem const_dioph (n : ℕ) : DiophFn (const (α → ℕ) n) :=
abs_poly_dioph (Poly.const n)
/-- The constant function is Diophantine. -/
scoped prefix:100 "D." => Dioph.const_dioph
section
variable {f g : (α → ℕ) → ℕ} (df : DiophFn f) (dg : DiophFn g)
include df dg
theorem dioph_comp2 {S : ℕ → ℕ → Prop} (d : Dioph fun v : Vector3 ℕ 2 => S (v &0) (v &1)) :
Dioph fun v => S (f v) (g v) := dioph_comp d [f, g] ⟨df, dg⟩
theorem diophFn_comp2 {h : ℕ → ℕ → ℕ} (d : DiophFn fun v : Vector3 ℕ 2 => h (v &0) (v &1)) :
DiophFn fun v => h (f v) (g v) := diophFn_comp d [f, g] ⟨df, dg⟩
/-- The set of places where two Diophantine functions are equal is Diophantine. -/
theorem eq_dioph : Dioph fun v => f v = g v :=
dioph_comp2 df dg <|
of_no_dummies _ (Poly.proj &0 - Poly.proj &1) fun v => by
exact Int.ofNat_inj.symm.trans ⟨@sub_eq_zero_of_eq ℤ _ (v &0) (v &1), eq_of_sub_eq_zero⟩
@[inherit_doc]
scoped infixl:50 " D= " => Dioph.eq_dioph
/-- Diophantine functions are closed under addition. -/
theorem add_dioph : DiophFn fun v => f v + g v :=
diophFn_comp2 df dg <| abs_poly_dioph (@Poly.proj (Fin2 2) &0 + @Poly.proj (Fin2 2) &1)
@[inherit_doc]
scoped infixl:80 " D+ " => Dioph.add_dioph
/-- Diophantine functions are closed under multiplication. -/
theorem mul_dioph : DiophFn fun v => f v * g v :=
diophFn_comp2 df dg <| abs_poly_dioph (@Poly.proj (Fin2 2) &0 * @Poly.proj (Fin2 2) &1)
@[inherit_doc]
scoped infixl:90 " D* " => Dioph.mul_dioph
/-- The set of places where one Diophantine function is at most another is Diophantine. -/
theorem le_dioph : Dioph {v | f v ≤ g v} :=
dioph_comp2 df dg <|
ext ((D∃) 2 <| D&1 D+ D&0 D= D&2) fun _ => ⟨fun ⟨_, hx⟩ => le.intro hx, le.dest⟩
@[inherit_doc]
scoped infixl:50 " D≤ " => Dioph.le_dioph
/-- The set of places where one Diophantine function is less than another is Diophantine. -/
theorem lt_dioph : Dioph {v | f v < g v} := df D+ D.1 D≤ dg
@[inherit_doc]
scoped infixl:50 " D< " => Dioph.lt_dioph
/-- The set of places where two Diophantine functions are unequal is Diophantine. -/
theorem ne_dioph : Dioph {v | f v ≠ g v} :=
ext (df D< dg D∨ dg D< df) fun v => by dsimp; exact lt_or_lt_iff_ne (α := ℕ)
@[inherit_doc]
scoped infixl:50 " D≠ " => Dioph.ne_dioph
/-- Diophantine functions are closed under subtraction. -/
theorem sub_dioph : DiophFn fun v => f v - g v :=
diophFn_comp2 df dg <|
(diophFn_vec _).2 <|
ext (D&1 D= D&0 D+ D&2 D∨ D&1 D≤ D&2 D∧ D&0 D= D.0) <|
(vectorAll_iff_forall _).1 fun x y z =>
show y = x + z ∨ y ≤ z ∧ x = 0 ↔ y - z = x from
⟨fun o => by
rcases o with (ae | ⟨yz, x0⟩)
· rw [ae, add_tsub_cancel_right]
· rw [x0, tsub_eq_zero_iff_le.mpr yz], by
cutsat⟩
@[inherit_doc]
scoped infixl:80 " D- " => Dioph.sub_dioph
/-- The set of places where one Diophantine function divides another is Diophantine. -/
theorem dvd_dioph : Dioph fun v => f v ∣ g v :=
dioph_comp ((D∃) 2 <| D&2 D= D&1 D* D&0) [f, g] ⟨df, dg⟩
@[inherit_doc]
scoped infixl:50 " D∣ " => Dioph.dvd_dioph
/-- Diophantine functions are closed under the modulo operation. -/
theorem mod_dioph : DiophFn fun v => f v % g v :=
have : Dioph fun v : Vector3 ℕ 3 => (v &2 = 0 ∨ v &0 < v &2) ∧ ∃ x : ℕ, v &0 + v &2 * x = v &1 :=
(D&2 D= D.0 D∨ D&0 D< D&2) D∧ (D∃) 3 <| D&1 D+ D&3 D* D&0 D= D&2
diophFn_comp2 df dg <|
(diophFn_vec _).2 <|
ext this <|
(vectorAll_iff_forall _).1 fun z x y =>
show ((y = 0 ∨ z < y) ∧ ∃ c, z + y * c = x) ↔ x % y = z from
⟨fun ⟨h, c, hc⟩ => by
rw [← hc]; simp only [add_mul_mod_self_left]; rcases h with x0 | hl
· rw [x0, mod_zero]
exact mod_eq_of_lt hl, fun e => by
rw [← e]
exact ⟨or_iff_not_imp_left.2 fun h => mod_lt _ (Nat.pos_of_ne_zero h), x / y,
mod_add_div _ _⟩⟩
@[inherit_doc]
scoped infixl:80 " D% " => Dioph.mod_dioph
/-- The set of places where two Diophantine functions are congruent modulo a third
is Diophantine. -/
theorem modEq_dioph {h : (α → ℕ) → ℕ} (dh : DiophFn h) : Dioph fun v => f v ≡ g v [MOD h v] :=
df D% dh D= dg D% dh
@[inherit_doc]
scoped notation "D≡ " => Dioph.modEq_dioph
/-- Diophantine functions are closed under integer division. -/
theorem div_dioph : DiophFn fun v => f v / g v :=
have :
Dioph fun v : Vector3 ℕ 3 =>
v &2 = 0 ∧ v &0 = 0 ∨ v &0 * v &2 ≤ v &1 ∧ v &1 < (v &0 + 1) * v &2 :=
(D&2 D= D.0 D∧ D&0 D= D.0) D∨ D&0 D* D&2 D≤ D&1 D∧ D&1 D< (D&0 D+ D.1) D* D&2
diophFn_comp2 df dg <|
(diophFn_vec _).2 <|
ext this <|
(vectorAll_iff_forall _).1 fun z x y =>
show y = 0 ∧ z = 0 ∨ z * y ≤ x ∧ x < (z + 1) * y ↔ x / y = z by
refine Iff.trans ?_ eq_comm
exact y.eq_zero_or_pos.elim
(fun y0 => by
rw [y0, Nat.div_zero]
exact ⟨fun o => (o.resolve_right fun ⟨_, h2⟩ => Nat.not_lt_zero _ h2).right,
fun z0 => Or.inl ⟨rfl, z0⟩⟩)
fun ypos =>
Iff.trans ⟨fun o => o.resolve_left fun ⟨h1, _⟩ => Nat.ne_of_gt ypos h1, Or.inr⟩
(le_antisymm_iff.trans <| and_congr (Nat.le_div_iff_mul_le ypos) <|
Iff.trans ⟨lt_succ_of_le, le_of_lt_succ⟩ (div_lt_iff_lt_mul ypos)).symm
end
@[inherit_doc]
scoped infixl:80 " D/ " => Dioph.div_dioph
open Pell
theorem pell_dioph :
Dioph fun v : Vector3 ℕ 4 => ∃ h : 1 < v &0, xn h (v &1) = v &2 ∧ yn h (v &1) = v &3 := by
have : Dioph {v : Vector3 ℕ 4 |
1 < v &0 ∧ v &1 ≤ v &3 ∧
(v &2 = 1 ∧ v &3 = 0 ∨
∃ u w s t b : ℕ,
v &2 * v &2 - (v &0 * v &0 - 1) * v &3 * v &3 = 1 ∧
u * u - (v &0 * v &0 - 1) * w * w = 1 ∧
s * s - (b * b - 1) * t * t = 1 ∧
1 < b ∧ b ≡ 1 [MOD 4 * v &3] ∧ b ≡ v &0 [MOD u] ∧
0 < w ∧ v &3 * v &3 ∣ w ∧
s ≡ v &2 [MOD u] ∧
t ≡ v &1 [MOD 4 * v &3])} :=
(D.1 D< D&0 D∧ D&1 D≤ D&3 D∧
((D&2 D= D.1 D∧ D&3 D= D.0) D∨
((D∃) 4 <| (D∃) 5 <| (D∃) 6 <| (D∃) 7 <| (D∃) 8 <|
D&7 D* D&7 D- (D&5 D* D&5 D- D.1) D* D&8 D* D&8 D= D.1 D∧
D&4 D* D&4 D- (D&5 D* D&5 D- D.1) D* D&3 D* D&3 D= D.1 D∧
D&2 D* D&2 D- (D&0 D* D&0 D- D.1) D* D&1 D* D&1 D= D.1 D∧
D.1 D< D&0 D∧ (D≡ (D&0) (D.1) (D.4 D* D&8)) D∧ (D≡ (D&0) (D&5) (D&4)) D∧
D.0 D< D&3 D∧ D&8 D* D&8 D∣ D&3 D∧
(D≡ (D&2) (D&7) (D&4)) D∧
(D≡ (D&1) (D&6) (D.4 D* (D&8))))) :)
exact Dioph.ext this fun v => matiyasevic.symm
theorem xn_dioph : DiophPFun fun v : Vector3 ℕ 2 => ⟨1 < v &0, fun h => xn h (v &1)⟩ :=
have : Dioph fun v : Vector3 ℕ 3 => ∃ y, ∃ h : 1 < v &1, xn h (v &2) = v &0 ∧ yn h (v &2) = y :=
let D_pell := pell_dioph.reindex_dioph (Fin2 4) [&2, &3, &1, &0]
(D∃) 3 D_pell
(diophPFun_vec _).2 <|
Dioph.ext this fun _ => ⟨fun ⟨_, h, xe, _⟩ => ⟨h, xe⟩, fun ⟨h, xe⟩ => ⟨_, h, xe, rfl⟩⟩
/-- A version of **Matiyasevic's theorem** -/
theorem pow_dioph {f g : (α → ℕ) → ℕ} (df : DiophFn f) (dg : DiophFn g) :
DiophFn fun v => f v ^ g v := by
have : Dioph {v : Vector3 ℕ 3 |
v &2 = 0 ∧ v &0 = 1 ∨ 0 < v &2 ∧
(v &1 = 0 ∧ v &0 = 0 ∨ 0 < v &1 ∧
∃ w a t z x y : ℕ,
(∃ a1 : 1 < a, xn a1 (v &2) = x ∧ yn a1 (v &2) = y) ∧
x ≡ y * (a - v &1) + v &0 [MOD t] ∧
2 * a * v &1 = t + (v &1 * v &1 + 1) ∧
v &0 < t ∧ v &1 ≤ w ∧ v &2 ≤ w ∧
a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)} :=
(D&2 D= D.0 D∧ D&0 D= D.1) D∨ (D.0 D< D&2 D∧
((D&1 D= D.0 D∧ D&0 D= D.0) D∨ (D.0 D< D&1 D∧
((D∃) 3 <| (D∃) 4 <| (D∃) 5 <| (D∃) 6 <| (D∃) 7 <| (D∃) 8 <|
pell_dioph.reindex_dioph (Fin2 9) [&4, &8, &1, &0] D∧
(D≡ (D&1) (D&0 D* (D&4 D- D&7) D+ D&6) (D&3)) D∧
D.2 D* D&4 D* D&7 D= D&3 D+ (D&7 D* D&7 D+ D.1) D∧
D&6 D< D&3 D∧ D&7 D≤ D&5 D∧ D&8 D≤ D&5 D∧
D&4 D* D&4 D- ((D&5 D+ D.1) D* (D&5 D+ D.1) D- D.1) D* (D&5 D* D&2) D* (D&5 D* D&2) D= D.1))) :)
exact diophFn_comp2 df dg <| (diophFn_vec _).2 <| Dioph.ext this fun v => Iff.symm <|
eq_pow_of_pell.trans <| or_congr Iff.rfl <| and_congr Iff.rfl <| or_congr Iff.rfl <|
and_congr Iff.rfl <|
⟨fun ⟨w, a, t, z, a1, h⟩ => ⟨w, a, t, z, _, _, ⟨a1, rfl, rfl⟩, h⟩,
fun ⟨w, a, t, z, _, _, ⟨a1, rfl, rfl⟩, h⟩ => ⟨w, a, t, z, a1, h⟩⟩
end
end Dioph |
.lake/packages/mathlib/Mathlib/NumberTheory/Pell.lean | import Mathlib.Data.ZMod.Basic
import Mathlib.NumberTheory.DiophantineApproximation.Basic
import Mathlib.NumberTheory.Zsqrtd.Basic
import Mathlib.Tactic.Qify
/-!
# Pell's Equation
*Pell's Equation* is the equation $x^2 - d y^2 = 1$, where $d$ is a positive integer
that is not a square, and one is interested in solutions in integers $x$ and $y$.
In this file, we aim at providing all of the essential theory of Pell's Equation for general $d$
(as opposed to the contents of `NumberTheory.PellMatiyasevic`, which is specific to the case
$d = a^2 - 1$ for some $a > 1$).
We begin by defining a type `Pell.Solution₁ d` for solutions of the equation,
show that it has a natural structure as an abelian group, and prove some basic
properties.
We then prove the following
**Theorem.** Let $d$ be a positive integer that is not a square. Then the equation
$x^2 - d y^2 = 1$ has a nontrivial (i.e., with $y \ne 0$) solution in integers.
See `Pell.exists_of_not_isSquare` and `Pell.Solution₁.exists_nontrivial_of_not_isSquare`.
We then define the *fundamental solution* to be the solution
with smallest $x$ among all solutions satisfying $x > 1$ and $y > 0$.
We show that every solution is a power (in the sense of the group structure mentioned above)
of the fundamental solution up to a (common) sign,
see `Pell.IsFundamental.eq_zpow_or_neg_zpow`, and that a (positive) solution has this property
if and only if it is fundamental, see `Pell.pos_generator_iff_fundamental`.
## References
* [K. Ireland, M. Rosen, *A classical introduction to modern number theory* (Section 17.5)]
[IrelandRosen1990]
## Tags
Pell's equation
## TODO
* Extend to `x ^ 2 - d * y ^ 2 = -1` and further generalizations.
* Connect solutions to the continued fraction expansion of `√d`.
-/
namespace Pell
/-!
### Group structure of the solution set
We define a structure of a commutative multiplicative group with distributive negation
on the set of all solutions to the Pell equation `x^2 - d*y^2 = 1`.
The type of such solutions is `Pell.Solution₁ d`. It corresponds to a pair of integers `x` and `y`
and a proof that `(x, y)` is indeed a solution.
The multiplication is given by `(x, y) * (x', y') = (x*y' + d*y*y', x*y' + y*x')`.
This is obtained by mapping `(x, y)` to `x + y*√d` and multiplying the results.
In fact, we define `Pell.Solution₁ d` to be `↥(unitary (ℤ√d))` and transport
the "commutative group with distributive negation" structure from `↥(unitary (ℤ√d))`.
We then set up an API for `Pell.Solution₁ d`.
-/
open CharZero Zsqrtd
/-- An element of `ℤ√d` has norm one (i.e., `a.re^2 - d*a.im^2 = 1`) if and only if
it is contained in the submonoid of unitary elements.
TODO: merge this result with `Pell.isPell_iff_mem_unitary`. -/
theorem is_pell_solution_iff_mem_unitary {d : ℤ} {a : ℤ√d} :
a.re ^ 2 - d * a.im ^ 2 = 1 ↔ a ∈ unitary (ℤ√d) := by
rw [← norm_eq_one_iff_mem_unitary, norm_def, sq, sq, ← mul_assoc]
-- We use `solution₁ d` to allow for a more general structure `solution d m` that
-- encodes solutions to `x^2 - d*y^2 = m` to be added later.
/-- `Pell.Solution₁ d` is the type of solutions to the Pell equation `x^2 - d*y^2 = 1`.
We define this in terms of elements of `ℤ√d` of norm one.
-/
def Solution₁ (d : ℤ) : Type :=
↥(unitary (ℤ√d))
namespace Solution₁
variable {d : ℤ}
instance instCommGroup : CommGroup (Solution₁ d) :=
inferInstanceAs (CommGroup (unitary (ℤ√d)))
instance instHasDistribNeg : HasDistribNeg (Solution₁ d) :=
inferInstanceAs (HasDistribNeg (unitary (ℤ√d)))
instance instInhabited : Inhabited (Solution₁ d) :=
inferInstanceAs (Inhabited (unitary (ℤ√d)))
instance : Coe (Solution₁ d) (ℤ√d) where coe := Subtype.val
/-- The `x` component of a solution to the Pell equation `x^2 - d*y^2 = 1` -/
protected def x (a : Solution₁ d) : ℤ :=
(a : ℤ√d).re
/-- The `y` component of a solution to the Pell equation `x^2 - d*y^2 = 1` -/
protected def y (a : Solution₁ d) : ℤ :=
(a : ℤ√d).im
/-- The proof that `a` is a solution to the Pell equation `x^2 - d*y^2 = 1` -/
theorem prop (a : Solution₁ d) : a.x ^ 2 - d * a.y ^ 2 = 1 :=
is_pell_solution_iff_mem_unitary.mpr a.property
/-- An alternative form of the equation, suitable for rewriting `x^2`. -/
theorem prop_x (a : Solution₁ d) : a.x ^ 2 = 1 + d * a.y ^ 2 := by rw [← a.prop]; ring
/-- An alternative form of the equation, suitable for rewriting `d * y^2`. -/
theorem prop_y (a : Solution₁ d) : d * a.y ^ 2 = a.x ^ 2 - 1 := by rw [← a.prop]; ring
/-- Two solutions are equal if their `x` and `y` components are equal. -/
@[ext]
theorem ext {a b : Solution₁ d} (hx : a.x = b.x) (hy : a.y = b.y) : a = b :=
Subtype.ext <| Zsqrtd.ext hx hy
/-- Construct a solution from `x`, `y` and a proof that the equation is satisfied. -/
def mk (x y : ℤ) (prop : x ^ 2 - d * y ^ 2 = 1) : Solution₁ d where
val := ⟨x, y⟩
property := is_pell_solution_iff_mem_unitary.mp prop
@[simp]
theorem x_mk (x y : ℤ) (prop : x ^ 2 - d * y ^ 2 = 1) : (mk x y prop).x = x :=
rfl
@[simp]
theorem y_mk (x y : ℤ) (prop : x ^ 2 - d * y ^ 2 = 1) : (mk x y prop).y = y :=
rfl
@[simp]
theorem coe_mk (x y : ℤ) (prop : x ^ 2 - d * y ^ 2 = 1) : (↑(mk x y prop) : ℤ√d) = ⟨x, y⟩ :=
Zsqrtd.ext (x_mk x y prop) (y_mk x y prop)
@[simp]
theorem x_one : (1 : Solution₁ d).x = 1 :=
rfl
@[simp]
theorem y_one : (1 : Solution₁ d).y = 0 :=
rfl
@[simp]
theorem x_mul (a b : Solution₁ d) : (a * b).x = a.x * b.x + d * (a.y * b.y) := by
rw [← mul_assoc]
rfl
@[simp]
theorem y_mul (a b : Solution₁ d) : (a * b).y = a.x * b.y + a.y * b.x :=
rfl
@[simp]
theorem x_inv (a : Solution₁ d) : a⁻¹.x = a.x :=
rfl
@[simp]
theorem y_inv (a : Solution₁ d) : a⁻¹.y = -a.y :=
rfl
@[simp]
theorem x_neg (a : Solution₁ d) : (-a).x = -a.x :=
rfl
@[simp]
theorem y_neg (a : Solution₁ d) : (-a).y = -a.y :=
rfl
/-- When `d` is negative, then `x` or `y` must be zero in a solution. -/
theorem eq_zero_of_d_neg (h₀ : d < 0) (a : Solution₁ d) : a.x = 0 ∨ a.y = 0 := by
have h := a.prop
contrapose! h
have h1 := sq_pos_of_ne_zero h.1
have h2 := sq_pos_of_ne_zero h.2
nlinarith
/-- A solution has `x ≠ 0`. -/
theorem x_ne_zero (h₀ : 0 ≤ d) (a : Solution₁ d) : a.x ≠ 0 := by
intro hx
have h : 0 ≤ d * a.y ^ 2 := mul_nonneg h₀ (sq_nonneg _)
rw [a.prop_y, hx, sq, zero_mul, zero_sub] at h
exact not_le.mpr (neg_one_lt_zero : (-1 : ℤ) < 0) h
/-- A solution with `x > 1` must have `y ≠ 0`. -/
theorem y_ne_zero_of_one_lt_x {a : Solution₁ d} (ha : 1 < a.x) : a.y ≠ 0 := by
intro hy
have prop := a.prop
rw [hy, sq (0 : ℤ), zero_mul, mul_zero, sub_zero] at prop
exact lt_irrefl _ (((one_lt_sq_iff₀ <| zero_le_one.trans ha.le).mpr ha).trans_eq prop)
/-- If a solution has `x > 1`, then `d` is positive. -/
theorem d_pos_of_one_lt_x {a : Solution₁ d} (ha : 1 < a.x) : 0 < d := by
refine pos_of_mul_pos_left ?_ (sq_nonneg a.y)
rw [a.prop_y, sub_pos]
exact one_lt_pow₀ ha two_ne_zero
/-- If a solution has `x > 1`, then `d` is not a square. -/
theorem d_nonsquare_of_one_lt_x {a : Solution₁ d} (ha : 1 < a.x) : ¬IsSquare d := by
have hp := a.prop
rintro ⟨b, rfl⟩
simp_rw [← sq, ← mul_pow, sq_sub_sq, Int.mul_eq_one_iff_eq_one_or_neg_one] at hp
cutsat
/-- A solution with `x = 1` is trivial. -/
theorem eq_one_of_x_eq_one (h₀ : d ≠ 0) {a : Solution₁ d} (ha : a.x = 1) : a = 1 := by
have prop := a.prop_y
rw [ha, one_pow, sub_self, mul_eq_zero, or_iff_right h₀, sq_eq_zero_iff] at prop
exact ext ha prop
/-- A solution is `1` or `-1` if and only if `y = 0`. -/
theorem eq_one_or_neg_one_iff_y_eq_zero {a : Solution₁ d} : a = 1 ∨ a = -1 ↔ a.y = 0 := by
refine ⟨fun H => H.elim (fun h => by simp [h]) fun h => by simp [h], fun H => ?_⟩
have prop := a.prop
rw [H, sq (0 : ℤ), mul_zero, mul_zero, sub_zero, sq_eq_one_iff] at prop
exact prop.imp (fun h => ext h H) fun h => ext h H
/-- The set of solutions with `x > 0` is closed under multiplication. -/
theorem x_mul_pos {a b : Solution₁ d} (ha : 0 < a.x) (hb : 0 < b.x) : 0 < (a * b).x := by
simp only [x_mul]
refine neg_lt_iff_pos_add'.mp (abs_lt.mp ?_).1
rw [← abs_of_pos ha, ← abs_of_pos hb, ← abs_mul, ← sq_lt_sq, mul_pow a.x, a.prop_x, b.prop_x, ←
sub_pos]
ring_nf
rcases le_or_gt 0 d with h | h
· positivity
· rw [(eq_zero_of_d_neg h a).resolve_left ha.ne', (eq_zero_of_d_neg h b).resolve_left hb.ne']
simp
/-- The set of solutions with `x` and `y` positive is closed under multiplication. -/
theorem y_mul_pos {a b : Solution₁ d} (hax : 0 < a.x) (hay : 0 < a.y) (hbx : 0 < b.x)
(hby : 0 < b.y) : 0 < (a * b).y := by
simp only [y_mul]
positivity
/-- If `(x, y)` is a solution with `x` positive, then all its powers with natural exponents
have positive `x`. -/
theorem x_pow_pos {a : Solution₁ d} (hax : 0 < a.x) (n : ℕ) : 0 < (a ^ n).x := by
induction n with
| zero => simp only [pow_zero, x_one, zero_lt_one]
| succ n ih => rw [pow_succ]; exact x_mul_pos ih hax
/-- If `(x, y)` is a solution with `x` and `y` positive, then all its powers with positive
natural exponents have positive `y`. -/
theorem y_pow_succ_pos {a : Solution₁ d} (hax : 0 < a.x) (hay : 0 < a.y) (n : ℕ) :
0 < (a ^ n.succ).y := by
induction n with
| zero => simp only [pow_one, hay]
| succ n ih => rw [pow_succ']; exact y_mul_pos hax hay (x_pow_pos hax _) ih
/-- If `(x, y)` is a solution with `x` and `y` positive, then all its powers with positive
exponents have positive `y`. -/
theorem y_zpow_pos {a : Solution₁ d} (hax : 0 < a.x) (hay : 0 < a.y) {n : ℤ} (hn : 0 < n) :
0 < (a ^ n).y := by
lift n to ℕ using hn.le
norm_cast at hn ⊢
rw [← Nat.succ_pred_eq_of_pos hn]
exact y_pow_succ_pos hax hay _
/-- If `(x, y)` is a solution with `x` positive, then all its powers have positive `x`. -/
theorem x_zpow_pos {a : Solution₁ d} (hax : 0 < a.x) (n : ℤ) : 0 < (a ^ n).x := by
cases n with
| ofNat n =>
rw [Int.ofNat_eq_coe, zpow_natCast]
exact x_pow_pos hax n
| negSucc n =>
rw [zpow_negSucc]
exact x_pow_pos hax (n + 1)
/-- If `(x, y)` is a solution with `x` and `y` positive, then the `y` component of any power
has the same sign as the exponent. -/
theorem sign_y_zpow_eq_sign_of_x_pos_of_y_pos {a : Solution₁ d} (hax : 0 < a.x) (hay : 0 < a.y)
(n : ℤ) : (a ^ n).y.sign = n.sign := by
rcases n with ((_ | n) | n)
· rfl
· rw [Int.ofNat_eq_coe, zpow_natCast]
exact Int.sign_eq_one_of_pos (y_pow_succ_pos hax hay n)
· rw [zpow_negSucc]
exact Int.sign_eq_neg_one_of_neg (neg_neg_of_pos (y_pow_succ_pos hax hay n))
/-- If `a` is any solution, then one of `a`, `a⁻¹`, `-a`, `-a⁻¹` has
positive `x` and nonnegative `y`. -/
theorem exists_pos_variant (h₀ : 0 < d) (a : Solution₁ d) :
∃ b : Solution₁ d, 0 < b.x ∧ 0 ≤ b.y ∧ a ∈ ({b, b⁻¹, -b, -b⁻¹} : Set (Solution₁ d)) := by
refine
(lt_or_gt_of_ne (a.x_ne_zero h₀.le)).elim
((le_total 0 a.y).elim (fun hy hx => ⟨-a⁻¹, ?_, ?_, ?_⟩) fun hy hx => ⟨-a, ?_, ?_, ?_⟩)
((le_total 0 a.y).elim (fun hy hx => ⟨a, hx, hy, ?_⟩) fun hy hx => ⟨a⁻¹, hx, ?_, ?_⟩) <;>
simp only [neg_neg, inv_inv, neg_inv, Set.mem_insert_iff, Set.mem_singleton_iff, true_or,
x_neg, x_inv, y_neg, y_inv, neg_pos, neg_nonneg, or_true] <;>
assumption
end Solution₁
section Existence
/-!
### Existence of nontrivial solutions
-/
variable {d : ℤ}
open Set Real
/-- If `d` is a positive integer that is not a square, then there is a nontrivial solution
to the Pell equation `x^2 - d*y^2 = 1`. -/
theorem exists_of_not_isSquare (h₀ : 0 < d) (hd : ¬IsSquare d) :
∃ x y : ℤ, x ^ 2 - d * y ^ 2 = 1 ∧ y ≠ 0 := by
let ξ : ℝ := √d
have hξ : Irrational ξ := by
refine irrational_nrt_of_notint_nrt 2 d (sq_sqrt <| Int.cast_nonneg h₀.le) ?_ two_pos
rintro ⟨x, hx⟩
refine hd ⟨x, @Int.cast_injective ℝ _ _ d (x * x) ?_⟩
rw [← sq_sqrt <| Int.cast_nonneg h₀.le, Int.cast_mul, ← hx, sq]
obtain ⟨M, hM₁⟩ := exists_int_gt (2 * |ξ| + 1)
have hM : {q : ℚ | |q.1 ^ 2 - d * (q.2 : ℤ) ^ 2| < M}.Infinite := by
refine Infinite.mono (fun q h => ?_) (infinite_rat_abs_sub_lt_one_div_den_sq_of_irrational hξ)
have h0 : 0 < (q.2 : ℝ) ^ 2 := pow_pos (Nat.cast_pos.mpr q.pos) 2
have h1 : (q.num : ℝ) / (q.den : ℝ) = q := mod_cast q.num_div_den
rw [mem_setOf, abs_sub_comm, ← @Int.cast_lt ℝ,
← div_lt_div_iff_of_pos_right (abs_pos_of_pos h0)]
push_cast
rw [← abs_div, abs_sq, sub_div, mul_div_cancel_right₀ _ h0.ne', ← div_pow, h1, ←
sq_sqrt (Int.cast_pos.mpr h₀).le, sq_sub_sq, abs_mul, ← mul_one_div]
refine mul_lt_mul'' (((abs_add_le ξ q).trans ?_).trans_lt hM₁) h (abs_nonneg _) (abs_nonneg _)
rw [two_mul, add_assoc, add_le_add_iff_left, ← sub_le_iff_le_add']
rw [mem_setOf, abs_sub_comm] at h
refine (abs_sub_abs_le_abs_sub (q : ℝ) ξ).trans (h.le.trans ?_)
rw [div_le_one h0, one_le_sq_iff_one_le_abs, Nat.abs_cast, Nat.one_le_cast]
exact q.pos
obtain ⟨m, hm⟩ : ∃ m : ℤ, {q : ℚ | q.1 ^ 2 - d * (q.den : ℤ) ^ 2 = m}.Infinite := by
contrapose! hM
simp only [not_infinite] at hM ⊢
refine (congr_arg _ (ext fun x => ?_)).mp (Finite.biUnion (finite_Ioo (-M) M) fun m _ => hM m)
simp only [abs_lt, mem_setOf, mem_Ioo, mem_iUnion, exists_prop, exists_eq_right']
have hm₀ : m ≠ 0 := by
rintro rfl
obtain ⟨q, hq⟩ := hm.nonempty
rw [mem_setOf, sub_eq_zero, mul_comm] at hq
obtain ⟨a, ha⟩ := (Int.pow_dvd_pow_iff two_ne_zero).mp ⟨d, hq⟩
rw [ha, mul_pow, mul_right_inj' (pow_pos (Int.natCast_pos.mpr q.pos) 2).ne'] at hq
exact hd ⟨a, sq a ▸ hq.symm⟩
haveI := neZero_iff.mpr (Int.natAbs_ne_zero.mpr hm₀)
let f : ℚ → ZMod m.natAbs × ZMod m.natAbs := fun q => (q.num, q.den)
obtain ⟨q₁, h₁ : q₁.num ^ 2 - d * (q₁.den : ℤ) ^ 2 = m,
q₂, h₂ : q₂.num ^ 2 - d * (q₂.den : ℤ) ^ 2 = m, hne, hqf⟩ :=
hm.exists_ne_map_eq_of_mapsTo (mapsTo_univ f _) finite_univ
obtain ⟨hq1 : (q₁.num : ZMod m.natAbs) = q₂.num, hq2 : (q₁.den : ZMod m.natAbs) = q₂.den⟩ :=
Prod.ext_iff.mp hqf
have hd₁ : m ∣ q₁.num * q₂.num - d * (q₁.den * q₂.den) := by
rw [← Int.natAbs_dvd, ← ZMod.intCast_zmod_eq_zero_iff_dvd]
push_cast
rw [hq1, hq2, ← sq, ← sq]
norm_cast
rw [ZMod.intCast_zmod_eq_zero_iff_dvd, Int.natAbs_dvd, Nat.cast_pow, ← h₂]
have hd₂ : m ∣ q₁.num * q₂.den - q₂.num * q₁.den := by
rw [← Int.natAbs_dvd, ← ZMod.intCast_eq_intCast_iff_dvd_sub]
push_cast
rw [hq1, hq2]
replace hm₀ : (m : ℚ) ≠ 0 := Int.cast_ne_zero.mpr hm₀
refine ⟨(q₁.num * q₂.num - d * (q₁.den * q₂.den)) / m, (q₁.num * q₂.den - q₂.num * q₁.den) / m,
?_, ?_⟩
· qify [hd₁, hd₂]
field_simp
norm_cast
grind
· qify [hd₂]
refine div_ne_zero_iff.mpr ⟨?_, hm₀⟩
exact mod_cast mt sub_eq_zero.mp (mt Rat.eq_iff_mul_eq_mul.mpr hne)
/-- If `d` is a positive integer, then there is a nontrivial solution
to the Pell equation `x^2 - d*y^2 = 1` if and only if `d` is not a square. -/
theorem exists_iff_not_isSquare (h₀ : 0 < d) :
(∃ x y : ℤ, x ^ 2 - d * y ^ 2 = 1 ∧ y ≠ 0) ↔ ¬IsSquare d := by
refine ⟨?_, exists_of_not_isSquare h₀⟩
rintro ⟨x, y, hxy, hy⟩ ⟨a, rfl⟩
rw [← sq, ← mul_pow, sq_sub_sq] at hxy
simpa [hy, mul_self_pos.mp h₀, sub_eq_add_neg, eq_neg_self_iff] using Int.eq_of_mul_eq_one hxy
namespace Solution₁
/-- If `d` is a positive integer that is not a square, then there exists a nontrivial solution
to the Pell equation `x^2 - d*y^2 = 1`. -/
theorem exists_nontrivial_of_not_isSquare (h₀ : 0 < d) (hd : ¬IsSquare d) :
∃ a : Solution₁ d, a ≠ 1 ∧ a ≠ -1 := by
obtain ⟨x, y, prop, hy⟩ := exists_of_not_isSquare h₀ hd
refine ⟨mk x y prop, fun H => ?_, fun H => ?_⟩ <;> apply_fun Solution₁.y at H <;>
simp [hy] at H
/-- If `d` is a positive integer that is not a square, then there exists a solution
to the Pell equation `x^2 - d*y^2 = 1` with `x > 1` and `y > 0`. -/
theorem exists_pos_of_not_isSquare (h₀ : 0 < d) (hd : ¬IsSquare d) :
∃ a : Solution₁ d, 1 < a.x ∧ 0 < a.y := by
obtain ⟨x, y, h, hy⟩ := exists_of_not_isSquare h₀ hd
refine ⟨mk |x| |y| (by rwa [sq_abs, sq_abs]), ?_, abs_pos.mpr hy⟩
rw [x_mk, ← one_lt_sq_iff_one_lt_abs, eq_add_of_sub_eq h, lt_add_iff_pos_right]
exact mul_pos h₀ (sq_pos_of_ne_zero hy)
end Solution₁
end Existence
/-! ### Fundamental solutions
We define the notion of a *fundamental solution* of Pell's equation and
show that it exists and is unique (when `d` is positive and non-square)
and generates the group of solutions up to sign.
-/
variable {d : ℤ}
/-- We define a solution to be *fundamental* if it has `x > 1` and `y > 0`
and its `x` is the smallest possible among solutions with `x > 1`. -/
def IsFundamental (a : Solution₁ d) : Prop :=
1 < a.x ∧ 0 < a.y ∧ ∀ {b : Solution₁ d}, 1 < b.x → a.x ≤ b.x
namespace IsFundamental
open Solution₁
/-- A fundamental solution has positive `x`. -/
theorem x_pos {a : Solution₁ d} (h : IsFundamental a) : 0 < a.x :=
zero_lt_one.trans h.1
/-- If a fundamental solution exists, then `d` must be positive. -/
theorem d_pos {a : Solution₁ d} (h : IsFundamental a) : 0 < d :=
d_pos_of_one_lt_x h.1
/-- If a fundamental solution exists, then `d` must be a non-square. -/
theorem d_nonsquare {a : Solution₁ d} (h : IsFundamental a) : ¬IsSquare d :=
d_nonsquare_of_one_lt_x h.1
/-- If there is a fundamental solution, it is unique. -/
theorem subsingleton {a b : Solution₁ d} (ha : IsFundamental a) (hb : IsFundamental b) : a = b := by
have hx := le_antisymm (ha.2.2 hb.1) (hb.2.2 ha.1)
refine Solution₁.ext hx ?_
have : d * a.y ^ 2 = d * b.y ^ 2 := by rw [a.prop_y, b.prop_y, hx]
exact (sq_eq_sq₀ ha.2.1.le hb.2.1.le).mp (Int.eq_of_mul_eq_mul_left ha.d_pos.ne' this)
/-- If `d` is positive and not a square, then a fundamental solution exists. -/
theorem exists_of_not_isSquare (h₀ : 0 < d) (hd : ¬IsSquare d) :
∃ a : Solution₁ d, IsFundamental a := by
obtain ⟨a, ha₁, ha₂⟩ := exists_pos_of_not_isSquare h₀ hd
-- convert to `x : ℕ` to be able to use `Nat.find`
have P : ∃ x' : ℕ, 1 < x' ∧ ∃ y' : ℤ, 0 < y' ∧ (x' : ℤ) ^ 2 - d * y' ^ 2 = 1 := by
have hax := a.prop
lift a.x to ℕ using by positivity with ax
norm_cast at ha₁
exact ⟨ax, ha₁, a.y, ha₂, hax⟩
classical
-- to avoid having to show that the predicate is decidable
let x₁ := Nat.find P
obtain ⟨hx, y₁, hy₀, hy₁⟩ := Nat.find_spec P
refine ⟨mk x₁ y₁ hy₁, by rw [x_mk]; exact mod_cast hx, hy₀, fun {b} hb => ?_⟩
rw [x_mk]
have hb' := (Int.toNat_of_nonneg <| zero_le_one.trans hb.le).symm
have hb'' := hb
rw [hb'] at hb ⊢
norm_cast at hb ⊢
refine Nat.find_min' P ⟨hb, |b.y|, abs_pos.mpr <| y_ne_zero_of_one_lt_x hb'', ?_⟩
rw [← hb', sq_abs]
exact b.prop
/-- The map sending an integer `n` to the `y`-coordinate of `a^n` for a fundamental
solution `a` is strictly increasing. -/
theorem y_strictMono {a : Solution₁ d} (h : IsFundamental a) :
StrictMono fun n : ℤ => (a ^ n).y := by
have H : ∀ n : ℤ, 0 ≤ n → (a ^ n).y < (a ^ (n + 1)).y := by
intro n hn
rw [← sub_pos, zpow_add, zpow_one, y_mul, add_sub_assoc]
rw [show (a ^ n).y * a.x - (a ^ n).y = (a ^ n).y * (a.x - 1) by ring]
refine
add_pos_of_pos_of_nonneg (mul_pos (x_zpow_pos h.x_pos _) h.2.1)
(mul_nonneg ?_ (by rw [sub_nonneg]; exact h.1.le))
rcases hn.eq_or_lt with (rfl | hn)
· simp only [zpow_zero, y_one, le_refl]
· exact (y_zpow_pos h.x_pos h.2.1 hn).le
refine strictMono_int_of_lt_succ fun n => ?_
rcases le_or_gt 0 n with hn | hn
· exact H n hn
· let m : ℤ := -n - 1
have hm : n = -m - 1 := by simp only [m, neg_sub, sub_neg_eq_add, add_tsub_cancel_left]
rw [hm, sub_add_cancel, ← neg_add', zpow_neg, zpow_neg, y_inv, y_inv, neg_lt_neg_iff]
exact H _ (by cutsat)
/-- If `a` is a fundamental solution, then `(a^m).y < (a^n).y` if and only if `m < n`. -/
theorem zpow_y_lt_iff_lt {a : Solution₁ d} (h : IsFundamental a) (m n : ℤ) :
(a ^ m).y < (a ^ n).y ↔ m < n := by
refine ⟨fun H => ?_, fun H => h.y_strictMono H⟩
contrapose! H
exact h.y_strictMono.monotone H
/-- The `n`th power of a fundamental solution is trivial if and only if `n = 0`. -/
theorem zpow_eq_one_iff {a : Solution₁ d} (h : IsFundamental a) (n : ℤ) : a ^ n = 1 ↔ n = 0 := by
rw [← zpow_zero a]
exact ⟨fun H => h.y_strictMono.injective (congr_arg Solution₁.y H), fun H => H ▸ rfl⟩
/-- A power of a fundamental solution is never equal to the negative of a power of this
fundamental solution. -/
theorem zpow_ne_neg_zpow {a : Solution₁ d} (h : IsFundamental a) {n n' : ℤ} : a ^ n ≠ -a ^ n' := by
intro hf
apply_fun Solution₁.x at hf
have H := x_zpow_pos h.x_pos n
rw [hf, x_neg, lt_neg, neg_zero] at H
exact lt_irrefl _ ((x_zpow_pos h.x_pos n').trans H)
/-- The `x`-coordinate of a fundamental solution is a lower bound for the `x`-coordinate
of any positive solution. -/
theorem x_le_x {a₁ : Solution₁ d} (h : IsFundamental a₁) {a : Solution₁ d} (hax : 1 < a.x) :
a₁.x ≤ a.x :=
h.2.2 hax
/-- The `y`-coordinate of a fundamental solution is a lower bound for the `y`-coordinate
of any positive solution. -/
theorem y_le_y {a₁ : Solution₁ d} (h : IsFundamental a₁) {a : Solution₁ d} (hax : 1 < a.x)
(hay : 0 < a.y) : a₁.y ≤ a.y := by
have H : d * (a₁.y ^ 2 - a.y ^ 2) = a₁.x ^ 2 - a.x ^ 2 := by rw [a.prop_x, a₁.prop_x]; ring
rw [← abs_of_pos hay, ← abs_of_pos h.2.1, ← sq_le_sq, ← mul_le_mul_iff_right₀ h.d_pos,
← sub_nonpos, ← mul_sub, H, sub_nonpos, sq_le_sq, abs_of_pos (zero_lt_one.trans h.1),
abs_of_pos (zero_lt_one.trans hax)]
exact h.x_le_x hax
-- helper lemma for the next three results
theorem x_mul_y_le_y_mul_x {a₁ : Solution₁ d} (h : IsFundamental a₁) {a : Solution₁ d}
(hax : 1 < a.x) (hay : 0 < a.y) : a.x * a₁.y ≤ a.y * a₁.x := by
rw [← abs_of_pos <| zero_lt_one.trans hax, ← abs_of_pos hay, ← abs_of_pos h.x_pos, ←
abs_of_pos h.2.1, ← abs_mul, ← abs_mul, ← sq_le_sq, mul_pow, mul_pow, a.prop_x, a₁.prop_x, ←
sub_nonneg]
ring_nf
rw [sub_nonneg, sq_le_sq, abs_of_pos hay, abs_of_pos h.2.1]
exact h.y_le_y hax hay
/-- If we multiply a positive solution with the inverse of a fundamental solution,
the `y`-coordinate remains nonnegative. -/
theorem mul_inv_y_nonneg {a₁ : Solution₁ d} (h : IsFundamental a₁) {a : Solution₁ d} (hax : 1 < a.x)
(hay : 0 < a.y) : 0 ≤ (a * a₁⁻¹).y := by
simpa only [y_inv, mul_neg, y_mul, le_neg_add_iff_add_le, add_zero] using
h.x_mul_y_le_y_mul_x hax hay
/-- If we multiply a positive solution with the inverse of a fundamental solution,
the `x`-coordinate stays positive. -/
theorem mul_inv_x_pos {a₁ : Solution₁ d} (h : IsFundamental a₁) {a : Solution₁ d} (hax : 1 < a.x)
(hay : 0 < a.y) : 0 < (a * a₁⁻¹).x := by
simp only [x_mul, x_inv, y_inv, mul_neg, lt_add_neg_iff_add_lt, zero_add]
refine lt_of_mul_lt_mul_left ?_ <| zero_le_one.trans hax.le
calc a.x * (d * (a.y * a₁.y))
_ = d * a.y * (a.x * a₁.y) := by ring
_ ≤ d * a.y * (a.y * a₁.x) := by have := x_mul_y_le_y_mul_x h hax hay; have := h.d_pos; gcongr
_ = (a.x ^ 2 - 1) * a₁.x := by rw [← a.prop_y]; ring
_ < a.x * (a.x * a₁.x) := by linarith [h.1]
/-- If we multiply a positive solution with the inverse of a fundamental solution,
the `x`-coordinate decreases. -/
theorem mul_inv_x_lt_x {a₁ : Solution₁ d} (h : IsFundamental a₁) {a : Solution₁ d} (hax : 1 < a.x)
(hay : 0 < a.y) : (a * a₁⁻¹).x < a.x := by
simp only [x_mul, x_inv, y_inv, mul_neg, add_neg_lt_iff_le_add']
refine lt_of_mul_lt_mul_left ?_ h.2.1.le
calc a₁.y * (a.x * a₁.x)
_ = a.x * a₁.y * a₁.x := by ring
_ ≤ a.y * a₁.x * a₁.x := by have := h.1; have := x_mul_y_le_y_mul_x h hax hay; gcongr
rw [mul_assoc, ← sq, a₁.prop_x, ← sub_neg]
suffices a.y - a.x * a₁.y < 0 by convert this using 1; ring
rw [sub_neg, ← abs_of_pos hay, ← abs_of_pos h.2.1, ← abs_of_pos <| zero_lt_one.trans hax, ←
abs_mul, ← sq_lt_sq, mul_pow, a.prop_x]
calc
a.y ^ 2 = 1 * a.y ^ 2 := (one_mul _).symm
_ ≤ d * a.y ^ 2 := (mul_le_mul_iff_left₀ <| sq_pos_of_pos hay).mpr h.d_pos
_ < d * a.y ^ 2 + 1 := lt_add_one _
_ = (1 + d * a.y ^ 2) * 1 := by rw [add_comm, mul_one]
_ ≤ (1 + d * a.y ^ 2) * a₁.y ^ 2 :=
(mul_le_mul_iff_right₀ (by have := h.d_pos; positivity)).mpr (sq_pos_of_pos h.2.1)
/-- Any nonnegative solution is a power with nonnegative exponent of a fundamental solution. -/
theorem eq_pow_of_nonneg {a₁ : Solution₁ d} (h : IsFundamental a₁) {a : Solution₁ d} (hax : 0 < a.x)
(hay : 0 ≤ a.y) : ∃ n : ℕ, a = a₁ ^ n := by
lift a.x to ℕ using hax.le with ax hax'
induction ax using Nat.strong_induction_on generalizing a with | h x ih =>
rcases hay.eq_or_lt with hy | hy
· -- case 1: `a = 1`
refine ⟨0, ?_⟩
simp only [pow_zero]
ext <;> simp only [x_one, y_one]
· have prop := a.prop
rw [← hy, sq (0 : ℤ), zero_mul, mul_zero, sub_zero,
sq_eq_one_iff] at prop
refine prop.resolve_right fun hf => ?_
have := (hax.trans_eq hax').le.trans_eq hf
norm_num at this
· exact hy.symm
· -- case 2: `a ≥ a₁`
have hx₁ : 1 < a.x := by nlinarith [a.prop, h.d_pos]
have hxx₁ := h.mul_inv_x_pos hx₁ hy
have hxx₂ := h.mul_inv_x_lt_x hx₁ hy
have hyy := h.mul_inv_y_nonneg hx₁ hy
lift (a * a₁⁻¹).x to ℕ using hxx₁.le with x' hx'
obtain ⟨n, hn⟩ := ih x' (mod_cast hxx₂.trans_eq hax'.symm) hyy hx' hxx₁
exact ⟨n + 1, by rw [pow_succ', ← hn, mul_comm a, ← mul_assoc, mul_inv_cancel, one_mul]⟩
/-- Every solution is, up to a sign, a power of a given fundamental solution. -/
theorem eq_zpow_or_neg_zpow {a₁ : Solution₁ d} (h : IsFundamental a₁) (a : Solution₁ d) :
∃ n : ℤ, a = a₁ ^ n ∨ a = -a₁ ^ n := by
obtain ⟨b, hbx, hby, hb⟩ := exists_pos_variant h.d_pos a
obtain ⟨n, hn⟩ := h.eq_pow_of_nonneg hbx hby
rcases hb with (rfl | rfl | rfl | hb)
· exact ⟨n, Or.inl (mod_cast hn)⟩
· exact ⟨-n, Or.inl (by simp [hn])⟩
· exact ⟨n, Or.inr (by simp [hn])⟩
· rw [Set.mem_singleton_iff] at hb
rw [hb]
exact ⟨-n, Or.inr (by simp [hn])⟩
end IsFundamental
open Solution₁ IsFundamental
/-- When `d` is positive and not a square, then the group of solutions to the Pell equation
`x^2 - d*y^2 = 1` has a unique positive generator (up to sign). -/
theorem existsUnique_pos_generator (h₀ : 0 < d) (hd : ¬IsSquare d) :
∃! a₁ : Solution₁ d,
1 < a₁.x ∧ 0 < a₁.y ∧ ∀ a : Solution₁ d, ∃ n : ℤ, a = a₁ ^ n ∨ a = -a₁ ^ n := by
obtain ⟨a₁, ha₁⟩ := IsFundamental.exists_of_not_isSquare h₀ hd
refine ⟨a₁, ⟨ha₁.1, ha₁.2.1, ha₁.eq_zpow_or_neg_zpow⟩, fun a (H : 1 < _ ∧ _) => ?_⟩
obtain ⟨Hx, Hy, H⟩ := H
obtain ⟨n₁, hn₁⟩ := H a₁
obtain ⟨n₂, hn₂⟩ := ha₁.eq_zpow_or_neg_zpow a
rcases hn₂ with (rfl | rfl)
· rw [← zpow_mul, eq_comm, @eq_comm _ a₁, ← mul_inv_eq_one, ← @mul_inv_eq_one _ _ _ a₁, ←
zpow_neg_one, neg_mul, ← zpow_add, ← sub_eq_add_neg] at hn₁
rcases hn₁ with hn₁ | hn₁
· rcases Int.isUnit_iff.mp
(.of_mul_eq_one _ <|
sub_eq_zero.mp <| (ha₁.zpow_eq_one_iff (n₂ * n₁ - 1)).mp hn₁) with
(rfl | rfl)
· rw [zpow_one]
· rw [zpow_neg_one, y_inv, lt_neg, neg_zero] at Hy
exact False.elim (lt_irrefl _ <| ha₁.2.1.trans Hy)
· rw [← zpow_zero a₁, eq_comm] at hn₁
exact False.elim (ha₁.zpow_ne_neg_zpow hn₁)
· rw [x_neg, lt_neg] at Hx
have := (x_zpow_pos (zero_lt_one.trans ha₁.1) n₂).trans Hx
norm_num at this
/-- A positive solution is a generator (up to sign) of the group of all solutions to the
Pell equation `x^2 - d*y^2 = 1` if and only if it is a fundamental solution. -/
theorem pos_generator_iff_fundamental (a : Solution₁ d) :
(1 < a.x ∧ 0 < a.y ∧ ∀ b : Solution₁ d, ∃ n : ℤ, b = a ^ n ∨ b = -a ^ n) ↔ IsFundamental a := by
refine ⟨fun h => ?_, fun H => ⟨H.1, H.2.1, H.eq_zpow_or_neg_zpow⟩⟩
have h₀ := d_pos_of_one_lt_x h.1
have hd := d_nonsquare_of_one_lt_x h.1
obtain ⟨a₁, ha₁⟩ := IsFundamental.exists_of_not_isSquare h₀ hd
obtain ⟨b, -, hb₂⟩ := existsUnique_pos_generator h₀ hd
rwa [hb₂ a h, ← hb₂ a₁ ⟨ha₁.1, ha₁.2.1, ha₁.eq_zpow_or_neg_zpow⟩]
end Pell |
.lake/packages/mathlib/Mathlib/NumberTheory/MaricaSchoenheim.lean | import Mathlib.Combinatorics.SetFamily.FourFunctions
import Mathlib.Data.Nat.Squarefree
/-!
# The Marica-Schönheim special case of Graham's conjecture
Graham's conjecture states that if $0 < a_1 < \dots a_n$ are integers, then
$\max_{i, j} \frac{a_i}{\gcd(a_i, a_j)} \ge n$. This file proves the conjecture when the $a_i$ are
squarefree as a corollary of the Marica-Schönheim inequality.
## References
[*Applications of the FKG Inequality and Its Relatives*, Graham][Graham1983]
-/
open Finset
open scoped FinsetFamily
namespace Nat
/-- Statement of Graham's conjecture (which is now a theorem in the literature).
Graham's conjecture states that if $0 < a_1 < \dots a_n$ are integers, then
$\max_{i, j} \frac{a_i}{\gcd(a_i, a_j)} \ge n$. -/
def GrahamConjecture (n : ℕ) (f : ℕ → ℕ) : Prop :=
n ≠ 0 → StrictMonoOn f (Set.Iio n) → ∃ i < n, ∃ j < n, (f i).gcd (f j) * n ≤ f i
/-- The special case of Graham's conjecture where all numbers are squarefree. -/
lemma grahamConjecture_of_squarefree {n : ℕ} (f : ℕ → ℕ) (hf' : ∀ k < n, Squarefree (f k)) :
GrahamConjecture n f := by
rintro hn hf
by_contra!
set 𝒜 := (Iio n).image fun n ↦ primeFactors (f n)
have hf'' : ∀ i < n, ∀ j, Squarefree (f i / (f i).gcd (f j)) :=
fun i hi j ↦ (hf' _ hi).squarefree_of_dvd <| div_dvd_of_dvd <| gcd_dvd_left _ _
refine lt_irrefl n ?_
calc
n = #𝒜 := ?_
_ ≤ #(𝒜 \\ 𝒜) := 𝒜.card_le_card_diffs
_ ≤ #(Ioo 0 n) := card_le_card_of_injOn (fun s ↦ ∏ p ∈ s, p) ?_ ?_
_ = n - 1 := by rw [card_Ioo, tsub_zero]
_ < n := tsub_lt_self hn.bot_lt zero_lt_one
· rw [Finset.card_image_of_injOn, card_Iio]
simpa using prod_primeFactors_invOn_squarefree.2.injOn.comp hf.injOn hf'
· simp only [𝒜, forall_mem_diffs, forall_mem_image, mem_Ioo, mem_Iio, Set.MapsTo, mem_coe]
rintro i hi j hj
rw [← primeFactors_div_gcd (hf' _ hi) (hf' _ hj).ne_zero,
prod_primeFactors_of_squarefree <| hf'' _ hi _]
exact ⟨Nat.div_pos (gcd_le_left _ (hf' _ hi).ne_zero.bot_lt) <|
Nat.gcd_pos_of_pos_left _ (hf' _ hi).ne_zero.bot_lt, Nat.div_lt_of_lt_mul <| this _ hi _ hj⟩
· simp only [𝒜, Set.InjOn, mem_coe, forall_mem_diffs, forall_mem_image, mem_Iio]
rintro a ha b hb c hc d hd
rw [← primeFactors_div_gcd (hf' _ ha) (hf' _ hb).ne_zero, ← primeFactors_div_gcd
(hf' _ hc) (hf' _ hd).ne_zero, prod_primeFactors_of_squarefree (hf'' _ ha _),
prod_primeFactors_of_squarefree (hf'' _ hc _)]
rintro h
rw [h]
end Nat |
.lake/packages/mathlib/Mathlib/NumberTheory/SumTwoSquares.lean | import Mathlib.Data.Nat.Squarefree
import Mathlib.NumberTheory.Zsqrtd.QuadraticReciprocity
import Mathlib.NumberTheory.Padics.PadicVal.Basic
/-!
# Sums of two squares
Fermat's theorem on the sum of two squares. Every prime `p` congruent to 1 mod 4 is the
sum of two squares; see `Nat.Prime.sq_add_sq` (which has the weaker assumption `p % 4 ≠ 3`).
We also give the result that characterizes the (positive) natural numbers that are sums
of two squares as those numbers `n` such that for every prime `q` congruent to 3 mod 4, the
exponent of the largest power of `q` dividing `n` is even; see `Nat.eq_sq_add_sq_iff`.
There is an alternative characterization as the numbers of the form `a^2 * b`, where `b` is a
natural number such that `-1` is a square modulo `b`; see `Nat.eq_sq_add_sq_iff_eq_sq_mul`.
-/
section Fermat
open GaussianInt
/-- **Fermat's theorem on the sum of two squares**. Every prime not congruent to 3 mod 4 is the sum
of two squares. Also known as **Fermat's Christmas theorem**. -/
theorem Nat.Prime.sq_add_sq {p : ℕ} [Fact p.Prime] (hp : p % 4 ≠ 3) :
∃ a b : ℕ, a ^ 2 + b ^ 2 = p := by
apply sq_add_sq_of_nat_prime_of_not_irreducible p
rwa [_root_.irreducible_iff_prime, prime_iff_mod_four_eq_three_of_nat_prime p]
end Fermat
/-!
### Generalities on sums of two squares
-/
section General
/-- The set of sums of two squares is closed under multiplication in any commutative ring.
See also `sq_add_sq_mul_sq_add_sq`. -/
theorem sq_add_sq_mul {R} [CommRing R] {a b x y u v : R} (ha : a = x ^ 2 + y ^ 2)
(hb : b = u ^ 2 + v ^ 2) : ∃ r s : R, a * b = r ^ 2 + s ^ 2 :=
⟨x * u - y * v, x * v + y * u, by rw [ha, hb]; ring⟩
/-- The set of natural numbers that are sums of two squares is closed under multiplication. -/
theorem Nat.sq_add_sq_mul {a b x y u v : ℕ} (ha : a = x ^ 2 + y ^ 2) (hb : b = u ^ 2 + v ^ 2) :
∃ r s : ℕ, a * b = r ^ 2 + s ^ 2 := by
zify at ha hb ⊢
obtain ⟨r, s, h⟩ := _root_.sq_add_sq_mul ha hb
refine ⟨r.natAbs, s.natAbs, ?_⟩
simpa only [Int.natCast_natAbs, sq_abs]
end General
/-!
### Results on when -1 is a square modulo a natural number
-/
section NegOneSquare
-- This could be formulated for a general integer `a` in place of `-1`,
-- but it would not directly specialize to `-1`,
-- because `((-1 : ℤ) : ZMod n)` is not the same as `(-1 : ZMod n)`.
/-- If `-1` is a square modulo `n` and `m` divides `n`, then `-1` is also a square modulo `m`. -/
theorem ZMod.isSquare_neg_one_of_dvd {m n : ℕ} (hd : m ∣ n) (hs : IsSquare (-1 : ZMod n)) :
IsSquare (-1 : ZMod m) := by
let f : ZMod n →+* ZMod m := ZMod.castHom hd _
rw [← RingHom.map_one f, ← RingHom.map_neg]
exact hs.map f
/-- If `-1` is a square modulo coprime natural numbers `m` and `n`, then `-1` is also
a square modulo `m*n`. -/
theorem ZMod.isSquare_neg_one_mul {m n : ℕ} (hc : m.Coprime n) (hm : IsSquare (-1 : ZMod m))
(hn : IsSquare (-1 : ZMod n)) : IsSquare (-1 : ZMod (m * n)) := by
have : IsSquare (-1 : ZMod m × ZMod n) := by
rw [show (-1 : ZMod m × ZMod n) = ((-1 : ZMod m), (-1 : ZMod n)) from rfl]
obtain ⟨x, hx⟩ := hm
obtain ⟨y, hy⟩ := hn
rw [hx, hy]
exact ⟨(x, y), rfl⟩
simpa only [RingEquiv.map_neg_one] using this.map (ZMod.chineseRemainder hc).symm
/-- If `p` is a prime factor of `n` such that `-1` is a square modulo `n`, then `p % 4 ≠ 3`. -/
theorem Nat.mod_four_ne_three_of_mem_primeFactors_of_isSquare_neg_one {p n : ℕ}
(hp : p ∈ n.primeFactors) (hs : IsSquare (-1 : ZMod n)) : p % 4 ≠ 3 := by
obtain ⟨y, h⟩ := ZMod.isSquare_neg_one_of_dvd (Nat.dvd_of_mem_primeFactors hp) hs
rw [← sq, eq_comm, show (-1 : ZMod p) = -1 ^ 2 by ring] at h
have : Fact p.Prime := ⟨Nat.prime_of_mem_primeFactors hp⟩
exact ZMod.mod_four_ne_three_of_sq_eq_neg_sq' one_ne_zero h
@[deprecated "Note that the statement now uses `Nat.primeFactors`, \
you can use `Nat.mem_primeFactors` to get the previous formulation" (since := "2025-10-15")]
alias Nat.Prime.mod_four_ne_three_of_dvd_isSquare_neg_one :=
Nat.mod_four_ne_three_of_mem_primeFactors_of_isSquare_neg_one
/-- If `n` is a squarefree natural number, then `-1` is a square modulo `n` if and only if
`n` does not have a prime factor `q` such that `q % 4 = 3`. -/
theorem ZMod.isSquare_neg_one_iff_forall_mem_primeFactors_mod_four_ne_three {n : ℕ}
(hn : Squarefree n) : IsSquare (-1 : ZMod n) ↔ ∀ q ∈ n.primeFactors, q % 4 ≠ 3 := by
refine ⟨fun H q hq ↦ Nat.mod_four_ne_three_of_mem_primeFactors_of_isSquare_neg_one hq H,
fun H ↦ ?_⟩
induction n using induction_on_primes with
| zero => exact False.elim (hn.ne_zero rfl)
| one => exact ⟨0, by simp only [mul_zero, eq_iff_true_of_subsingleton]⟩
| prime_mul p n hpp ih =>
have : Fact p.Prime := ⟨hpp⟩
have hcp : p.Coprime n := by
by_contra hc
exact hpp.not_isUnit (hn p <| mul_dvd_mul_left p <| hpp.dvd_iff_not_coprime.mpr hc)
have hp₁ := ZMod.exists_sq_eq_neg_one_iff.mpr <| H _ <|
Nat.mem_primeFactors.mpr ⟨hpp, Nat.dvd_mul_right .., Squarefree.ne_zero hn⟩
exact ZMod.isSquare_neg_one_mul hcp hp₁ <| ih hn.of_mul_right fun q hqp => H q <|
Nat.mem_primeFactors.mpr ⟨Nat.prime_of_mem_primeFactors hqp,
dvd_mul_of_dvd_right (Nat.dvd_of_mem_primeFactors hqp) _, Squarefree.ne_zero hn⟩
@[deprecated "Note that the statement now uses `Nat.primeFactors`, \
you can use `Nat.mem_primeFactors` and `Squarefree.ne_zero` to get the previous formulation"
(since := "2025-10-15")]
alias ZMod.isSquare_neg_one_iff :=
ZMod.isSquare_neg_one_iff_forall_mem_primeFactors_mod_four_ne_three
/-- If `n` is a squarefree natural number, then `-1` is a square modulo `n` if and only if
`n` has no divisor `q` that is `≡ 3 mod 4`. -/
theorem ZMod.isSquare_neg_one_iff' {n : ℕ} (hn : Squarefree n) :
IsSquare (-1 : ZMod n) ↔ ∀ {q : ℕ}, q ∣ n → q % 4 ≠ 3 := by
have help : ∀ a b : ZMod 4, a ≠ 3 → b ≠ 3 → a * b ≠ 3 := by decide
rw [ZMod.isSquare_neg_one_iff_forall_mem_primeFactors_mod_four_ne_three hn]
refine ⟨?_, fun H q hq => H <| Nat.dvd_of_mem_primeFactors hq⟩
intro H
refine @induction_on_primes _ ?_ ?_ (fun p q hp hq hpq => ?_)
· exact fun _ => by simp
· exact fun _ => by simp
· replace hp := H _ <|
Nat.mem_primeFactors.mpr ⟨hp, dvd_of_mul_right_dvd hpq, Squarefree.ne_zero hn⟩
replace hq := hq (dvd_of_mul_left_dvd hpq)
rw [show 3 = 3 % 4 by simp, Ne, ← ZMod.natCast_eq_natCast_iff'] at hp hq ⊢
rw [Nat.cast_mul]
exact help p q hp hq
/-!
### Relation to sums of two squares
-/
/-- If `-1` is a square modulo the natural number `n`, then `n` is a sum of two squares. -/
theorem Nat.eq_sq_add_sq_of_isSquare_mod_neg_one {n : ℕ} (h : IsSquare (-1 : ZMod n)) :
∃ x y : ℕ, n = x ^ 2 + y ^ 2 := by
induction n using induction_on_primes with
| zero => exact ⟨0, 0, rfl⟩
| one => exact ⟨0, 1, rfl⟩
| prime_mul p n hpp ih =>
have : Fact p.Prime := ⟨hpp⟩
have hp : IsSquare (-1 : ZMod p) := ZMod.isSquare_neg_one_of_dvd ⟨n, rfl⟩ h
obtain ⟨u, v, huv⟩ := Nat.Prime.sq_add_sq (ZMod.exists_sq_eq_neg_one_iff.mp hp)
obtain ⟨x, y, hxy⟩ := ih (ZMod.isSquare_neg_one_of_dvd ⟨p, mul_comm _ _⟩ h)
exact Nat.sq_add_sq_mul huv.symm hxy
/-- If the integer `n` is a sum of two squares of coprime integers,
then `-1` is a square modulo `n`. -/
theorem ZMod.isSquare_neg_one_of_eq_sq_add_sq_of_isCoprime {n x y : ℤ} (h : n = x ^ 2 + y ^ 2)
(hc : IsCoprime x y) : IsSquare (-1 : ZMod n.natAbs) := by
obtain ⟨u, v, huv⟩ : IsCoprime x n := by
have hc2 : IsCoprime (x ^ 2) (y ^ 2) := hc.pow
rw [show y ^ 2 = n + -1 * x ^ 2 by cutsat] at hc2
exact (IsCoprime.pow_left_iff zero_lt_two).mp hc2.of_add_mul_right_right
have H : u * y * (u * y) - -1 = n * (-v ^ 2 * n + u ^ 2 + 2 * v) := by
linear_combination -u ^ 2 * h + (n * v - u * x - 1) * huv
refine ⟨u * y, ?_⟩
conv_rhs => tactic => norm_cast
rw [(by norm_cast : (-1 : ZMod n.natAbs) = (-1 : ℤ))]
exact (ZMod.intCast_eq_intCast_iff_dvd_sub _ _ _).mpr (Int.natAbs_dvd.mpr ⟨_, H⟩)
/-- If the natural number `n` is a sum of two squares of coprime natural numbers, then
`-1` is a square modulo `n`. -/
theorem ZMod.isSquare_neg_one_of_eq_sq_add_sq_of_coprime {n x y : ℕ} (h : n = x ^ 2 + y ^ 2)
(hc : x.Coprime y) : IsSquare (-1 : ZMod n) := by
zify at h
exact ZMod.isSquare_neg_one_of_eq_sq_add_sq_of_isCoprime h hc.isCoprime
/-- A natural number `n` is a sum of two squares if and only if `n = a^2 * b` with natural
numbers `a` and `b` such that `-1` is a square modulo `b`. -/
theorem Nat.eq_sq_add_sq_iff_eq_sq_mul {n : ℕ} :
(∃ x y : ℕ, n = x ^ 2 + y ^ 2) ↔ ∃ a b : ℕ, n = a ^ 2 * b ∧ IsSquare (-1 : ZMod b) := by
constructor
· rintro ⟨x, y, h⟩
by_cases hxy : x = 0 ∧ y = 0
· exact ⟨0, 1, by rw [h, hxy.1, hxy.2, zero_pow two_ne_zero, add_zero, zero_mul],
⟨0, by rw [zero_mul, neg_eq_zero, Fin.one_eq_zero_iff]⟩⟩
· have hg := Nat.pos_of_ne_zero (mt Nat.gcd_eq_zero_iff.mp hxy)
obtain ⟨g, x₁, y₁, _, h₂, h₃, h₄⟩ := Nat.exists_coprime' hg
exact ⟨g, x₁ ^ 2 + y₁ ^ 2, by rw [h, h₃, h₄]; ring,
ZMod.isSquare_neg_one_of_eq_sq_add_sq_of_coprime rfl h₂⟩
· rintro ⟨a, b, h₁, h₂⟩
obtain ⟨x', y', h⟩ := Nat.eq_sq_add_sq_of_isSquare_mod_neg_one h₂
exact ⟨a * x', a * y', by rw [h₁, h]; ring⟩
end NegOneSquare
/-!
### Characterization in terms of the prime factorization
-/
section Main
/-- A (positive) natural number `n` is a sum of two squares if and only if the exponent of
every prime `q` such that `q % 4 = 3` in the prime factorization of `n` is even.
(The assumption `0 < n` is not present, since for `n = 0`, both sides are satisfied;
the right-hand side holds, since `padicValNat q 0 = 0` by definition.) -/
theorem Nat.eq_sq_add_sq_iff {n : ℕ} :
(∃ x y, n = x ^ 2 + y ^ 2) ↔ ∀ q ∈ n.primeFactors, q % 4 = 3 → Even (padicValNat q n) := by
rcases n.eq_zero_or_pos with (rfl | hn₀)
· exact ⟨fun _ q _ _ ↦ padicValNat.zero.symm ▸ Even.zero, fun _ ↦ ⟨0, 0, rfl⟩⟩
-- now `0 < n`
refine eq_sq_add_sq_iff_eq_sq_mul.trans ⟨fun ⟨a, b, h₁, h₂⟩ q hq h ↦ ?_, fun H ↦ ?_⟩
· have : Fact q.Prime := ⟨prime_of_mem_primeFactors hq⟩
have : q ∣ b → q ∈ b.primeFactors := by grind [mem_primeFactors]
grind [padicValNat.mul, padicValNat.pow,
padicValNat.eq_zero_of_not_dvd, mod_four_ne_three_of_mem_primeFactors_of_isSquare_neg_one]
· obtain ⟨b, a, hb₀, ha₀, hab, hb⟩ := sq_mul_squarefree_of_pos hn₀
refine ⟨a, b, hab.symm, ZMod.isSquare_neg_one_iff_forall_mem_primeFactors_mod_four_ne_three hb
|>.mpr fun q hq hq4 ↦ ?_⟩
have : Fact q.Prime := ⟨prime_of_mem_primeFactors hq⟩
have := Nat.primeFactors_mono <| Dvd.intro_left _ hab
have : b.factorization q = 1 := by grind [Squarefree.natFactorization_le_one,
Prime.dvd_iff_one_le_factorization, prime_of_mem_primeFactors, dvd_of_mem_primeFactors]
grind [factorization_def, prime_of_mem_primeFactors, padicValNat.mul, padicValNat.pow]
end Main
instance {n : ℕ} : Decidable (∃ x y, n = x ^ 2 + y ^ 2) :=
decidable_of_iff' _ Nat.eq_sq_add_sq_iff |
.lake/packages/mathlib/Mathlib/NumberTheory/Bernoulli.lean | import Mathlib.Algebra.BigOperators.Field
import Mathlib.RingTheory.PowerSeries.Inverse
import Mathlib.RingTheory.PowerSeries.WellKnown
/-!
# Bernoulli numbers
The Bernoulli numbers are a sequence of rational numbers that frequently show up in
number theory.
## Mathematical overview
The Bernoulli numbers $(B_0, B_1, B_2, \ldots)=(1, -1/2, 1/6, 0, -1/30, \ldots)$ are
a sequence of rational numbers. They show up in the formula for the sums of $k$th
powers. They are related to the Taylor series expansions of $x/\tan(x)$ and
of $\coth(x)$, and also show up in the values that the Riemann Zeta function
takes both at both negative and positive integers (and hence in the
theory of modular forms). For example, if $1 \leq n$ then
$$\zeta(2n)=\sum_{t\geq1}t^{-2n}=(-1)^{n+1}\frac{(2\pi)^{2n}B_{2n}}{2(2n)!}.$$
This result is formalised in Lean: `riemannZeta_two_mul_nat`.
The Bernoulli numbers can be formally defined using the power series
$$\sum B_n\frac{t^n}{n!}=\frac{t}{1-e^{-t}}$$
although that happens to not be the definition in mathlib (this is an *implementation
detail* and need not concern the mathematician).
Note that $B_1=-1/2$, meaning that we are using the $B_n^-$ of
[from Wikipedia](https://en.wikipedia.org/wiki/Bernoulli_number).
## Implementation detail
The Bernoulli numbers are defined using well-founded induction, by the formula
$$B_n=1-\sum_{k\lt n}\frac{\binom{n}{k}}{n-k+1}B_k.$$
This formula is true for all $n$ and in particular $B_0=1$. Note that this is the definition
for positive Bernoulli numbers, which we call `bernoulli'`. The negative Bernoulli numbers are
then defined as `bernoulli := (-1)^n * bernoulli'`.
## Main theorems
`sum_bernoulli : ∑ k ∈ Finset.range n, (n.choose k : ℚ) * bernoulli k = if n = 1 then 1 else 0`
-/
open Nat Finset Finset.Nat PowerSeries
variable (A : Type*) [CommRing A] [Algebra ℚ A]
/-! ### Definitions -/
/-- The Bernoulli numbers:
the $n$-th Bernoulli number $B_n$ is defined recursively via
$$B_n = 1 - \sum_{k < n} \binom{n}{k}\frac{B_k}{n+1-k}$$ -/
def bernoulli' (n : ℕ) : ℚ :=
1 - ∑ k : Fin n, n.choose k / (n - k + 1) * bernoulli' k
theorem bernoulli'_def' (n : ℕ) :
bernoulli' n = 1 - ∑ k : Fin n, n.choose k / (n - k + 1) * bernoulli' k := by
rw [bernoulli']
theorem bernoulli'_def (n : ℕ) :
bernoulli' n = 1 - ∑ k ∈ range n, n.choose k / (n - k + 1) * bernoulli' k := by
rw [bernoulli'_def', ← Fin.sum_univ_eq_sum_range]
theorem bernoulli'_spec (n : ℕ) :
(∑ k ∈ range n.succ, (n.choose (n - k) : ℚ) / (n - k + 1) * bernoulli' k) = 1 := by
rw [sum_range_succ_comm, bernoulli'_def n, tsub_self, choose_zero_right, sub_self, zero_add,
div_one, cast_one, one_mul, sub_add, ← sum_sub_distrib, ← sub_eq_zero, sub_sub_cancel_left,
neg_eq_zero]
exact Finset.sum_eq_zero (fun x hx => by rw [choose_symm (le_of_lt (mem_range.1 hx)), sub_self])
theorem bernoulli'_spec' (n : ℕ) :
(∑ k ∈ antidiagonal n, ((k.1 + k.2).choose k.2 : ℚ) / (k.2 + 1) * bernoulli' k.1) = 1 := by
refine ((sum_antidiagonal_eq_sum_range_succ_mk _ n).trans ?_).trans (bernoulli'_spec n)
refine sum_congr rfl fun x hx => ?_
simp only [add_tsub_cancel_of_le, mem_range_succ_iff.mp hx, cast_sub]
/-! ### Examples -/
section Examples
@[simp]
theorem bernoulli'_zero : bernoulli' 0 = 1 := by
rw [bernoulli'_def]
simp
@[simp]
theorem bernoulli'_one : bernoulli' 1 = 1 / 2 := by
rw [bernoulli'_def]
norm_num
@[simp]
theorem bernoulli'_two : bernoulli' 2 = 1 / 6 := by
rw [bernoulli'_def]
norm_num [sum_range_succ, sum_range_succ, sum_range_zero]
@[simp]
theorem bernoulli'_three : bernoulli' 3 = 0 := by
rw [bernoulli'_def]
norm_num [sum_range_succ, sum_range_succ, sum_range_zero]
@[simp]
theorem bernoulli'_four : bernoulli' 4 = -1 / 30 := by
have : Nat.choose 4 2 = 6 := by decide -- shrug
rw [bernoulli'_def]
norm_num [sum_range_succ, sum_range_succ, sum_range_zero, this]
end Examples
@[simp]
theorem sum_bernoulli' (n : ℕ) : (∑ k ∈ range n, (n.choose k : ℚ) * bernoulli' k) = n := by
cases n with | zero => simp | succ n =>
suffices
((n + 1 : ℚ) * ∑ k ∈ range n, ↑(n.choose k) / (n - k + 1) * bernoulli' k) =
∑ x ∈ range n, ↑(n.succ.choose x) * bernoulli' x by
rw_mod_cast [sum_range_succ, bernoulli'_def, ← this, choose_succ_self_right]
ring
simp_rw [mul_sum, ← mul_assoc]
refine sum_congr rfl fun k hk => ?_
congr
have : ((n - k : ℕ) : ℚ) + 1 ≠ 0 := by norm_cast
simp only [← cast_sub (mem_range.1 hk).le, succ_eq_add_one, field, mul_comm]
rw_mod_cast [tsub_add_eq_add_tsub (mem_range.1 hk).le, choose_mul_succ_eq]
/-- The exponential generating function for the Bernoulli numbers `bernoulli' n`. -/
def bernoulli'PowerSeries :=
mk fun n => algebraMap ℚ A (bernoulli' n / n !)
theorem bernoulli'PowerSeries_mul_exp_sub_one :
bernoulli'PowerSeries A * (exp A - 1) = X * exp A := by
ext n
-- constant coefficient is a special case
cases n with | zero => simp | succ n =>
rw [bernoulli'PowerSeries, coeff_mul, mul_comm X, sum_antidiagonal_succ']
suffices (∑ p ∈ antidiagonal n,
bernoulli' p.1 / p.1! * ((p.2 + 1) * p.2! : ℚ)⁻¹) = (n ! : ℚ)⁻¹ by
simpa [map_sum, Nat.factorial] using congr_arg (algebraMap ℚ A) this
apply eq_inv_of_mul_eq_one_left
rw [sum_mul]
convert bernoulli'_spec' n using 1
apply sum_congr rfl
simp_rw [mem_antidiagonal]
rintro ⟨i, j⟩ rfl
have := factorial_mul_factorial_dvd_factorial_add i j
simp [field, add_choose, *]
/-- Odd Bernoulli numbers (greater than 1) are zero. -/
theorem bernoulli'_odd_eq_zero {n : ℕ} (h_odd : Odd n) (hlt : 1 < n) : bernoulli' n = 0 := by
let B := mk fun n => bernoulli' n / (n ! : ℚ)
suffices (B - evalNegHom B) * (exp ℚ - 1) = X * (exp ℚ - 1) by
rcases mul_eq_mul_right_iff.mp this with h | h <;>
simp only [PowerSeries.ext_iff, evalNegHom, coeff_X] at h
· apply eq_zero_of_neg_eq
specialize h n
split_ifs at h <;> simp_all [B, h_odd.neg_one_pow, factorial_ne_zero]
· simpa +decide [Nat.factorial] using h 1
have h : B * (exp ℚ - 1) = X * exp ℚ := by
simpa [bernoulli'PowerSeries] using bernoulli'PowerSeries_mul_exp_sub_one ℚ
rw [sub_mul, h, mul_sub X, sub_right_inj, ← neg_sub, mul_neg, neg_eq_iff_eq_neg]
suffices evalNegHom (B * (exp ℚ - 1)) * exp ℚ = evalNegHom (X * exp ℚ) * exp ℚ by
simpa [mul_assoc, sub_mul, mul_comm (evalNegHom (exp ℚ)), exp_mul_exp_neg_eq_one]
congr
/-- The Bernoulli numbers are defined to be `bernoulli'` with a parity sign. -/
def bernoulli (n : ℕ) : ℚ :=
(-1) ^ n * bernoulli' n
theorem bernoulli'_eq_bernoulli (n : ℕ) : bernoulli' n = (-1) ^ n * bernoulli n := by
simp [bernoulli, ← mul_assoc, ← sq, ← pow_mul, mul_comm n 2]
@[simp]
theorem bernoulli_zero : bernoulli 0 = 1 := by simp [bernoulli]
@[simp]
theorem bernoulli_one : bernoulli 1 = -1 / 2 := by norm_num [bernoulli]
theorem bernoulli_eq_bernoulli'_of_ne_one {n : ℕ} (hn : n ≠ 1) : bernoulli n = bernoulli' n := by
by_cases h0 : n = 0; · simp [h0]
rw [bernoulli, neg_one_pow_eq_pow_mod_two]
rcases mod_two_eq_zero_or_one n with h | h
· simp [h]
· simp [bernoulli'_odd_eq_zero (odd_iff.mpr h) (one_lt_iff_ne_zero_and_ne_one.mpr ⟨h0, hn⟩)]
@[simp]
theorem sum_bernoulli (n : ℕ) :
(∑ k ∈ range n, (n.choose k : ℚ) * bernoulli k) = if n = 1 then 1 else 0 := by
cases n with | zero => simp | succ n =>
cases n with
| zero => simp
| succ n =>
suffices (∑ i ∈ range n, ↑((n + 2).choose (i + 2)) * bernoulli (i + 2)) = n / 2 by
simp only [this, sum_range_succ', cast_succ, bernoulli_one, bernoulli_zero, choose_one_right,
mul_one, choose_zero_right, cast_zero, if_false, zero_add, succ_succ_ne_one]
ring
have f := sum_bernoulli' n.succ.succ
simp_rw [sum_range_succ', cast_succ, ← eq_sub_iff_add_eq] at f
refine Eq.trans ?_ (Eq.trans f ?_)
· congr
funext x
rw [bernoulli_eq_bernoulli'_of_ne_one (succ_ne_zero x ∘ succ.inj)]
· simp only [one_div, mul_one, bernoulli'_zero, choose_zero_right,
zero_add, choose_one_right, cast_succ, bernoulli'_one, one_div]
ring
theorem bernoulli_spec' (n : ℕ) :
(∑ k ∈ antidiagonal n, ((k.1 + k.2).choose k.2 : ℚ) / (k.2 + 1) * bernoulli k.1) =
if n = 0 then 1 else 0 := by
cases n with | zero => simp | succ n =>
rw [if_neg (succ_ne_zero _)]
-- algebra facts
have h₁ : (1, n) ∈ antidiagonal n.succ := by simp [mem_antidiagonal, add_comm]
have h₂ : (n : ℚ) + 1 ≠ 0 := by norm_cast
have h₃ : (1 + n).choose n = n + 1 := by simp [add_comm]
-- key equation: the corresponding fact for `bernoulli'`
have H := bernoulli'_spec' n.succ
-- massage it to match the structure of the goal, then convert piece by piece
rw [sum_eq_add_sum_diff_singleton h₁] at H ⊢
apply add_eq_of_eq_sub'
convert eq_sub_of_add_eq' H using 1
· refine sum_congr rfl fun p h => ?_
obtain ⟨h', h''⟩ : p ∈ _ ∧ p ≠ _ := by rwa [mem_sdiff, mem_singleton] at h
simp [bernoulli_eq_bernoulli'_of_ne_one ((not_congr (antidiagonal_congr h' h₁)).mp h'')]
· simp [field, h₃]
norm_num
/-- The exponential generating function for the Bernoulli numbers `bernoulli n`. -/
def bernoulliPowerSeries :=
mk fun n => algebraMap ℚ A (bernoulli n / n !)
theorem bernoulliPowerSeries_mul_exp_sub_one : bernoulliPowerSeries A * (exp A - 1) = X := by
ext n
-- constant coefficient is a special case
cases n with | zero => simp | succ n =>
simp only [bernoulliPowerSeries, coeff_mul, coeff_X, sum_antidiagonal_succ', one_div, coeff_mk,
coeff_one, coeff_exp, LinearMap.map_sub, factorial, if_pos, cast_succ, cast_mul,
sub_zero, add_eq_zero, if_false, one_ne_zero,
and_false, ← RingHom.map_mul, ← map_sum]
cases n with | zero => simp | succ n =>
rw [if_neg n.succ_succ_ne_one]
have hfact : ∀ m, (m ! : ℚ) ≠ 0 := fun m => mod_cast factorial_ne_zero m
have hite2 : ite (n.succ = 0) 1 0 = (0 : ℚ) := if_neg n.succ_ne_zero
simp only [CharP.cast_eq_zero, zero_add, inv_one, map_one, sub_self, mul_zero]
rw [← map_zero (algebraMap ℚ A), ← zero_div (n.succ ! : ℚ), ← hite2, ← bernoulli_spec', sum_div]
refine congr_arg (algebraMap ℚ A) (sum_congr rfl fun x h => eq_div_of_mul_eq (hfact n.succ) ?_)
rw [mem_antidiagonal] at h
rw [← h, add_choose, cast_div_charZero (factorial_mul_factorial_dvd_factorial_add _ _)]
simp [field, mul_comm _ (bernoulli x.1), mul_assoc]
section Faulhaber
/-- **Faulhaber's theorem** relating the **sum of p-th powers** to the Bernoulli numbers:
$$\sum_{k=0}^{n-1} k^p = \sum_{i=0}^p B_i\binom{p+1}{i}\frac{n^{p+1-i}}{p+1}.$$
See https://proofwiki.org/wiki/Faulhaber%27s_Formula and [orosi2018faulhaber] for
the proof provided here. -/
theorem sum_range_pow (n p : ℕ) :
(∑ k ∈ range n, (k : ℚ) ^ p) =
∑ i ∈ range (p + 1), bernoulli i * ((p + 1).choose i) * (n : ℚ) ^ (p + 1 - i) / (p + 1) := by
have hne : ∀ m : ℕ, (m ! : ℚ) ≠ 0 := fun m => mod_cast factorial_ne_zero m
-- compute the Cauchy product of two power series
have h_cauchy :
((mk fun p => bernoulli p / p !) * mk fun q => coeff (q + 1) (exp ℚ ^ n)) =
mk fun p => ∑ i ∈ range (p + 1),
bernoulli i * (p + 1).choose i * (n : ℚ) ^ (p + 1 - i) / (p + 1)! := by
ext q : 1
let f a b := bernoulli a / a ! * coeff (b + 1) (exp ℚ ^ n)
-- key step: use `PowerSeries.coeff_mul` and then rewrite sums
simp only [f, coeff_mul, coeff_mk, sum_antidiagonal_eq_sum_range_succ f]
apply sum_congr rfl
intro m h
simp only [exp_pow_eq_rescale_exp, rescale, RingHom.coe_mk]
-- manipulate factorials and binomial coefficients
have h : m < q + 1 := by simpa using h
rw [choose_eq_factorial_div_factorial h.le, eq_comm, div_eq_iff (hne q.succ), succ_eq_add_one,
mul_assoc _ _ (q.succ ! : ℚ), mul_comm _ (q.succ ! : ℚ), ← mul_assoc, div_mul_eq_mul_div]
simp only [MonoidHom.coe_mk, OneHom.coe_mk, coeff_exp, Algebra.algebraMap_self, one_div,
map_inv₀, map_natCast, coeff_mk]
rw [mul_comm ((n : ℚ) ^ (q - m + 1)), ← mul_assoc _ _ ((n : ℚ) ^ (q - m + 1)), ← one_div,
mul_one_div, div_div, tsub_add_eq_add_tsub (le_of_lt_succ h), cast_div, cast_mul]
· ring
· exact factorial_mul_factorial_dvd_factorial h.le
· simp [factorial_ne_zero]
-- same as our goal except we pull out `p!` for convenience
have hps :
(∑ k ∈ range n, (k : ℚ) ^ p) =
(∑ i ∈ range (p + 1),
bernoulli i * (p + 1).choose i * (n : ℚ) ^ (p + 1 - i) / (p + 1)!) * p ! := by
suffices
(mk fun p => ∑ k ∈ range n, (k : ℚ) ^ p * algebraMap ℚ ℚ p !⁻¹) =
mk fun p =>
∑ i ∈ range (p + 1), bernoulli i * (p + 1).choose i * (n : ℚ) ^ (p + 1 - i) / (p + 1)! by
rw [← div_eq_iff (hne p), div_eq_mul_inv, sum_mul]
rw [PowerSeries.ext_iff] at this
simpa using this p
-- the power series `exp ℚ - 1` is non-zero, a fact we need in order to use `mul_right_inj'`
have hexp : exp ℚ - 1 ≠ 0 := by
simp only [exp, PowerSeries.ext_iff, Ne, not_forall]
use 1
simp
have h_r : exp ℚ ^ n - 1 = X * mk fun p => coeff (p + 1) (exp ℚ ^ n) := by
have h_const : C (constantCoeff (exp ℚ ^ n)) = 1 := by simp
rw [← h_const, sub_const_eq_X_mul_shift]
-- key step: a chain of equalities of power series
rw [← mul_right_inj' hexp, mul_comm]
rw [← exp_pow_sum, geom_sum_mul, h_r, ← bernoulliPowerSeries_mul_exp_sub_one,
bernoulliPowerSeries, mul_right_comm]
simp only [mul_comm, mul_eq_mul_left_iff, hexp, or_false]
refine Eq.trans (mul_eq_mul_right_iff.mpr ?_) (Eq.trans h_cauchy ?_)
· left
congr
· simp only [mul_comm, factorial]
-- massage `hps` into our goal
rw [hps, sum_mul]
refine sum_congr rfl fun x _ => ?_
simp [field, factorial]
/-- Alternate form of **Faulhaber's theorem**, relating the sum of p-th powers to the Bernoulli
numbers: $$\sum_{k=1}^{n} k^p = \sum_{i=0}^p (-1)^iB_i\binom{p+1}{i}\frac{n^{p+1-i}}{p+1}.$$
Deduced from `sum_range_pow`. -/
theorem sum_Ico_pow (n p : ℕ) :
(∑ k ∈ Ico 1 (n + 1), (k : ℚ) ^ p) =
∑ i ∈ range (p + 1), bernoulli' i * (p + 1).choose i * (n : ℚ) ^ (p + 1 - i) / (p + 1) := by
rw [← Nat.cast_succ]
-- dispose of the trivial case
cases p with | zero => simp | succ p =>
let f i := bernoulli i * p.succ.succ.choose i * (n : ℚ) ^ (p.succ.succ - i) / p.succ.succ
let f' i := bernoulli' i * p.succ.succ.choose i * (n : ℚ) ^ (p.succ.succ - i) / p.succ.succ
suffices (∑ k ∈ Ico 1 n.succ, (k : ℚ) ^ p.succ) = ∑ i ∈ range p.succ.succ, f' i by convert this
-- prove some algebraic facts that will make things easier for us later on
have hle := Nat.le_add_left 1 n
have hne : (p + 1 + 1 : ℚ) ≠ 0 := by norm_cast
have h1 : ∀ r : ℚ, r * (p + 1 + 1) * (n : ℚ) ^ p.succ / (p + 1 + 1 : ℚ) = r * (n : ℚ) ^ p.succ :=
fun r => by rw [mul_div_right_comm, mul_div_cancel_right₀ _ hne]
have h2 : f 1 + (n : ℚ) ^ p.succ = 1 / 2 * (n : ℚ) ^ p.succ := by
simp_rw [f, bernoulli_one, choose_one_right, succ_sub_succ_eq_sub, cast_succ, tsub_zero, h1]
ring
have :
(∑ i ∈ range p, bernoulli (i + 2) * (p + 2).choose (i + 2) * (n : ℚ) ^ (p - i) / ↑(p + 2)) =
∑ i ∈ range p, bernoulli' (i + 2) * (p + 2).choose (i + 2) * (n : ℚ) ^ (p - i) / ↑(p + 2) :=
sum_congr rfl fun i _ => by rw [bernoulli_eq_bernoulli'_of_ne_one (succ_succ_ne_one i)]
calc
(-- replace sum over `Ico` with sum over `range` and simplify
∑ k ∈ Ico 1 n.succ, (k : ℚ) ^ p.succ)
_ = ∑ k ∈ range n.succ, (k : ℚ) ^ p.succ := by simp [sum_Ico_eq_sub _ hle]
-- extract the last term of the sum
_ = (∑ k ∈ range n, (k : ℚ) ^ p.succ) + (n : ℚ) ^ p.succ := by rw [sum_range_succ]
-- apply the key lemma, `sum_range_pow`
_ = (∑ i ∈ range p.succ.succ, f i) + (n : ℚ) ^ p.succ := by simp [f, sum_range_pow]
-- extract the first two terms of the sum
_ = (∑ i ∈ range p, f i.succ.succ) + f 1 + f 0 + (n : ℚ) ^ p.succ := by
simp_rw [sum_range_succ']
_ = (∑ i ∈ range p, f i.succ.succ) + (f 1 + (n : ℚ) ^ p.succ) + f 0 := by ring
_ = (∑ i ∈ range p, f i.succ.succ) + 1 / 2 * (n : ℚ) ^ p.succ + f 0 := by rw [h2]
-- convert from `bernoulli` to `bernoulli'`
_ = (∑ i ∈ range p, f' i.succ.succ) + f' 1 + f' 0 := by
simpa [f, f', h1, fun i => show i + 2 = i + 1 + 1 from rfl]
-- rejoin the first two terms of the sum
_ = ∑ i ∈ range p.succ.succ, f' i := by simp_rw [sum_range_succ']
end Faulhaber |
.lake/packages/mathlib/Mathlib/NumberTheory/Rayleigh.lean | import Mathlib.Data.Real.ConjExponents
import Mathlib.NumberTheory.Real.Irrational
/-!
# Rayleigh's theorem on Beatty sequences
This file proves Rayleigh's theorem on Beatty sequences. We start by proving `compl_beattySeq`,
which is a generalization of Rayleigh's theorem, and eventually prove
`Irrational.beattySeq_symmDiff_beattySeq_pos`, which is Rayleigh's theorem.
## Main definitions
* `beattySeq`: In the Beatty sequence for real number `r`, the `k`th term is `⌊k * r⌋`.
* `beattySeq'`: In this variant of the Beatty sequence for `r`, the `k`th term is `⌈k * r⌉ - 1`.
## Main statements
Define the following Beatty sets, where `r` denotes a real number:
* `B_r := {⌊k * r⌋ | k ∈ ℤ}`
* `B'_r := {⌈k * r⌉ - 1 | k ∈ ℤ}`
* `B⁺_r := {⌊r⌋, ⌊2r⌋, ⌊3r⌋, ...}`
* `B⁺'_r := {⌈r⌉-1, ⌈2r⌉-1, ⌈3r⌉-1, ...}`
The main statements are:
* `compl_beattySeq`: Let `r` be a real number greater than 1, and `1/r + 1/s = 1`.
Then the complement of `B_r` is `B'_s`.
* `beattySeq_symmDiff_beattySeq'_pos`: Let `r` be a real number greater than 1, and `1/r + 1/s = 1`.
Then `B⁺_r` and `B⁺'_s` partition the positive integers.
* `Irrational.beattySeq_symmDiff_beattySeq_pos`: Let `r` be an irrational number greater than 1, and
`1/r + 1/s = 1`. Then `B⁺_r` and `B⁺_s` partition the positive integers.
## References
* [Wikipedia, *Beatty sequence*](https://en.wikipedia.org/wiki/Beatty_sequence)
## Tags
beatty, sequence, rayleigh, irrational, floor, positive
-/
/-- In the Beatty sequence for real number `r`, the `k`th term is `⌊k * r⌋`. -/
noncomputable def beattySeq (r : ℝ) : ℤ → ℤ :=
fun k ↦ ⌊k * r⌋
/-- In this variant of the Beatty sequence for `r`, the `k`th term is `⌈k * r⌉ - 1`. -/
noncomputable def beattySeq' (r : ℝ) : ℤ → ℤ :=
fun k ↦ ⌈k * r⌉ - 1
namespace Beatty
variable {r s : ℝ} {j : ℤ}
/-- Let `r > 1` and `1/r + 1/s = 1`. Then `B_r` and `B'_s` are disjoint (i.e. no collision exists).
-/
private theorem no_collision (hrs : r.HolderConjugate s) :
Disjoint {beattySeq r k | k} {beattySeq' s k | k} := by
rw [Set.disjoint_left]
intro j ⟨k, h₁⟩ ⟨m, h₂⟩
rw [beattySeq, Int.floor_eq_iff, ← div_le_iff₀ hrs.pos, ← lt_div_iff₀ hrs.pos] at h₁
rw [beattySeq', sub_eq_iff_eq_add, Int.ceil_eq_iff, Int.cast_add, Int.cast_one,
add_sub_cancel_right, ← div_lt_iff₀ hrs.symm.pos, ← le_div_iff₀ hrs.symm.pos] at h₂
have h₃ := add_lt_add_of_le_of_lt h₁.1 h₂.1
have h₄ := add_lt_add_of_lt_of_le h₁.2 h₂.2
simp_rw [div_eq_inv_mul, ← right_distrib, hrs.inv_add_inv_eq_one, one_mul] at h₃ h₄
rw [← Int.cast_one] at h₄
simp_rw [← Int.cast_add, Int.cast_lt, Int.lt_add_one_iff] at h₃ h₄
exact h₄.not_gt h₃
/-- Let `r > 1` and `1/r + 1/s = 1`. Suppose there is an integer `j` where `B_r` and `B'_s` both
jump over `j` (i.e. an anti-collision). Then this leads to a contradiction. -/
private theorem no_anticollision (hrs : r.HolderConjugate s) :
¬∃ j k m : ℤ, k < j / r ∧ (j + 1) / r ≤ k + 1 ∧ m ≤ j / s ∧ (j + 1) / s < m + 1 := by
intro ⟨j, k, m, h₁₁, h₁₂, h₂₁, h₂₂⟩
have h₃ := add_lt_add_of_lt_of_le h₁₁ h₂₁
have h₄ := add_lt_add_of_le_of_lt h₁₂ h₂₂
simp_rw [div_eq_inv_mul, ← right_distrib, hrs.inv_add_inv_eq_one, one_mul] at h₃ h₄
rw [← Int.cast_one, ← add_assoc, add_lt_add_iff_right, add_right_comm] at h₄
simp_rw [← Int.cast_add, Int.cast_lt, Int.lt_add_one_iff] at h₃ h₄
exact h₄.not_gt h₃
/-- Let `0 < r ∈ ℝ` and `j ∈ ℤ`. Then either `j ∈ B_r` or `B_r` jumps over `j`. -/
private theorem hit_or_miss (h : r > 0) :
j ∈ {beattySeq r k | k} ∨ ∃ k : ℤ, k < j / r ∧ (j + 1) / r ≤ k + 1 := by
-- for both cases, the candidate is `k = ⌈(j + 1) / r⌉ - 1`
cases lt_or_ge ((⌈(j + 1) / r⌉ - 1) * r) j
· refine Or.inr ⟨⌈(j + 1) / r⌉ - 1, ?_⟩
rw [Int.cast_sub, Int.cast_one, lt_div_iff₀ h, sub_add_cancel]
exact ⟨‹_›, Int.le_ceil _⟩
· refine Or.inl ⟨⌈(j + 1) / r⌉ - 1, ?_⟩
rw [beattySeq, Int.floor_eq_iff, Int.cast_sub, Int.cast_one, ← lt_div_iff₀ h, sub_lt_iff_lt_add]
exact ⟨‹_›, Int.ceil_lt_add_one _⟩
/-- Let `0 < r ∈ ℝ` and `j ∈ ℤ`. Then either `j ∈ B'_r` or `B'_r` jumps over `j`. -/
private theorem hit_or_miss' (h : r > 0) :
j ∈ {beattySeq' r k | k} ∨ ∃ k : ℤ, k ≤ j / r ∧ (j + 1) / r < k + 1 := by
-- for both cases, the candidate is `k = ⌊(j + 1) / r⌋`
cases le_or_gt (⌊(j + 1) / r⌋ * r) j
· exact Or.inr ⟨⌊(j + 1) / r⌋, (le_div_iff₀ h).2 ‹_›, Int.lt_floor_add_one _⟩
· refine Or.inl ⟨⌊(j + 1) / r⌋, ?_⟩
rw [beattySeq', sub_eq_iff_eq_add, Int.ceil_eq_iff, Int.cast_add, Int.cast_one]
constructor
· rwa [add_sub_cancel_right]
exact sub_nonneg.1 (Int.sub_floor_div_mul_nonneg (j + 1 : ℝ) h)
end Beatty
/-- Generalization of Rayleigh's theorem on Beatty sequences. Let `r` be a real number greater
than 1, and `1/r + 1/s = 1`. Then the complement of `B_r` is `B'_s`. -/
theorem compl_beattySeq {r s : ℝ} (hrs : r.HolderConjugate s) :
{beattySeq r k | k}ᶜ = {beattySeq' s k | k} := by
ext j
by_cases h₁ : j ∈ {beattySeq r k | k} <;> by_cases h₂ : j ∈ {beattySeq' s k | k}
· exact (Set.not_disjoint_iff.2 ⟨j, h₁, h₂⟩ (Beatty.no_collision hrs)).elim
· simp only [Set.mem_compl_iff, h₁, h₂, not_true_eq_false]
· simp only [Set.mem_compl_iff, h₁, h₂, not_false_eq_true]
· have ⟨k, h₁₁, h₁₂⟩ := (Beatty.hit_or_miss hrs.pos).resolve_left h₁
have ⟨m, h₂₁, h₂₂⟩ := (Beatty.hit_or_miss' hrs.symm.pos).resolve_left h₂
exact (Beatty.no_anticollision hrs ⟨j, k, m, h₁₁, h₁₂, h₂₁, h₂₂⟩).elim
theorem compl_beattySeq' {r s : ℝ} (hrs : r.HolderConjugate s) :
{beattySeq' r k | k}ᶜ = {beattySeq s k | k} := by
rw [← compl_beattySeq hrs.symm, compl_compl]
open scoped symmDiff
/-- Generalization of Rayleigh's theorem on Beatty sequences. Let `r` be a real number greater
than 1, and `1/r + 1/s = 1`. Then `B⁺_r` and `B⁺'_s` partition the positive integers. -/
theorem beattySeq_symmDiff_beattySeq'_pos {r s : ℝ} (hrs : r.HolderConjugate s) :
{beattySeq r k | k > 0} ∆ {beattySeq' s k | k > 0} = {n | 0 < n} := by
apply Set.eq_of_subset_of_subset
· rintro j (⟨⟨k, hk, hjk⟩, -⟩ | ⟨⟨k, hk, hjk⟩, -⟩)
· rw [Set.mem_setOf_eq, ← hjk, beattySeq, Int.floor_pos]
exact one_le_mul_of_one_le_of_one_le (by norm_cast) hrs.lt.le
· rw [Set.mem_setOf_eq, ← hjk, beattySeq', sub_pos, Int.lt_ceil, Int.cast_one]
exact one_lt_mul_of_le_of_lt (by norm_cast) hrs.symm.lt
intro j (hj : 0 < j)
have hb₁ : ∀ s ≥ 0, j ∈ {beattySeq s k | k > 0} ↔ j ∈ {beattySeq s k | k} := by
intro _ hs
refine ⟨fun ⟨k, _, hk⟩ ↦ ⟨k, hk⟩, fun ⟨k, hk⟩ ↦ ⟨k, ?_, hk⟩⟩
rw [← hk, beattySeq, Int.floor_pos] at hj
exact_mod_cast pos_of_mul_pos_left (zero_lt_one.trans_le hj) hs
have hb₂ : ∀ s ≥ 0, j ∈ {beattySeq' s k | k > 0} ↔ j ∈ {beattySeq' s k | k} := by
intro _ hs
refine ⟨fun ⟨k, _, hk⟩ ↦ ⟨k, hk⟩, fun ⟨k, hk⟩ ↦ ⟨k, ?_, hk⟩⟩
rw [← hk, beattySeq', sub_pos, Int.lt_ceil, Int.cast_one] at hj
exact_mod_cast pos_of_mul_pos_left (zero_lt_one.trans hj) hs
rw [Set.mem_symmDiff, hb₁ _ hrs.nonneg, hb₂ _ hrs.symm.nonneg, ← compl_beattySeq hrs,
Set.notMem_compl_iff, Set.mem_compl_iff, and_self, and_self]
exact or_not
theorem beattySeq'_symmDiff_beattySeq_pos {r s : ℝ} (hrs : r.HolderConjugate s) :
{beattySeq' r k | k > 0} ∆ {beattySeq s k | k > 0} = {n | 0 < n} := by
rw [symmDiff_comm, beattySeq_symmDiff_beattySeq'_pos hrs.symm]
/-- Let `r` be an irrational number. Then `B⁺_r` and `B⁺'_r` are equal. -/
theorem Irrational.beattySeq'_pos_eq {r : ℝ} (hr : Irrational r) :
{beattySeq' r k | k > 0} = {beattySeq r k | k > 0} := by
dsimp only [beattySeq, beattySeq']
congr! 4; rename_i k; rw [and_congr_right_iff]; intro hk; congr!
rw [sub_eq_iff_eq_add, Int.ceil_eq_iff, Int.cast_add, Int.cast_one, add_sub_cancel_right]
refine ⟨(Int.floor_le _).lt_of_ne fun h ↦ ?_, (Int.lt_floor_add_one _).le⟩
exact (hr.intCast_mul hk.ne').ne_int ⌊k * r⌋ h.symm
/-- **Rayleigh's theorem** on Beatty sequences. Let `r` be an irrational number greater than 1, and
`1/r + 1/s = 1`. Then `B⁺_r` and `B⁺_s` partition the positive integers. -/
theorem Irrational.beattySeq_symmDiff_beattySeq_pos {r s : ℝ}
(hrs : r.HolderConjugate s) (hr : Irrational r) :
{beattySeq r k | k > 0} ∆ {beattySeq s k | k > 0} = {n | 0 < n} := by
rw [← hr.beattySeq'_pos_eq, beattySeq'_symmDiff_beattySeq_pos hrs] |
.lake/packages/mathlib/Mathlib/NumberTheory/SumFourSquares.lean | import Mathlib.FieldTheory.Finite.Basic
/-!
# Lagrange's four square theorem
The main result in this file is `sum_four_squares`,
a proof that every natural number is the sum of four square numbers.
## Implementation Notes
The proof used is close to Lagrange's original proof.
-/
open Finset Polynomial FiniteField Equiv
/-- **Euler's four-square identity**. -/
theorem euler_four_squares {R : Type*} [CommRing R] (a b c d x y z w : R) :
(a * x - b * y - c * z - d * w) ^ 2 + (a * y + b * x + c * w - d * z) ^ 2 +
(a * z - b * w + c * x + d * y) ^ 2 + (a * w + b * z - c * y + d * x) ^ 2 =
(a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2 + w ^ 2) := by ring
/-- **Euler's four-square identity**, a version for natural numbers. -/
theorem Nat.euler_four_squares (a b c d x y z w : ℕ) :
((a : ℤ) * x - b * y - c * z - d * w).natAbs ^ 2 +
((a : ℤ) * y + b * x + c * w - d * z).natAbs ^ 2 +
((a : ℤ) * z - b * w + c * x + d * y).natAbs ^ 2 +
((a : ℤ) * w + b * z - c * y + d * x).natAbs ^ 2 =
(a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2 + w ^ 2) := by
rw [← Int.natCast_inj]
push_cast
simp only [sq_abs, _root_.euler_four_squares]
namespace Int
theorem sq_add_sq_of_two_mul_sq_add_sq {m x y : ℤ} (h : 2 * m = x ^ 2 + y ^ 2) :
m = ((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2 :=
have : Even (x ^ 2 + y ^ 2) := by simp [← h]
mul_right_injective₀ (show (2 * 2 : ℤ) ≠ 0 by decide) <|
calc
2 * 2 * m = (x - y) ^ 2 + (x + y) ^ 2 := by rw [mul_assoc, h]; ring
_ = (2 * ((x - y) / 2)) ^ 2 + (2 * ((x + y) / 2)) ^ 2 := by
rw [Int.mul_ediv_cancel' _, Int.mul_ediv_cancel' _] <;>
simpa [sq, parity_simps, ← even_iff_two_dvd]
_ = 2 * 2 * (((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2) := by nlinarith
theorem lt_of_sum_four_squares_eq_mul {a b c d k m : ℕ}
(h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = k * m)
(ha : 2 * a < m) (hb : 2 * b < m) (hc : 2 * c < m) (hd : 2 * d < m) :
k < m := by nlinarith
theorem exists_sq_add_sq_add_one_eq_mul (p : ℕ) [hp : Fact p.Prime] :
∃ (a b k : ℕ), 0 < k ∧ k < p ∧ a ^ 2 + b ^ 2 + 1 = k * p := by
rcases hp.1.eq_two_or_odd' with (rfl | hodd)
· use 1, 0, 1; simp
rcases Nat.sq_add_sq_zmodEq p (-1) with ⟨a, b, ha, hb, hab⟩
rcases Int.modEq_iff_dvd.1 hab.symm with ⟨k, hk⟩
rw [sub_neg_eq_add, mul_comm] at hk
have hk₀ : 0 < k := by
refine pos_of_mul_pos_left ?_ (Nat.cast_nonneg p)
rw [← hk]
positivity
lift k to ℕ using hk₀.le
refine ⟨a, b, k, Nat.cast_pos.1 hk₀, ?_, mod_cast hk⟩
replace hk : a ^ 2 + b ^ 2 + 1 ^ 2 + 0 ^ 2 = k * p := mod_cast hk
refine lt_of_sum_four_squares_eq_mul hk ?_ ?_ ?_ ?_
· exact (mul_le_mul' le_rfl ha).trans_lt (Nat.mul_div_lt_iff_not_dvd.2 hodd.not_two_dvd_nat)
· exact (mul_le_mul' le_rfl hb).trans_lt (Nat.mul_div_lt_iff_not_dvd.2 hodd.not_two_dvd_nat)
· exact lt_of_le_of_ne hp.1.two_le (hodd.ne_two_of_dvd_nat (dvd_refl _)).symm
· exact hp.1.pos
end Int
namespace Nat
open Int
private theorem sum_four_squares_of_two_mul_sum_four_squares {m a b c d : ℤ}
(h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m) :
∃ w x y z : ℤ, w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = m := by
have : ∀ f : Fin 4 → ZMod 2, f 0 ^ 2 + f 1 ^ 2 + f 2 ^ 2 + f 3 ^ 2 = 0 → ∃ i : Fin 4,
f i ^ 2 + f (swap i 0 1) ^ 2 = 0 ∧ f (swap i 0 2) ^ 2 + f (swap i 0 3) ^ 2 = 0 := by
decide
set f : Fin 4 → ℤ := ![a, b, c, d]
obtain ⟨i, hσ⟩ := this (fun x => ↑(f x)) <| by
rw [← @zero_mul (ZMod 2) _ m, ← show ((2 : ℤ) : ZMod 2) = 0 from rfl, ← Int.cast_mul, ← h]
simp only [Int.cast_add, Int.cast_pow]
rfl
set σ := swap i 0
obtain ⟨x, hx⟩ : (2 : ℤ) ∣ f (σ 0) ^ 2 + f (σ 1) ^ 2 :=
(CharP.intCast_eq_zero_iff (ZMod 2) 2 _).1 <| by
simpa only [σ, Int.cast_pow, Int.cast_add, Equiv.swap_apply_right, ZMod.pow_card] using hσ.1
obtain ⟨y, hy⟩ : (2 : ℤ) ∣ f (σ 2) ^ 2 + f (σ 3) ^ 2 :=
(CharP.intCast_eq_zero_iff (ZMod 2) 2 _).1 <| by
simpa only [Int.cast_pow, Int.cast_add, ZMod.pow_card] using hσ.2
refine ⟨(f (σ 0) - f (σ 1)) / 2, (f (σ 0) + f (σ 1)) / 2, (f (σ 2) - f (σ 3)) / 2,
(f (σ 2) + f (σ 3)) / 2, ?_⟩
rw [← Int.sq_add_sq_of_two_mul_sq_add_sq hx.symm, add_assoc,
← Int.sq_add_sq_of_two_mul_sq_add_sq hy.symm, ← mul_right_inj' two_ne_zero, ← h, mul_add]
have : (∑ x, f (σ x) ^ 2) = ∑ x, f x ^ 2 := Equiv.sum_comp σ (f · ^ 2)
simpa only [← hx, ← hy, Fin.sum_univ_four, add_assoc] using this
/-- Lagrange's **four squares theorem** for a prime number. Use `Nat.sum_four_squares` instead. -/
protected theorem Prime.sum_four_squares {p : ℕ} (hp : p.Prime) :
∃ a b c d : ℕ, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = p := by
classical
have := Fact.mk hp
-- Find `a`, `b`, `c`, `d`, `0 < m < p` such that `a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p`
have natAbs_iff {a b c d : ℤ} {k : ℕ} :
a.natAbs ^ 2 + b.natAbs ^ 2 + c.natAbs ^ 2 + d.natAbs ^ 2 = k ↔
a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = k := by
rw [← @Nat.cast_inj ℤ]; push_cast [sq_abs]; rfl
have hm : ∃ m < p, 0 < m ∧ ∃ a b c d : ℕ, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p := by
obtain ⟨a, b, k, hk₀, hkp, hk⟩ := exists_sq_add_sq_add_one_eq_mul p
refine ⟨k, hkp, hk₀, a, b, 1, 0, ?_⟩
simpa
-- Take the minimal possible `m`
rcases Nat.findX hm with ⟨m, ⟨hmp, hm₀, a, b, c, d, habcd⟩, hmin⟩
-- If `m = 1`, then we are done
rcases (Nat.one_le_iff_ne_zero.2 hm₀.ne').eq_or_lt with rfl | hm₁
· use a, b, c, d; simpa using habcd
-- Otherwise, let us find a contradiction
exfalso
have : NeZero m := ⟨hm₀.ne'⟩
by_cases hm : 2 ∣ m
· -- If `m` is an even number, then `(m / 2) * p` can be represented as a sum of four squares
rcases hm with ⟨m, rfl⟩
rw [mul_pos_iff_of_pos_left two_pos] at hm₀
have hm₂ : m < 2 * m := by simpa [two_mul]
apply_fun (Nat.cast : ℕ → ℤ) at habcd
push_cast [mul_assoc] at habcd
obtain ⟨_, _, _, _, h⟩ := sum_four_squares_of_two_mul_sum_four_squares habcd
exact hmin m hm₂ ⟨hm₂.trans hmp, hm₀, _, _, _, _, natAbs_iff.2 h⟩
· -- For each `x` in `a`, `b`, `c`, `d`, take a number `f x ≡ x [ZMOD m]` with least possible
-- absolute value
obtain ⟨f, hf_lt, hf_mod⟩ :
∃ f : ℕ → ℤ, (∀ x, 2 * (f x).natAbs < m) ∧ ∀ x, (f x : ZMod m) = x := by
refine ⟨fun x ↦ (x : ZMod m).valMinAbs, fun x ↦ ?_, fun x ↦ (x : ZMod m).coe_valMinAbs⟩
exact (mul_le_mul' le_rfl (x : ZMod m).natAbs_valMinAbs_le).trans_lt
(Nat.mul_div_lt_iff_not_dvd.2 hm)
-- Since `|f x| ^ 2 = (f x) ^ 2 ≡ x ^ 2 [ZMOD m]`, we have
-- `m ∣ |f a| ^ 2 + |f b| ^ 2 + |f c| ^ 2 + |f d| ^ 2`
obtain ⟨r, hr⟩ :
m ∣ (f a).natAbs ^ 2 + (f b).natAbs ^ 2 + (f c).natAbs ^ 2 + (f d).natAbs ^ 2 := by
simp only [← Int.natCast_dvd_natCast, ← ZMod.intCast_zmod_eq_zero_iff_dvd]
push_cast [hf_mod, sq_abs]
norm_cast
simp [habcd]
-- The quotient `r` is not zero, because otherwise `f a = f b = f c = f d = 0`, hence
-- `m` divides each `a`, `b`, `c`, `d`, thus `m ∣ p` which is impossible.
rcases (zero_le r).eq_or_lt with rfl | hr₀
· replace hr : f a = 0 ∧ f b = 0 ∧ f c = 0 ∧ f d = 0 := by simpa [and_assoc] using hr
obtain ⟨⟨a, rfl⟩, ⟨b, rfl⟩, ⟨c, rfl⟩, ⟨d, rfl⟩⟩ : m ∣ a ∧ m ∣ b ∧ m ∣ c ∧ m ∣ d := by
simp only [← ZMod.natCast_eq_zero_iff, ← hf_mod, hr, Int.cast_zero, and_self]
have : m * m ∣ m * p := habcd ▸ ⟨a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2, by ring⟩
rw [mul_dvd_mul_iff_left hm₀.ne'] at this
exact (hp.eq_one_or_self_of_dvd _ this).elim hm₁.ne' hmp.ne
-- Since `2 * |f x| < m` for each `x ∈ {a, b, c, d}`, we have `r < m`
have hrm : r < m := by
rw [mul_comm] at hr
apply lt_of_sum_four_squares_eq_mul hr <;> apply hf_lt
-- Now it suffices to represent `r * p` as a sum of four squares
-- More precisely, we will represent `(m * r) * (m * p)` as a sum of squares of four numbers,
-- each of them is divisible by `m`
rsuffices ⟨w, x, y, z, hw, hx, hy, hz, h⟩ : ∃ w x y z : ℤ, ↑m ∣ w ∧ ↑m ∣ x ∧ ↑m ∣ y ∧ ↑m ∣ z ∧
w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = ↑(m * r) * ↑(m * p)
· have : (w / m) ^ 2 + (x / m) ^ 2 + (y / m) ^ 2 + (z / m) ^ 2 = ↑(r * p) := by
refine mul_left_cancel₀ (pow_ne_zero 2 (Nat.cast_ne_zero.2 hm₀.ne')) ?_
conv_rhs => rw [← Nat.cast_pow, ← Nat.cast_mul, sq m, mul_mul_mul_comm, Nat.cast_mul, ← h]
simp only [mul_add, ← mul_pow, Int.mul_ediv_cancel', *]
rw [← natAbs_iff] at this
exact hmin r hrm ⟨hrm.trans hmp, hr₀, _, _, _, _, this⟩
-- To do the last step, we apply the Euler's four square identity once more
replace hr : (f b) ^ 2 + (f a) ^ 2 + (f d) ^ 2 + (-f c) ^ 2 = ↑(m * r) := by
rw [← natAbs_iff, natAbs_neg, ← hr]
ac_rfl
have := congr_arg₂ (· * Nat.cast ·) hr habcd
simp only [← _root_.euler_four_squares, Nat.cast_add, Nat.cast_pow] at this
refine ⟨_, _, _, _, ?_, ?_, ?_, ?_, this⟩
· simp [← ZMod.intCast_zmod_eq_zero_iff_dvd, hf_mod, mul_comm]
· suffices ((a : ZMod m) ^ 2 + (b : ZMod m) ^ 2 + (c : ZMod m) ^ 2 + (d : ZMod m) ^ 2) = 0 by
simpa [← ZMod.intCast_zmod_eq_zero_iff_dvd, hf_mod, sq, add_comm, add_assoc,
add_left_comm] using this
norm_cast
simp [habcd]
· simp [← ZMod.intCast_zmod_eq_zero_iff_dvd, hf_mod, mul_comm]
· simp [← ZMod.intCast_zmod_eq_zero_iff_dvd, hf_mod, mul_comm]
/-- **Four squares theorem** -/
theorem sum_four_squares (n : ℕ) : ∃ a b c d : ℕ, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = n := by
-- The proof is by induction on prime factorization. The case of prime `n` was proved above,
-- the inductive step follows from `Nat.euler_four_squares`.
induction n using Nat.recOnMul with
| zero => exact ⟨0, 0, 0, 0, rfl⟩
| one => exact ⟨1, 0, 0, 0, rfl⟩
| prime p hp => exact hp.sum_four_squares
| mul m n hm hn =>
rcases hm with ⟨a, b, c, d, rfl⟩
rcases hn with ⟨w, x, y, z, rfl⟩
exact ⟨_, _, _, _, euler_four_squares _ _ _ _ _ _ _ _⟩
end Nat |
.lake/packages/mathlib/Mathlib/NumberTheory/Modular.lean | import Mathlib.Analysis.Complex.UpperHalfPlane.MoebiusAction
import Mathlib.LinearAlgebra.GeneralLinearGroup
import Mathlib.LinearAlgebra.Matrix.GeneralLinearGroup.Basic
import Mathlib.Topology.Instances.Matrix
import Mathlib.Topology.Algebra.Module.FiniteDimension
import Mathlib.Topology.Instances.ZMultiples
/-!
# The action of the modular group SL(2, ℤ) on the upper half-plane
We define the action of `SL(2,ℤ)` on `ℍ` (via restriction of the `SL(2,ℝ)` action in
`Analysis.Complex.UpperHalfPlane`). We then define the standard fundamental domain
(`ModularGroup.fd`, `𝒟`) for this action and show
(`ModularGroup.exists_smul_mem_fd`) that any point in `ℍ` can be
moved inside `𝒟`.
## Main definitions
The standard (closed) fundamental domain of the action of `SL(2,ℤ)` on `ℍ`, denoted `𝒟`:
`fd := {z | 1 ≤ (z : ℂ).normSq ∧ |z.re| ≤ (1 : ℝ) / 2}`
The standard open fundamental domain of the action of `SL(2,ℤ)` on `ℍ`, denoted `𝒟ᵒ`:
`fdo := {z | 1 < (z : ℂ).normSq ∧ |z.re| < (1 : ℝ) / 2}`
These notations are localized in the `Modular` scope and can be enabled via `open scoped Modular`.
## Main results
Any `z : ℍ` can be moved to `𝒟` by an element of `SL(2,ℤ)`:
`exists_smul_mem_fd (z : ℍ) : ∃ g : SL(2,ℤ), g • z ∈ 𝒟`
If both `z` and `γ • z` are in the open domain `𝒟ᵒ` then `z = γ • z`:
`eq_smul_self_of_mem_fdo_mem_fdo {z : ℍ} {g : SL(2,ℤ)} (hz : z ∈ 𝒟ᵒ) (hg : g • z ∈ 𝒟ᵒ) : z = g • z`
## Discussion
Standard proofs make use of the identity
`g • z = a / c - 1 / (c (cz + d))`
for `g = [[a, b], [c, d]]` in `SL(2)`, but this requires separate handling of whether `c = 0`.
Instead, our proof makes use of the following perhaps novel identity (see
`ModularGroup.smul_eq_lcRow0_add`):
`g • z = (a c + b d) / (c^2 + d^2) + (d z - c) / ((c^2 + d^2) (c z + d))`
where there is no issue of division by zero.
Another feature is that we delay until the very end the consideration of special matrices
`T=[[1,1],[0,1]]` (see `ModularGroup.T`) and `S=[[0,-1],[1,0]]` (see `ModularGroup.S`), by
instead using abstract theory on the properness of certain maps (phrased in terms of the filters
`Filter.cocompact`, `Filter.cofinite`, etc) to deduce existence theorems, first to prove the
existence of `g` maximizing `(g•z).im` (see `ModularGroup.exists_max_im`), and then among
those, to minimize `|(g•z).re|` (see `ModularGroup.exists_row_one_eq_and_min_re`).
-/
open Complex
open Matrix hiding mul_smul
open Matrix.SpecialLinearGroup UpperHalfPlane ModularGroup Topology
noncomputable section
open scoped ComplexConjugate MatrixGroups
namespace ModularGroup
variable {g : SL(2, ℤ)} (z : ℍ)
section BottomRow
/-- The two numbers `c`, `d` in the "bottom_row" of `g=[[*,*],[c,d]]` in `SL(2, ℤ)` are coprime. -/
theorem bottom_row_coprime {R : Type*} [CommRing R] (g : SL(2, R)) :
IsCoprime ((↑g : Matrix (Fin 2) (Fin 2) R) 1 0) ((↑g : Matrix (Fin 2) (Fin 2) R) 1 1) :=
isCoprime_row g 1
/-- Every pair `![c, d]` of coprime integers is the "bottom_row" of some element `g=[[*,*],[c,d]]`
of `SL(2,ℤ)`. -/
theorem bottom_row_surj {R : Type*} [CommRing R] :
Set.SurjOn (fun g : SL(2, R) => (↑g : Matrix (Fin 2) (Fin 2) R) 1) Set.univ
{cd | IsCoprime (cd 0) (cd 1)} := by
rintro cd ⟨b₀, a, gcd_eqn⟩
let A := of ![![a, -b₀], cd]
have det_A_1 : det A = 1 := by
convert gcd_eqn
rw [det_fin_two]
simp [A, (by ring : a * cd 1 + b₀ * cd 0 = b₀ * cd 0 + a * cd 1)]
refine ⟨⟨A, det_A_1⟩, Set.mem_univ _, ?_⟩
ext; simp [A]
end BottomRow
section TendstoLemmas
open Filter ContinuousLinearMap
attribute [local simp] ContinuousLinearMap.coe_smul
/-- The function `(c,d) → |cz+d|^2` is proper, that is, preimages of bounded-above sets are finite.
-/
theorem tendsto_normSq_coprime_pair :
Filter.Tendsto (fun p : Fin 2 → ℤ => normSq ((p 0 : ℂ) * z + p 1)) cofinite atTop := by
-- using this instance rather than the automatic `Function.module` makes unification issues in
-- `LinearEquiv.isClosedEmbedding_of_injective` less bad later in the proof.
letI : Module ℝ (Fin 2 → ℝ) := NormedSpace.toModule
let π₀ : (Fin 2 → ℝ) →ₗ[ℝ] ℝ := LinearMap.proj 0
let π₁ : (Fin 2 → ℝ) →ₗ[ℝ] ℝ := LinearMap.proj 1
let f : (Fin 2 → ℝ) →ₗ[ℝ] ℂ := π₀.smulRight (z : ℂ) + π₁.smulRight 1
have f_def : ⇑f = fun p : Fin 2 → ℝ => (p 0 : ℂ) * ↑z + p 1 := by
ext1
dsimp only [π₀, π₁, f, LinearMap.coe_proj, real_smul, LinearMap.coe_smulRight,
LinearMap.add_apply]
rw [mul_one]
have :
(fun p : Fin 2 → ℤ => normSq ((p 0 : ℂ) * ↑z + ↑(p 1))) =
normSq ∘ f ∘ fun p : Fin 2 → ℤ => ((↑) : ℤ → ℝ) ∘ p := by
ext1
rw [f_def]
dsimp only [Function.comp_def]
rw [ofReal_intCast, ofReal_intCast]
rw [this]
have hf : LinearMap.ker f = ⊥ := by
let g : ℂ →ₗ[ℝ] Fin 2 → ℝ :=
LinearMap.pi ![imLm, imLm.comp ((z : ℂ) • ((conjAe : ℂ →ₐ[ℝ] ℂ) : ℂ →ₗ[ℝ] ℂ))]
suffices ((z : ℂ).im⁻¹ • g).comp f = LinearMap.id by exact LinearMap.ker_eq_bot_of_inverse this
apply LinearMap.ext
intro c
have hz : (z : ℂ).im ≠ 0 := z.2.ne'
rw [LinearMap.comp_apply, LinearMap.smul_apply, LinearMap.id_apply]
ext i
dsimp only [Pi.smul_apply, LinearMap.pi_apply, smul_eq_mul]
fin_cases i
· change (z : ℂ).im⁻¹ * (f c).im = c 0
rw [f_def, add_im, im_ofReal_mul, ofReal_im, add_zero, mul_left_comm, inv_mul_cancel₀ hz,
mul_one]
· change (z : ℂ).im⁻¹ * ((z : ℂ) * conj (f c)).im = c 1
rw [f_def, RingHom.map_add, RingHom.map_mul, mul_add, mul_left_comm, mul_conj, conj_ofReal,
conj_ofReal, ← ofReal_mul, add_im, ofReal_im, zero_add, inv_mul_eq_iff_eq_mul₀ hz]
simp only [ofReal_im, ofReal_re, mul_im, zero_add, mul_zero]
have hf' : IsClosedEmbedding f := f.isClosedEmbedding_of_injective hf
have h₂ : Tendsto (fun p : Fin 2 → ℤ => ((↑) : ℤ → ℝ) ∘ p) cofinite (cocompact _) := by
convert Tendsto.pi_map_coprodᵢ fun _ => Int.tendsto_coe_cofinite
· rw [coprodᵢ_cofinite]
· rw [coprodᵢ_cocompact]
exact tendsto_normSq_cocompact_atTop.comp (hf'.tendsto_cocompact.comp h₂)
/-- Given `coprime_pair` `p=(c,d)`, the matrix `[[a,b],[*,*]]` is sent to `a*c+b*d`.
This is the linear map version of this operation.
-/
def lcRow0 (p : Fin 2 → ℤ) : Matrix (Fin 2) (Fin 2) ℝ →ₗ[ℝ] ℝ :=
((p 0 : ℝ) • LinearMap.proj (0 : Fin 2) +
(p 1 : ℝ) • LinearMap.proj (1 : Fin 2) : (Fin 2 → ℝ) →ₗ[ℝ] ℝ).comp
(LinearMap.proj 0)
@[simp]
theorem lcRow0_apply (p : Fin 2 → ℤ) (g : Matrix (Fin 2) (Fin 2) ℝ) :
lcRow0 p g = p 0 * g 0 0 + p 1 * g 0 1 :=
rfl
/-- Linear map sending the matrix [a, b; c, d] to the matrix [ac₀ + bd₀, - ad₀ + bc₀; c, d], for
some fixed `(c₀, d₀)`. -/
@[simps!]
def lcRow0Extend {cd : Fin 2 → ℤ} (hcd : IsCoprime (cd 0) (cd 1)) :
Matrix (Fin 2) (Fin 2) ℝ ≃ₗ[ℝ] Matrix (Fin 2) (Fin 2) ℝ :=
LinearEquiv.piCongrRight
![by
refine
LinearMap.GeneralLinearGroup.generalLinearEquiv ℝ (Fin 2 → ℝ)
(GeneralLinearGroup.toLin (planeConformalMatrix (cd 0 : ℝ) (-(cd 1 : ℝ)) ?_))
norm_cast
rw [neg_sq]
exact hcd.sq_add_sq_ne_zero, LinearEquiv.refl ℝ (Fin 2 → ℝ)]
/-- The map `lcRow0` is proper, that is, preimages of cocompact sets are finite in
`[[* , *], [c, d]]`. -/
theorem tendsto_lcRow0 {cd : Fin 2 → ℤ} (hcd : IsCoprime (cd 0) (cd 1)) :
Tendsto (fun g : { g : SL(2, ℤ) // g 1 = cd } => lcRow0 cd ↑(↑g : SL(2, ℝ))) cofinite
(cocompact ℝ) := by
let mB : ℝ → Matrix (Fin 2) (Fin 2) ℝ := fun t => of ![![t, (-(1 : ℤ) : ℝ)], (↑) ∘ cd]
have hmB : Continuous mB := by
refine continuous_matrix ?_
simp only [mB, Fin.forall_fin_two, continuous_const, continuous_id', of_apply, cons_val_zero,
cons_val_one, and_self_iff]
refine Filter.Tendsto.of_tendsto_comp ?_ (comap_cocompact_le hmB)
let f₁ : SL(2, ℤ) → Matrix (Fin 2) (Fin 2) ℝ := fun g =>
Matrix.map (↑g : Matrix _ _ ℤ) ((↑) : ℤ → ℝ)
have cocompact_ℝ_to_cofinite_ℤ_matrix :
Tendsto (fun m : Matrix (Fin 2) (Fin 2) ℤ => Matrix.map m ((↑) : ℤ → ℝ)) cofinite
(cocompact _) := by
simpa only [coprodᵢ_cofinite, coprodᵢ_cocompact] using
Tendsto.pi_map_coprodᵢ fun _ : Fin 2 =>
Tendsto.pi_map_coprodᵢ fun _ : Fin 2 => Int.tendsto_coe_cofinite
have hf₁ : Tendsto f₁ cofinite (cocompact _) :=
cocompact_ℝ_to_cofinite_ℤ_matrix.comp Subtype.coe_injective.tendsto_cofinite
have hf₂ : IsClosedEmbedding (lcRow0Extend hcd) :=
(lcRow0Extend hcd).toContinuousLinearEquiv.toHomeomorph.isClosedEmbedding
convert hf₂.tendsto_cocompact.comp (hf₁.comp Subtype.coe_injective.tendsto_cofinite) using 1
ext ⟨g, rfl⟩ i j : 3
fin_cases i <;> [fin_cases j; skip]
-- the following are proved by `simp`, but it is replaced by `simp only` to avoid timeouts.
· simp only [Fin.isValue, Int.cast_one, map_apply_coe, RingHom.mapMatrix_apply,
Int.coe_castRingHom, lcRow0_apply, map_apply, Fin.zero_eta, Function.comp_apply,
of_apply, cons_val', cons_val_zero, empty_val', cons_val_fin_one, lcRow0Extend_apply,
LinearMap.GeneralLinearGroup.coeFn_generalLinearEquiv, GeneralLinearGroup.coe_toLin,
val_planeConformalMatrix, neg_neg, mulVecLin_apply, mulVec, dotProduct, Fin.sum_univ_two,
cons_val_one, mB, f₁]
· convert congr_arg (fun n : ℤ => (-n : ℝ)) g.det_coe.symm using 1
simp only [Fin.zero_eta, Function.comp_apply, lcRow0Extend_apply, cons_val_zero,
LinearMap.GeneralLinearGroup.coeFn_generalLinearEquiv, GeneralLinearGroup.coe_toLin,
mulVecLin_apply, mulVec, dotProduct, det_fin_two, f₁]
simp only [Fin.isValue, Fin.mk_one, val_planeConformalMatrix, neg_neg, of_apply, cons_val',
empty_val', cons_val_fin_one, cons_val_one, map_apply, Fin.sum_univ_two,
cons_val_zero, neg_mul, Int.cast_sub, Int.cast_mul, neg_sub]
ring
· rfl
/-- This replaces `(g•z).re = a/c + *` in the standard theory with the following novel identity:
`g • z = (a c + b d) / (c^2 + d^2) + (d z - c) / ((c^2 + d^2) (c z + d))`
which does not need to be decomposed depending on whether `c = 0`. -/
theorem smul_eq_lcRow0_add {p : Fin 2 → ℤ} (hp : IsCoprime (p 0) (p 1)) (hg : g 1 = p) :
↑(g • z) =
(lcRow0 p ↑(g : SL(2, ℝ)) : ℂ) / ((p 0 : ℂ) ^ 2 + (p 1 : ℂ) ^ 2) +
((p 1 : ℂ) * z - p 0) / (((p 0 : ℂ) ^ 2 + (p 1 : ℂ) ^ 2) * (p 0 * z + p 1)) := by
have nonZ1 : (p 0 : ℂ) ^ 2 + (p 1 : ℂ) ^ 2 ≠ 0 := mod_cast hp.sq_add_sq_ne_zero
have : ((↑) : ℤ → ℝ) ∘ p ≠ 0 := fun h => hp.ne_zero (by ext i; simpa using congr_fun h i)
have nonZ2 : (p 0 : ℂ) * z + p 1 ≠ 0 := by simpa using linear_ne_zero z this
subst hg
rw [coe_specialLinearGroup_apply]
replace nonZ2 : z * (g 1 0 : ℂ) + g 1 1 ≠ 0 := by convert nonZ2 using 1; ring
have H := congr(Int.cast (R := ℂ) $(det_fin_two g))
simp at H
simp [field]
linear_combination -((z : ℂ) * (g 1 1 : ℂ) - g 1 0) * H
theorem tendsto_abs_re_smul {p : Fin 2 → ℤ} (hp : IsCoprime (p 0) (p 1)) :
Tendsto
(fun g : { g : SL(2, ℤ) // g 1 = p } => |((g : SL(2, ℤ)) • z).re|) cofinite atTop := by
suffices
Tendsto (fun g : (fun g : SL(2, ℤ) => g 1) ⁻¹' {p} => ((g : SL(2, ℤ)) • z).re) cofinite
(cocompact ℝ)
by exact tendsto_norm_cocompact_atTop.comp this
have : ((p 0 : ℝ) ^ 2 + (p 1 : ℝ) ^ 2)⁻¹ ≠ 0 := by
apply inv_ne_zero
exact mod_cast hp.sq_add_sq_ne_zero
let f := Homeomorph.mulRight₀ _ this
let ff := Homeomorph.addRight
(((p 1 : ℂ) * z - p 0) / (((p 0 : ℂ) ^ 2 + (p 1 : ℂ) ^ 2) * (p 0 * z + p 1))).re
convert (f.trans ff).isClosedEmbedding.tendsto_cocompact.comp (tendsto_lcRow0 hp) with _ _ g
change
((g : SL(2, ℤ)) • z).re =
lcRow0 p ↑(↑g : SL(2, ℝ)) / ((p 0 : ℝ) ^ 2 + (p 1 : ℝ) ^ 2) +
Complex.re (((p 1 : ℂ) * z - p 0) / (((p 0 : ℂ) ^ 2 + (p 1 : ℂ) ^ 2) * (p 0 * z + p 1)))
exact mod_cast congr_arg Complex.re (smul_eq_lcRow0_add z hp g.2)
end TendstoLemmas
section FundamentalDomain
attribute [local simp] UpperHalfPlane.coe_specialLinearGroup_apply
/-- For `z : ℍ`, there is a `g : SL(2,ℤ)` maximizing `(g•z).im` -/
theorem exists_max_im : ∃ g : SL(2, ℤ), ∀ g' : SL(2, ℤ), (g' • z).im ≤ (g • z).im := by
classical
let s : Set (Fin 2 → ℤ) := {cd | IsCoprime (cd 0) (cd 1)}
have hs : s.Nonempty := ⟨![1, 1], isCoprime_one_left⟩
obtain ⟨p, hp_coprime, hp⟩ :=
Filter.Tendsto.exists_within_forall_le hs (tendsto_normSq_coprime_pair z)
obtain ⟨g, -, hg⟩ := bottom_row_surj hp_coprime
refine ⟨g, fun g' => ?_⟩
rw [ModularGroup.im_smul_eq_div_normSq, ModularGroup.im_smul_eq_div_normSq,
div_le_div_iff_of_pos_left]
· simpa [← hg] using hp (g' 1) (bottom_row_coprime g')
· exact z.im_pos
· exact normSq_denom_pos g' z.im_ne_zero
· exact normSq_denom_pos g z.im_ne_zero
/-- Given `z : ℍ` and a bottom row `(c,d)`, among the `g : SL(2,ℤ)` with this bottom row, minimize
`|(g•z).re|`. -/
theorem exists_row_one_eq_and_min_re {cd : Fin 2 → ℤ} (hcd : IsCoprime (cd 0) (cd 1)) :
∃ g : SL(2, ℤ), g 1 = cd ∧ ∀ g' : SL(2, ℤ), g 1 = g' 1 →
|(g • z).re| ≤ |(g' • z).re| := by
haveI : Nonempty { g : SL(2, ℤ) // g 1 = cd } :=
let ⟨x, hx⟩ := bottom_row_surj hcd
⟨⟨x, hx.2⟩⟩
obtain ⟨g, hg⟩ := Filter.Tendsto.exists_forall_le (tendsto_abs_re_smul z hcd)
refine ⟨g, g.2, ?_⟩
intro g1 hg1
have : g1 ∈ (fun g : SL(2, ℤ) => g 1) ⁻¹' {cd} := by
rw [Set.mem_preimage, Set.mem_singleton_iff]
exact Eq.trans hg1.symm (Set.mem_singleton_iff.mp (Set.mem_preimage.mp g.2))
exact hg ⟨g1, this⟩
theorem coe_T_zpow_smul_eq {n : ℤ} : (↑(T ^ n • z) : ℂ) = z + n := by
rw [UpperHalfPlane.coe_specialLinearGroup_apply]
simp [coe_T_zpow, -map_zpow]
theorem re_T_zpow_smul (n : ℤ) : (T ^ n • z).re = z.re + n := by
rw [← coe_re, coe_T_zpow_smul_eq, add_re, intCast_re, coe_re]
theorem im_T_zpow_smul (n : ℤ) : (T ^ n • z).im = z.im := by
rw [← coe_im, coe_T_zpow_smul_eq, add_im, intCast_im, add_zero, coe_im]
theorem re_T_smul : (T • z).re = z.re + 1 := by simpa using re_T_zpow_smul z 1
theorem im_T_smul : (T • z).im = z.im := by simpa using im_T_zpow_smul z 1
theorem re_T_inv_smul : (T⁻¹ • z).re = z.re - 1 := by simpa using re_T_zpow_smul z (-1)
theorem im_T_inv_smul : (T⁻¹ • z).im = z.im := by simpa using im_T_zpow_smul z (-1)
variable {z}
-- If instead we had `g` and `T` of type `PSL(2, ℤ)`, then we could simply state `g = T^n`.
theorem exists_eq_T_zpow_of_c_eq_zero (hc : g 1 0 = 0) :
∃ n : ℤ, ∀ z : ℍ, g • z = T ^ n • z := by
have had := g.det_coe
replace had : g 0 0 * g 1 1 = 1 := by rw [det_fin_two, hc] at had; omega
rcases Int.eq_one_or_neg_one_of_mul_eq_one' had with (⟨ha, hd⟩ | ⟨ha, hd⟩)
· use g 0 1
suffices g = T ^ g 0 1 by intro z; conv_lhs => rw [this]
ext i j; fin_cases i <;> fin_cases j <;>
simp [ha, hc, hd, coe_T_zpow, show (1 : Fin (0 + 2)) = (1 : Fin 2) from rfl]
· use -(g 0 1)
suffices g = -T ^ (-(g 0 1)) by intro z; conv_lhs => rw [this, SL_neg_smul]
ext i j; fin_cases i <;> fin_cases j <;>
simp [ha, hc, hd, coe_T_zpow, show (1 : Fin (0 + 2)) = (1 : Fin 2) from rfl]
-- If `c = 1`, then `g` factorises into a product terms involving only `T` and `S`.
theorem g_eq_of_c_eq_one (hc : g 1 0 = 1) : g = T ^ g 0 0 * S * T ^ g 1 1 := by
have hg := g.det_coe.symm
replace hg : g 0 1 = g 0 0 * g 1 1 - 1 := by rw [det_fin_two, hc] at hg; omega
refine Subtype.ext ?_
conv_lhs => rw [(g : Matrix _ _ ℤ).eta_fin_two]
simp only [hg, sub_eq_add_neg, hc, coe_mul, coe_T_zpow, coe_S, mul_fin_two, mul_zero, mul_one,
zero_add, one_mul, add_zero, zero_mul]
/-- If `1 < |z|`, then `|S • z| < 1`. -/
theorem normSq_S_smul_lt_one (h : 1 < normSq z) : normSq ↑(S • z) < 1 := by
rw [UpperHalfPlane.coe_specialLinearGroup_apply]
simpa [coe_S, num, denom] using (inv_lt_inv₀ z.normSq_pos zero_lt_one).mpr h
/-- If `|z| < 1`, then applying `S` strictly decreases `im`. -/
theorem im_lt_im_S_smul (h : normSq z < 1) : z.im < (S • z).im := by
rw [ModularGroup.im_smul_eq_div_normSq]
have : z.im < z.im / normSq (z : ℂ) := by
have imz : 0 < z.im := im_pos z
apply (lt_div_iff₀ z.normSq_pos).mpr
nlinarith
simpa [denom, coe_S, SpecialLinearGroup.toGL]
/-- The standard (closed) fundamental domain of the action of `SL(2,ℤ)` on `ℍ`. -/
def fd : Set ℍ :=
{z | 1 ≤ normSq (z : ℂ) ∧ |z.re| ≤ (1 : ℝ) / 2}
/-- The standard open fundamental domain of the action of `SL(2,ℤ)` on `ℍ`. -/
def fdo : Set ℍ :=
{z | 1 < normSq (z : ℂ) ∧ |z.re| < (1 : ℝ) / 2}
@[inherit_doc ModularGroup.fd]
scoped[Modular] notation "𝒟" => ModularGroup.fd
@[inherit_doc ModularGroup.fdo]
scoped[Modular] notation "𝒟ᵒ" => ModularGroup.fdo
open scoped Modular
theorem abs_two_mul_re_lt_one_of_mem_fdo (h : z ∈ 𝒟ᵒ) : |2 * z.re| < 1 := by
rw [abs_mul, abs_two, ← lt_div_iff₀' (zero_lt_two' ℝ)]
exact h.2
theorem three_lt_four_mul_im_sq_of_mem_fdo (h : z ∈ 𝒟ᵒ) : 3 < 4 * z.im ^ 2 := by
have : 1 < z.re * z.re + z.im * z.im := by simpa [Complex.normSq_apply] using h.1
have := h.2
cases abs_cases z.re <;> nlinarith
/-- non-strict variant of `ModularGroup.three_le_four_mul_im_sq_of_mem_fdo` -/
theorem three_le_four_mul_im_sq_of_mem_fd {τ : ℍ} (h : τ ∈ 𝒟) : 3 ≤ 4 * τ.im ^ 2 := by
have : 1 ≤ τ.re * τ.re + τ.im * τ.im := by simpa [Complex.normSq_apply] using h.1
cases abs_cases τ.re <;> nlinarith [h.2]
/-- If `z ∈ 𝒟ᵒ`, and `n : ℤ`, then `|z + n| > 1`. -/
theorem one_lt_normSq_T_zpow_smul (hz : z ∈ 𝒟ᵒ) (n : ℤ) : 1 < normSq (T ^ n • z : ℍ) := by
rw [coe_T_zpow_smul_eq]
have hz₁ : 1 < z.re * z.re + z.im * z.im := hz.1
have hzn := Int.nneg_mul_add_sq_of_abs_le_one n (abs_two_mul_re_lt_one_of_mem_fdo hz).le
have : 1 < (z.re + ↑n) * (z.re + ↑n) + z.im * z.im := by linarith
simpa [normSq, num, denom]
theorem eq_zero_of_mem_fdo_of_T_zpow_mem_fdo {n : ℤ} (hz : z ∈ 𝒟ᵒ) (hg : T ^ n • z ∈ 𝒟ᵒ) :
n = 0 := by
suffices |(n : ℝ)| < 1 by
rwa [← Int.cast_abs, ← Int.cast_one, Int.cast_lt, Int.abs_lt_one_iff] at this
have h₁ := hz.2
have h₂ := hg.2
rw [re_T_zpow_smul] at h₂
calc
|(n : ℝ)| ≤ |z.re| + |z.re + (n : ℝ)| := abs_add' (n : ℝ) z.re
_ < 1 / 2 + 1 / 2 := add_lt_add h₁ h₂
_ = 1 := add_halves 1
/-- First Fundamental Domain Lemma: Any `z : ℍ` can be moved to `𝒟` by an element of
`SL(2,ℤ)` -/
theorem exists_smul_mem_fd (z : ℍ) : ∃ g : SL(2, ℤ), g • z ∈ 𝒟 := by
-- obtain a g₀ which maximizes im (g • z),
obtain ⟨g₀, hg₀⟩ := exists_max_im z
-- then among those, minimize re
obtain ⟨g, hg, hg'⟩ := exists_row_one_eq_and_min_re z (bottom_row_coprime g₀)
refine ⟨g, ?_⟩
-- `g` has same max im property as `g₀`
have hg₀' : ∀ g' : SL(2, ℤ), (g' • z).im ≤ (g • z).im := by
have hg'' : (g • z).im = (g₀ • z).im := by
rw [ModularGroup.im_smul_eq_div_normSq, ModularGroup.im_smul_eq_div_normSq,
denom_apply, denom_apply, hg]
simpa only [hg''] using hg₀
constructor
· -- Claim: `1 ≤ ⇑norm_sq ↑(g • z)`. If not, then `S•g•z` has larger imaginary part
contrapose! hg₀'
refine ⟨S * g, ?_⟩
rw [mul_smul]
exact im_lt_im_S_smul hg₀'
· change |(g • z).re| ≤ 1 / 2
-- if not, then either `T` or `T'` decrease |Re|.
rw [abs_le]
constructor
· contrapose! hg'
refine ⟨T * g, (T_mul_apply_one _).symm, ?_⟩
rw [mul_smul, re_T_smul]
cases abs_cases ((g • z).re + 1) <;> cases abs_cases (g • z).re <;> linarith
· contrapose! hg'
refine ⟨T⁻¹ * g, (T_inv_mul_apply_one _).symm, ?_⟩
rw [mul_smul, re_T_inv_smul]
cases abs_cases ((g • z).re - 1) <;> cases abs_cases (g • z).re <;> linarith
section UniqueRepresentative
/-- An auxiliary result en route to `ModularGroup.c_eq_zero`. -/
theorem abs_c_le_one (hz : z ∈ 𝒟ᵒ) (hg : g • z ∈ 𝒟ᵒ) : |g 1 0| ≤ 1 := by
let c' : ℤ := g 1 0
let c := (c' : ℝ)
suffices 3 * c ^ 2 < 4 by
rw [← Int.cast_pow, ← Int.cast_three, ← Int.cast_four, ← Int.cast_mul, Int.cast_lt] at this
replace this : c' ^ 2 ≤ 1 ^ 2 := by omega
rwa [sq_le_sq, abs_one] at this
suffices c ≠ 0 → 9 * c ^ 4 < 16 by
rcases eq_or_ne c 0 with (hc | hc)
· rw [hc]; simp
· refine (abs_lt_of_sq_lt_sq' ?_ (by simp)).2
specialize this hc
linarith
intro hc
have h₁ : 3 * 3 * c ^ 4 < 4 * (g • z).im ^ 2 * (4 * z.im ^ 2) * c ^ 4 := by
gcongr <;> apply three_lt_four_mul_im_sq_of_mem_fdo <;> assumption
have h₂ : (c * z.im) ^ 4 / normSq (denom (↑g) z) ^ 2 ≤ 1 :=
div_le_one_of_le₀
(pow_four_le_pow_two_of_pow_two_le (z.c_mul_im_sq_le_normSq_denom g))
(sq_nonneg _)
let nsq := normSq (denom g z)
calc
9 * c ^ 4 < c ^ 4 * z.im ^ 2 * (g • z).im ^ 2 * 16 := by linarith
_ = c ^ 4 * z.im ^ 4 / nsq ^ 2 * 16 := by
rw [im_smul_eq_div_normSq, div_pow]
ring
_ ≤ 16 := by rw [← mul_pow]; linarith
/-- An auxiliary result en route to `ModularGroup.eq_smul_self_of_mem_fdo_mem_fdo`. -/
theorem c_eq_zero (hz : z ∈ 𝒟ᵒ) (hg : g • z ∈ 𝒟ᵒ) : g 1 0 = 0 := by
have hp : ∀ {g' : SL(2, ℤ)}, g' • z ∈ 𝒟ᵒ → g' 1 0 ≠ 1 := by
intro g' hg'
by_contra hc
let a := g' 0 0
let d := g' 1 1
have had : T ^ (-a) * g' = S * T ^ d := by
rw [g_eq_of_c_eq_one hc]
dsimp [a, d]
group
let w := T ^ (-a) • g' • z
have h₁ : w = S • T ^ d • z := by simp only [w, ← mul_smul, had]
replace h₁ : normSq w < 1 := h₁.symm ▸ normSq_S_smul_lt_one (one_lt_normSq_T_zpow_smul hz d)
have h₂ : 1 < normSq w := one_lt_normSq_T_zpow_smul hg' (-a)
linarith
have hn : g 1 0 ≠ -1 := by
intro hc
replace hc : (-g) 1 0 = 1 := by simp [← neg_eq_iff_eq_neg.mpr hc]
replace hg : -g • z ∈ 𝒟ᵒ := (SL_neg_smul g z).symm ▸ hg
exact hp hg hc
specialize hp hg
rcases Int.abs_le_one_iff.mp <| abs_c_le_one hz hg with ⟨⟩ <;> tauto
/-- Second Fundamental Domain Lemma: if both `z` and `g • z` are in the open domain `𝒟ᵒ`,
where `z : ℍ` and `g : SL(2,ℤ)`, then `z = g • z`. -/
theorem eq_smul_self_of_mem_fdo_mem_fdo (hz : z ∈ 𝒟ᵒ) (hg : g • z ∈ 𝒟ᵒ) : z = g • z := by
obtain ⟨n, hn⟩ := exists_eq_T_zpow_of_c_eq_zero (c_eq_zero hz hg)
rw [hn] at hg ⊢
simp [eq_zero_of_mem_fdo_of_T_zpow_mem_fdo hz hg, one_smul]
end UniqueRepresentative
end FundamentalDomain
lemma exists_one_half_le_im_smul (τ : ℍ) : ∃ γ : SL(2, ℤ), 1 / 2 ≤ im (γ • τ) := by
obtain ⟨γ, hγ⟩ := exists_smul_mem_fd τ
use γ
nlinarith [three_le_four_mul_im_sq_of_mem_fd hγ, im_pos (γ • τ)]
/-- For every `τ : ℍ` there is some `γ ∈ SL(2, ℤ)` that sends it to an element whose
imaginary part is at least `1/2` and such that `denom γ τ` has norm at most 1. -/
lemma exists_one_half_le_im_smul_and_norm_denom_le (τ : ℍ) :
∃ γ : SL(2, ℤ), 1 / 2 ≤ im (γ • τ) ∧ ‖denom γ τ‖ ≤ 1 := by
rcases le_total (1 / 2) τ.im with h | h
· exact ⟨1, (one_smul SL(2, ℤ) τ).symm ▸ h, by
simp only [map_one, denom_one, norm_one, le_refl]⟩
· refine (exists_one_half_le_im_smul τ).imp (fun γ hγ ↦ ⟨hγ, ?_⟩)
have h1 : τ.im ≤ (γ • τ).im := h.trans hγ
rw [im_smul_eq_div_normSq, le_div_iff₀ (normSq_denom_pos γ τ.im_ne_zero),
normSq_eq_norm_sq] at h1
simpa only [sq_le_one_iff_abs_le_one, abs_norm] using
(mul_le_iff_le_one_right τ.2).mp h1
end ModularGroup |
.lake/packages/mathlib/Mathlib/NumberTheory/VonMangoldt.lean | import Mathlib.Analysis.SpecialFunctions.Log.Basic
import Mathlib.Data.Nat.Cast.Field
import Mathlib.Data.Nat.Factorization.PrimePow
import Mathlib.NumberTheory.ArithmeticFunction
/-!
# The von Mangoldt Function
In this file we define the von Mangoldt function: the function on natural numbers that returns
`log p` if the input can be expressed as `p^k` for a prime `p`.
## Main Results
The main definition for this file is
- `ArithmeticFunction.vonMangoldt`: The von Mangoldt function `Λ`.
We then prove the classical summation property of the von Mangoldt function in
`ArithmeticFunction.vonMangoldt_sum`, that `∑ i ∈ n.divisors, Λ i = Real.log n`, and use this
to deduce alternative expressions for the von Mangoldt function via Möbius inversion, see
`ArithmeticFunction.sum_moebius_mul_log_eq`.
## Notation
We use the standard notation `Λ` to represent the von Mangoldt function.
It is accessible in the locales `ArithmeticFunction` (like the notations for other arithmetic
functions) and also in the scope `ArithmeticFunction.vonMangoldt`.
-/
namespace ArithmeticFunction
open Finset Nat
open scoped ArithmeticFunction
/-- `log` as an arithmetic function `ℕ → ℝ`. Note this is in the `ArithmeticFunction`
namespace to indicate that it is bundled as an `ArithmeticFunction` rather than being the usual
real logarithm. -/
noncomputable def log : ArithmeticFunction ℝ :=
⟨fun n => Real.log n, by simp⟩
@[simp]
theorem log_apply {n : ℕ} : log n = Real.log n :=
rfl
/--
The `vonMangoldt` function is the function on natural numbers that returns `log p` if the input can
be expressed as `p^k` for a prime `p`.
In the case when `n` is a prime power, `Nat.minFac` will give the appropriate prime, as it is the
smallest prime factor.
In the `ArithmeticFunction` locale, we have the notation `Λ` for this function.
This is also available in the `ArithmeticFunction.vonMangoldt` locale, allowing for selective
access to the notation.
-/
noncomputable def vonMangoldt : ArithmeticFunction ℝ :=
⟨fun n => if IsPrimePow n then Real.log (minFac n) else 0, if_neg not_isPrimePow_zero⟩
@[inherit_doc] scoped[ArithmeticFunction] notation "Λ" => ArithmeticFunction.vonMangoldt
@[inherit_doc] scoped[ArithmeticFunction.vonMangoldt] notation "Λ" =>
ArithmeticFunction.vonMangoldt
theorem vonMangoldt_apply {n : ℕ} : Λ n = if IsPrimePow n then Real.log (minFac n) else 0 :=
rfl
@[simp]
theorem vonMangoldt_apply_one : Λ 1 = 0 := by simp [vonMangoldt_apply]
@[simp]
theorem vonMangoldt_nonneg {n : ℕ} : 0 ≤ Λ n := by
rw [vonMangoldt_apply]
split_ifs
· exact Real.log_nonneg (one_le_cast.2 (Nat.minFac_pos n))
rfl
theorem vonMangoldt_apply_pow {n k : ℕ} (hk : k ≠ 0) : Λ (n ^ k) = Λ n := by
simp only [vonMangoldt_apply, isPrimePow_pow_iff hk, pow_minFac hk]
theorem vonMangoldt_apply_prime {p : ℕ} (hp : p.Prime) : Λ p = Real.log p := by
rw [vonMangoldt_apply, Prime.minFac_eq hp, if_pos hp.prime.isPrimePow]
theorem vonMangoldt_ne_zero_iff {n : ℕ} : Λ n ≠ 0 ↔ IsPrimePow n := by
rcases eq_or_ne n 1 with (rfl | hn); · simp [not_isPrimePow_one]
exact (Real.log_pos (one_lt_cast.2 (minFac_prime hn).one_lt)).ne'.ite_ne_right_iff
theorem vonMangoldt_pos_iff {n : ℕ} : 0 < Λ n ↔ IsPrimePow n :=
vonMangoldt_nonneg.lt_iff_ne.trans (ne_comm.trans vonMangoldt_ne_zero_iff)
theorem vonMangoldt_eq_zero_iff {n : ℕ} : Λ n = 0 ↔ ¬IsPrimePow n :=
vonMangoldt_ne_zero_iff.not_right
theorem vonMangoldt_sum {n : ℕ} : ∑ i ∈ n.divisors, Λ i = Real.log n := by
refine recOnPrimeCoprime ?_ ?_ ?_ n
· simp
· intro p k hp
rw [sum_divisors_prime_pow hp, cast_pow, Real.log_pow, Finset.sum_range_succ', Nat.pow_zero,
vonMangoldt_apply_one]
simp [vonMangoldt_apply_pow (Nat.succ_ne_zero _), vonMangoldt_apply_prime hp]
intro a b ha' hb' hab ha hb
simp only [vonMangoldt_apply, ← sum_filter] at ha hb ⊢
rw [mul_divisors_filter_prime_pow hab, filter_union,
sum_union (disjoint_divisors_filter_isPrimePow hab), ha, hb, Nat.cast_mul,
Real.log_mul (cast_ne_zero.2 (pos_of_gt ha').ne') (cast_ne_zero.2 (pos_of_gt hb').ne')]
-- access notation `ζ` and `μ`
open scoped zeta Moebius
@[simp]
theorem vonMangoldt_mul_zeta : Λ * ζ = log := by
ext n; rw [coe_mul_zeta_apply, vonMangoldt_sum]; rfl
@[simp]
theorem zeta_mul_vonMangoldt : (ζ : ArithmeticFunction ℝ) * Λ = log := by rw [mul_comm]; simp
@[simp]
theorem log_mul_moebius_eq_vonMangoldt : log * μ = Λ := by
rw [← vonMangoldt_mul_zeta, mul_assoc, coe_zeta_mul_coe_moebius, mul_one]
@[simp]
theorem moebius_mul_log_eq_vonMangoldt : (μ : ArithmeticFunction ℝ) * log = Λ := by
rw [mul_comm]; simp
theorem sum_moebius_mul_log_eq {n : ℕ} : (∑ d ∈ n.divisors, (μ d : ℝ) * log d) = -Λ n := by
simp only [← log_mul_moebius_eq_vonMangoldt, mul_comm log, mul_apply, log_apply, intCoe_apply, ←
Finset.sum_neg_distrib, neg_mul_eq_mul_neg]
rw [sum_divisorsAntidiagonal fun i j => (μ i : ℝ) * -Real.log j]
have : (∑ i ∈ n.divisors, (μ i : ℝ) * -Real.log (n / i : ℕ)) =
∑ i ∈ n.divisors, ((μ i : ℝ) * Real.log i - μ i * Real.log n) := by
apply sum_congr rfl
simp only [and_imp, Ne, mem_divisors]
intro m mn hn
have : (m : ℝ) ≠ 0 := by
rw [cast_ne_zero]
rintro rfl
exact hn (by simpa using mn)
rw [Nat.cast_div mn this, Real.log_div (cast_ne_zero.2 hn) this, neg_sub, mul_sub]
rw [this, sum_sub_distrib, ← sum_mul, ← Int.cast_sum, ← coe_mul_zeta_apply, eq_comm, sub_eq_self,
moebius_mul_coe_zeta]
rcases eq_or_ne n 1 with (hn | hn) <;> simp [hn]
theorem vonMangoldt_le_log : ∀ {n : ℕ}, Λ n ≤ Real.log (n : ℝ)
| 0 => by simp
| n + 1 => by
rw [← vonMangoldt_sum]
exact single_le_sum (by exact fun _ _ => vonMangoldt_nonneg)
(mem_divisors_self _ n.succ_ne_zero)
end ArithmeticFunction |
.lake/packages/mathlib/Mathlib/NumberTheory/PrimesCongruentOne.lean | import Mathlib.RingTheory.Polynomial.Cyclotomic.Eval
/-!
# Primes congruent to one
We prove that, for any positive `k : ℕ`, there are infinitely many primes `p` such that
`p ≡ 1 [MOD k]`.
-/
namespace Nat
open Polynomial Nat Filter
open scoped Nat
/-- For any positive `k : ℕ` there exists an arbitrarily large prime `p` such that
`p ≡ 1 [MOD k]`. -/
theorem exists_prime_gt_modEq_one {k : ℕ} (n : ℕ) (hk0 : k ≠ 0) :
∃ p : ℕ, Nat.Prime p ∧ n < p ∧ p ≡ 1 [MOD k] := by
rcases (one_le_iff_ne_zero.2 hk0).eq_or_lt with (rfl | hk1)
· rcases exists_infinite_primes (n + 1) with ⟨p, hnp, hp⟩
exact ⟨p, hp, hnp, modEq_one⟩
let b := k * (n !)
have hgt : 1 < (eval (↑b) (cyclotomic k ℤ)).natAbs := by
rcases le_iff_exists_add'.1 hk1.le with ⟨k, rfl⟩
have hb : 2 ≤ b := le_mul_of_le_of_one_le hk1 n.factorial_pos
calc
1 ≤ b - 1 := le_tsub_of_add_le_left hb
_ < (eval (b : ℤ) (cyclotomic (k + 1) ℤ)).natAbs :=
sub_one_lt_natAbs_cyclotomic_eval hk1 (succ_le_iff.1 hb).ne'
let p := minFac (eval (↑b) (cyclotomic k ℤ)).natAbs
haveI hprime : Fact p.Prime := ⟨minFac_prime (ne_of_lt hgt).symm⟩
have hroot : IsRoot (cyclotomic k (ZMod p)) (castRingHom (ZMod p) b) := by
have : ((b : ℤ) : ZMod p) = ↑(Int.castRingHom (ZMod p) b) := by simp
rw [IsRoot.def, ← map_cyclotomic_int k (ZMod p), eval_map, coe_castRingHom,
← Int.cast_natCast, this, eval₂_hom, Int.coe_castRingHom, ZMod.intCast_zmod_eq_zero_iff_dvd]
apply Int.dvd_natAbs.1
exact mod_cast minFac_dvd (eval (↑b) (cyclotomic k ℤ)).natAbs
have hpb : ¬p ∣ b :=
hprime.1.coprime_iff_not_dvd.1 (coprime_of_root_cyclotomic hk0.bot_lt hroot).symm
refine ⟨p, hprime.1, not_le.1 fun habs => ?_, ?_⟩
· exact hpb (dvd_mul_of_dvd_right (dvd_factorial (minFac_pos _) habs) _)
· have hdiv : orderOf (b : ZMod p) ∣ p - 1 :=
ZMod.orderOf_dvd_card_sub_one (mt (CharP.cast_eq_zero_iff _ _ _).1 hpb)
haveI : NeZero (k : ZMod p) :=
NeZero.of_not_dvd (ZMod p) fun hpk => hpb (dvd_mul_of_dvd_left hpk _)
have : k = orderOf (b : ZMod p) := (isRoot_cyclotomic_iff.mp hroot).eq_orderOf
rw [← this] at hdiv
exact ((modEq_iff_dvd' hprime.1.pos).2 hdiv).symm
theorem frequently_atTop_modEq_one {k : ℕ} (hk0 : k ≠ 0) :
∃ᶠ p in atTop, Nat.Prime p ∧ p ≡ 1 [MOD k] := by
refine frequently_atTop.2 fun n => ?_
obtain ⟨p, hp⟩ := exists_prime_gt_modEq_one n hk0
exact ⟨p, ⟨hp.2.1.le, hp.1, hp.2.2⟩⟩
/-- For any positive `k : ℕ` there are infinitely many primes `p` such that `p ≡ 1 [MOD k]`. -/
theorem infinite_setOf_prime_modEq_one {k : ℕ} (hk0 : k ≠ 0) :
Set.Infinite {p : ℕ | Nat.Prime p ∧ p ≡ 1 [MOD k]} :=
frequently_atTop_iff_infinite.1 (frequently_atTop_modEq_one hk0)
end Nat |
.lake/packages/mathlib/Mathlib/NumberTheory/Multiplicity.lean | import Mathlib.Algebra.Order.Ring.Basic
import Mathlib.Algebra.Ring.GeomSum
import Mathlib.Algebra.Ring.Int.Parity
import Mathlib.Data.Nat.Choose.Sum
import Mathlib.Data.Nat.Prime.Int
import Mathlib.NumberTheory.Padics.PadicVal.Defs
import Mathlib.RingTheory.Ideal.Quotient.Defs
import Mathlib.RingTheory.Ideal.Span
/-!
# Multiplicity in Number Theory
This file contains results in number theory relating to multiplicity.
## Main statements
* `multiplicity.Int.pow_sub_pow` is the lifting the exponent lemma for odd primes.
We also prove several variations of the lemma.
## References
* [Wikipedia, *Lifting-the-exponent lemma*]
(https://en.wikipedia.org/wiki/Lifting-the-exponent_lemma)
-/
open Ideal Ideal.Quotient Finset
variable {R : Type*} {n : ℕ}
section CommRing
variable [CommRing R] {a b x y : R}
theorem dvd_geom_sum₂_iff_of_dvd_sub {x y p : R} (h : p ∣ x - y) :
(p ∣ ∑ i ∈ range n, x ^ i * y ^ (n - 1 - i)) ↔ p ∣ n * y ^ (n - 1) := by
rw [← mem_span_singleton, ← Ideal.Quotient.eq] at h
simp only [← mem_span_singleton, ← eq_zero_iff_mem, RingHom.map_geom_sum₂, h, geom_sum₂_self,
map_mul, map_pow, map_natCast]
theorem dvd_geom_sum₂_iff_of_dvd_sub' {x y p : R} (h : p ∣ x - y) :
(p ∣ ∑ i ∈ range n, x ^ i * y ^ (n - 1 - i)) ↔ p ∣ n * x ^ (n - 1) := by
rw [geom_sum₂_comm, dvd_geom_sum₂_iff_of_dvd_sub]; simpa using h.neg_right
theorem dvd_geom_sum₂_self {x y : R} (h : ↑n ∣ x - y) :
↑n ∣ ∑ i ∈ range n, x ^ i * y ^ (n - 1 - i) :=
(dvd_geom_sum₂_iff_of_dvd_sub h).mpr (dvd_mul_right _ _)
theorem sq_dvd_add_pow_sub_sub (p x : R) (n : ℕ) :
p ^ 2 ∣ (x + p) ^ n - x ^ (n - 1) * p * n - x ^ n := by
rcases n with - | n
· simp only [pow_zero, Nat.cast_zero, sub_zero, sub_self, dvd_zero, mul_zero]
· simp only [Nat.succ_sub_succ_eq_sub, tsub_zero, Nat.cast_succ, add_pow, Finset.sum_range_succ,
Nat.choose_self, tsub_self, pow_one, Nat.choose_succ_self_right, pow_zero,
mul_one, Nat.cast_zero, zero_add, add_tsub_cancel_left]
suffices p ^ 2 ∣ ∑ i ∈ range n, x ^ i * p ^ (n + 1 - i) * ↑((n + 1).choose i) by
convert this; abel
apply Finset.dvd_sum
intro y hy
calc
p ^ 2 ∣ p ^ (n + 1 - y) :=
pow_dvd_pow p (le_tsub_of_add_le_left (by linarith [Finset.mem_range.mp hy]))
_ ∣ x ^ y * p ^ (n + 1 - y) * ↑((n + 1).choose y) :=
dvd_mul_of_dvd_left (dvd_mul_left _ _) _
theorem not_dvd_geom_sum₂ {p : R} (hp : Prime p) (hxy : p ∣ x - y) (hx : ¬p ∣ x) (hn : ¬p ∣ n) :
¬p ∣ ∑ i ∈ range n, x ^ i * y ^ (n - 1 - i) := fun h =>
hx <|
hp.dvd_of_dvd_pow <| (hp.dvd_or_dvd <| (dvd_geom_sum₂_iff_of_dvd_sub' hxy).mp h).resolve_left hn
variable {p : ℕ} (a b)
theorem odd_sq_dvd_geom_sum₂_sub (hp : Odd p) :
(p : R) ^ 2 ∣ (∑ i ∈ range p, (a + p * b) ^ i * a ^ (p - 1 - i)) - p * a ^ (p - 1) := by
have h1 : ∀ (i : ℕ),
(p : R) ^ 2 ∣ (a + ↑p * b) ^ i - (a ^ (i - 1) * (↑p * b) * i + a ^ i) := by
intro i
calc
↑p ^ 2 ∣ (↑p * b) ^ 2 := by simp only [mul_pow, dvd_mul_right]
_ ∣ (a + ↑p * b) ^ i - (a ^ (i - 1) * (↑p * b) * ↑i + a ^ i) := by
simp only [sq_dvd_add_pow_sub_sub (↑p * b) a i, ← sub_sub]
simp_rw [← mem_span_singleton, ← Ideal.Quotient.eq] at *
let s : R := (p : R) ^ 2
calc
(Ideal.Quotient.mk (span {s})) (∑ i ∈ range p, (a + (p : R) * b) ^ i * a ^ (p - 1 - i)) =
∑ i ∈ Finset.range p,
mk (span {s}) ((a ^ (i - 1) * (↑p * b) * ↑i + a ^ i) * a ^ (p - 1 - i)) := by
simp_rw [s, RingHom.map_geom_sum₂, ← map_pow, h1, ← map_mul]
_ =
mk (span {s})
(∑ x ∈ Finset.range p, a ^ (x - 1) * (a ^ (p - 1 - x) * (↑p * (b * ↑x)))) +
mk (span {s}) (∑ x ∈ Finset.range p, a ^ (x + (p - 1 - x))) := by
ring_nf
simp_rw [← map_sum, sum_add_distrib, map_add]
_ =
mk (span {s})
(∑ x ∈ Finset.range p, a ^ (x - 1) * (a ^ (p - 1 - x) * (↑p * (b * ↑x)))) +
mk (span {s}) (∑ _x ∈ Finset.range p, a ^ (p - 1)) := by
rw [add_right_inj]
have : ∀ (x : ℕ), (hx : x ∈ range p) → a ^ (x + (p - 1 - x)) = a ^ (p - 1) := by
intro x hx
rw [← Nat.add_sub_assoc _ x, Nat.add_sub_cancel_left]
exact Nat.le_sub_one_of_lt (Finset.mem_range.mp hx)
rw [Finset.sum_congr rfl this]
_ =
mk (span {s})
(∑ x ∈ Finset.range p, a ^ (x - 1) * (a ^ (p - 1 - x) * (↑p * (b * ↑x)))) +
mk (span {s}) (↑p * a ^ (p - 1)) := by
simp only [Finset.sum_const, Finset.card_range, nsmul_eq_mul]
_ =
mk (span {s}) (↑p * b * ∑ x ∈ Finset.range p, a ^ (p - 2) * x) +
mk (span {s}) (↑p * a ^ (p - 1)) := by
simp only [Finset.mul_sum, ← mul_assoc, ← pow_add]
rw [Finset.sum_congr rfl]
rintro (⟨⟩ | ⟨x⟩) hx
· rw [Nat.cast_zero, mul_zero, mul_zero]
· have : x.succ - 1 + (p - 1 - x.succ) = p - 2 := by
rw [← Nat.add_sub_assoc (Nat.le_sub_one_of_lt (Finset.mem_range.mp hx))]
exact congr_arg Nat.pred (Nat.add_sub_cancel_left _ _)
rw [this]
ring1
_ = mk (span {s}) (↑p * a ^ (p - 1)) := by
have : Finset.sum (range p) (fun (x : ℕ) ↦ (x : R)) =
((Finset.sum (range p) (fun (x : ℕ) ↦ (x : ℕ)))) := by simp only [Nat.cast_sum]
simp only [add_eq_right, ← Finset.mul_sum, this]
norm_cast
simp only [Finset.sum_range_id]
norm_cast
simp only [Nat.cast_mul, map_mul,
Nat.mul_div_assoc p (even_iff_two_dvd.mp (Nat.Odd.sub_odd hp odd_one))]
ring_nf
rw [mul_assoc, mul_assoc]
refine mul_eq_zero_of_left ?_ _
refine Ideal.Quotient.eq_zero_iff_mem.mpr ?_
simp [s, mem_span_singleton]
section IntegralDomain
variable [IsDomain R]
theorem emultiplicity_pow_sub_pow_of_prime {p : R} (hp : Prime p) {x y : R}
(hxy : p ∣ x - y) (hx : ¬p ∣ x) {n : ℕ} (hn : ¬p ∣ n) :
emultiplicity p (x ^ n - y ^ n) = emultiplicity p (x - y) := by
rw [← geom_sum₂_mul, emultiplicity_mul hp,
emultiplicity_eq_zero.2 (not_dvd_geom_sum₂ hp hxy hx hn), zero_add]
variable (hp : Prime (p : R)) (hp1 : Odd p) (hxy : ↑p ∣ x - y) (hx : ¬↑p ∣ x)
include hp hp1 hxy hx
theorem emultiplicity_geom_sum₂_eq_one :
emultiplicity (↑p) (∑ i ∈ range p, x ^ i * y ^ (p - 1 - i)) = 1 := by
rw [← Nat.cast_one]
refine emultiplicity_eq_coe.2 ⟨?_, ?_⟩
· rw [pow_one]
exact dvd_geom_sum₂_self hxy
rw [dvd_iff_dvd_of_dvd_sub hxy] at hx
obtain ⟨k, hk⟩ := hxy
rw [one_add_one_eq_two, eq_add_of_sub_eq' hk]
refine mt (dvd_iff_dvd_of_dvd_sub (@odd_sq_dvd_geom_sum₂_sub _ _ y k _ hp1)).mp ?_
rw [pow_two, mul_dvd_mul_iff_left hp.ne_zero]
exact mt hp.dvd_of_dvd_pow hx
theorem emultiplicity_pow_prime_sub_pow_prime :
emultiplicity (↑p) (x ^ p - y ^ p) = emultiplicity (↑p) (x - y) + 1 := by
rw [← geom_sum₂_mul, emultiplicity_mul hp, emultiplicity_geom_sum₂_eq_one hp hp1 hxy hx, add_comm]
theorem emultiplicity_pow_prime_pow_sub_pow_prime_pow (a : ℕ) :
emultiplicity (↑p) (x ^ p ^ a - y ^ p ^ a) = emultiplicity (↑p) (x - y) + a := by
induction a with
| zero => rw [Nat.cast_zero, add_zero, pow_zero, pow_one, pow_one]
| succ a h_ind =>
rw [Nat.cast_add, Nat.cast_one, ← add_assoc, ← h_ind, pow_succ, pow_mul, pow_mul]
apply emultiplicity_pow_prime_sub_pow_prime hp hp1
· rw [← geom_sum₂_mul]
exact dvd_mul_of_dvd_right hxy _
· exact fun h => hx (hp.dvd_of_dvd_pow h)
end IntegralDomain
section LiftingTheExponent
variable (hp : Nat.Prime p) (hp1 : Odd p)
include hp hp1
/-- **Lifting the exponent lemma** for odd primes. -/
theorem Int.emultiplicity_pow_sub_pow {x y : ℤ} (hxy : ↑p ∣ x - y) (hx : ¬↑p ∣ x) (n : ℕ) :
emultiplicity (↑p) (x ^ n - y ^ n) = emultiplicity (↑p) (x - y) + emultiplicity p n := by
rcases n with - | n
· simp only [emultiplicity_zero, add_top, pow_zero, sub_self]
have h : FiniteMultiplicity _ _ := Nat.finiteMultiplicity_iff.mpr ⟨hp.ne_one, n.succ_pos⟩
simp only [Nat.succ_eq_add_one] at h
rcases emultiplicity_eq_coe.mp h.emultiplicity_eq_multiplicity with ⟨⟨k, hk⟩, hpn⟩
conv_lhs => rw [hk, pow_mul, pow_mul]
rw [Nat.prime_iff_prime_int] at hp
rw [emultiplicity_pow_sub_pow_of_prime hp,
emultiplicity_pow_prime_pow_sub_pow_prime_pow hp hp1 hxy hx, h.emultiplicity_eq_multiplicity]
· rw [← geom_sum₂_mul]
exact dvd_mul_of_dvd_right hxy _
· exact fun h => hx (hp.dvd_of_dvd_pow h)
· rw [Int.natCast_dvd_natCast]
rintro ⟨c, rfl⟩
refine hpn ⟨c, ?_⟩
rwa [pow_succ, mul_assoc]
theorem Int.emultiplicity_pow_add_pow {x y : ℤ} (hxy : ↑p ∣ x + y) (hx : ¬↑p ∣ x)
{n : ℕ} (hn : Odd n) :
emultiplicity (↑p) (x ^ n + y ^ n) = emultiplicity (↑p) (x + y) + emultiplicity p n := by
rw [← sub_neg_eq_add] at hxy
rw [← sub_neg_eq_add, ← sub_neg_eq_add, ← Odd.neg_pow hn]
exact Int.emultiplicity_pow_sub_pow hp hp1 hxy hx n
theorem Nat.emultiplicity_pow_sub_pow {x y : ℕ} (hxy : p ∣ x - y) (hx : ¬p ∣ x) (n : ℕ) :
emultiplicity p (x ^ n - y ^ n) = emultiplicity p (x - y) + emultiplicity p n := by
obtain hyx | hyx := le_total y x
· iterate 2 rw [← Int.natCast_emultiplicity]
rw [Int.ofNat_sub (Nat.pow_le_pow_left hyx n)]
rw [← Int.natCast_dvd_natCast] at hxy hx
rw [Int.natCast_sub hyx] at *
push_cast at *
exact Int.emultiplicity_pow_sub_pow hp hp1 hxy hx n
· simp only [Nat.sub_eq_zero_iff_le.mpr (Nat.pow_le_pow_left hyx n), emultiplicity_zero,
Nat.sub_eq_zero_iff_le.mpr hyx, top_add]
theorem Nat.emultiplicity_pow_add_pow {x y : ℕ} (hxy : p ∣ x + y) (hx : ¬p ∣ x)
{n : ℕ} (hn : Odd n) :
emultiplicity p (x ^ n + y ^ n) = emultiplicity p (x + y) + emultiplicity p n := by
iterate 2 rw [← Int.natCast_emultiplicity]
rw [← Int.natCast_dvd_natCast] at hxy hx
push_cast at *
exact Int.emultiplicity_pow_add_pow hp hp1 hxy hx hn
end LiftingTheExponent
end CommRing
theorem pow_two_pow_sub_pow_two_pow [CommRing R] {x y : R} (n : ℕ) :
x ^ 2 ^ n - y ^ 2 ^ n = (∏ i ∈ Finset.range n, (x ^ 2 ^ i + y ^ 2 ^ i)) * (x - y) := by
induction n with
| zero => simp only [pow_zero, pow_one, range_zero, prod_empty, one_mul]
| succ d hd =>
suffices x ^ 2 ^ d.succ - y ^ 2 ^ d.succ = (x ^ 2 ^ d + y ^ 2 ^ d) * (x ^ 2 ^ d - y ^ 2 ^ d) by
rw [this, hd, Finset.prod_range_succ, ← mul_assoc, mul_comm (x ^ 2 ^ d + y ^ 2 ^ d)]
rw [Nat.succ_eq_add_one]
ring
theorem Int.sq_mod_four_eq_one_of_odd {x : ℤ} : Odd x → x ^ 2 % 4 = 1 := by
intro hx
unfold Odd at hx
rcases hx with ⟨_, rfl⟩
ring_nf
rw [add_assoc, ← add_mul, Int.add_mul_emod_self_right]
decide
lemma Int.eight_dvd_sq_sub_one_of_odd {k : ℤ} (hk : Odd k) : 8 ∣ k ^ 2 - 1 := by
rcases hk with ⟨m, rfl⟩
have eq : (2 * m + 1) ^ 2 - 1 = 4 * (m * (m + 1)) := by ring
simpa [eq] using (mul_dvd_mul_iff_left four_ne_zero).mpr (two_dvd_mul_add_one m)
lemma Nat.eight_dvd_sq_sub_one_of_odd {k : ℕ} (hk : Odd k) : 8 ∣ k ^ 2 - 1 := by
rcases hk with ⟨m, rfl⟩
have eq : (2 * m + 1) ^ 2 - 1 = 4 * (m * (m + 1)) := by ring_nf; grind
simpa [eq] using (mul_dvd_mul_iff_left four_ne_zero).mpr (two_dvd_mul_add_one m)
theorem Int.two_pow_two_pow_add_two_pow_two_pow {x y : ℤ} (hx : ¬2 ∣ x) (hxy : 4 ∣ x - y) (i : ℕ) :
emultiplicity 2 (x ^ 2 ^ i + y ^ 2 ^ i) = ↑(1 : ℕ) := by
have hx_odd : Odd x := by rwa [← Int.not_even_iff_odd, even_iff_two_dvd]
have hxy_even : Even (x - y) := even_iff_two_dvd.mpr (dvd_trans (by decide) hxy)
have hy_odd : Odd y := by simpa using hx_odd.sub_even hxy_even
refine emultiplicity_eq_coe.mpr ⟨?_, ?_⟩
· rw [pow_one, ← even_iff_two_dvd]
exact hx_odd.pow.add_odd hy_odd.pow
rcases i with - | i
· grind
suffices ∀ x : ℤ, Odd x → x ^ 2 ^ (i + 1) % 4 = 1 by
rw [show (2 ^ (1 + 1) : ℤ) = 4 by simp, Int.dvd_iff_emod_eq_zero, Int.add_emod,
this _ hx_odd, this _ hy_odd]
decide
intro x hx
rw [pow_succ', mul_comm, pow_mul, Int.sq_mod_four_eq_one_of_odd hx.pow]
theorem Int.two_pow_two_pow_sub_pow_two_pow {x y : ℤ} (n : ℕ) (hxy : 4 ∣ x - y) (hx : ¬2 ∣ x) :
emultiplicity 2 (x ^ 2 ^ n - y ^ 2 ^ n) = emultiplicity 2 (x - y) + n := by
simp only [pow_two_pow_sub_pow_two_pow n, emultiplicity_mul Int.prime_two,
Finset.emultiplicity_prod Int.prime_two, add_comm, Nat.cast_one, Finset.sum_const,
Finset.card_range, nsmul_one, Int.two_pow_two_pow_add_two_pow_two_pow hx hxy]
theorem Int.two_pow_sub_pow' {x y : ℤ} (n : ℕ) (hxy : 4 ∣ x - y) (hx : ¬2 ∣ x) :
emultiplicity 2 (x ^ n - y ^ n) = emultiplicity 2 (x - y) + emultiplicity (2 : ℤ) n := by
have hx_odd : Odd x := by rwa [← Int.not_even_iff_odd, even_iff_two_dvd]
have hxy_even : Even (x - y) := even_iff_two_dvd.mpr (dvd_trans (by decide) hxy)
have hy_odd : Odd y := by simpa using hx_odd.sub_even hxy_even
rcases n with - | n
· simp only [pow_zero, sub_self, emultiplicity_zero, Int.ofNat_zero, add_top]
have h : FiniteMultiplicity 2 n.succ := Nat.finiteMultiplicity_iff.mpr ⟨by simp, n.succ_pos⟩
simp only [Nat.succ_eq_add_one] at h
rcases emultiplicity_eq_coe.mp h.emultiplicity_eq_multiplicity with ⟨⟨k, hk⟩, hpn⟩
rw [hk, pow_mul, pow_mul, emultiplicity_pow_sub_pow_of_prime,
Int.two_pow_two_pow_sub_pow_two_pow _ hxy hx, ← hk]
· norm_cast
rw [h.emultiplicity_eq_multiplicity]
· exact Int.prime_two
· simpa only [even_iff_two_dvd] using hx_odd.pow.sub_odd hy_odd.pow
· simpa only [even_iff_two_dvd, ← Int.not_even_iff_odd] using hx_odd.pow
norm_cast
contrapose! hpn
rw [pow_succ]
conv_rhs => rw [hk]
exact mul_dvd_mul_left _ hpn
/-- **Lifting the exponent lemma** for `p = 2` -/
theorem Int.two_pow_sub_pow {x y : ℤ} {n : ℕ} (hxy : 2 ∣ x - y) (hx : ¬2 ∣ x) (hn : Even n) :
emultiplicity 2 (x ^ n - y ^ n) + 1 =
emultiplicity 2 (x + y) + emultiplicity 2 (x - y) + emultiplicity (2 : ℤ) n := by
have hy : Odd y := by
rw [← even_iff_two_dvd, Int.not_even_iff_odd] at hx
replace hxy := (@even_neg _ _ (x - y)).mpr (even_iff_two_dvd.mpr hxy)
convert Even.add_odd hxy hx
abel
obtain ⟨d, hd⟩ := hn
subst hd
simp only [← two_mul, pow_mul]
have hxy4 : 4 ∣ x ^ 2 - y ^ 2 := by
rw [Int.dvd_iff_emod_eq_zero, Int.sub_emod, Int.sq_mod_four_eq_one_of_odd _,
Int.sq_mod_four_eq_one_of_odd hy]
· simp
· simp only [← Int.not_even_iff_odd, even_iff_two_dvd, hx, not_false_iff]
rw [Int.two_pow_sub_pow' d hxy4 _, sq_sub_sq, ← Int.ofNat_mul_out,
emultiplicity_mul Int.prime_two, emultiplicity_mul Int.prime_two]
· suffices emultiplicity (2 : ℤ) ↑(2 : ℕ) = 1 by rw [this, add_comm 1, ← add_assoc]
norm_cast
rw [FiniteMultiplicity.emultiplicity_self]
rw [Nat.finiteMultiplicity_iff]
decide
· rw [← even_iff_two_dvd, Int.not_even_iff_odd]
apply Odd.pow
simp only [← Int.not_even_iff_odd, even_iff_two_dvd, hx, not_false_iff]
theorem Nat.two_pow_sub_pow {x y : ℕ} (hxy : 2 ∣ x - y) (hx : ¬2 ∣ x) {n : ℕ} (hn : Even n) :
emultiplicity 2 (x ^ n - y ^ n) + 1 =
emultiplicity 2 (x + y) + emultiplicity 2 (x - y) + emultiplicity 2 n := by
obtain hyx | hyx := le_total y x
· iterate 3 rw [← Int.natCast_emultiplicity]
simp only [Int.ofNat_sub hyx, Int.ofNat_sub (pow_le_pow_left' hyx _), Int.natCast_add,
Int.natCast_pow]
rw [← Int.natCast_dvd_natCast] at hx
rw [← Int.natCast_dvd_natCast, Int.ofNat_sub hyx] at hxy
convert Int.two_pow_sub_pow hxy hx hn using 2
rw [← Int.natCast_emultiplicity]
rfl
· simp only [Nat.sub_eq_zero_iff_le.mpr hyx,
Nat.sub_eq_zero_iff_le.mpr (pow_le_pow_left' hyx n), emultiplicity_zero,
top_add, add_top]
namespace padicValNat
variable {x y : ℕ}
theorem pow_two_sub_pow (hyx : y < x) (hxy : 2 ∣ x - y) (hx : ¬2 ∣ x) {n : ℕ} (hn : n ≠ 0)
(hneven : Even n) :
padicValNat 2 (x ^ n - y ^ n) + 1 =
padicValNat 2 (x + y) + padicValNat 2 (x - y) + padicValNat 2 n := by
simp only [← Nat.cast_inj (R := ℕ∞), Nat.cast_add]
iterate 4 rw [padicValNat_eq_emultiplicity]
· exact Nat.two_pow_sub_pow hxy hx hneven
· exact hn
· exact Nat.sub_ne_zero_of_lt hyx
· cutsat
· simp [← Nat.pos_iff_ne_zero, tsub_pos_iff_lt, Nat.pow_lt_pow_left hyx hn]
variable {p : ℕ} [hp : Fact p.Prime] (hp1 : Odd p)
include hp hp1
theorem pow_sub_pow (hyx : y < x) (hxy : p ∣ x - y) (hx : ¬p ∣ x) {n : ℕ} (hn : n ≠ 0) :
padicValNat p (x ^ n - y ^ n) = padicValNat p (x - y) + padicValNat p n := by
rw [← Nat.cast_inj (R := ℕ∞), Nat.cast_add]
iterate 3 rw [padicValNat_eq_emultiplicity]
· exact Nat.emultiplicity_pow_sub_pow hp.out hp1 hxy hx n
· exact hn
· exact Nat.sub_ne_zero_of_lt hyx
· exact Nat.sub_ne_zero_of_lt (Nat.pow_lt_pow_left hyx hn)
theorem pow_add_pow (hxy : p ∣ x + y) (hx : ¬p ∣ x) {n : ℕ} (hn : Odd n) :
padicValNat p (x ^ n + y ^ n) = padicValNat p (x + y) + padicValNat p n := by
rcases y with - | y
· contradiction
rw [← Nat.cast_inj (R := ℕ∞), Nat.cast_add]
iterate 3 rw [padicValNat_eq_emultiplicity]
· exact Nat.emultiplicity_pow_add_pow hp.out hp1 hxy hx hn
· exact (Odd.pos hn).ne'
· simp only [← Nat.pos_iff_ne_zero, add_pos_iff, Nat.succ_pos', or_true]
· exact (Nat.lt_add_left _ (pow_pos y.succ_pos _)).ne'
end padicValNat |
.lake/packages/mathlib/Mathlib/NumberTheory/LucasPrimality.lean | import Mathlib.Algebra.Field.ZMod
import Mathlib.RingTheory.IntegralDomain
/-!
# The Lucas test for primes
This file implements the Lucas test for primes (not to be confused with the Lucas-Lehmer test for
Mersenne primes). A number `a` witnesses that `n` is prime if `a` has order `n-1` in the
multiplicative group of integers mod `n`. This is checked by verifying that `a^(n-1) = 1 (mod n)`
and `a^d ≠ 1 (mod n)` for any divisor `d | n - 1`. This test is the basis of the Pratt primality
certificate.
## TODO
- Write a tactic that uses this theorem to generate Pratt primality certificates
- Integrate Pratt primality certificates into the norm_num primality verifier
## Implementation notes
Note that the proof for `lucas_primality` relies on analyzing the multiplicative group
modulo `p`. Despite this, the theorem still holds vacuously for `p = 0` and `p = 1`. In these
cases, we can take `q` to be any prime and see that `hd` does not hold, since `a^((p-1)/q)` reduces
to `1`.
-/
/-- If `a^(p-1) = 1 mod p`, but `a^((p-1)/q) ≠ 1 mod p` for all prime factors `q` of `p-1`, then `p`
is prime. This is true because `a` has order `p-1` in the multiplicative group mod `p`, so this
group must itself have order `p-1`, which only happens when `p` is prime.
-/
theorem lucas_primality (p : ℕ) (a : ZMod p) (ha : a ^ (p - 1) = 1)
(hd : ∀ q : ℕ, q.Prime → q ∣ p - 1 → a ^ ((p - 1) / q) ≠ 1) : p.Prime := by
have h : p ≠ 0 ∧ p ≠ 1 := by
constructor <;> rintro rfl <;> exact hd 2 Nat.prime_two (dvd_zero _) (pow_zero _)
have hp1 : 1 < p := Nat.one_lt_iff_ne_zero_and_ne_one.2 h
have : NeZero p := ⟨h.1⟩
rw [Nat.prime_iff_card_units]
apply (Nat.card_units_zmod_lt_sub_one hp1).antisymm
let a' : (ZMod p)ˣ := Units.mkOfMulEqOne a _ (by rwa [← pow_succ', tsub_add_eq_add_tsub hp1])
calc p - 1 = orderOf a := (orderOf_eq_of_pow_and_pow_div_prime (tsub_pos_of_lt hp1) ha hd).symm
_ = orderOf a' := orderOf_injective (Units.coeHom _) Units.val_injective a'
_ ≤ Fintype.card (ZMod p)ˣ := orderOf_le_card_univ
/-- If `p` is prime, then there exists an `a` such that `a^(p-1) = 1 mod p`
and `a^((p-1)/q) ≠ 1 mod p` for all prime factors `q` of `p-1`.
The multiplicative group mod `p` is cyclic, so `a` can be any generator of the group
(which must have order `p-1`).
-/
theorem reverse_lucas_primality (p : ℕ) (hP : p.Prime) :
∃ a : ZMod p, a ^ (p - 1) = 1 ∧ ∀ q : ℕ, q.Prime → q ∣ p - 1 → a ^ ((p - 1) / q) ≠ 1 := by
have : Fact p.Prime := ⟨hP⟩
obtain ⟨g, hg⟩ := IsCyclic.exists_generator (α := (ZMod p)ˣ)
have h1 : orderOf g = p - 1 := by
rwa [orderOf_eq_card_of_forall_mem_zpowers hg, Nat.card_eq_fintype_card,
← Nat.prime_iff_card_units]
have h2 := tsub_pos_iff_lt.2 hP.one_lt
rw [← orderOf_injective (Units.coeHom _) Units.val_injective _, orderOf_eq_iff h2] at h1
refine ⟨g, h1.1, fun q hq hqd ↦ ?_⟩
replace hq := hq.one_lt
exact h1.2 _ (Nat.div_lt_self h2 hq) (Nat.div_pos (Nat.le_of_dvd h2 hqd) (zero_lt_one.trans hq))
/-- A number `p` is prime if and only if there exists an `a` such that
`a^(p-1) = 1 mod p` and `a^((p-1)/q) ≠ 1 mod p` for all prime factors `q` of `p-1`.
-/
theorem lucas_primality_iff (p : ℕ) : p.Prime ↔
∃ a : ZMod p, a ^ (p - 1) = 1 ∧ ∀ q : ℕ, q.Prime → q ∣ p - 1 → a ^ ((p - 1) / q) ≠ 1 :=
⟨reverse_lucas_primality p, fun ⟨a, ⟨ha, hb⟩⟩ ↦ lucas_primality p a ha hb⟩ |
.lake/packages/mathlib/Mathlib/NumberTheory/ArithmeticFunction.lean | import Mathlib.Algebra.BigOperators.Ring.Finset
import Mathlib.Algebra.Module.BigOperators
import Mathlib.NumberTheory.Divisors
import Mathlib.Data.Nat.Squarefree
import Mathlib.Data.Nat.GCD.BigOperators
import Mathlib.Data.Nat.Factorization.Induction
import Mathlib.Data.Nat.Factorization.PrimePow
import Mathlib.Tactic.ArithMult
/-!
# Arithmetic Functions and Dirichlet Convolution
This file defines arithmetic functions, which are functions from `ℕ` to a specified type that map 0
to 0. In the literature, they are often instead defined as functions from `ℕ+`. These arithmetic
functions are endowed with a multiplication, given by Dirichlet convolution, and pointwise addition,
to form the Dirichlet ring.
## Main Definitions
* `ArithmeticFunction R` consists of functions `f : ℕ → R` such that `f 0 = 0`.
* An arithmetic function `f` `IsMultiplicative` when `x.Coprime y → f (x * y) = f x * f y`.
* The pointwise operations `pmul` and `ppow` differ from the multiplication
and power instances on `ArithmeticFunction R`, which use Dirichlet multiplication.
* `ζ` is the arithmetic function such that `ζ x = 1` for `0 < x`.
* `σ k` is the arithmetic function such that `σ k x = ∑ y ∈ divisors x, y ^ k` for `0 < x`.
* `pow k` is the arithmetic function such that `pow k x = x ^ k` for `0 < x`.
* `id` is the identity arithmetic function on `ℕ`.
* `ω n` is the number of distinct prime factors of `n`.
* `Ω n` is the number of prime factors of `n` counted with multiplicity.
* `μ` is the Möbius function (spelled `moebius` in code).
## Main Results
* Several forms of Möbius inversion:
* `sum_eq_iff_sum_mul_moebius_eq` for functions to a `CommRing`
* `sum_eq_iff_sum_smul_moebius_eq` for functions to an `AddCommGroup`
* `prod_eq_iff_prod_pow_moebius_eq` for functions to a `CommGroup`
* `prod_eq_iff_prod_pow_moebius_eq_of_nonzero` for functions to a `CommGroupWithZero`
* And variants that apply when the equalities only hold on a set `S : Set ℕ` such that
`m ∣ n → n ∈ S → m ∈ S`:
* `sum_eq_iff_sum_mul_moebius_eq_on` for functions to a `CommRing`
* `sum_eq_iff_sum_smul_moebius_eq_on` for functions to an `AddCommGroup`
* `prod_eq_iff_prod_pow_moebius_eq_on` for functions to a `CommGroup`
* `prod_eq_iff_prod_pow_moebius_eq_on_of_nonzero` for functions to a `CommGroupWithZero`
## Notation
The arithmetic functions `ζ`, `σ`, `ω`, `Ω` and `μ` have Greek letter names.
This notation is scpoed to the separate locales `ArithmeticFunction.zeta` for `ζ`,
`ArithmeticFunction.sigma` for `σ`, `ArithmeticFunction.omega` for `ω`,
`ArithmeticFunction.Omega` for `Ω`, and `ArithmeticFunction.Moebius` for `μ`,
to allow for selective access.
The arithmetic function $$n \mapsto \prod_{p \mid n} f(p)$$ is given custom notation
`∏ᵖ p ∣ n, f p` when applied to `n`.
## Tags
arithmetic functions, dirichlet convolution, divisors
-/
open Finset
open Nat
variable (R : Type*)
/-- An arithmetic function is a function from `ℕ` that maps 0 to 0. In the literature, they are
often instead defined as functions from `ℕ+`. Multiplication on `ArithmeticFunctions` is by
Dirichlet convolution. -/
def ArithmeticFunction [Zero R] :=
ZeroHom ℕ R
instance ArithmeticFunction.zero [Zero R] : Zero (ArithmeticFunction R) :=
inferInstanceAs (Zero (ZeroHom ℕ R))
instance [Zero R] : Inhabited (ArithmeticFunction R) := inferInstanceAs (Inhabited (ZeroHom ℕ R))
variable {R}
namespace ArithmeticFunction
section Zero
variable [Zero R]
instance : FunLike (ArithmeticFunction R) ℕ R :=
inferInstanceAs (FunLike (ZeroHom ℕ R) ℕ R)
@[simp]
theorem toFun_eq (f : ArithmeticFunction R) : f.toFun = f := rfl
@[simp]
theorem coe_mk (f : ℕ → R) (hf) : @DFunLike.coe (ArithmeticFunction R) _ _ _
(ZeroHom.mk f hf) = f := rfl
@[simp]
theorem map_zero {f : ArithmeticFunction R} : f 0 = 0 :=
ZeroHom.map_zero' f
theorem coe_inj {f g : ArithmeticFunction R} : (f : ℕ → R) = g ↔ f = g :=
DFunLike.coe_fn_eq
@[simp]
theorem zero_apply {x : ℕ} : (0 : ArithmeticFunction R) x = 0 :=
rfl
@[ext]
theorem ext ⦃f g : ArithmeticFunction R⦄ (h : ∀ x, f x = g x) : f = g :=
ZeroHom.ext h
section One
variable [One R]
instance one : One (ArithmeticFunction R) :=
⟨⟨fun x => ite (x = 1) 1 0, rfl⟩⟩
theorem one_apply {x : ℕ} : (1 : ArithmeticFunction R) x = ite (x = 1) 1 0 :=
rfl
@[simp]
theorem one_one : (1 : ArithmeticFunction R) 1 = 1 :=
rfl
@[simp]
theorem one_apply_ne {x : ℕ} (h : x ≠ 1) : (1 : ArithmeticFunction R) x = 0 :=
if_neg h
end One
end Zero
/-- Coerce an arithmetic function with values in `ℕ` to one with values in `R`. We cannot inline
this in `natCoe` because it gets unfolded too much. -/
@[coe]
def natToArithmeticFunction [AddMonoidWithOne R] :
(ArithmeticFunction ℕ) → (ArithmeticFunction R) :=
fun f => ⟨fun n => ↑(f n), by simp⟩
instance natCoe [AddMonoidWithOne R] : Coe (ArithmeticFunction ℕ) (ArithmeticFunction R) :=
⟨natToArithmeticFunction⟩
@[simp]
theorem natCoe_nat (f : ArithmeticFunction ℕ) : natToArithmeticFunction f = f :=
ext fun _ => cast_id _
@[simp]
theorem natCoe_apply [AddMonoidWithOne R] {f : ArithmeticFunction ℕ} {x : ℕ} :
(f : ArithmeticFunction R) x = f x :=
rfl
/-- Coerce an arithmetic function with values in `ℤ` to one with values in `R`. We cannot inline
this in `intCoe` because it gets unfolded too much. -/
@[coe]
def ofInt [AddGroupWithOne R] :
(ArithmeticFunction ℤ) → (ArithmeticFunction R) :=
fun f => ⟨fun n => ↑(f n), by simp⟩
instance intCoe [AddGroupWithOne R] : Coe (ArithmeticFunction ℤ) (ArithmeticFunction R) :=
⟨ofInt⟩
@[simp]
theorem intCoe_int (f : ArithmeticFunction ℤ) : ofInt f = f :=
ext fun _ => Int.cast_id
@[simp]
theorem intCoe_apply [AddGroupWithOne R] {f : ArithmeticFunction ℤ} {x : ℕ} :
(f : ArithmeticFunction R) x = f x := rfl
@[simp]
theorem coe_coe [AddGroupWithOne R] {f : ArithmeticFunction ℕ} :
((f : ArithmeticFunction ℤ) : ArithmeticFunction R) = (f : ArithmeticFunction R) := by
ext
simp
@[simp]
theorem natCoe_one [AddMonoidWithOne R] :
((1 : ArithmeticFunction ℕ) : ArithmeticFunction R) = 1 := by
ext n
simp [one_apply]
@[simp]
theorem intCoe_one [AddGroupWithOne R] : ((1 : ArithmeticFunction ℤ) :
ArithmeticFunction R) = 1 := by
ext n
simp [one_apply]
section AddMonoid
variable [AddMonoid R]
instance add : Add (ArithmeticFunction R) :=
⟨fun f g => ⟨fun n => f n + g n, by simp⟩⟩
@[simp]
theorem add_apply {f g : ArithmeticFunction R} {n : ℕ} : (f + g) n = f n + g n :=
rfl
instance instAddMonoid : AddMonoid (ArithmeticFunction R) :=
{ ArithmeticFunction.zero R,
ArithmeticFunction.add with
add_assoc := fun _ _ _ => ext fun _ => add_assoc _ _ _
zero_add := fun _ => ext fun _ => zero_add _
add_zero := fun _ => ext fun _ => add_zero _
nsmul := nsmulRec }
end AddMonoid
instance instAddMonoidWithOne [AddMonoidWithOne R] : AddMonoidWithOne (ArithmeticFunction R) :=
{ ArithmeticFunction.instAddMonoid,
ArithmeticFunction.one with
natCast := fun n => ⟨fun x => if x = 1 then (n : R) else 0, by simp⟩
natCast_zero := by ext; simp
natCast_succ := fun n => by ext x; by_cases h : x = 1 <;> simp [h] }
instance instAddCommMonoid [AddCommMonoid R] : AddCommMonoid (ArithmeticFunction R) :=
{ ArithmeticFunction.instAddMonoid with add_comm := fun _ _ => ext fun _ => add_comm _ _ }
instance [NegZeroClass R] : Neg (ArithmeticFunction R) where
neg f := ⟨fun n => -f n, by simp⟩
instance [AddGroup R] : AddGroup (ArithmeticFunction R) :=
{ ArithmeticFunction.instAddMonoid with
neg_add_cancel := fun _ => ext fun _ => neg_add_cancel _
zsmul := zsmulRec }
instance [AddCommGroup R] : AddCommGroup (ArithmeticFunction R) :=
{ show AddGroup (ArithmeticFunction R) by infer_instance with
add_comm := fun _ _ ↦ add_comm _ _ }
section SMul
variable {M : Type*} [Zero R] [AddCommMonoid M] [SMul R M]
/-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function
such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/
instance : SMul (ArithmeticFunction R) (ArithmeticFunction M) :=
⟨fun f g => ⟨fun n => ∑ x ∈ divisorsAntidiagonal n, f x.fst • g x.snd, by simp⟩⟩
@[simp]
theorem smul_apply {f : ArithmeticFunction R} {g : ArithmeticFunction M} {n : ℕ} :
(f • g) n = ∑ x ∈ divisorsAntidiagonal n, f x.fst • g x.snd :=
rfl
end SMul
/-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function
such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/
instance [Semiring R] : Mul (ArithmeticFunction R) :=
⟨(· • ·)⟩
@[simp]
theorem mul_apply [Semiring R] {f g : ArithmeticFunction R} {n : ℕ} :
(f * g) n = ∑ x ∈ divisorsAntidiagonal n, f x.fst * g x.snd :=
rfl
theorem mul_apply_one [Semiring R] {f g : ArithmeticFunction R} : (f * g) 1 = f 1 * g 1 := by simp
@[simp, norm_cast]
theorem natCoe_mul [Semiring R] {f g : ArithmeticFunction ℕ} :
(↑(f * g) : ArithmeticFunction R) = f * g := by
ext n
simp
@[simp, norm_cast]
theorem intCoe_mul [Ring R] {f g : ArithmeticFunction ℤ} :
(↑(f * g) : ArithmeticFunction R) = ↑f * g := by
ext n
simp
section Module
variable {M : Type*} [Semiring R] [AddCommMonoid M] [Module R M]
theorem mul_smul' (f g : ArithmeticFunction R) (h : ArithmeticFunction M) :
(f * g) • h = f • g • h := by
ext n
simp only [mul_apply, smul_apply, sum_smul, mul_smul, smul_sum, Finset.sum_sigma']
apply Finset.sum_nbij' (fun ⟨⟨_i, j⟩, ⟨k, l⟩⟩ ↦ ⟨(k, l * j), (l, j)⟩)
(fun ⟨⟨i, _j⟩, ⟨k, l⟩⟩ ↦ ⟨(i * k, l), (i, k)⟩) <;> aesop (add simp mul_assoc)
theorem one_smul' (b : ArithmeticFunction M) : (1 : ArithmeticFunction R) • b = b := by
ext x
rw [smul_apply]
by_cases x0 : x = 0
· simp [x0]
have h : {(1, x)} ⊆ divisorsAntidiagonal x := by simp [x0]
rw [← sum_subset h]
· simp
intro y ymem ynotMem
have y1ne : y.fst ≠ 1 := fun con => by simp_all [Prod.ext_iff]
simp [y1ne]
end Module
section Semiring
variable [Semiring R]
instance instMonoid : Monoid (ArithmeticFunction R) where
one_mul := one_smul'
mul_one := fun f => by
ext x
rw [mul_apply]
by_cases x0 : x = 0
· simp [x0]
have h : {(x, 1)} ⊆ divisorsAntidiagonal x := by simp [x0]
rw [← sum_subset h]
· simp
intro ⟨y₁, y₂⟩ ymem ynotMem
have y2ne : y₂ ≠ 1 := by
intro con
simp_all
simp [y2ne]
mul_assoc := mul_smul'
instance instSemiring : Semiring (ArithmeticFunction R) :=
{ ArithmeticFunction.instAddMonoidWithOne,
ArithmeticFunction.instMonoid,
ArithmeticFunction.instAddCommMonoid with
zero_mul := fun f => by
ext
simp
mul_zero := fun f => by
ext
simp
left_distrib := fun a b c => by
ext
simp [← sum_add_distrib, mul_add]
right_distrib := fun a b c => by
ext
simp [← sum_add_distrib, add_mul] }
end Semiring
instance [CommSemiring R] : CommSemiring (ArithmeticFunction R) :=
{ ArithmeticFunction.instSemiring with
mul_comm := fun f g => by
ext
rw [mul_apply, ← map_swap_divisorsAntidiagonal, sum_map]
simp [mul_comm] }
instance [CommRing R] : CommRing (ArithmeticFunction R) :=
{ ArithmeticFunction.instSemiring with
neg_add_cancel := neg_add_cancel
mul_comm := mul_comm
zsmul := (· • ·) }
instance {M : Type*} [Semiring R] [AddCommMonoid M] [Module R M] :
Module (ArithmeticFunction R) (ArithmeticFunction M) where
one_smul := one_smul'
mul_smul := mul_smul'
smul_add r x y := by
ext
simp only [sum_add_distrib, smul_add, smul_apply, add_apply]
smul_zero r := by
ext
simp only [smul_apply, sum_const_zero, smul_zero, zero_apply]
add_smul r s x := by
ext
simp only [add_smul, sum_add_distrib, smul_apply, add_apply]
zero_smul r := by
ext
simp only [smul_apply, sum_const_zero, zero_smul, zero_apply]
section Zeta
/-- `ζ 0 = 0`, otherwise `ζ x = 1`. The Dirichlet Series is the Riemann `ζ`. -/
def zeta : ArithmeticFunction ℕ :=
⟨fun x => ite (x = 0) 0 1, rfl⟩
@[inherit_doc]
scoped[ArithmeticFunction.zeta] notation "ζ" => ArithmeticFunction.zeta
open scoped zeta
@[simp]
theorem zeta_apply {x : ℕ} : ζ x = if x = 0 then 0 else 1 :=
rfl
theorem zeta_apply_ne {x : ℕ} (h : x ≠ 0) : ζ x = 1 :=
if_neg h
theorem zeta_eq_zero {x : ℕ} : ζ x = 0 ↔ x = 0 := by simp [zeta]
theorem zeta_pos {x : ℕ} : 0 < ζ x ↔ 0 < x := by simp [Nat.pos_iff_ne_zero]
theorem coe_zeta_smul_apply {M} [Semiring R] [AddCommMonoid M] [MulAction R M]
{f : ArithmeticFunction M} {x : ℕ} :
((↑ζ : ArithmeticFunction R) • f) x = ∑ i ∈ divisors x, f i := by
rw [smul_apply]
trans ∑ i ∈ divisorsAntidiagonal x, f i.snd
· refine sum_congr rfl fun i hi => ?_
rcases mem_divisorsAntidiagonal.1 hi with ⟨rfl, h⟩
rw [natCoe_apply, zeta_apply_ne (left_ne_zero_of_mul h), cast_one, one_smul]
· rw [← map_div_left_divisors, sum_map, Function.Embedding.coeFn_mk]
/-- `@[simp]`-normal form of `coe_zeta_smul_apply`. -/
@[simp]
theorem sum_divisorsAntidiagonal_eq_sum_divisors {M} [Semiring R] [AddCommMonoid M] [MulAction R M]
{f : ArithmeticFunction M} {x : ℕ} :
(∑ x ∈ x.divisorsAntidiagonal, if x.1 = 0 then (0 : R) • f x.2 else f x.2) =
∑ i ∈ divisors x, f i := by
rw [← coe_zeta_smul_apply (R := R)]
simp
theorem coe_zeta_mul_apply [Semiring R] {f : ArithmeticFunction R} {x : ℕ} :
(ζ * f) x = ∑ i ∈ divisors x, f i :=
coe_zeta_smul_apply
theorem coe_mul_zeta_apply [Semiring R] {f : ArithmeticFunction R} {x : ℕ} :
(f * ζ) x = ∑ i ∈ divisors x, f i := by
rw [mul_apply]
trans ∑ i ∈ divisorsAntidiagonal x, f i.1
· refine sum_congr rfl fun i hi => ?_
rcases mem_divisorsAntidiagonal.1 hi with ⟨rfl, h⟩
rw [natCoe_apply, zeta_apply_ne (right_ne_zero_of_mul h), cast_one, mul_one]
· rw [← map_div_right_divisors, sum_map, Function.Embedding.coeFn_mk]
theorem coe_zeta_mul_comm [Semiring R] {f : ArithmeticFunction R} : ζ * f = f * ζ := by
ext x
rw [coe_zeta_mul_apply, coe_mul_zeta_apply]
theorem zeta_mul_apply {f : ArithmeticFunction ℕ} {x : ℕ} : (ζ * f) x = ∑ i ∈ divisors x, f i := by
rw [← natCoe_nat ζ, coe_zeta_mul_apply]
theorem mul_zeta_apply {f : ArithmeticFunction ℕ} {x : ℕ} : (f * ζ) x = ∑ i ∈ divisors x, f i := by
rw [← natCoe_nat ζ, coe_mul_zeta_apply]
theorem zeta_mul_comm {f : ArithmeticFunction ℕ} : ζ * f = f * ζ := by
rw [← natCoe_nat ζ, coe_zeta_mul_comm]
end Zeta
open ArithmeticFunction
section Pmul
/-- This is the pointwise product of `ArithmeticFunction`s. -/
def pmul [MulZeroClass R] (f g : ArithmeticFunction R) : ArithmeticFunction R :=
⟨fun x => f x * g x, by simp⟩
@[simp]
theorem pmul_apply [MulZeroClass R] {f g : ArithmeticFunction R} {x : ℕ} : f.pmul g x = f x * g x :=
rfl
theorem pmul_comm [CommMonoidWithZero R] (f g : ArithmeticFunction R) : f.pmul g = g.pmul f := by
ext
simp [mul_comm]
lemma pmul_assoc [SemigroupWithZero R] (f₁ f₂ f₃ : ArithmeticFunction R) :
pmul (pmul f₁ f₂) f₃ = pmul f₁ (pmul f₂ f₃) := by
ext
simp only [pmul_apply, mul_assoc]
section NonAssocSemiring
variable [NonAssocSemiring R]
open scoped zeta
@[simp]
theorem pmul_zeta (f : ArithmeticFunction R) : f.pmul ↑ζ = f := by
ext x
cases x <;> simp
@[simp]
theorem zeta_pmul (f : ArithmeticFunction R) : (ζ : ArithmeticFunction R).pmul f = f := by
ext x
cases x <;> simp
end NonAssocSemiring
variable [Semiring R]
open scoped zeta
/-- This is the pointwise power of `ArithmeticFunction`s. -/
def ppow (f : ArithmeticFunction R) (k : ℕ) : ArithmeticFunction R :=
if h0 : k = 0 then ζ else ⟨fun x ↦ f x ^ k, by simp_rw [map_zero, zero_pow h0]⟩
@[simp]
theorem ppow_zero {f : ArithmeticFunction R} : f.ppow 0 = ζ := by rw [ppow, dif_pos rfl]
@[simp]
theorem ppow_one {f : ArithmeticFunction R} : f.ppow 1 = f := by
ext; simp [ppow]
@[simp]
theorem ppow_apply {f : ArithmeticFunction R} {k x : ℕ} (kpos : 0 < k) : f.ppow k x = f x ^ k := by
rw [ppow, dif_neg (Nat.ne_of_gt kpos), coe_mk]
theorem ppow_succ' {f : ArithmeticFunction R} {k : ℕ} : f.ppow (k + 1) = f.pmul (f.ppow k) := by
ext x
rw [ppow_apply (Nat.succ_pos k), _root_.pow_succ']
induction k <;> simp
theorem ppow_succ {f : ArithmeticFunction R} {k : ℕ} {kpos : 0 < k} :
f.ppow (k + 1) = (f.ppow k).pmul f := by
ext x
rw [ppow_apply (Nat.succ_pos k), _root_.pow_succ]
induction k <;> simp
end Pmul
section Pdiv
/-- This is the pointwise division of `ArithmeticFunction`s. -/
def pdiv [GroupWithZero R] (f g : ArithmeticFunction R) : ArithmeticFunction R :=
⟨fun n => f n / g n, by simp only [map_zero, div_zero]⟩
@[simp]
theorem pdiv_apply [GroupWithZero R] (f g : ArithmeticFunction R) (n : ℕ) :
pdiv f g n = f n / g n := rfl
/-- This result only holds for `DivisionSemiring`s instead of `GroupWithZero`s because zeta takes
values in ℕ, and hence the coercion requires an `AddMonoidWithOne`. TODO: Generalise zeta -/
@[simp]
theorem pdiv_zeta [DivisionSemiring R] (f : ArithmeticFunction R) :
pdiv f zeta = f := by
ext n
cases n <;> simp
end Pdiv
section ProdPrimeFactors
/-- The map $n \mapsto \prod_{p \mid n} f(p)$ as an arithmetic function -/
def prodPrimeFactors [CommMonoidWithZero R] (f : ℕ → R) : ArithmeticFunction R where
toFun d := if d = 0 then 0 else ∏ p ∈ d.primeFactors, f p
map_zero' := if_pos rfl
open Batteries.ExtendedBinder
/-- `∏ᵖ p ∣ n, f p` is custom notation for `prodPrimeFactors f n` -/
scoped syntax (name := bigproddvd) "∏ᵖ " extBinder " ∣ " term ", " term:67 : term
scoped macro_rules (kind := bigproddvd)
| `(∏ᵖ $x:ident ∣ $n, $r) => `(prodPrimeFactors (fun $x ↦ $r) $n)
@[simp]
theorem prodPrimeFactors_apply [CommMonoidWithZero R] {f : ℕ → R} {n : ℕ} (hn : n ≠ 0) :
∏ᵖ p ∣ n, f p = ∏ p ∈ n.primeFactors, f p :=
if_neg hn
end ProdPrimeFactors
/-- Multiplicative functions -/
def IsMultiplicative [MonoidWithZero R] (f : ArithmeticFunction R) : Prop :=
f 1 = 1 ∧ ∀ {m n : ℕ}, m.Coprime n → f (m * n) = f m * f n
namespace IsMultiplicative
section MonoidWithZero
variable [MonoidWithZero R]
@[simp, arith_mult]
theorem map_one {f : ArithmeticFunction R} (h : f.IsMultiplicative) : f 1 = 1 :=
h.1
@[simp]
theorem map_mul_of_coprime {f : ArithmeticFunction R} (hf : f.IsMultiplicative) {m n : ℕ}
(h : m.gcd n = 1) : f (m * n) = f m * f n :=
hf.2 h
end MonoidWithZero
open scoped Function in -- required for scoped `on` notation
theorem map_prod {ι : Type*} [CommMonoidWithZero R] (g : ι → ℕ) {f : ArithmeticFunction R}
(hf : f.IsMultiplicative) (s : Finset ι) (hs : (s : Set ι).Pairwise (Coprime on g)) :
f (∏ i ∈ s, g i) = ∏ i ∈ s, f (g i) := by
classical
induction s using Finset.induction_on with
| empty => simp [hf]
| insert _ _ has ih =>
rw [coe_insert, Set.pairwise_insert_of_symmetric (Coprime.symmetric.comap g)] at hs
rw [prod_insert has, prod_insert has, hf.map_mul_of_coprime, ih hs.1]
exact Coprime.prod_right fun i hi => hs.2 _ hi (hi.ne_of_notMem has).symm
theorem map_prod_of_prime [CommMonoidWithZero R] {f : ArithmeticFunction R}
(h_mult : ArithmeticFunction.IsMultiplicative f)
(t : Finset ℕ) (ht : ∀ p ∈ t, p.Prime) :
f (∏ a ∈ t, a) = ∏ a ∈ t, f a :=
map_prod _ h_mult t fun x hx y hy hxy => (coprime_primes (ht x hx) (ht y hy)).mpr hxy
theorem map_prod_of_subset_primeFactors [CommMonoidWithZero R] {f : ArithmeticFunction R}
(h_mult : ArithmeticFunction.IsMultiplicative f) (l : ℕ)
(t : Finset ℕ) (ht : t ⊆ l.primeFactors) :
f (∏ a ∈ t, a) = ∏ a ∈ t, f a :=
map_prod_of_prime h_mult t fun _ a => prime_of_mem_primeFactors (ht a)
theorem prod_primeFactors [CommMonoidWithZero R] {f : ArithmeticFunction R}
(h_mult : f.IsMultiplicative) {l : ℕ} (hl : Squarefree l) :
∏ a ∈ l.primeFactors, f a = f l := by
rw [← h_mult.map_prod_of_subset_primeFactors l _ Finset.Subset.rfl,
prod_primeFactors_of_squarefree hl]
theorem map_div_of_coprime [GroupWithZero R] {f : ArithmeticFunction R}
(hf : IsMultiplicative f) {l d : ℕ} (hdl : d ∣ l) (hl : (l / d).Coprime d) (hd : f d ≠ 0) :
f (l / d) = f l / f d := by
apply (div_eq_of_eq_mul hd ..).symm
rw [← hf.right hl, Nat.div_mul_cancel hdl]
@[arith_mult]
theorem natCast {f : ArithmeticFunction ℕ} [Semiring R] (h : f.IsMultiplicative) :
IsMultiplicative (f : ArithmeticFunction R) :=
⟨by simp [h], fun {m n} cop => by simp [h.2 cop]⟩
@[arith_mult]
theorem intCast {f : ArithmeticFunction ℤ} [Ring R] (h : f.IsMultiplicative) :
IsMultiplicative (f : ArithmeticFunction R) :=
⟨by simp [h], fun {m n} cop => by simp [h.2 cop]⟩
@[arith_mult]
theorem mul [CommSemiring R] {f g : ArithmeticFunction R} (hf : f.IsMultiplicative)
(hg : g.IsMultiplicative) : IsMultiplicative (f * g) := by
refine ⟨by simp [hf.1, hg.1], ?_⟩
simp only [mul_apply]
intro m n cop
rw [sum_mul_sum, ← sum_product']
symm
apply sum_nbij fun ((i, j), k, l) ↦ (i * k, j * l)
· rintro ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h
simp only [mem_divisorsAntidiagonal, Ne, mem_product] at h
rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩
simp only [mem_divisorsAntidiagonal, Nat.mul_eq_zero, Ne]
constructor
· ring
rw [Nat.mul_eq_zero] at *
apply not_or_intro ha hb
· simp only [Set.InjOn, mem_coe, mem_divisorsAntidiagonal, Ne, mem_product, Prod.mk_inj]
rintro ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩ ⟨⟨c1, c2⟩, ⟨d1, d2⟩⟩ hcd h
simp only at h
ext <;> dsimp only
· trans Nat.gcd (a1 * a2) (a1 * b1)
· rw [Nat.gcd_mul_left, cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one]
· rw [← hcd.1.1, ← hcd.2.1] at cop
rw [← hcd.1.1, h.1, Nat.gcd_mul_left,
cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one]
· trans Nat.gcd (a1 * a2) (a2 * b2)
· rw [mul_comm, Nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one,
mul_one]
· rw [← hcd.1.1, ← hcd.2.1] at cop
rw [← hcd.1.1, h.2, mul_comm, Nat.gcd_mul_left,
cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one, mul_one]
· trans Nat.gcd (b1 * b2) (a1 * b1)
· rw [mul_comm, Nat.gcd_mul_right,
cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, one_mul]
· rw [← hcd.1.1, ← hcd.2.1] at cop
rw [← hcd.2.1, h.1, mul_comm c1 d1, Nat.gcd_mul_left,
cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, mul_one]
· trans Nat.gcd (b1 * b2) (a2 * b2)
· rw [Nat.gcd_mul_right, cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one,
one_mul]
· rw [← hcd.1.1, ← hcd.2.1] at cop
rw [← hcd.2.1, h.2, Nat.gcd_mul_right,
cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul]
· simp only [Set.SurjOn, Set.subset_def, mem_coe, mem_divisorsAntidiagonal, Ne, mem_product,
Set.mem_image]
rintro ⟨b1, b2⟩ h
dsimp at h
use ((b1.gcd m, b2.gcd m), (b1.gcd n, b2.gcd n))
rw [← cop.gcd_mul _, ← cop.gcd_mul _, ← h.1, Nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop h.1,
Nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop.symm _]
· rw [Nat.mul_eq_zero, not_or] at h
simp [h.2.1, h.2.2]
rw [mul_comm n m, h.1]
· simp only [mem_divisorsAntidiagonal, Ne, mem_product]
rintro ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩
dsimp only
rw [hf.map_mul_of_coprime cop.coprime_mul_right.coprime_mul_right_right,
hg.map_mul_of_coprime cop.coprime_mul_left.coprime_mul_left_right]
ring
@[arith_mult]
theorem pmul [CommSemiring R] {f g : ArithmeticFunction R} (hf : f.IsMultiplicative)
(hg : g.IsMultiplicative) : IsMultiplicative (f.pmul g) :=
⟨by simp [hf, hg], fun {m n} cop => by
simp only [pmul_apply, hf.map_mul_of_coprime cop, hg.map_mul_of_coprime cop]
ring⟩
@[arith_mult]
theorem pdiv [CommGroupWithZero R] {f g : ArithmeticFunction R} (hf : IsMultiplicative f)
(hg : IsMultiplicative g) : IsMultiplicative (pdiv f g) :=
⟨by simp [hf, hg], fun {m n} cop => by
simp only [pdiv_apply, map_mul_of_coprime hf cop, map_mul_of_coprime hg cop,
div_eq_mul_inv, mul_inv]
apply mul_mul_mul_comm ⟩
/-- For any multiplicative function `f` and any `n > 0`,
we can evaluate `f n` by evaluating `f` at `p ^ k` over the factorization of `n` -/
theorem multiplicative_factorization [CommMonoidWithZero R] (f : ArithmeticFunction R)
(hf : f.IsMultiplicative) {n : ℕ} (hn : n ≠ 0) :
f n = n.factorization.prod fun p k => f (p ^ k) :=
Nat.multiplicative_factorization f (fun _ _ => hf.2) hf.1 hn
/-- A recapitulation of the definition of multiplicative that is simpler for proofs -/
theorem iff_ne_zero [MonoidWithZero R] {f : ArithmeticFunction R} :
IsMultiplicative f ↔
f 1 = 1 ∧ ∀ {m n : ℕ}, m ≠ 0 → n ≠ 0 → m.Coprime n → f (m * n) = f m * f n := by
refine and_congr_right' (forall₂_congr fun m n => ⟨fun h _ _ => h, fun h hmn => ?_⟩)
rcases eq_or_ne m 0 with (rfl | hm)
· simp
rcases eq_or_ne n 0 with (rfl | hn)
· simp
exact h hm hn hmn
/-- Two multiplicative functions `f` and `g` are equal if and only if
they agree on prime powers -/
theorem eq_iff_eq_on_prime_powers [CommMonoidWithZero R] (f : ArithmeticFunction R)
(hf : f.IsMultiplicative) (g : ArithmeticFunction R) (hg : g.IsMultiplicative) :
f = g ↔ ∀ p i : ℕ, Nat.Prime p → f (p ^ i) = g (p ^ i) := by
constructor
· intro h p i _
rw [h]
intro h
ext n
by_cases hn : n = 0
· rw [hn, ArithmeticFunction.map_zero, ArithmeticFunction.map_zero]
rw [multiplicative_factorization f hf hn, multiplicative_factorization g hg hn]
exact Finset.prod_congr rfl fun p hp ↦ h p _ (Nat.prime_of_mem_primeFactors hp)
@[arith_mult]
theorem prodPrimeFactors [CommMonoidWithZero R] (f : ℕ → R) :
IsMultiplicative (prodPrimeFactors f) := by
rw [iff_ne_zero]
simp only [ne_eq, one_ne_zero, not_false_eq_true, prodPrimeFactors_apply, primeFactors_one,
prod_empty, true_and]
intro x y hx hy hxy
have hxy₀ : x * y ≠ 0 := mul_ne_zero hx hy
rw [prodPrimeFactors_apply hxy₀, prodPrimeFactors_apply hx, prodPrimeFactors_apply hy,
Nat.primeFactors_mul hx hy, ← Finset.prod_union hxy.disjoint_primeFactors]
theorem prodPrimeFactors_add_of_squarefree [CommSemiring R] {f g : ArithmeticFunction R}
(hf : IsMultiplicative f) (hg : IsMultiplicative g) {n : ℕ} (hn : Squarefree n) :
∏ᵖ p ∣ n, (f + g) p = (f * g) n := by
rw [prodPrimeFactors_apply hn.ne_zero]
simp_rw [add_apply (f := f) (g := g)]
rw [Finset.prod_add, mul_apply, sum_divisorsAntidiagonal (f · * g ·),
← divisors_filter_squarefree_of_squarefree hn, sum_divisors_filter_squarefree hn.ne_zero,
factors_eq]
apply Finset.sum_congr rfl
intro t ht
rw [t.prod_val, Function.id_def,
← prod_primeFactors_sdiff_of_squarefree hn (Finset.mem_powerset.mp ht),
hf.map_prod_of_subset_primeFactors n t (Finset.mem_powerset.mp ht),
← hg.map_prod_of_subset_primeFactors n (_ \ t) Finset.sdiff_subset]
theorem lcm_apply_mul_gcd_apply [CommMonoidWithZero R] {f : ArithmeticFunction R}
(hf : f.IsMultiplicative) {x y : ℕ} :
f (x.lcm y) * f (x.gcd y) = f x * f y := by
by_cases hx : x = 0
· simp only [hx, f.map_zero, zero_mul, Nat.lcm_zero_left, Nat.gcd_zero_left]
by_cases hy : y = 0
· simp only [hy, f.map_zero, mul_zero, Nat.lcm_zero_right, Nat.gcd_zero_right, zero_mul]
have hgcd_ne_zero : x.gcd y ≠ 0 := gcd_ne_zero_left hx
have hlcm_ne_zero : x.lcm y ≠ 0 := lcm_ne_zero hx hy
have hfi_zero : ∀ {i}, f (i ^ 0) = 1 := by
intro i; rw [Nat.pow_zero, hf.1]
iterate 4 rw [hf.multiplicative_factorization f (by assumption),
Finsupp.prod_of_support_subset _ _ _ (fun _ _ => hfi_zero)
(s := (x.primeFactors ∪ y.primeFactors))]
· rw [← Finset.prod_mul_distrib, ← Finset.prod_mul_distrib]
apply Finset.prod_congr rfl
intro p _
rcases Nat.le_or_le (x.factorization p) (y.factorization p) with h | h <;>
simp only [factorization_lcm hx hy, Finsupp.sup_apply, h, sup_of_le_right,
sup_of_le_left, inf_of_le_right, Nat.factorization_gcd hx hy, Finsupp.inf_apply,
inf_of_le_left, mul_comm]
· apply Finset.subset_union_right
· apply Finset.subset_union_left
· rw [factorization_gcd hx hy, Finsupp.support_inf]
apply Finset.inter_subset_union
· simp [factorization_lcm hx hy]
theorem map_gcd [CommGroupWithZero R] {f : ArithmeticFunction R}
(hf : f.IsMultiplicative) {x y : ℕ} (hf_lcm : f (x.lcm y) ≠ 0) :
f (x.gcd y) = f x * f y / f (x.lcm y) := by
rw [← hf.lcm_apply_mul_gcd_apply, mul_div_cancel_left₀ _ hf_lcm]
theorem map_lcm [CommGroupWithZero R] {f : ArithmeticFunction R}
(hf : f.IsMultiplicative) {x y : ℕ} (hf_gcd : f (x.gcd y) ≠ 0) :
f (x.lcm y) = f x * f y / f (x.gcd y) := by
rw [← hf.lcm_apply_mul_gcd_apply, mul_div_cancel_right₀ _ hf_gcd]
theorem eq_zero_of_squarefree_of_dvd_eq_zero [MonoidWithZero R] {f : ArithmeticFunction R}
(hf : IsMultiplicative f) {m n : ℕ} (hn : Squarefree n) (hmn : m ∣ n)
(h_zero : f m = 0) :
f n = 0 := by
rcases hmn with ⟨k, rfl⟩
simp only [zero_mul, hf.map_mul_of_coprime (coprime_of_squarefree_mul hn), h_zero]
end IsMultiplicative
section SpecialFunctions
open scoped zeta
/-- The identity on `ℕ` as an `ArithmeticFunction`. -/
def id : ArithmeticFunction ℕ :=
⟨_root_.id, rfl⟩
@[simp]
theorem id_apply {x : ℕ} : id x = x :=
rfl
/-- `pow k n = n ^ k`, except `pow 0 0 = 0`. -/
def pow (k : ℕ) : ArithmeticFunction ℕ :=
id.ppow k
@[simp]
theorem pow_apply {k n : ℕ} : pow k n = if k = 0 ∧ n = 0 then 0 else n ^ k := by
cases k <;> simp [pow]
theorem pow_zero_eq_zeta : pow 0 = ζ := by
ext n
simp
theorem pow_one_eq_id : pow 1 = id := by
ext n
simp
/-- `σ k n` is the sum of the `k`th powers of the divisors of `n` -/
def sigma (k : ℕ) : ArithmeticFunction ℕ :=
⟨fun n => ∑ d ∈ divisors n, d ^ k, by simp⟩
@[inherit_doc]
scoped[ArithmeticFunction.sigma] notation "σ" => ArithmeticFunction.sigma
open scoped sigma
theorem sigma_apply {k n : ℕ} : σ k n = ∑ d ∈ divisors n, d ^ k :=
rfl
@[simp]
theorem sigma_eq_zero {k n : ℕ} : σ k n = 0 ↔ n = 0 := by
rcases eq_or_ne n 0 with rfl | hn
· simp
· refine iff_of_false ?_ hn
simp_rw [ArithmeticFunction.sigma_apply, Finset.sum_eq_zero_iff, not_forall]
use 1
simp [hn]
@[simp]
theorem sigma_pos_iff {k n} : 0 < σ k n ↔ 0 < n := by
simp [pos_iff_ne_zero]
theorem sigma_apply_prime_pow {k p i : ℕ} (hp : p.Prime) :
σ k (p ^ i) = ∑ j ∈ .range (i + 1), p ^ (j * k) := by
simp [sigma_apply, divisors_prime_pow hp, Nat.pow_mul]
theorem sigma_one_apply (n : ℕ) : σ 1 n = ∑ d ∈ divisors n, d := by simp [sigma_apply]
theorem sigma_one_apply_prime_pow {p i : ℕ} (hp : p.Prime) :
σ 1 (p ^ i) = ∑ k ∈ .range (i + 1), p ^ k := by
simp [sigma_apply_prime_pow hp]
theorem sigma_eq_sum_div (k n : ℕ) : sigma k n = ∑ d ∈ Nat.divisors n, (n / d) ^ k := by
rw [sigma_apply, ← Nat.sum_div_divisors]
theorem sigma_zero_apply (n : ℕ) : σ 0 n = #n.divisors := by simp [sigma_apply]
theorem sigma_zero_apply_prime_pow {p i : ℕ} (hp : p.Prime) : σ 0 (p ^ i) = i + 1 := by
simp [sigma_apply_prime_pow hp]
@[simp]
theorem sigma_one (k : ℕ) : σ k 1 = 1 := by
simp only [sigma_apply, divisors_one, sum_singleton, one_pow]
theorem sigma_pos (k n : ℕ) (hn0 : n ≠ 0) : 0 < σ k n := by
rwa [sigma_pos_iff, pos_iff_ne_zero]
theorem sigma_mono (k k' n : ℕ) (hk : k ≤ k') : σ k n ≤ σ k' n := by
simp_rw [sigma_apply]
gcongr with d hd
exact Nat.pos_of_mem_divisors hd
theorem zeta_mul_pow_eq_sigma {k : ℕ} : ζ * pow k = σ k := by
ext
rw [sigma, zeta_mul_apply]
apply sum_congr rfl
intro x hx
rw [pow_apply, if_neg (not_and_of_not_right _ _)]
contrapose! hx
simp [hx]
@[arith_mult]
theorem isMultiplicative_one [MonoidWithZero R] : IsMultiplicative (1 : ArithmeticFunction R) :=
IsMultiplicative.iff_ne_zero.2
⟨by simp, by
intro m n hm _hn hmn
rcases eq_or_ne m 1 with (rfl | hm')
· simp
rw [one_apply_ne, one_apply_ne hm', zero_mul]
rw [Ne, mul_eq_one, not_and_or]
exact Or.inl hm'⟩
@[arith_mult]
theorem isMultiplicative_zeta : IsMultiplicative ζ :=
IsMultiplicative.iff_ne_zero.2 ⟨by simp, by simp +contextual⟩
@[arith_mult]
theorem isMultiplicative_id : IsMultiplicative ArithmeticFunction.id :=
⟨rfl, fun {_ _} _ => rfl⟩
@[arith_mult]
theorem IsMultiplicative.ppow [CommSemiring R] {f : ArithmeticFunction R} (hf : f.IsMultiplicative)
{k : ℕ} : IsMultiplicative (f.ppow k) := by
induction k with
| zero => exact isMultiplicative_zeta.natCast
| succ k hi => rw [ppow_succ']; apply hf.pmul hi
@[arith_mult]
theorem isMultiplicative_pow {k : ℕ} : IsMultiplicative (pow k) :=
isMultiplicative_id.ppow
@[arith_mult]
theorem isMultiplicative_sigma {k : ℕ} : IsMultiplicative (σ k) := by
rw [← zeta_mul_pow_eq_sigma]
apply isMultiplicative_zeta.mul isMultiplicative_pow
theorem _root_.Nat.card_divisors {n : ℕ} (hn : n ≠ 0) :
#n.divisors = n.primeFactors.prod (n.factorization · + 1) := by
rw [← sigma_zero_apply, isMultiplicative_sigma.multiplicative_factorization _ hn]
exact Finset.prod_congr n.support_factorization fun _ h =>
sigma_zero_apply_prime_pow <| Nat.prime_of_mem_primeFactors h
@[simp]
theorem _root_.Nat.divisors_card_eq_one_iff (n : ℕ) : #n.divisors = 1 ↔ n = 1 := by
rcases eq_or_ne n 0 with rfl | hn
· simp
· refine ⟨fun h ↦ ?_, fun h ↦ by simp [h]⟩
exact (card_le_one.mp h.le 1 (one_mem_divisors.mpr hn) n (n.mem_divisors_self hn)).symm
/-- `sigma_eq_one_iff` is to be preferred. -/
private theorem sigma_zero_eq_one_iff (n : ℕ) : σ 0 n = 1 ↔ n = 1 := by
simp [sigma_zero_apply]
@[simp]
theorem sigma_eq_one_iff (k n : ℕ) : σ k n = 1 ↔ n = 1 := by
by_cases hn0 : n = 0
· subst hn0
simp
constructor
· intro h
rw [← sigma_zero_eq_one_iff]
have zero_lt_sigma := sigma_pos 0 n hn0
have sigma_zero_le_sigma := sigma_mono 0 k n (Nat.zero_le k)
cutsat
· rintro rfl
simp
theorem sigma_eq_prod_primeFactors_sum_range_factorization_pow_mul {k n : ℕ} (hn : n ≠ 0) :
σ k n = ∏ p ∈ n.primeFactors, ∑ i ∈ .range (n.factorization p + 1), p ^ (i * k) := by
rw [isMultiplicative_sigma.multiplicative_factorization _ hn]
exact Finset.prod_congr n.support_factorization fun _ h ↦
sigma_apply_prime_pow <| Nat.prime_of_mem_primeFactors h
theorem _root_.Nat.sum_divisors {n : ℕ} (hn : n ≠ 0) :
∑ d ∈ n.divisors, d = ∏ p ∈ n.primeFactors, ∑ k ∈ .range (n.factorization p + 1), p ^ k := by
rw [← sigma_one_apply, isMultiplicative_sigma.multiplicative_factorization _ hn]
exact Finset.prod_congr n.support_factorization fun _ h =>
sigma_one_apply_prime_pow <| Nat.prime_of_mem_primeFactors h
/-- `Ω n` is the number of prime factors of `n`. -/
def cardFactors : ArithmeticFunction ℕ :=
⟨fun n => n.primeFactorsList.length, by simp⟩
@[inherit_doc]
scoped[ArithmeticFunction.Omega] notation "Ω" => ArithmeticFunction.cardFactors
open scoped Omega
theorem cardFactors_apply {n : ℕ} : Ω n = n.primeFactorsList.length :=
rfl
lemma cardFactors_zero : Ω 0 = 0 := by simp
@[simp] theorem cardFactors_one : Ω 1 = 0 := by simp [cardFactors_apply]
@[simp]
theorem cardFactors_eq_zero_iff_eq_zero_or_one {n : ℕ} : Ω n = 0 ↔ n = 0 ∨ n = 1 := by
rw [cardFactors_apply, List.length_eq_zero_iff, primeFactorsList_eq_nil]
@[simp]
theorem cardFactors_pos_iff_one_lt {n : ℕ} : 0 < Ω n ↔ 1 < n := by
rw [cardFactors_apply, List.length_pos_iff, primeFactorsList_ne_nil]
@[simp]
theorem cardFactors_eq_one_iff_prime {n : ℕ} : Ω n = 1 ↔ n.Prime := by
refine ⟨fun h => ?_, fun h => List.length_eq_one_iff.2 ⟨n, primeFactorsList_prime h⟩⟩
cases n with | zero => simp at h | succ n =>
rcases List.length_eq_one_iff.1 h with ⟨x, hx⟩
rw [← prod_primeFactorsList n.add_one_ne_zero, hx, List.prod_singleton]
apply prime_of_mem_primeFactorsList
rw [hx, List.mem_singleton]
theorem cardFactors_mul {m n : ℕ} (m0 : m ≠ 0) (n0 : n ≠ 0) : Ω (m * n) = Ω m + Ω n := by
rw [cardFactors_apply, cardFactors_apply, cardFactors_apply, ← Multiset.coe_card, ← factors_eq,
UniqueFactorizationMonoid.normalizedFactors_mul m0 n0, factors_eq, factors_eq,
Multiset.card_add, Multiset.coe_card, Multiset.coe_card]
theorem cardFactors_multiset_prod {s : Multiset ℕ} (h0 : s.prod ≠ 0) :
Ω s.prod = (Multiset.map Ω s).sum := by
induction s using Multiset.induction_on with
| empty => simp
| cons ih => simp_all [cardFactors_mul, not_or]
@[simp]
theorem cardFactors_apply_prime {p : ℕ} (hp : p.Prime) : Ω p = 1 :=
cardFactors_eq_one_iff_prime.2 hp
lemma cardFactors_pow {m k : ℕ} : Ω (m ^ k) = k * Ω m := by
by_cases hm : m = 0
· subst hm
cases k <;> simp
induction k with
| zero => simp
| succ n ih =>
rw [pow_succ, cardFactors_mul (pow_ne_zero n hm) hm, ih]
ring
@[simp]
theorem cardFactors_apply_prime_pow {p k : ℕ} (hp : p.Prime) : Ω (p ^ k) = k := by
simp [cardFactors_pow, hp]
theorem cardFactors_eq_sum_factorization {n : ℕ} :
Ω n = n.factorization.sum fun _ k => k := by
simp [cardFactors_apply, ← List.sum_toFinset_count_eq_length, Finsupp.sum]
/-- `ω n` is the number of distinct prime factors of `n`. -/
def cardDistinctFactors : ArithmeticFunction ℕ :=
⟨fun n => n.primeFactorsList.dedup.length, by simp⟩
@[inherit_doc]
scoped[ArithmeticFunction.omega] notation "ω" => ArithmeticFunction.cardDistinctFactors
open scoped omega
theorem cardDistinctFactors_zero : ω 0 = 0 := by simp
@[simp]
theorem cardDistinctFactors_one : ω 1 = 0 := by simp [cardDistinctFactors]
theorem cardDistinctFactors_apply {n : ℕ} : ω n = n.primeFactorsList.dedup.length :=
rfl
@[simp]
theorem cardDistinctFactors_eq_zero {n : ℕ} : ω n = 0 ↔ n ≤ 1 := by
simp [cardDistinctFactors_apply, Nat.le_one_iff_eq_zero_or_eq_one]
@[simp]
theorem cardDistinctFactors_pos {n : ℕ} : 0 < ω n ↔ 1 < n := by simp [pos_iff_ne_zero]
theorem cardDistinctFactors_eq_cardFactors_iff_squarefree {n : ℕ} (h0 : n ≠ 0) :
ω n = Ω n ↔ Squarefree n := by
rw [squarefree_iff_nodup_primeFactorsList h0, cardDistinctFactors_apply]
constructor <;> intro h
· rw [← n.primeFactorsList.dedup_sublist.eq_of_length h]
apply List.nodup_dedup
· simp [h.dedup, cardFactors]
theorem cardDistinctFactors_eq_one_iff {n : ℕ} : ω n = 1 ↔ IsPrimePow n := by
rw [ArithmeticFunction.cardDistinctFactors_apply, isPrimePow_iff_card_primeFactors_eq_one,
← Nat.toFinset_factors, List.card_toFinset]
@[simp]
theorem cardDistinctFactors_apply_prime_pow {p k : ℕ} (hp : p.Prime) (hk : k ≠ 0) :
ω (p ^ k) = 1 :=
cardDistinctFactors_eq_one_iff.mpr <| hp.isPrimePow.pow hk
@[simp]
theorem cardDistinctFactors_apply_prime {p : ℕ} (hp : p.Prime) : ω p = 1 := by
rw [← pow_one p, cardDistinctFactors_apply_prime_pow hp one_ne_zero]
theorem cardDistinctFactors_mul {m n : ℕ} (h : m.Coprime n) : ω (m * n) = ω m + ω n := by
simp [cardDistinctFactors_apply, Nat.perm_primeFactorsList_mul_of_coprime h |>.dedup |>.length_eq,
Nat.coprime_primeFactorsList_disjoint h |>.dedup_append]
open scoped Function in
theorem cardDistinctFactors_prod {ι : Type*} {s : Finset ι} {f : ι → ℕ}
(h : (s : Set ι).Pairwise (Nat.Coprime on f)) : ω (∏ i ∈ s, f i) = ∑ i ∈ s, ω (f i) := by
induction s using Finset.cons_induction_on with
| empty => simp
| cons a s ha ih =>
rw [prod_cons, sum_cons, cardDistinctFactors_mul, ih]
· exact fun {x} hx {y} hy hxy => h (by simp [hx]) (by simp [hy]) hxy
· exact Coprime.prod_right fun i hi =>
h (by simp) (by simp [hi]) (ne_of_mem_of_not_mem hi ha).symm
/-- `μ` is the Möbius function. If `n` is squarefree with an even number of distinct prime factors,
`μ n = 1`. If `n` is squarefree with an odd number of distinct prime factors, `μ n = -1`.
If `n` is not squarefree, `μ n = 0`. -/
def moebius : ArithmeticFunction ℤ :=
⟨fun n => if Squarefree n then (-1) ^ cardFactors n else 0, by simp⟩
@[inherit_doc]
scoped[ArithmeticFunction.Moebius] notation "μ" => ArithmeticFunction.moebius
open scoped Moebius
@[simp]
theorem moebius_apply_of_squarefree {n : ℕ} (h : Squarefree n) : μ n = (-1) ^ cardFactors n :=
if_pos h
@[simp]
theorem moebius_eq_zero_of_not_squarefree {n : ℕ} (h : ¬Squarefree n) : μ n = 0 :=
if_neg h
theorem moebius_apply_one : μ 1 = 1 := by simp
theorem moebius_ne_zero_iff_squarefree {n : ℕ} : μ n ≠ 0 ↔ Squarefree n := by
constructor <;> intro h
· contrapose! h
simp [h]
· simp [h]
theorem moebius_eq_or (n : ℕ) : μ n = 0 ∨ μ n = 1 ∨ μ n = -1 := by
simp only [moebius, coe_mk]
split_ifs
· right
exact neg_one_pow_eq_or ..
· left
rfl
theorem moebius_ne_zero_iff_eq_or {n : ℕ} : μ n ≠ 0 ↔ μ n = 1 ∨ μ n = -1 := by
have := moebius_eq_or n
cutsat
theorem moebius_sq_eq_one_of_squarefree {l : ℕ} (hl : Squarefree l) : μ l ^ 2 = 1 := by
rw [moebius_apply_of_squarefree hl, ← pow_mul, mul_comm, pow_mul, neg_one_sq, one_pow]
theorem abs_moebius_eq_one_of_squarefree {l : ℕ} (hl : Squarefree l) : |μ l| = 1 := by
simp only [moebius_apply_of_squarefree hl, abs_pow, abs_neg, abs_one, one_pow]
theorem moebius_sq {n : ℕ} :
μ n ^ 2 = if Squarefree n then 1 else 0 := by
split_ifs with h
· exact moebius_sq_eq_one_of_squarefree h
· simp only [moebius_eq_zero_of_not_squarefree h,
zero_pow (show 2 ≠ 0 by simp)]
theorem abs_moebius {n : ℕ} :
|μ n| = if Squarefree n then 1 else 0 := by
split_ifs with h
· exact abs_moebius_eq_one_of_squarefree h
· simp only [moebius_eq_zero_of_not_squarefree h, abs_zero]
theorem abs_moebius_le_one {n : ℕ} : |μ n| ≤ 1 := by
rw [abs_moebius, apply_ite (· ≤ 1)]
simp
theorem moebius_apply_prime {p : ℕ} (hp : p.Prime) : μ p = -1 := by
rw [moebius_apply_of_squarefree hp.squarefree, cardFactors_apply_prime hp, pow_one]
theorem moebius_apply_prime_pow {p k : ℕ} (hp : p.Prime) (hk : k ≠ 0) :
μ (p ^ k) = if k = 1 then -1 else 0 := by
split_ifs with h
· rw [h, pow_one, moebius_apply_prime hp]
rw [moebius_eq_zero_of_not_squarefree]
rw [squarefree_pow_iff hp.ne_one hk, not_and_or]
exact Or.inr h
theorem moebius_apply_isPrimePow_not_prime {n : ℕ} (hn : IsPrimePow n) (hn' : ¬n.Prime) :
μ n = 0 := by
obtain ⟨p, k, hp, hk, rfl⟩ := (isPrimePow_nat_iff _).1 hn
rw [moebius_apply_prime_pow hp hk.ne', if_neg]
rintro rfl
exact hn' (by simpa)
@[arith_mult]
theorem isMultiplicative_moebius : IsMultiplicative μ := by
rw [IsMultiplicative.iff_ne_zero]
refine ⟨by simp, fun {n m} hn hm hnm => ?_⟩
simp only [moebius, coe_mk,
squarefree_mul hnm, ite_zero_mul_ite_zero,
cardFactors_mul hn hm, pow_add]
theorem IsMultiplicative.prodPrimeFactors_one_add_of_squarefree [CommSemiring R]
{f : ArithmeticFunction R} (h_mult : f.IsMultiplicative) {n : ℕ} (hn : Squarefree n) :
∏ p ∈ n.primeFactors, (1 + f p) = ∑ d ∈ n.divisors, f d := by
trans (∏ᵖ p ∣ n, ((ζ : ArithmeticFunction R) + f) p)
· simp_rw [prodPrimeFactors_apply hn.ne_zero, add_apply, natCoe_apply]
apply Finset.prod_congr rfl; intro p hp
rw [zeta_apply_ne (prime_of_mem_primeFactorsList <| List.mem_toFinset.mp hp).ne_zero, cast_one]
rw [isMultiplicative_zeta.natCast.prodPrimeFactors_add_of_squarefree h_mult hn,
coe_zeta_mul_apply]
theorem IsMultiplicative.prodPrimeFactors_one_sub_of_squarefree [CommRing R]
(f : ArithmeticFunction R) (hf : f.IsMultiplicative) {n : ℕ} (hn : Squarefree n) :
∏ p ∈ n.primeFactors, (1 - f p) = ∑ d ∈ n.divisors, μ d * f d := by
trans (∏ p ∈ n.primeFactors, (1 + (ArithmeticFunction.pmul (μ : ArithmeticFunction R) f) p))
· apply Finset.prod_congr rfl; intro p hp
rw [pmul_apply, intCoe_apply, ArithmeticFunction.moebius_apply_prime
(prime_of_mem_primeFactorsList (List.mem_toFinset.mp hp))]
ring
· rw [(isMultiplicative_moebius.intCast.pmul hf).prodPrimeFactors_one_add_of_squarefree hn]
simp_rw [pmul_apply, intCoe_apply]
open UniqueFactorizationMonoid
@[simp]
theorem moebius_mul_coe_zeta : (μ * ζ : ArithmeticFunction ℤ) = 1 := by
ext n
induction n using recOnPosPrimePosCoprime with
| zero => rw [ZeroHom.map_zero, ZeroHom.map_zero]
| one => simp
| prime_pow p n hp hn =>
rw [coe_mul_zeta_apply, sum_divisors_prime_pow hp, sum_range_succ']
simp_rw [Nat.pow_zero, moebius_apply_one,
moebius_apply_prime_pow hp (Nat.succ_ne_zero _), Nat.succ_inj, sum_ite_eq', mem_range,
if_pos hn, neg_add_cancel]
rw [one_apply_ne]
rw [Ne, pow_eq_one_iff]
· exact hp.ne_one
· exact hn.ne'
| coprime a b _ha _hb hab ha' hb' =>
rw [IsMultiplicative.map_mul_of_coprime _ hab, ha', hb',
IsMultiplicative.map_mul_of_coprime isMultiplicative_one hab]
exact isMultiplicative_moebius.mul isMultiplicative_zeta.natCast
@[simp]
theorem coe_zeta_mul_moebius : (ζ * μ : ArithmeticFunction ℤ) = 1 := by
rw [mul_comm, moebius_mul_coe_zeta]
@[simp]
theorem coe_moebius_mul_coe_zeta [Ring R] : (μ * ζ : ArithmeticFunction R) = 1 := by
rw [← coe_coe, ← intCoe_mul, moebius_mul_coe_zeta, intCoe_one]
@[simp]
theorem coe_zeta_mul_coe_moebius [Ring R] : (ζ * μ : ArithmeticFunction R) = 1 := by
rw [← coe_coe, ← intCoe_mul, coe_zeta_mul_moebius, intCoe_one]
section CommRing
variable [CommRing R]
instance : Invertible (ζ : ArithmeticFunction R) where
invOf := μ
invOf_mul_self := coe_moebius_mul_coe_zeta
mul_invOf_self := coe_zeta_mul_coe_moebius
/-- A unit in `ArithmeticFunction R` that evaluates to `ζ`, with inverse `μ`. -/
def zetaUnit : (ArithmeticFunction R)ˣ :=
⟨ζ, μ, coe_zeta_mul_coe_moebius, coe_moebius_mul_coe_zeta⟩
@[simp]
theorem coe_zetaUnit : ((zetaUnit : (ArithmeticFunction R)ˣ) : ArithmeticFunction R) = ζ :=
rfl
@[simp]
theorem inv_zetaUnit : ((zetaUnit⁻¹ : (ArithmeticFunction R)ˣ) : ArithmeticFunction R) = μ :=
rfl
end CommRing
/-- Möbius inversion for functions to an `AddCommGroup`. -/
theorem sum_eq_iff_sum_smul_moebius_eq [AddCommGroup R] {f g : ℕ → R} :
(∀ n > 0, ∑ i ∈ n.divisors, f i = g n) ↔
∀ n > 0, ∑ x ∈ n.divisorsAntidiagonal, μ x.fst • g x.snd = f n := by
let f' : ArithmeticFunction R := ⟨fun x => if x = 0 then 0 else f x, if_pos rfl⟩
let g' : ArithmeticFunction R := ⟨fun x => if x = 0 then 0 else g x, if_pos rfl⟩
trans (ζ : ArithmeticFunction ℤ) • f' = g'
· rw [ArithmeticFunction.ext_iff]
apply forall_congr'
intro n
cases n with
| zero => simp
| succ n =>
rw [coe_zeta_smul_apply]
simp only [forall_prop_of_true, succ_pos']
simp only [f', g', coe_mk, succ_ne_zero, ite_false]
rw [sum_congr rfl fun x hx => ?_]
rw [if_neg (Nat.pos_of_mem_divisors hx).ne']
trans μ • g' = f'
· constructor <;> intro h
· rw [← h, ← mul_smul, moebius_mul_coe_zeta, one_smul]
· rw [← h, ← mul_smul, coe_zeta_mul_moebius, one_smul]
· rw [ArithmeticFunction.ext_iff]
apply forall_congr'
intro n
cases n with
| zero => simp
| succ n =>
simp only [forall_prop_of_true, succ_pos', smul_apply, f', g', coe_mk, succ_ne_zero,
ite_false]
rw [sum_congr rfl fun x hx => ?_]
simp [if_neg (Nat.pos_of_mem_divisors (snd_mem_divisors_of_mem_antidiagonal hx)).ne']
/-- Möbius inversion for functions to a `Ring`. -/
theorem sum_eq_iff_sum_mul_moebius_eq [NonAssocRing R] {f g : ℕ → R} :
(∀ n > 0, ∑ i ∈ n.divisors, f i = g n) ↔
∀ n > 0, ∑ x ∈ n.divisorsAntidiagonal, (μ x.fst : R) * g x.snd = f n := by
rw [sum_eq_iff_sum_smul_moebius_eq]
apply forall_congr'
refine fun a => imp_congr_right fun _ => (sum_congr rfl fun x _hx => ?_).congr_left
rw [zsmul_eq_mul]
/-- Möbius inversion for functions to a `CommGroup`. -/
theorem prod_eq_iff_prod_pow_moebius_eq [CommGroup R] {f g : ℕ → R} :
(∀ n > 0, ∏ i ∈ n.divisors, f i = g n) ↔
∀ n > 0, ∏ x ∈ n.divisorsAntidiagonal, g x.snd ^ μ x.fst = f n :=
@sum_eq_iff_sum_smul_moebius_eq (Additive R) _ _ _
/-- Möbius inversion for functions to a `CommGroupWithZero`. -/
theorem prod_eq_iff_prod_pow_moebius_eq_of_nonzero [CommGroupWithZero R] {f g : ℕ → R}
(hf : ∀ n : ℕ, 0 < n → f n ≠ 0) (hg : ∀ n : ℕ, 0 < n → g n ≠ 0) :
(∀ n > 0, ∏ i ∈ n.divisors, f i = g n) ↔
∀ n > 0, ∏ x ∈ n.divisorsAntidiagonal, g x.snd ^ μ x.fst = f n := by
refine
Iff.trans
(Iff.trans (forall_congr' fun n => ?_)
(@prod_eq_iff_prod_pow_moebius_eq Rˣ _
(fun n => if h : 0 < n then Units.mk0 (f n) (hf n h) else 1) fun n =>
if h : 0 < n then Units.mk0 (g n) (hg n h) else 1))
(forall_congr' fun n => ?_) <;>
refine imp_congr_right fun hn => ?_
· dsimp
rw [dif_pos hn, ← Units.val_inj, ← Units.coeHom_apply, map_prod, Units.val_mk0,
prod_congr rfl _]
intro x hx
rw [dif_pos (Nat.pos_of_mem_divisors hx), Units.coeHom_apply, Units.val_mk0]
· dsimp
rw [dif_pos hn, ← Units.val_inj, ← Units.coeHom_apply, map_prod, Units.val_mk0,
prod_congr rfl _]
intro x hx
rw [dif_pos (Nat.pos_of_mem_divisors (Nat.snd_mem_divisors_of_mem_antidiagonal hx)),
Units.coeHom_apply, Units.val_zpow_eq_zpow_val, Units.val_mk0]
/-- Möbius inversion for functions to an `AddCommGroup`, where the equalities only hold on a
well-behaved set. -/
theorem sum_eq_iff_sum_smul_moebius_eq_on [AddCommGroup R] {f g : ℕ → R}
(s : Set ℕ) (hs : ∀ m n, m ∣ n → n ∈ s → m ∈ s) :
(∀ n > 0, n ∈ s → (∑ i ∈ n.divisors, f i) = g n) ↔
∀ n > 0, n ∈ s → (∑ x ∈ n.divisorsAntidiagonal, μ x.fst • g x.snd) = f n := by
constructor
· intro h
let G := fun (n : ℕ) => (∑ i ∈ n.divisors, f i)
intro n hn hnP
suffices ∑ d ∈ n.divisors, μ (n/d) • G d = f n by
rw [Nat.sum_divisorsAntidiagonal' (f := fun x y => μ x • g y), ← this, sum_congr rfl]
intro d hd
rw [← h d (Nat.pos_of_mem_divisors hd) <| hs d n (Nat.dvd_of_mem_divisors hd) hnP]
rw [← Nat.sum_divisorsAntidiagonal' (f := fun x y => μ x • G y)]
apply sum_eq_iff_sum_smul_moebius_eq.mp _ n hn
intro _ _; rfl
· intro h
let F := fun (n : ℕ) => ∑ x ∈ n.divisorsAntidiagonal, μ x.fst • g x.snd
intro n hn hnP
suffices ∑ d ∈ n.divisors, F d = g n by
rw [← this, sum_congr rfl]
intro d hd
rw [← h d (Nat.pos_of_mem_divisors hd) <| hs d n (Nat.dvd_of_mem_divisors hd) hnP]
apply sum_eq_iff_sum_smul_moebius_eq.mpr _ n hn
intro _ _; rfl
theorem sum_eq_iff_sum_smul_moebius_eq_on' [AddCommGroup R] {f g : ℕ → R}
(s : Set ℕ) (hs : ∀ m n, m ∣ n → n ∈ s → m ∈ s) (hs₀ : 0 ∉ s) :
(∀ n ∈ s, (∑ i ∈ n.divisors, f i) = g n) ↔
∀ n ∈ s, (∑ x ∈ n.divisorsAntidiagonal, μ x.fst • g x.snd) = f n := by
have : ∀ P : ℕ → Prop, ((∀ n ∈ s, P n) ↔ (∀ n > 0, n ∈ s → P n)) := fun P ↦ by
refine forall_congr' (fun n ↦ ⟨fun h _ ↦ h, fun h hn ↦ h ?_ hn⟩)
contrapose! hs₀
simpa [nonpos_iff_eq_zero.mp hs₀] using hn
simpa only [this] using sum_eq_iff_sum_smul_moebius_eq_on s hs
/-- Möbius inversion for functions to a `Ring`, where the equalities only hold on a well-behaved
set. -/
theorem sum_eq_iff_sum_mul_moebius_eq_on [NonAssocRing R] {f g : ℕ → R}
(s : Set ℕ) (hs : ∀ m n, m ∣ n → n ∈ s → m ∈ s) :
(∀ n > 0, n ∈ s → (∑ i ∈ n.divisors, f i) = g n) ↔
∀ n > 0, n ∈ s →
(∑ x ∈ n.divisorsAntidiagonal, (μ x.fst : R) * g x.snd) = f n := by
rw [sum_eq_iff_sum_smul_moebius_eq_on s hs]
apply forall_congr'
intro a; refine imp_congr_right ?_
refine fun _ => imp_congr_right fun _ => (sum_congr rfl fun x _hx => ?_).congr_left
rw [zsmul_eq_mul]
/-- Möbius inversion for functions to a `CommGroup`, where the equalities only hold on a
well-behaved set. -/
theorem prod_eq_iff_prod_pow_moebius_eq_on [CommGroup R] {f g : ℕ → R}
(s : Set ℕ) (hs : ∀ m n, m ∣ n → n ∈ s → m ∈ s) :
(∀ n > 0, n ∈ s → (∏ i ∈ n.divisors, f i) = g n) ↔
∀ n > 0, n ∈ s → (∏ x ∈ n.divisorsAntidiagonal, g x.snd ^ μ x.fst) = f n :=
@sum_eq_iff_sum_smul_moebius_eq_on (Additive R) _ _ _ s hs
/-- Möbius inversion for functions to a `CommGroupWithZero`, where the equalities only hold on
a well-behaved set. -/
theorem prod_eq_iff_prod_pow_moebius_eq_on_of_nonzero [CommGroupWithZero R]
(s : Set ℕ) (hs : ∀ m n, m ∣ n → n ∈ s → m ∈ s) {f g : ℕ → R}
(hf : ∀ n > 0, f n ≠ 0) (hg : ∀ n > 0, g n ≠ 0) :
(∀ n > 0, n ∈ s → (∏ i ∈ n.divisors, f i) = g n) ↔
∀ n > 0, n ∈ s → (∏ x ∈ n.divisorsAntidiagonal, g x.snd ^ μ x.fst) = f n := by
refine
Iff.trans
(Iff.trans (forall_congr' fun n => ?_)
(@prod_eq_iff_prod_pow_moebius_eq_on Rˣ _
(fun n => if h : 0 < n then Units.mk0 (f n) (hf n h) else 1)
(fun n => if h : 0 < n then Units.mk0 (g n) (hg n h) else 1)
s hs) )
(forall_congr' fun n => ?_) <;>
refine imp_congr_right fun hn => ?_
· dsimp
rw [dif_pos hn, ← Units.val_inj, ← Units.coeHom_apply, map_prod, Units.val_mk0,
prod_congr rfl _]
intro x hx
rw [dif_pos (Nat.pos_of_mem_divisors hx), Units.coeHom_apply, Units.val_mk0]
· dsimp
rw [dif_pos hn, ← Units.val_inj, ← Units.coeHom_apply, map_prod, Units.val_mk0,
prod_congr rfl _]
intro x hx
rw [dif_pos (Nat.pos_of_mem_divisors (Nat.snd_mem_divisors_of_mem_antidiagonal hx)),
Units.coeHom_apply, Units.val_zpow_eq_zpow_val, Units.val_mk0]
end SpecialFunctions
end ArithmeticFunction
namespace Nat.Coprime
open ArithmeticFunction
theorem card_divisors_mul {m n : ℕ} (hmn : m.Coprime n) :
#(m * n).divisors = #m.divisors * #n.divisors := by
simp only [← sigma_zero_apply, isMultiplicative_sigma.map_mul_of_coprime hmn]
theorem sum_divisors_mul {m n : ℕ} (hmn : m.Coprime n) :
∑ d ∈ (m * n).divisors, d = (∑ d ∈ m.divisors, d) * ∑ d ∈ n.divisors, d := by
simp only [← sigma_one_apply, isMultiplicative_sigma.map_mul_of_coprime hmn]
end Nat.Coprime
namespace Mathlib.Meta.Positivity
open Lean Meta Qq
/-- Extension for `ArithmeticFunction.sigma`. -/
@[positivity ArithmeticFunction.sigma _ _]
def evalArithmeticFunctionSigma : PositivityExt where eval {u α} z p e := do
match u, α, e with
| 0, ~q(ℕ), ~q(ArithmeticFunction.sigma $k $n) =>
let rn ← core z p n
assumeInstancesCommute
match rn with
| .positive pn => return .positive q(Iff.mpr ArithmeticFunction.sigma_pos_iff $pn)
| _ => return .nonnegative q(Nat.zero_le _)
| _, _, _ => throwError "not ArithmeticFunction.sigma"
/-- Extension for `ArithmeticFunction.zeta`. -/
@[positivity ArithmeticFunction.zeta _]
def evalArithmeticFunctionZeta : PositivityExt where eval {u α} z p e := do
match u, α, e with
| 0, ~q(ℕ), ~q(ArithmeticFunction.zeta $n) =>
let rn ← core z p n
assumeInstancesCommute
match rn with
| .positive pn => return .positive q(Iff.mpr ArithmeticFunction.zeta_pos $pn)
| _ => return .nonnegative q(Nat.zero_le _)
| _, _, _ => throwError "not ArithmeticFunction.zeta"
end Mathlib.Meta.Positivity |
.lake/packages/mathlib/Mathlib/NumberTheory/PrimeCounting.lean | import Mathlib.Data.Nat.Prime.Nth
import Mathlib.Data.Nat.Totient
import Mathlib.NumberTheory.SmoothNumbers
import Mathlib.Order.Filter.AtTopBot.Basic
/-!
# The Prime Counting Function
In this file we define the prime counting function: the function on natural numbers that returns
the number of primes less than or equal to its input.
## Main Results
The main definitions for this file are
- `Nat.primeCounting`: The prime counting function π
- `Nat.primeCounting'`: π(n - 1)
We then prove that these are monotone in `Nat.monotone_primeCounting` and
`Nat.monotone_primeCounting'`. The last main theorem `Nat.primeCounting'_add_le` is an upper
bound on `π'` which arises by observing that all numbers greater than `k` and not coprime to `k`
are not prime, and so only at most `φ(k)/k` fraction of the numbers from `k` to `n` are prime.
## Notation
With `open scoped Nat.Prime`, we use the standard notation `π` to represent the prime counting
function (and `π'` to represent the reindexed version).
-/
namespace Nat
open Finset
/-- A variant of the traditional prime counting function which gives the number of primes
*strictly* less than the input. More convenient for avoiding off-by-one errors.
With `open scoped Nat.Prime`, this has notation `π'`. -/
def primeCounting' : ℕ → ℕ :=
Nat.count Prime
/-- The prime counting function: Returns the number of primes less than or equal to the input.
With `open scoped Nat.Prime`, this has notation `π`. -/
def primeCounting (n : ℕ) : ℕ :=
primeCounting' (n + 1)
@[inherit_doc] scoped[Nat.Prime] notation "π" => Nat.primeCounting
@[inherit_doc] scoped[Nat.Prime] notation "π'" => Nat.primeCounting'
open scoped Nat.Prime
@[simp]
theorem primeCounting_sub_one (n : ℕ) : π (n - 1) = π' n := by
cases n <;> rfl
theorem monotone_primeCounting' : Monotone primeCounting' :=
count_monotone Prime
theorem monotone_primeCounting : Monotone primeCounting :=
monotone_primeCounting'.comp (monotone_id.add_const _)
@[simp]
theorem primeCounting'_nth_eq (n : ℕ) : π' (nth Prime n) = n :=
count_nth_of_infinite infinite_setOf_prime _
/-- The `n`th prime is greater or equal to `n + 2`. -/
theorem add_two_le_nth_prime (n : ℕ) : n + 2 ≤ nth Prime n :=
nth_prime_zero_eq_two ▸ (nth_strictMono infinite_setOf_prime).add_le_nat n 0
theorem surjective_primeCounting' : Function.Surjective π' :=
Nat.surjective_count_of_infinite_setOf infinite_setOf_prime
theorem surjective_primeCounting : Function.Surjective π := by
suffices Function.Surjective (π ∘ fun n => n - 1) from this.of_comp
convert surjective_primeCounting'
ext
exact primeCounting_sub_one _
open Filter
theorem tendsto_primeCounting' : Tendsto π' atTop atTop := by
apply tendsto_atTop_atTop_of_monotone' monotone_primeCounting'
simp [Set.range_eq_univ.mpr surjective_primeCounting']
theorem tendsto_primeCounting : Tendsto π atTop atTop :=
(tendsto_add_atTop_iff_nat 1).mpr tendsto_primeCounting'
@[deprecated (since := "2025-07-08")] alias tensto_primeCounting := tendsto_primeCounting
@[simp]
theorem prime_nth_prime (n : ℕ) : Prime (nth Prime n) :=
nth_mem_of_infinite infinite_setOf_prime _
@[simp]
lemma primeCounting'_eq_zero_iff {n : ℕ} : n.primeCounting' = 0 ↔ n ≤ 2 := by
rw [primeCounting', Nat.count_eq_zero ⟨_, Nat.prime_two⟩, Nat.nth_prime_zero_eq_two]
@[simp]
lemma primeCounting_eq_zero_iff {n : ℕ} : n.primeCounting = 0 ↔ n ≤ 1 := by
simp [primeCounting]
@[simp]
lemma primeCounting_zero : primeCounting 0 = 0 :=
primeCounting_eq_zero_iff.mpr zero_le_one
@[simp]
lemma primeCounting_one : primeCounting 1 = 0 :=
primeCounting_eq_zero_iff.mpr le_rfl
/-- The cardinality of the finset `primesBelow n` equals the counting function
`primeCounting'` at `n`. -/
theorem primesBelow_card_eq_primeCounting' (n : ℕ) : #n.primesBelow = primeCounting' n := by
simp only [primesBelow, primeCounting']
exact (count_eq_card_filter_range Prime n).symm
/-- A linear upper bound on the size of the `primeCounting'` function -/
theorem primeCounting'_add_le {a k : ℕ} (h0 : a ≠ 0) (h1 : a < k) (n : ℕ) :
π' (k + n) ≤ π' k + Nat.totient a * (n / a + 1) :=
calc
π' (k + n) ≤ #{p ∈ range k | p.Prime} + #{p ∈ Ico k (k + n) | p.Prime} := by
rw [primeCounting', count_eq_card_filter_range, range_eq_Ico, ←
Ico_union_Ico_eq_Ico (zero_le k) le_self_add, filter_union]
apply card_union_le
_ ≤ π' k + #{p ∈ Ico k (k + n) | p.Prime} := by
rw [primeCounting', count_eq_card_filter_range]
_ ≤ π' k + #{b ∈ Ico k (k + n) | a.Coprime b} := by
gcongr with p hp
rw [coprime_comm]
exact coprime_of_lt_prime h0 <| h1.trans_le (mem_Ico.1 hp).1
_ ≤ π' k + totient a * (n / a + 1) := by
rw [add_le_add_iff_left]
exact Ico_filter_coprime_le k n h0
end Nat |
.lake/packages/mathlib/Mathlib/NumberTheory/Primorial.lean | import Mathlib.Algebra.BigOperators.Associated
import Mathlib.Algebra.Order.BigOperators.Ring.Finset
import Mathlib.Algebra.Order.Ring.Abs
import Mathlib.Data.Nat.Choose.Sum
import Mathlib.Data.Nat.Choose.Dvd
import Mathlib.Data.Nat.Prime.Basic
/-!
# Primorial
This file defines the primorial function (the product of primes less than or equal to some bound),
and proves that `primorial n ≤ 4 ^ n`.
## Notation
We use the local notation `n#` for the primorial of `n`: that is, the product of the primes less
than or equal to `n`.
-/
open Finset
open Nat
/-- The primorial `n#` of `n` is the product of the primes less than or equal to `n`.
-/
def primorial (n : ℕ) : ℕ := ∏ p ∈ range (n + 1) with p.Prime, p
local notation x "#" => primorial x
theorem primorial_pos (n : ℕ) : 0 < n# :=
prod_pos fun _p hp ↦ (mem_filter.1 hp).2.pos
theorem primorial_succ {n : ℕ} (hn1 : n ≠ 1) (hn : Odd n) : (n + 1)# = n# := by
refine prod_congr ?_ fun _ _ ↦ rfl
rw [range_add_one, filter_insert, if_neg fun h ↦ not_even_iff_odd.2 hn _]
exact fun h ↦ h.even_sub_one <| mt succ.inj hn1
theorem primorial_add (m n : ℕ) :
(m + n)# = m# * ∏ p ∈ Ico (m + 1) (m + n + 1) with p.Prime, p := by
rw [primorial, primorial, ← Ico_zero_eq_range, ← prod_union, ← filter_union, Ico_union_Ico_eq_Ico]
exacts [Nat.zero_le _, by cutsat, disjoint_filter_filter <| Ico_disjoint_Ico_consecutive _ _ _]
theorem primorial_add_dvd {m n : ℕ} (h : n ≤ m) : (m + n)# ∣ m# * choose (m + n) m :=
calc
(m + n)# = m# * ∏ p ∈ Ico (m + 1) (m + n + 1) with p.Prime, p := primorial_add _ _
_ ∣ m# * choose (m + n) m :=
mul_dvd_mul_left _ <|
prod_primes_dvd _ (fun _ hk ↦ (mem_filter.1 hk).2.prime) fun p hp ↦ by
rw [mem_filter, mem_Ico] at hp
exact hp.2.dvd_choose_add hp.1.1 (h.trans_lt (m.lt_succ_self.trans_le hp.1.1))
(Nat.lt_succ_iff.1 hp.1.2)
theorem primorial_add_le {m n : ℕ} (h : n ≤ m) : (m + n)# ≤ m# * choose (m + n) m :=
le_of_dvd (mul_pos (primorial_pos _) (choose_pos <| Nat.le_add_right _ _)) (primorial_add_dvd h)
theorem primorial_le_4_pow (n : ℕ) : n# ≤ 4 ^ n := by
induction n using Nat.strong_induction_on with | h n ihn =>
rcases n with - | n; · rfl
rcases n.even_or_odd with (⟨m, rfl⟩ | ho)
· rcases m.eq_zero_or_pos with (rfl | hm)
· decide
calc
(m + m + 1)# = (m + 1 + m)# := by rw [add_right_comm]
_ ≤ (m + 1)# * choose (m + 1 + m) (m + 1) := primorial_add_le m.le_succ
_ = (m + 1)# * choose (2 * m + 1) m := by rw [choose_symm_add, two_mul, add_right_comm]
_ ≤ 4 ^ (m + 1) * 4 ^ m :=
mul_le_mul' (ihn _ <| succ_lt_succ <| (lt_add_iff_pos_left _).2 hm) (choose_middle_le_pow _)
_ ≤ 4 ^ (m + m + 1) := by rw [← pow_add, add_right_comm]
· rcases Decidable.eq_or_ne n 1 with (rfl | hn)
· decide
· calc
(n + 1)# = n# := primorial_succ hn ho
_ ≤ 4 ^ n := ihn n n.lt_succ_self
_ ≤ 4 ^ (n + 1) := Nat.pow_le_pow_right four_pos n.le_succ |
.lake/packages/mathlib/Mathlib/NumberTheory/KummerDedekind.lean | import Mathlib.RingTheory.Conductor
import Mathlib.RingTheory.DedekindDomain.Ideal.Lemmas
import Mathlib.RingTheory.IsAdjoinRoot
/-!
# Kummer-Dedekind theorem
This file proves the Kummer-Dedekind theorem on the splitting of prime ideals in an extension of
the ring of integers. This states the following: assume we are given
- A prime ideal `I` of Dedekind domain `R`
- An `R`-algebra `S` that is a Dedekind Domain
- An `α : S` that is integral over `R` with minimal polynomial `f`
If the conductor `𝓒` of `x` is such that `𝓒 ∩ R` is coprime to `I` then the prime
factorisations of `I * S` and `f mod I` have the same shape, i.e. they have the same number of
prime factors, and each prime factors of `I * S` can be paired with a prime factor of `f mod I` in
a way that ensures multiplicities match (in fact, this pairing can be made explicit
with a formula).
## Main definitions
* `normalizedFactorsMapEquivNormalizedFactorsMinPolyMk` : The bijection in the Kummer-Dedekind
theorem. This is the pairing between the prime factors of `I * S` and the prime factors of
`f mod I`.
## Main results
* `normalizedFactors_ideal_map_eq_normalizedFactors_min_poly_mk_map` : The Kummer-Dedekind
theorem.
* `Ideal.irreducible_map_of_irreducible_minpoly` : `I.map (algebraMap R S)` is irreducible if
`(map (Ideal.Quotient.mk I) (minpoly R pb.gen))` is irreducible, where `pb` is a power basis
of `S` over `R`.
* `normalizedFactorsMapEquivNormalizedFactorsMinPolyMk_symm_apply_eq_span` : Let `Q` be a lift of
factor of the minimal polynomial of `x`, a generator of `S` over `R`, taken
`mod I`. Then (the reduction of) `Q` corresponds via
`normalizedFactorsMapEquivNormalizedFactorsMinPolyMk` to
`span (I.map (algebraMap R S) ∪ {Q.aeval x})`.
## TODO
* Prove the converse of `Ideal.irreducible_map_of_irreducible_minpoly`.
## References
* [J. Neukirch, *Algebraic Number Theory*][Neukirch1992]
## Tags
kummer, dedekind, kummer dedekind, dedekind-kummer, dedekind kummer
-/
variable {R : Type*} {S : Type*} [CommRing R] [CommRing S] [Algebra R S] {x : S} {I : Ideal R}
open Ideal Polynomial DoubleQuot UniqueFactorizationMonoid Algebra RingHom
namespace KummerDedekind
variable [IsDomain R] [IsIntegrallyClosed R]
variable [IsDedekindDomain S]
variable [NoZeroSMulDivisors R S]
attribute [local instance] Ideal.Quotient.field
/--
The isomorphism of rings between `S / I` and `(R / I)[X] / minpoly x` when `I`
and `(conductor R x) ∩ R` are coprime.
-/
noncomputable def quotMapEquivQuotQuotMap (hx : (conductor R x).comap (algebraMap R S) ⊔ I = ⊤)
(hx' : IsIntegral R x) :
S ⧸ I.map (algebraMap R S) ≃+* (R ⧸ I)[X] ⧸ span {(minpoly R x).map (Ideal.Quotient.mk I)} :=
(quotAdjoinEquivQuotMap hx (FaithfulSMul.algebraMap_injective
(Algebra.adjoin R {x}) S)).symm.trans <|
((Algebra.adjoin.powerBasis' hx').quotientEquivQuotientMinpolyMap I).toRingEquiv.trans <|
quotEquivOfEq (by rw [Algebra.adjoin.powerBasis'_minpoly_gen hx'])
lemma quotMapEquivQuotQuotMap_symm_apply (hx : (conductor R x).comap (algebraMap R S) ⊔ I = ⊤)
(hx' : IsIntegral R x) (Q : R[X]) :
(quotMapEquivQuotQuotMap hx hx').symm (Q.map (Ideal.Quotient.mk I)) = Q.aeval x := by
apply (quotMapEquivQuotQuotMap hx hx').injective
rw [quotMapEquivQuotQuotMap, AlgEquiv.toRingEquiv_eq_coe, RingEquiv.symm_trans_apply,
RingEquiv.symm_symm, RingEquiv.coe_trans, Function.comp_apply, RingEquiv.symm_apply_apply,
RingEquiv.symm_trans_apply, quotEquivOfEq_symm, quotEquivOfEq_mk]
congr
convert (adjoin.powerBasis' hx').quotientEquivQuotientMinpolyMap_symm_apply_mk I Q
apply (quotAdjoinEquivQuotMap hx
(FaithfulSMul.algebraMap_injective ((adjoin R {x})) S)).injective
simp only [RingEquiv.apply_symm_apply, adjoin.powerBasis'_gen, quotAdjoinEquivQuotMap_apply_mk,
coe_aeval_mk_apply]
open Classical in
/-- The first half of the **Kummer-Dedekind Theorem**, stating that the prime
factors of `I*S` are in bijection with those of the minimal polynomial of the generator of `S`
over `R`, taken `mod I`. -/
noncomputable def normalizedFactorsMapEquivNormalizedFactorsMinPolyMk (hI : IsMaximal I)
(hI' : I ≠ ⊥) (hx : (conductor R x).comap (algebraMap R S) ⊔ I = ⊤) (hx' : IsIntegral R x) :
{J : Ideal S | J ∈ normalizedFactors (I.map (algebraMap R S))} ≃
{d : (R ⧸ I)[X] |
d ∈ normalizedFactors (Polynomial.map (Ideal.Quotient.mk I) (minpoly R x))} := by
refine (normalizedFactorsEquivOfQuotEquiv (quotMapEquivQuotQuotMap hx hx') ?_ ?_).trans ?_
· rwa [Ne, map_eq_bot_iff_of_injective (FaithfulSMul.algebraMap_injective R S), ← Ne]
· by_contra h
exact (show Polynomial.map (Ideal.Quotient.mk I) (minpoly R x) ≠ 0 from
Polynomial.map_monic_ne_zero (minpoly.monic hx')) (span_singleton_eq_bot.mp h)
· refine (normalizedFactorsEquivSpanNormalizedFactors ?_).symm
exact Polynomial.map_monic_ne_zero (minpoly.monic hx')
open Classical in
/-- The second half of the **Kummer-Dedekind Theorem**, stating that the
bijection `FactorsEquiv'` defined in the first half preserves multiplicities. -/
theorem emultiplicity_factors_map_eq_emultiplicity
(hI : IsMaximal I) (hI' : I ≠ ⊥)
(hx : (conductor R x).comap (algebraMap R S) ⊔ I = ⊤) (hx' : IsIntegral R x) {J : Ideal S}
(hJ : J ∈ normalizedFactors (I.map (algebraMap R S))) :
emultiplicity J (I.map (algebraMap R S)) =
emultiplicity (↑(normalizedFactorsMapEquivNormalizedFactorsMinPolyMk hI hI' hx hx' ⟨J, hJ⟩))
(Polynomial.map (Ideal.Quotient.mk I) (minpoly R x)) := by
rw [normalizedFactorsMapEquivNormalizedFactorsMinPolyMk, Equiv.coe_trans, Function.comp_apply,
emultiplicity_normalizedFactorsEquivSpanNormalizedFactors_symm_eq_emultiplicity,
normalizedFactorsEquivOfQuotEquiv_emultiplicity_eq_emultiplicity]
open Classical in
/-- The **Kummer-Dedekind Theorem**. -/
theorem normalizedFactors_ideal_map_eq_normalizedFactors_min_poly_mk_map (hI : IsMaximal I)
(hI' : I ≠ ⊥) (hx : (conductor R x).comap (algebraMap R S) ⊔ I = ⊤) (hx' : IsIntegral R x) :
normalizedFactors (I.map (algebraMap R S)) =
Multiset.map
(fun f =>
((normalizedFactorsMapEquivNormalizedFactorsMinPolyMk hI hI' hx hx').symm f : Ideal S))
(normalizedFactors (Polynomial.map (Ideal.Quotient.mk I) (minpoly R x))).attach := by
ext J
-- WLOG, assume J is a normalized factor
by_cases hJ : J ∈ normalizedFactors (I.map (algebraMap R S))
swap
· rw [Multiset.count_eq_zero.mpr hJ, eq_comm, Multiset.count_eq_zero, Multiset.mem_map]
simp only [not_exists]
rintro J' ⟨_, rfl⟩
exact
hJ ((normalizedFactorsMapEquivNormalizedFactorsMinPolyMk hI hI' hx hx').symm J').prop
-- Then we just have to compare the multiplicities, which we already proved are equal.
have := emultiplicity_factors_map_eq_emultiplicity hI hI' hx hx' hJ
rw [emultiplicity_eq_count_normalizedFactors, emultiplicity_eq_count_normalizedFactors,
UniqueFactorizationMonoid.normalize_normalized_factor _ hJ,
UniqueFactorizationMonoid.normalize_normalized_factor, Nat.cast_inj] at this
· refine this.trans ?_
-- Get rid of the `map` by applying the equiv to both sides.
generalize hJ' :
(normalizedFactorsMapEquivNormalizedFactorsMinPolyMk hI hI' hx hx') ⟨J, hJ⟩ = J'
have : ((normalizedFactorsMapEquivNormalizedFactorsMinPolyMk hI hI' hx hx').symm J' : Ideal S) =
J := by
rw [← hJ', Equiv.symm_apply_apply _ _, Subtype.coe_mk]
subst this
-- Get rid of the `attach` by applying the subtype `coe` to both sides.
rw [Multiset.count_map_eq_count' fun f =>
((normalizedFactorsMapEquivNormalizedFactorsMinPolyMk hI hI' hx hx').symm f :
Ideal S),
Multiset.count_attach]
· exact Subtype.coe_injective.comp (Equiv.injective _)
· exact (normalizedFactorsMapEquivNormalizedFactorsMinPolyMk hI hI' hx hx' _).prop
· exact irreducible_of_normalized_factor _
(normalizedFactorsMapEquivNormalizedFactorsMinPolyMk hI hI' hx hx' _).prop
· exact Polynomial.map_monic_ne_zero (minpoly.monic hx')
· exact irreducible_of_normalized_factor _ hJ
· rwa [← bot_eq_zero, Ne,
map_eq_bot_iff_of_injective (FaithfulSMul.algebraMap_injective R S)]
theorem Ideal.irreducible_map_of_irreducible_minpoly (hI : IsMaximal I) (hI' : I ≠ ⊥)
(hx : (conductor R x).comap (algebraMap R S) ⊔ I = ⊤) (hx' : IsIntegral R x)
(hf : Irreducible (Polynomial.map (Ideal.Quotient.mk I) (minpoly R x))) :
Irreducible (I.map (algebraMap R S)) := by
classical
have mem_norm_factors : normalize (Polynomial.map (Ideal.Quotient.mk I) (minpoly R x)) ∈
normalizedFactors (Polynomial.map (Ideal.Quotient.mk I) (minpoly R x)) := by
simp [normalizedFactors_irreducible hf]
suffices ∃ y, normalizedFactors (I.map (algebraMap R S)) = {y} by
obtain ⟨y, hy⟩ := this
have h := prod_normalizedFactors (show I.map (algebraMap R S) ≠ 0 by
rwa [← bot_eq_zero, Ne,
map_eq_bot_iff_of_injective (FaithfulSMul.algebraMap_injective R S)])
rw [associated_iff_eq, hy, Multiset.prod_singleton] at h
rw [← h]
exact
irreducible_of_normalized_factor y
(show y ∈ normalizedFactors (I.map (algebraMap R S)) by simp [hy])
rw [normalizedFactors_ideal_map_eq_normalizedFactors_min_poly_mk_map hI hI' hx hx']
use ((normalizedFactorsMapEquivNormalizedFactorsMinPolyMk hI hI' hx hx').symm
⟨normalize (Polynomial.map (Ideal.Quotient.mk I) (minpoly R x)), mem_norm_factors⟩ :
Ideal S)
rw [Multiset.map_eq_singleton]
use ⟨normalize (Polynomial.map (Ideal.Quotient.mk I) (minpoly R x)), mem_norm_factors⟩
refine ⟨?_, rfl⟩
apply Multiset.map_injective Subtype.coe_injective
rw [Multiset.attach_map_val, Multiset.map_singleton, Subtype.coe_mk]
exact normalizedFactors_irreducible hf
open Set Classical in
/-- Let `Q` be a lift of factor of the minimal polynomial of `x`, a generator of `S` over `R`, taken
`mod I`. Then (the reduction of) `Q` corresponds via
`normalizedFactorsMapEquivNormalizedFactorsMinPolyMk` to
`span (I.map (algebraMap R S) ∪ {Q.aeval x})`. -/
theorem normalizedFactorsMapEquivNormalizedFactorsMinPolyMk_symm_apply_eq_span
(hI : I.IsMaximal) {Q : R[X]}
(hQ : Q.map (Ideal.Quotient.mk I) ∈ normalizedFactors ((minpoly R x).map (Ideal.Quotient.mk I)))
(hI' : I ≠ ⊥) (hx : (conductor R x).comap (algebraMap R S) ⊔ I = ⊤) (hx' : IsIntegral R x) :
((normalizedFactorsMapEquivNormalizedFactorsMinPolyMk hI hI' hx hx').symm ⟨_, hQ⟩).val =
span (I.map (algebraMap R S) ∪ {Q.aeval x}) := by
dsimp [normalizedFactorsMapEquivNormalizedFactorsMinPolyMk,
normalizedFactorsEquivSpanNormalizedFactors]
rw [normalizedFactorsEquivOfQuotEquiv_symm]
dsimp [normalizedFactorsEquivOfQuotEquiv, idealFactorsEquivOfQuotEquiv, OrderIso.ofHomInv]
simp only [map_span, image_singleton, coe_coe, quotMapEquivQuotQuotMap_symm_apply hx hx' Q]
refine le_antisymm (fun a ha ↦ ?_) (span_le.mpr <| union_subset_iff.mpr <|
⟨le_comap_of_map_le (by simp), by simp [mem_span_singleton]⟩)
rw [mem_comap, Ideal.mem_span_singleton] at ha
obtain ⟨a', ha'⟩ := ha
obtain ⟨b, hb⟩ := Ideal.Quotient.mk_surjective a'
rw [← hb, ← map_mul, Quotient.mk_eq_mk_iff_sub_mem] at ha'
rw [union_comm, span_union, span_eq, mem_span_singleton_sup]
exact ⟨b, a - Q.aeval x * b, ha', by ring⟩
end KummerDedekind |
.lake/packages/mathlib/Mathlib/NumberTheory/GaussSum.lean | import Mathlib.NumberTheory.LegendreSymbol.AddCharacter
import Mathlib.NumberTheory.LegendreSymbol.ZModChar
import Mathlib.Algebra.CharP.CharAndCard
/-!
# Gauss sums
We define the Gauss sum associated to a multiplicative and an additive
character of a finite field and prove some results about them.
## Main definition
Let `R` be a finite commutative ring and let `R'` be another commutative ring.
If `χ` is a multiplicative character `R → R'` (type `MulChar R R'`) and `ψ`
is an additive character `R → R'` (type `AddChar R R'`, which abbreviates
`(Multiplicative R) →* R'`), then the *Gauss sum* of `χ` and `ψ` is `∑ a, χ a * ψ a`.
## Main results
Some important results are as follows.
* `gaussSum_mul_gaussSum_eq_card`: The product of the Gauss
sums of `χ` and `ψ` and that of `χ⁻¹` and `ψ⁻¹` is the cardinality
of the source ring `R` (if `χ` is nontrivial, `ψ` is primitive and `R` is a field).
* `gaussSum_sq`: The square of the Gauss sum is `χ(-1)` times
the cardinality of `R` if in addition `χ` is a quadratic character.
* `MulChar.IsQuadratic.gaussSum_frob`: For a quadratic character `χ`, raising
the Gauss sum to the `p`th power (where `p` is the characteristic of
the target ring `R'`) multiplies it by `χ p`.
* `Char.card_pow_card`: When `F` and `F'` are finite fields and `χ : F → F'`
is a nontrivial quadratic character, then `(χ (-1) * #F)^(#F'/2) = χ #F'`.
* `FiniteField.two_pow_card`: For every finite field `F` of odd characteristic,
we have `2^(#F/2) = χ₈ #F` in `F`.
This machinery can be used to derive (a generalization of) the Law of
Quadratic Reciprocity.
## Tags
additive character, multiplicative character, Gauss sum
-/
universe u v
open AddChar MulChar
section GaussSumDef
-- `R` is the domain of the characters
variable {R : Type u} [CommRing R] [Fintype R]
-- `R'` is the target of the characters
variable {R' : Type v} [CommRing R']
/-!
### Definition and first properties
-/
/-- Definition of the Gauss sum associated to a multiplicative and an additive character. -/
def gaussSum (χ : MulChar R R') (ψ : AddChar R R') : R' :=
∑ a, χ a * ψ a
/-- Replacing `ψ` by `mulShift ψ a` and multiplying the Gauss sum by `χ a` does not change it. -/
theorem gaussSum_mulShift (χ : MulChar R R') (ψ : AddChar R R') (a : Rˣ) :
χ a * gaussSum χ (mulShift ψ a) = gaussSum χ ψ := by
simp only [gaussSum, mulShift_apply, Finset.mul_sum]
simp_rw [← mul_assoc, ← map_mul]
exact Fintype.sum_bijective _ a.mulLeft_bijective _ _ fun x ↦ rfl
end GaussSumDef
/-!
### The product of two Gauss sums
-/
section GaussSumProd
open Finset in
/-- A formula for the product of two Gauss sums with the same additive character. -/
lemma gaussSum_mul {R : Type u} [CommRing R] [Fintype R] {R' : Type v} [CommRing R']
(χ φ : MulChar R R') (ψ : AddChar R R') :
gaussSum χ ψ * gaussSum φ ψ = ∑ t : R, ∑ x : R, χ x * φ (t - x) * ψ t := by
rw [gaussSum, gaussSum, sum_mul_sum]
conv => enter [1, 2, x, 2, x_1]; rw [mul_mul_mul_comm]
simp only [← ψ.map_add_eq_mul]
have sum_eq x : ∑ y : R, χ x * φ y * ψ (x + y) = ∑ y : R, χ x * φ (y - x) * ψ y := by
rw [sum_bij (fun a _ ↦ a + x)]
· simp only [mem_univ, forall_const]
· simp only [mem_univ, add_left_inj, imp_self, forall_const]
· exact fun b _ ↦ ⟨b - x, mem_univ _, by rw [sub_add_cancel]⟩
· exact fun a _ ↦ by rw [add_sub_cancel_right, add_comm]
rw [sum_congr rfl fun x _ ↦ sum_eq x, sum_comm]
-- In the following, we need `R` to be a finite field.
variable {R : Type u} [Field R] [Fintype R] {R' : Type v} [CommRing R']
lemma mul_gaussSum_inv_eq_gaussSum (χ : MulChar R R') (ψ : AddChar R R') :
χ (-1) * gaussSum χ ψ⁻¹ = gaussSum χ ψ := by
rw [ψ.inv_mulShift, ← Units.coe_neg_one]
exact gaussSum_mulShift χ ψ (-1)
variable [IsDomain R'] -- From now on, `R'` needs to be a domain.
-- A helper lemma for `gaussSum_mul_gaussSum_eq_card` below
-- Is this useful enough in other contexts to be public?
private theorem gaussSum_mul_aux {χ : MulChar R R'} (hχ : χ ≠ 1) (ψ : AddChar R R')
(b : R) :
∑ a, χ (a * b⁻¹) * ψ (a - b) = ∑ c, χ c * ψ (b * (c - 1)) := by
rcases eq_or_ne b 0 with hb | hb
· -- case `b = 0`
simp only [hb, inv_zero, mul_zero, MulChar.map_zero, zero_mul,
Finset.sum_const_zero, map_zero_eq_one, mul_one, χ.sum_eq_zero_of_ne_one hχ]
· -- case `b ≠ 0`
refine (Fintype.sum_bijective _ (mulLeft_bijective₀ b hb) _ _ fun x ↦ ?_).symm
rw [mul_assoc, mul_comm x, ← mul_assoc, mul_inv_cancel₀ hb, one_mul, mul_sub, mul_one]
/-- We have `gaussSum χ ψ * gaussSum χ⁻¹ ψ⁻¹ = Fintype.card R`
when `χ` is nontrivial and `ψ` is primitive (and `R` is a field). -/
theorem gaussSum_mul_gaussSum_eq_card {χ : MulChar R R'} (hχ : χ ≠ 1) {ψ : AddChar R R'}
(hψ : IsPrimitive ψ) :
gaussSum χ ψ * gaussSum χ⁻¹ ψ⁻¹ = Fintype.card R := by
simp only [gaussSum, AddChar.inv_apply, Finset.sum_mul, Finset.mul_sum, MulChar.inv_apply']
conv =>
enter [1, 2, x, 2, y]
rw [mul_mul_mul_comm, ← map_mul, ← map_add_eq_mul, ← sub_eq_add_neg]
-- conv in _ * _ * (_ * _) => rw [mul_mul_mul_comm, ← map_mul, ← map_add_eq_mul, ← sub_eq_add_neg]
simp_rw [gaussSum_mul_aux hχ ψ]
rw [Finset.sum_comm]
classical -- to get `[DecidableEq R]` for `sum_mulShift`
simp_rw [← Finset.mul_sum, sum_mulShift _ hψ, sub_eq_zero, apply_ite, Nat.cast_zero, mul_zero]
rw [Finset.sum_ite_eq' Finset.univ (1 : R)]
simp only [Finset.mem_univ, map_one, one_mul, if_true]
/-- If `χ` is a multiplicative character of order `n` on a finite field `F`,
then `g(χ) * g(χ^(n-1)) = χ(-1)*#F` -/
lemma gaussSum_mul_gaussSum_pow_orderOf_sub_one {χ : MulChar R R'} {ψ : AddChar R R'}
(hχ : χ ≠ 1) (hψ : ψ.IsPrimitive) :
gaussSum χ ψ * gaussSum (χ ^ (orderOf χ - 1)) ψ = χ (-1) * Fintype.card R := by
have h : χ ^ (orderOf χ - 1) = χ⁻¹ := by
refine (inv_eq_of_mul_eq_one_right ?_).symm
rw [← pow_succ', Nat.sub_one_add_one_eq_of_pos χ.orderOf_pos, pow_orderOf_eq_one]
rw [h, ← mul_gaussSum_inv_eq_gaussSum χ⁻¹, mul_left_comm, gaussSum_mul_gaussSum_eq_card hχ hψ,
MulChar.inv_apply', inv_neg_one]
/-- The Gauss sum of a nontrivial character on a finite field does not vanish. -/
lemma gaussSum_ne_zero_of_nontrivial (h : (Fintype.card R : R') ≠ 0) {χ : MulChar R R'}
(hχ : χ ≠ 1) {ψ : AddChar R R'} (hψ : ψ.IsPrimitive) :
gaussSum χ ψ ≠ 0 :=
fun H ↦ h.symm <| zero_mul (gaussSum χ⁻¹ _) ▸ H ▸ gaussSum_mul_gaussSum_eq_card hχ hψ
/-- When `χ` is a nontrivial quadratic character, then the square of `gaussSum χ ψ`
is `χ(-1)` times the cardinality of `R`. -/
theorem gaussSum_sq {χ : MulChar R R'} (hχ₁ : χ ≠ 1) (hχ₂ : IsQuadratic χ)
{ψ : AddChar R R'} (hψ : IsPrimitive ψ) :
gaussSum χ ψ ^ 2 = χ (-1) * Fintype.card R := by
rw [pow_two, ← gaussSum_mul_gaussSum_eq_card hχ₁ hψ, hχ₂.inv, mul_rotate']
congr
rw [mul_comm, ← gaussSum_mulShift _ _ (-1 : Rˣ), inv_mulShift]
rfl
end GaussSumProd
/-!
### Gauss sums and Frobenius
-/
section gaussSum_frob
variable {R : Type u} [CommRing R] [Fintype R] {R' : Type v} [CommRing R']
-- We assume that the target ring `R'` has prime characteristic `p`.
variable (p : ℕ) [fp : Fact p.Prime] [hch : CharP R' p]
/-- When `R'` has prime characteristic `p`, then the `p`th power of the Gauss sum
of `χ` and `ψ` is the Gauss sum of `χ^p` and `ψ^p`. -/
theorem gaussSum_frob (χ : MulChar R R') (ψ : AddChar R R') :
gaussSum χ ψ ^ p = gaussSum (χ ^ p) (ψ ^ p) := by
rw [← frobenius_def, gaussSum, gaussSum, map_sum]
simp_rw [pow_apply' χ fp.1.ne_zero, map_mul, frobenius_def]
rfl
/-- For a quadratic character `χ` and when the characteristic `p` of the target ring
is a unit in the source ring, the `p`th power of the Gauss sum of`χ` and `ψ` is
`χ p` times the original Gauss sum. -/
theorem MulChar.IsQuadratic.gaussSum_frob (hp : IsUnit (p : R)) {χ : MulChar R R'}
(hχ : IsQuadratic χ) (ψ : AddChar R R') :
gaussSum χ ψ ^ p = χ p * gaussSum χ ψ := by
rw [_root_.gaussSum_frob, pow_mulShift, hχ.pow_char p, ← gaussSum_mulShift χ ψ hp.unit,
← mul_assoc, hp.unit_spec, ← pow_two, ← pow_apply' _ two_ne_zero, hχ.sq_eq_one, ← hp.unit_spec,
one_apply_coe, one_mul]
/-- For a quadratic character `χ` and when the characteristic `p` of the target ring
is a unit in the source ring and `n` is a natural number, the `p^n`th power of the Gauss
sum of`χ` and `ψ` is `χ (p^n)` times the original Gauss sum. -/
theorem MulChar.IsQuadratic.gaussSum_frob_iter (n : ℕ) (hp : IsUnit (p : R)) {χ : MulChar R R'}
(hχ : IsQuadratic χ) (ψ : AddChar R R') :
gaussSum χ ψ ^ p ^ n = χ ((p : R) ^ n) * gaussSum χ ψ := by
induction n with
| zero => rw [pow_zero, pow_one, pow_zero, MulChar.map_one, one_mul]
| succ n ih =>
rw [pow_succ, pow_mul, ih, mul_pow, hχ.gaussSum_frob _ hp, ← mul_assoc, pow_succ, map_mul,
← pow_apply' χ fp.1.ne_zero ((p : R) ^ n), hχ.pow_char p]
end gaussSum_frob
/-!
### Values of quadratic characters
-/
section GaussSumValues
variable {R : Type u} [CommRing R] [Fintype R] {R' : Type v} [CommRing R'] [IsDomain R']
/-- If the square of the Gauss sum of a quadratic character is `χ(-1) * #R`,
then we get, for all `n : ℕ`, the relation `(χ(-1) * #R) ^ (p^n/2) = χ(p^n)`,
where `p` is the (odd) characteristic of the target ring `R'`.
This version can be used when `R` is not a field, e.g., `ℤ/8ℤ`. -/
theorem Char.card_pow_char_pow {χ : MulChar R R'} (hχ : IsQuadratic χ) (ψ : AddChar R R') (p n : ℕ)
[fp : Fact p.Prime] [hch : CharP R' p] (hp : IsUnit (p : R)) (hp' : p ≠ 2)
(hg : gaussSum χ ψ ^ 2 = χ (-1) * Fintype.card R) :
(χ (-1) * Fintype.card R) ^ (p ^ n / 2) = χ ((p : R) ^ n) := by
have : gaussSum χ ψ ≠ 0 := by
intro hf
rw [hf, zero_pow two_ne_zero, eq_comm, mul_eq_zero] at hg
exact not_isUnit_prime_of_dvd_card
((CharP.cast_eq_zero_iff R' p _).mp <| hg.resolve_left (isUnit_one.neg.map χ).ne_zero) hp
rw [← hg]
apply mul_right_cancel₀ this
rw [← hχ.gaussSum_frob_iter p n hp ψ, ← pow_mul, ← pow_succ,
Nat.two_mul_div_two_add_one_of_odd (fp.1.eq_two_or_odd'.resolve_left hp').pow]
/-- When `F` and `F'` are finite fields and `χ : F → F'` is a nontrivial quadratic character,
then `(χ(-1) * #F)^(#F'/2) = χ #F'`. -/
theorem Char.card_pow_card {F : Type*} [Field F] [Fintype F] {F' : Type*} [Field F'] [Fintype F']
{χ : MulChar F F'} (hχ₁ : χ ≠ 1) (hχ₂ : IsQuadratic χ)
(hch₁ : ringChar F' ≠ ringChar F) (hch₂ : ringChar F' ≠ 2) :
(χ (-1) * Fintype.card F) ^ (Fintype.card F' / 2) = χ (Fintype.card F') := by
obtain ⟨n, hp, hc⟩ := FiniteField.card F (ringChar F)
obtain ⟨n', hp', hc'⟩ := FiniteField.card F' (ringChar F')
let ψ := FiniteField.primitiveChar F F' hch₁
let FF' := CyclotomicField ψ.n F'
have hchar := Algebra.ringChar_eq F' FF'
apply (algebraMap F' FF').injective
rw [map_pow, map_mul, map_natCast, hc', hchar, Nat.cast_pow]
simp only [← MulChar.ringHomComp_apply]
have := Fact.mk hp'
have := Fact.mk (hchar.subst hp')
rw [Ne, ← Nat.prime_dvd_prime_iff_eq hp' hp, ← isUnit_iff_not_dvd_char, hchar] at hch₁
exact Char.card_pow_char_pow (hχ₂.comp _) ψ.char (ringChar FF') n' hch₁ (hchar ▸ hch₂)
(gaussSum_sq ((ringHomComp_ne_one_iff (RingHom.injective _)).mpr hχ₁) (hχ₂.comp _) ψ.prim)
end GaussSumValues
section GaussSumTwo
/-!
### The quadratic character of 2
This section proves the following result.
For every finite field `F` of odd characteristic, we have `2^(#F/2) = χ₈#F` in `F`.
This can be used to show that the quadratic character of `F` takes the value
`χ₈#F` at `2`.
The proof uses the Gauss sum of `χ₈` and a primitive additive character on `ℤ/8ℤ`;
in this way, the result is reduced to `card_pow_char_pow`.
-/
open ZMod
/-- For every finite field `F` of odd characteristic, we have `2^(#F/2) = χ₈ #F` in `F`. -/
theorem FiniteField.two_pow_card {F : Type*} [Fintype F] [Field F] (hF : ringChar F ≠ 2) :
(2 : F) ^ (Fintype.card F / 2) = χ₈ (Fintype.card F) := by
have hp2 (n : ℕ) : (2 ^ n : F) ≠ 0 := pow_ne_zero n (Ring.two_ne_zero hF)
obtain ⟨n, hp, hc⟩ := FiniteField.card F (ringChar F)
-- we work in `FF`, the eighth cyclotomic field extension of `F`
let FF := CyclotomicField 8 F
have hchar := Algebra.ringChar_eq F FF
have FFp := hchar.subst hp
have := Fact.mk FFp
have hFF := hchar ▸ hF -- `ringChar FF ≠ 2`
have hu : IsUnit (ringChar FF : ZMod 8) := by
rw [isUnit_iff_not_dvd_char, ringChar_zmod_n]
rw [Ne, ← Nat.prime_dvd_prime_iff_eq FFp Nat.prime_two] at hFF
change ¬_ ∣ 2 ^ 3
exact mt FFp.dvd_of_dvd_pow hFF
-- there is a primitive additive character `ℤ/8ℤ → FF`, sending `a + 8ℤ ↦ τ^a`
-- with a primitive eighth root of unity `τ`
let ψ₈ := primitiveZModChar 8 F (by convert hp2 3 using 1; norm_cast)
-- We cast from `AddChar (ZMod (8 : ℕ+)) FF` to `AddChar (ZMod 8) FF`
-- This is needed to make `simp_rw [← h₁]` below work.
let ψ₈char : AddChar (ZMod 8) FF := ψ₈.char
let τ : FF := ψ₈char 1
have τ_spec : τ ^ 4 = -1 := by
rw [show τ = ψ₈.char 1 from rfl] -- to make `rw [ψ₈.prim.zmod_char_eq_one_iff]` work
refine (sq_eq_one_iff.1 ?_).resolve_left ?_
· rw [← pow_mul, ← map_nsmul_eq_pow ψ₈.char, ψ₈.prim.zmod_char_eq_one_iff]
decide
· rw [← map_nsmul_eq_pow ψ₈.char, ψ₈.prim.zmod_char_eq_one_iff]
decide
-- we consider `χ₈` as a multiplicative character `ℤ/8ℤ → FF`
let χ := χ₈.ringHomComp (Int.castRingHom FF)
have hχ : χ (-1) = 1 := Int.cast_one
have hq : IsQuadratic χ := isQuadratic_χ₈.comp _
-- we now show that the Gauss sum of `χ` and `ψ₈` has the relevant property
have h₁ : (fun (a : Fin 8) ↦ ↑(χ₈ a) * τ ^ (a : ℕ)) = fun a ↦ χ a * ↑(ψ₈char a) := by
ext1; congr; apply pow_one
have hg₁ : gaussSum χ ψ₈char = 2 * (τ - τ ^ 3) := by
rw [gaussSum, ← h₁, Fin.sum_univ_eight,
-- evaluate `χ₈`
show χ₈ 0 = 0 from rfl, show χ₈ 1 = 1 from rfl, show χ₈ 2 = 0 from rfl,
show χ₈ 3 = -1 from rfl, show χ₈ 4 = 0 from rfl, show χ₈ 5 = -1 from rfl,
show χ₈ 6 = 0 from rfl, show χ₈ 7 = 1 from rfl,
-- normalize exponents
show ((3 : Fin 8) : ℕ) = 3 from rfl, show ((5 : Fin 8) : ℕ) = 5 from rfl,
show ((7 : Fin 8) : ℕ) = 7 from rfl]
simp only [Int.cast_zero, zero_mul, Int.cast_one, Fin.val_one, pow_one, one_mul, zero_add,
Fin.val_two, add_zero, Int.reduceNeg, Int.cast_neg]
linear_combination (τ ^ 3 - τ) * τ_spec
have hg : gaussSum χ ψ₈char ^ 2 = χ (-1) * Fintype.card (ZMod 8) := by
rw [hχ, one_mul, ZMod.card, Nat.cast_ofNat, hg₁]
linear_combination (4 * τ ^ 2 - 8) * τ_spec
-- this allows us to apply `card_pow_char_pow` to our situation
have h := Char.card_pow_char_pow (R := ZMod 8) hq ψ₈char (ringChar FF) n hu hFF hg
rw [ZMod.card, ← hchar, hχ, one_mul, ← hc, ← Nat.cast_pow (ringChar F), ← hc] at h
-- finally, we change `2` to `8` on the left-hand side
convert_to (8 : F) ^ (Fintype.card F / 2) = _
· rw [(by norm_num : (8 : F) = 2 ^ 2 * 2), mul_pow,
(FiniteField.isSquare_iff hF <| hp2 2).mp ⟨2, pow_two 2⟩, one_mul]
apply (algebraMap F FF).injective
simpa only [map_pow, map_ofNat, map_intCast, Nat.cast_ofNat] using h
end GaussSumTwo |
.lake/packages/mathlib/Mathlib/NumberTheory/PowModTotient.lean | import Mathlib.FieldTheory.Finite.Basic
/-!
# Modular exponentiation with the totient function
This file contains lemmas about modular exponentiation.
In particular, it contains lemmas showing that an exponent can be reduced modulo the totient
function when the base is coprime to the modulus.
## Main Results
* `pow_totient_mod`: If `x` is coprime to `n`, then the modular exponentiation
`x ^ k % n` can be reduced to `x ^ (k % φ n) % n`.
## TODOs
- Extend to results in cases where the base is not coprime to the modulus.
- Write a tactic or simproc that can automatically reduce exponents
or towers of exponents using these results.
-/
namespace Nat
lemma pow_totient_mod_eq_one {x n : ℕ} (hn : 1 < n) (h : x.Coprime n) :
(x ^ φ n) % n = 1 := by
exact mod_eq_of_modEq (ModEq.pow_totient h) hn
lemma pow_add_totient_mod_eq {x k n : ℕ} (hn : 1 < n) (h : x.Coprime n) :
(x ^ (k + φ n)) % n = (x ^ k) % n := by
rw [pow_add, mul_mod, pow_totient_mod_eq_one hn h]
simp only [mul_one, dvd_refl, mod_mod_of_dvd]
lemma pow_add_mul_totient_mod_eq {x k l n : ℕ} (hn : 1 < n) (h : x.Coprime n) :
(x ^ (k + l * φ n)) % n = (x ^ k) % n := by
induction l with
| zero => simp
| succ l ih =>
rw [add_mul, one_mul, ← add_assoc, pow_add_totient_mod_eq hn h, ih]
lemma pow_totient_mod {x k n : ℕ} (hn : 1 < n) (h : x.Coprime n) :
x ^ k % n = x ^ (k % φ n) % n := by
rw [← div_add_mod' k (φ n), add_comm, pow_add_mul_totient_mod_eq hn h, add_mul_mod_self_right,
mod_mod k (φ n)]
end Nat |
.lake/packages/mathlib/Mathlib/NumberTheory/Basic.lean | import Mathlib.Algebra.Ring.GeomSum
import Mathlib.RingTheory.Ideal.Quotient.Defs
import Mathlib.RingTheory.Ideal.Span
/-!
# Basic results in number theory
This file should contain basic results in number theory. So far, it only contains the essential
lemma in the construction of the ring of Witt vectors.
## Main statement
`dvd_sub_pow_of_dvd_sub` proves that for elements `a` and `b` in a commutative ring `R` and for
all natural numbers `p` and `k` if `p` divides `a-b` in `R`, then `p ^ (k + 1)` divides
`a ^ (p ^ k) - b ^ (p ^ k)`.
-/
section
open Ideal Ideal.Quotient
theorem dvd_sub_pow_of_dvd_sub {R : Type*} [CommRing R] {p : ℕ} {a b : R} (h : (p : R) ∣ a - b)
(k : ℕ) : (p ^ (k + 1) : R) ∣ a ^ p ^ k - b ^ p ^ k := by
induction k with
| zero => rwa [pow_one, pow_zero, pow_one, pow_one]
| succ k ih =>
rw [pow_succ p k, pow_mul, pow_mul, ← geom_sum₂_mul, pow_succ']
refine mul_dvd_mul ?_ ih
let f : R →+* R ⧸ span {(p : R)} := mk (span {(p : R)})
have hf : ∀ r : R, (p : R) ∣ r ↔ f r = 0 := fun r ↦ by rw [eq_zero_iff_mem, mem_span_singleton]
rw [hf, map_sub, sub_eq_zero] at h
rw [hf, RingHom.map_geom_sum₂, map_pow, map_pow, h, geom_sum₂_self, mul_eq_zero_of_left]
rw [← map_natCast f, eq_zero_iff_mem, mem_span_singleton]
end |
.lake/packages/mathlib/Mathlib/NumberTheory/Divisors.lean | import Mathlib.Algebra.IsPrimePow
import Mathlib.Algebra.Order.BigOperators.Group.Finset
import Mathlib.Algebra.Order.Interval.Finset.SuccPred
import Mathlib.Algebra.Order.Ring.Int
import Mathlib.Algebra.Ring.CharZero
import Mathlib.Data.Nat.Cast.Order.Ring
import Mathlib.Data.Nat.PrimeFin
import Mathlib.Data.Nat.SuccPred
import Mathlib.Order.Interval.Finset.Nat
/-!
# Divisor Finsets
This file defines sets of divisors of a natural number. This is particularly useful as background
for defining Dirichlet convolution.
## Main Definitions
Let `n : ℕ`. All of the following definitions are in the `Nat` namespace:
* `divisors n` is the `Finset` of natural numbers that divide `n`.
* `properDivisors n` is the `Finset` of natural numbers that divide `n`, other than `n`.
* `divisorsAntidiagonal n` is the `Finset` of pairs `(x,y)` such that `x * y = n`.
* `Perfect n` is true when `n` is positive and the sum of `properDivisors n` is `n`.
## Conventions
Since `0` has infinitely many divisors, none of the definitions in this file make sense for it.
Therefore we adopt the convention that `Nat.divisors 0`, `Nat.properDivisors 0`,
`Nat.divisorsAntidiagonal 0` and `Int.divisorsAntidiag 0` are all `∅`.
## Tags
divisors, perfect numbers
-/
open Finset
namespace Nat
variable (n : ℕ)
/-- `divisors n` is the `Finset` of divisors of `n`. By convention, we set `divisors 0 = ∅`. -/
def divisors : Finset ℕ := {d ∈ Ico 1 (n + 1) | d ∣ n}
/-- `properDivisors n` is the `Finset` of divisors of `n`, other than `n`.
By convention, we set `properDivisors 0 = ∅`. -/
def properDivisors : Finset ℕ := {d ∈ Ico 1 n | d ∣ n}
/-- Pairs of divisors of a natural number as a finset.
`n.divisorsAntidiagonal` is the finset of pairs `(a, b) : ℕ × ℕ` such that `a * b = n`.
By convention, we set `Nat.divisorsAntidiagonal 0 = ∅`.
O(n). -/
def divisorsAntidiagonal : Finset (ℕ × ℕ) :=
(Icc 1 n).filterMap (fun x ↦ let y := n / x; if x * y = n then some (x, y) else none)
fun x₁ x₂ (x, y) hx₁ hx₂ ↦ by aesop
/-- Pairs of divisors of a natural number, as a list.
`n.divisorsAntidiagonalList` is the list of pairs `(a, b) : ℕ × ℕ` such that `a * b = n`, ordered
by increasing `a`. By convention, we set `Nat.divisorsAntidiagonalList 0 = []`.
-/
def divisorsAntidiagonalList (n : ℕ) : List (ℕ × ℕ) :=
(List.range' 1 n).filterMap
(fun x ↦ let y := n / x; if x * y = n then some (x, y) else none)
variable {n}
@[simp]
theorem filter_dvd_eq_divisors (h : n ≠ 0) : {d ∈ range n.succ | d ∣ n} = n.divisors := by
ext
simp only [divisors, mem_filter, mem_range, mem_Ico, and_congr_left_iff, iff_and_self]
exact fun ha _ => succ_le_iff.mpr (pos_of_dvd_of_pos ha h.bot_lt)
@[simp]
theorem filter_dvd_eq_properDivisors (h : n ≠ 0) : {d ∈ range n | d ∣ n} = n.properDivisors := by
ext
simp only [properDivisors, mem_filter, mem_range, mem_Ico, and_congr_left_iff, iff_and_self]
exact fun ha _ => succ_le_iff.mpr (pos_of_dvd_of_pos ha h.bot_lt)
theorem self_notMem_properDivisors : n ∉ properDivisors n := by simp [properDivisors]
@[deprecated (since := "2025-05-23")]
alias properDivisors.not_self_mem := self_notMem_properDivisors
@[simp]
theorem mem_properDivisors {m : ℕ} : n ∈ properDivisors m ↔ n ∣ m ∧ n < m := by
rcases eq_or_ne m 0 with (rfl | hm); · simp [properDivisors]
simp only [and_comm, ← filter_dvd_eq_properDivisors hm, mem_filter, mem_range]
theorem insert_self_properDivisors (h : n ≠ 0) : insert n (properDivisors n) = divisors n := by
rw [divisors, properDivisors,
← Finset.insert_Ico_right_eq_Ico_add_one (one_le_iff_ne_zero.2 h),
Finset.filter_insert, if_pos (dvd_refl n)]
theorem cons_self_properDivisors (h : n ≠ 0) :
cons n (properDivisors n) self_notMem_properDivisors = divisors n := by
rw [cons_eq_insert, insert_self_properDivisors h]
@[simp]
theorem mem_divisors {m : ℕ} : n ∈ divisors m ↔ n ∣ m ∧ m ≠ 0 := by
rcases eq_or_ne m 0 with (rfl | hm); · simp [divisors]
simp only [hm, Ne, not_false_iff, and_true, ← filter_dvd_eq_divisors hm, mem_filter,
mem_range, and_iff_right_iff_imp, Nat.lt_succ_iff]
exact le_of_dvd hm.bot_lt
theorem dvd_of_mem_divisors {m : ℕ} (h : n ∈ divisors m) : n ∣ m := (mem_divisors.mp h).1
theorem ne_zero_of_mem_divisors {m : ℕ} (h : n ∈ divisors m) : m ≠ 0 := (mem_divisors.mp h).2
theorem one_mem_divisors : 1 ∈ divisors n ↔ n ≠ 0 := by simp
theorem mem_divisors_self (n : ℕ) (h : n ≠ 0) : n ∈ n.divisors :=
mem_divisors.2 ⟨dvd_rfl, h⟩
@[simp]
theorem mem_divisorsAntidiagonal {x : ℕ × ℕ} :
x ∈ divisorsAntidiagonal n ↔ x.fst * x.snd = n ∧ n ≠ 0 := by
obtain ⟨a, b⟩ := x
simp only [divisorsAntidiagonal, mul_div_eq_iff_dvd, mem_filterMap, mem_Icc, one_le_iff_ne_zero,
Option.ite_none_right_eq_some, Option.some.injEq, Prod.ext_iff, and_left_comm, exists_eq_left]
constructor
· rintro ⟨han, ⟨ha, han'⟩, rfl⟩
simp [Nat.mul_div_eq_iff_dvd, han]
cutsat
· rintro ⟨rfl, hab⟩
rw [mul_ne_zero_iff] at hab
simpa [hab.1, hab.2] using Nat.le_mul_of_pos_right _ hab.2.bot_lt
@[simp] lemma divisorsAntidiagonalList_zero : divisorsAntidiagonalList 0 = [] := rfl
@[simp] lemma divisorsAntidiagonalList_one : divisorsAntidiagonalList 1 = [(1, 1)] := rfl
@[simp]
lemma toFinset_divisorsAntidiagonalList {n : ℕ} :
n.divisorsAntidiagonalList.toFinset = n.divisorsAntidiagonal := by
rw [divisorsAntidiagonalList, divisorsAntidiagonal, List.toFinset_filterMap
(f_inj := by simp_all), List.toFinset_range'_1_1]
lemma sorted_divisorsAntidiagonalList_fst {n : ℕ} :
n.divisorsAntidiagonalList.Sorted (·.fst < ·.fst) := by
refine (List.sorted_lt_range' _ _ Nat.one_ne_zero).filterMap fun a b c d h h' ha => ?_
rw [Option.ite_none_right_eq_some, Option.some.injEq] at h h'
simpa [← h.right, ← h'.right]
lemma sorted_divisorsAntidiagonalList_snd {n : ℕ} :
n.divisorsAntidiagonalList.Sorted (·.snd > ·.snd) := by
obtain rfl | hn := eq_or_ne n 0
· simp
refine (List.sorted_lt_range' _ _ Nat.one_ne_zero).filterMap ?_
simp only [Option.ite_none_right_eq_some, Option.some.injEq, gt_iff_lt, and_imp, Prod.forall,
Prod.mk.injEq]
rintro a b _ _ _ _ ha rfl rfl hb rfl rfl hab
rwa [Nat.div_lt_div_left hn ⟨_, hb.symm⟩ ⟨_, ha.symm⟩]
lemma nodup_divisorsAntidiagonalList {n : ℕ} : n.divisorsAntidiagonalList.Nodup :=
have : IsIrrefl (ℕ × ℕ) (·.fst < ·.fst) := ⟨by simp⟩
sorted_divisorsAntidiagonalList_fst.nodup
/-- The `Finset` and `List` versions agree by definition. -/
@[simp]
theorem val_divisorsAntidiagonal (n : ℕ) :
(divisorsAntidiagonal n).val = divisorsAntidiagonalList n :=
rfl
@[simp]
lemma mem_divisorsAntidiagonalList {n : ℕ} {a : ℕ × ℕ} :
a ∈ n.divisorsAntidiagonalList ↔ a.1 * a.2 = n ∧ n ≠ 0 := by
rw [← List.mem_toFinset, toFinset_divisorsAntidiagonalList, mem_divisorsAntidiagonal]
@[simp high]
lemma swap_mem_divisorsAntidiagonalList {a : ℕ × ℕ} :
a.swap ∈ n.divisorsAntidiagonalList ↔ a ∈ n.divisorsAntidiagonalList := by simp [mul_comm]
lemma reverse_divisorsAntidiagonalList (n : ℕ) :
n.divisorsAntidiagonalList.reverse = n.divisorsAntidiagonalList.map .swap := by
have : IsAsymm (ℕ × ℕ) (·.snd < ·.snd) := ⟨fun _ _ ↦ lt_asymm⟩
refine List.eq_of_perm_of_sorted ?_ sorted_divisorsAntidiagonalList_snd.reverse <|
sorted_divisorsAntidiagonalList_fst.map _ fun _ _ ↦ id
simp [List.reverse_perm', List.perm_ext_iff_of_nodup nodup_divisorsAntidiagonalList
(nodup_divisorsAntidiagonalList.map Prod.swap_injective), mul_comm]
lemma ne_zero_of_mem_divisorsAntidiagonal {p : ℕ × ℕ} (hp : p ∈ n.divisorsAntidiagonal) :
p.1 ≠ 0 ∧ p.2 ≠ 0 := by
obtain ⟨hp₁, hp₂⟩ := Nat.mem_divisorsAntidiagonal.mp hp
exact mul_ne_zero_iff.mp (hp₁.symm ▸ hp₂)
lemma left_ne_zero_of_mem_divisorsAntidiagonal {p : ℕ × ℕ} (hp : p ∈ n.divisorsAntidiagonal) :
p.1 ≠ 0 :=
(ne_zero_of_mem_divisorsAntidiagonal hp).1
lemma right_ne_zero_of_mem_divisorsAntidiagonal {p : ℕ × ℕ} (hp : p ∈ n.divisorsAntidiagonal) :
p.2 ≠ 0 :=
(ne_zero_of_mem_divisorsAntidiagonal hp).2
theorem divisor_le {m : ℕ} : n ∈ divisors m → n ≤ m := by
rcases m with - | m
· simp
· simp only [mem_divisors, Nat.succ_ne_zero m, and_true, Ne, not_false_iff]
exact Nat.le_of_dvd (Nat.succ_pos m)
@[gcongr]
theorem divisors_subset_of_dvd {m : ℕ} (hzero : n ≠ 0) (h : m ∣ n) : divisors m ⊆ divisors n :=
Finset.subset_iff.2 fun _x hx => Nat.mem_divisors.mpr ⟨(Nat.mem_divisors.mp hx).1.trans h, hzero⟩
theorem card_divisors_le_self (n : ℕ) : #n.divisors ≤ n := calc
_ ≤ #(Ico 1 (n + 1)) := by
apply card_le_card
simp only [divisors, filter_subset]
_ = n := by rw [card_Ico, add_tsub_cancel_right]
theorem divisors_subset_properDivisors {m : ℕ} (hzero : n ≠ 0) (h : m ∣ n) (hdiff : m ≠ n) :
divisors m ⊆ properDivisors n := by
apply Finset.subset_iff.2
intro x hx
exact
Nat.mem_properDivisors.2
⟨(Nat.mem_divisors.1 hx).1.trans h,
lt_of_le_of_lt (divisor_le hx)
(lt_of_le_of_ne (divisor_le (Nat.mem_divisors.2 ⟨h, hzero⟩)) hdiff)⟩
lemma divisors_filter_dvd_of_dvd {n m : ℕ} (hn : n ≠ 0) (hm : m ∣ n) :
{d ∈ n.divisors | d ∣ m} = m.divisors := by
ext k
simp_rw [mem_filter, mem_divisors]
exact ⟨fun ⟨_, hkm⟩ ↦ ⟨hkm, ne_zero_of_dvd_ne_zero hn hm⟩, fun ⟨hk, _⟩ ↦ ⟨⟨hk.trans hm, hn⟩, hk⟩⟩
@[simp]
theorem divisors_zero : divisors 0 = ∅ := by
ext
simp
@[simp]
theorem properDivisors_zero : properDivisors 0 = ∅ := by
ext
simp
@[simp]
lemma nonempty_divisors : (divisors n).Nonempty ↔ n ≠ 0 :=
⟨fun ⟨m, hm⟩ hn ↦ by simp [hn] at hm, fun hn ↦ ⟨1, one_mem_divisors.2 hn⟩⟩
@[simp]
lemma divisors_eq_empty : divisors n = ∅ ↔ n = 0 :=
not_nonempty_iff_eq_empty.symm.trans nonempty_divisors.not_left
theorem properDivisors_subset_divisors : properDivisors n ⊆ divisors n :=
filter_subset_filter _ <| Ico_subset_Ico_right n.le_succ
@[simp]
theorem divisors_one : divisors 1 = {1} := by
ext
simp
@[simp]
theorem properDivisors_one : properDivisors 1 = ∅ := by rw [properDivisors, Ico_self, filter_empty]
theorem pos_of_mem_divisors {m : ℕ} (h : m ∈ n.divisors) : 0 < m := by
cases m
· rw [mem_divisors, zero_dvd_iff (a := n)] at h
cases h.2 h.1
apply Nat.succ_pos
theorem pos_of_mem_properDivisors {m : ℕ} (h : m ∈ n.properDivisors) : 0 < m :=
pos_of_mem_divisors (properDivisors_subset_divisors h)
theorem one_mem_properDivisors_iff_one_lt : 1 ∈ n.properDivisors ↔ 1 < n := by
rw [mem_properDivisors, and_iff_right (one_dvd _)]
@[simp]
lemma sup_divisors_id (n : ℕ) : n.divisors.sup id = n := by
refine le_antisymm (Finset.sup_le fun _ ↦ divisor_le) ?_
rcases Decidable.eq_or_ne n 0 with rfl | hn
· apply zero_le
· exact Finset.le_sup (f := id) <| mem_divisors_self n hn
lemma one_lt_of_mem_properDivisors {m n : ℕ} (h : m ∈ n.properDivisors) : 1 < n :=
lt_of_le_of_lt (pos_of_mem_properDivisors h) (mem_properDivisors.1 h).2
lemma one_lt_div_of_mem_properDivisors {m n : ℕ} (h : m ∈ n.properDivisors) :
1 < n / m := by
obtain ⟨h_dvd, h_lt⟩ := mem_properDivisors.mp h
rwa [Nat.lt_div_iff_mul_lt' h_dvd, mul_one]
/-- See also `Nat.mem_properDivisors`. -/
lemma mem_properDivisors_iff_exists {m n : ℕ} (hn : n ≠ 0) :
m ∈ n.properDivisors ↔ ∃ k > 1, n = m * k := by
refine ⟨fun h ↦ ⟨n / m, one_lt_div_of_mem_properDivisors h, ?_⟩, ?_⟩
· exact (Nat.mul_div_cancel' (mem_properDivisors.mp h).1).symm
· rintro ⟨k, hk, rfl⟩
rw [mul_ne_zero_iff] at hn
exact mem_properDivisors.mpr ⟨⟨k, rfl⟩, lt_mul_of_one_lt_right (Nat.pos_of_ne_zero hn.1) hk⟩
@[simp]
lemma nonempty_properDivisors : n.properDivisors.Nonempty ↔ 1 < n :=
⟨fun ⟨_m, hm⟩ ↦ one_lt_of_mem_properDivisors hm, fun hn ↦
⟨1, one_mem_properDivisors_iff_one_lt.2 hn⟩⟩
@[simp]
lemma properDivisors_eq_empty : n.properDivisors = ∅ ↔ n ≤ 1 := by
rw [← not_nonempty_iff_eq_empty, nonempty_properDivisors, not_lt]
@[simp]
theorem divisorsAntidiagonal_zero : divisorsAntidiagonal 0 = ∅ := by
ext
simp
@[simp]
theorem divisorsAntidiagonal_one : divisorsAntidiagonal 1 = {(1, 1)} := by
ext
simp [mul_eq_one, Prod.ext_iff]
@[simp high]
theorem swap_mem_divisorsAntidiagonal {x : ℕ × ℕ} :
x.swap ∈ divisorsAntidiagonal n ↔ x ∈ divisorsAntidiagonal n := by
rw [mem_divisorsAntidiagonal, mem_divisorsAntidiagonal, mul_comm, Prod.swap]
lemma prodMk_mem_divisorsAntidiag {x y : ℕ} (hn : n ≠ 0) :
(x, y) ∈ n.divisorsAntidiagonal ↔ x * y = n := by simp [hn]
theorem fst_mem_divisors_of_mem_antidiagonal {x : ℕ × ℕ} (h : x ∈ divisorsAntidiagonal n) :
x.fst ∈ divisors n := by
rw [mem_divisorsAntidiagonal] at h
simp [Dvd.intro _ h.1, h.2]
theorem snd_mem_divisors_of_mem_antidiagonal {x : ℕ × ℕ} (h : x ∈ divisorsAntidiagonal n) :
x.snd ∈ divisors n := by
rw [mem_divisorsAntidiagonal] at h
simp [Dvd.intro_left _ h.1, h.2]
@[simp]
theorem map_swap_divisorsAntidiagonal :
(divisorsAntidiagonal n).map (Equiv.prodComm _ _).toEmbedding = divisorsAntidiagonal n := by
rw [← coe_inj, coe_map, Equiv.coe_toEmbedding, Equiv.coe_prodComm,
Set.image_swap_eq_preimage_swap]
ext
exact swap_mem_divisorsAntidiagonal
@[simp]
theorem image_fst_divisorsAntidiagonal : (divisorsAntidiagonal n).image Prod.fst = divisors n := by
ext
simp [Dvd.dvd, @eq_comm _ n (_ * _)]
@[simp]
theorem image_snd_divisorsAntidiagonal : (divisorsAntidiagonal n).image Prod.snd = divisors n := by
rw [← map_swap_divisorsAntidiagonal, map_eq_image, image_image]
exact image_fst_divisorsAntidiagonal
theorem map_div_right_divisors :
n.divisors.map ⟨fun d => (d, n / d), fun _ _ => congr_arg Prod.fst⟩ =
n.divisorsAntidiagonal := by
ext ⟨d, nd⟩
simp only [mem_map, mem_divisorsAntidiagonal, Function.Embedding.coeFn_mk, mem_divisors,
Prod.ext_iff, and_left_comm, exists_eq_left]
constructor
· rintro ⟨⟨⟨k, rfl⟩, hn⟩, rfl⟩
rw [Nat.mul_div_cancel_left _ (left_ne_zero_of_mul hn).bot_lt]
exact ⟨rfl, hn⟩
· rintro ⟨rfl, hn⟩
exact ⟨⟨dvd_mul_right _ _, hn⟩, Nat.mul_div_cancel_left _ (left_ne_zero_of_mul hn).bot_lt⟩
theorem map_div_left_divisors :
n.divisors.map ⟨fun d => (n / d, d), fun _ _ => congr_arg Prod.snd⟩ =
n.divisorsAntidiagonal := by
apply Finset.map_injective (Equiv.prodComm _ _).toEmbedding
ext
rw [map_swap_divisorsAntidiagonal, ← map_div_right_divisors, Finset.map_map]
simp
theorem sum_divisors_eq_sum_properDivisors_add_self :
∑ i ∈ divisors n, i = (∑ i ∈ properDivisors n, i) + n := by
rcases Decidable.eq_or_ne n 0 with (rfl | hn)
· simp
· rw [← cons_self_properDivisors hn, Finset.sum_cons, add_comm]
/-- `n : ℕ` is perfect if and only the sum of the proper divisors of `n` is `n` and `n`
is positive. -/
def Perfect (n : ℕ) : Prop :=
∑ i ∈ properDivisors n, i = n ∧ 0 < n
theorem perfect_iff_sum_properDivisors (h : 0 < n) : Perfect n ↔ ∑ i ∈ properDivisors n, i = n :=
and_iff_left h
theorem perfect_iff_sum_divisors_eq_two_mul (h : 0 < n) :
Perfect n ↔ ∑ i ∈ divisors n, i = 2 * n := by
rw [perfect_iff_sum_properDivisors h, sum_divisors_eq_sum_properDivisors_add_self, two_mul]
constructor <;> intro h
· rw [h]
· apply add_right_cancel h
theorem mem_divisors_prime_pow {p : ℕ} (pp : p.Prime) (k : ℕ) {x : ℕ} :
x ∈ divisors (p ^ k) ↔ ∃ j ≤ k, x = p ^ j := by
rw [mem_divisors, Nat.dvd_prime_pow pp, and_iff_left (ne_of_gt (pow_pos pp.pos k))]
theorem Prime.divisors {p : ℕ} (pp : p.Prime) : divisors p = {1, p} := by
ext
rw [mem_divisors, dvd_prime pp, and_iff_left pp.ne_zero, Finset.mem_insert, Finset.mem_singleton]
theorem Prime.properDivisors {p : ℕ} (pp : p.Prime) : properDivisors p = {1} := by
rw [← erase_insert self_notMem_properDivisors, insert_self_properDivisors pp.ne_zero,
pp.divisors, pair_comm, erase_insert fun con => pp.ne_one (mem_singleton.1 con)]
theorem divisors_prime_pow {p : ℕ} (pp : p.Prime) (k : ℕ) :
divisors (p ^ k) = (Finset.range (k + 1)).map ⟨(p ^ ·), Nat.pow_right_injective pp.two_le⟩ := by
ext a
rw [mem_divisors_prime_pow pp]
simp [Nat.lt_succ, eq_comm]
theorem divisors_injective : Function.Injective divisors :=
Function.LeftInverse.injective sup_divisors_id
@[simp]
theorem divisors_inj {a b : ℕ} : a.divisors = b.divisors ↔ a = b :=
divisors_injective.eq_iff
theorem eq_properDivisors_of_subset_of_sum_eq_sum {s : Finset ℕ} (hsub : s ⊆ n.properDivisors) :
((∑ x ∈ s, x) = ∑ x ∈ n.properDivisors, x) → s = n.properDivisors := by
cases n
· rw [properDivisors_zero, subset_empty] at hsub
simp [hsub]
classical
rw [← sum_sdiff hsub]
intro h
apply Subset.antisymm hsub
rw [← sdiff_eq_empty_iff_subset]
contrapose h
rw [← Ne, ← nonempty_iff_ne_empty] at h
apply ne_of_lt
rw [← zero_add (∑ x ∈ s, x), ← add_assoc, add_zero]
gcongr
have hlt :=
sum_lt_sum_of_nonempty h fun x hx => pos_of_mem_properDivisors (sdiff_subset hx)
simp only [sum_const_zero] at hlt
apply hlt
theorem sum_properDivisors_dvd (h : (∑ x ∈ n.properDivisors, x) ∣ n) :
∑ x ∈ n.properDivisors, x = 1 ∨ ∑ x ∈ n.properDivisors, x = n := by
rcases n with - | n
· simp
· rcases n with - | n
· simp at h
· rw [or_iff_not_imp_right]
intro ne_n
have hlt : ∑ x ∈ n.succ.succ.properDivisors, x < n.succ.succ :=
lt_of_le_of_ne (Nat.le_of_dvd (Nat.succ_pos _) h) ne_n
symm
rw [← mem_singleton, eq_properDivisors_of_subset_of_sum_eq_sum (singleton_subset_iff.2
(mem_properDivisors.2 ⟨h, hlt⟩)) (sum_singleton _ _), mem_properDivisors]
exact ⟨one_dvd _, Nat.succ_lt_succ (Nat.succ_pos _)⟩
@[to_additive (attr := simp)]
theorem Prime.prod_properDivisors {α : Type*} [CommMonoid α] {p : ℕ} {f : ℕ → α} (h : p.Prime) :
∏ x ∈ p.properDivisors, f x = f 1 := by simp [h.properDivisors]
@[to_additive (attr := simp)]
theorem Prime.prod_divisors {α : Type*} [CommMonoid α] {p : ℕ} {f : ℕ → α} (h : p.Prime) :
∏ x ∈ p.divisors, f x = f p * f 1 := by
rw [← cons_self_properDivisors h.ne_zero, prod_cons, h.prod_properDivisors]
theorem properDivisors_eq_singleton_one_iff_prime : n.properDivisors = {1} ↔ n.Prime := by
refine ⟨?_, ?_⟩
· intro h
refine Nat.prime_def.mpr ⟨?_, fun m hdvd => ?_⟩
· match n with
| 0 => contradiction
| 1 => contradiction
| Nat.succ (Nat.succ n) => simp
· rw [← mem_singleton, ← h, mem_properDivisors]
have := Nat.le_of_dvd ?_ hdvd
· simpa [hdvd, this] using (le_iff_eq_or_lt.mp this).symm
· by_contra!
simp only [nonpos_iff_eq_zero.mp this] at h
contradiction
· exact fun h => Prime.properDivisors h
theorem sum_properDivisors_eq_one_iff_prime : ∑ x ∈ n.properDivisors, x = 1 ↔ n.Prime := by
rcases n with - | n
· simp [Nat.not_prime_zero]
· cases n
· simp [Nat.not_prime_one]
· rw [← properDivisors_eq_singleton_one_iff_prime]
refine ⟨fun h => ?_, fun h => h.symm ▸ sum_singleton _ _⟩
rw [@eq_comm (Finset ℕ) _ _]
apply
eq_properDivisors_of_subset_of_sum_eq_sum
(singleton_subset_iff.2
(one_mem_properDivisors_iff_one_lt.2 (succ_lt_succ (Nat.succ_pos _))))
((sum_singleton _ _).trans h.symm)
theorem mem_properDivisors_prime_pow {p : ℕ} (pp : p.Prime) (k : ℕ) {x : ℕ} :
x ∈ properDivisors (p ^ k) ↔ ∃ (j : ℕ) (_ : j < k), x = p ^ j := by
rw [mem_properDivisors, Nat.dvd_prime_pow pp, ← exists_and_right]
simp only [exists_prop, and_assoc]
apply exists_congr
intro a
constructor <;> intro h
· rcases h with ⟨_h_left, rfl, h_right⟩
rw [Nat.pow_lt_pow_iff_right pp.one_lt] at h_right
exact ⟨h_right, rfl⟩
· rcases h with ⟨h_left, rfl⟩
rw [Nat.pow_lt_pow_iff_right pp.one_lt]
simp [h_left, le_of_lt]
theorem properDivisors_prime_pow {p : ℕ} (pp : p.Prime) (k : ℕ) :
properDivisors (p ^ k) = (Finset.range k).map ⟨(p ^ ·), Nat.pow_right_injective pp.two_le⟩ := by
ext a
simp only [mem_properDivisors, mem_map, mem_range, Function.Embedding.coeFn_mk]
have := mem_properDivisors_prime_pow pp k (x := a)
rw [mem_properDivisors] at this
grind
@[to_additive (attr := simp)]
theorem prod_properDivisors_prime_pow {α : Type*} [CommMonoid α] {k p : ℕ} {f : ℕ → α}
(h : p.Prime) : (∏ x ∈ (p ^ k).properDivisors, f x) = ∏ x ∈ range k, f (p ^ x) := by
simp [h, properDivisors_prime_pow]
@[to_additive (attr := simp) sum_divisors_prime_pow]
theorem prod_divisors_prime_pow {α : Type*} [CommMonoid α] {k p : ℕ} {f : ℕ → α} (h : p.Prime) :
(∏ x ∈ (p ^ k).divisors, f x) = ∏ x ∈ range (k + 1), f (p ^ x) := by
simp [h, divisors_prime_pow]
@[to_additive]
theorem prod_divisorsAntidiagonal {M : Type*} [CommMonoid M] (f : ℕ → ℕ → M) {n : ℕ} :
∏ i ∈ n.divisorsAntidiagonal, f i.1 i.2 = ∏ i ∈ n.divisors, f i (n / i) := by
rw [← map_div_right_divisors, Finset.prod_map]
rfl
@[to_additive]
theorem prod_divisorsAntidiagonal' {M : Type*} [CommMonoid M] (f : ℕ → ℕ → M) {n : ℕ} :
∏ i ∈ n.divisorsAntidiagonal, f i.1 i.2 = ∏ i ∈ n.divisors, f (n / i) i := by
rw [← map_swap_divisorsAntidiagonal, Finset.prod_map]
exact prod_divisorsAntidiagonal fun i j => f j i
/-- The factors of `n` are the prime divisors -/
theorem primeFactors_eq_to_filter_divisors_prime (n : ℕ) :
n.primeFactors = {p ∈ divisors n | p.Prime} := by
rcases n.eq_zero_or_pos with (rfl | hn)
· simp
· ext q
simpa [hn, hn.ne', mem_primeFactorsList] using and_comm
lemma primeFactors_filter_dvd_of_dvd {m n : ℕ} (hn : n ≠ 0) (hmn : m ∣ n) :
{p ∈ n.primeFactors | p ∣ m} = m.primeFactors := by
simp_rw [primeFactors_eq_to_filter_divisors_prime, filter_comm,
divisors_filter_dvd_of_dvd hn hmn]
@[simp]
theorem image_div_divisors_eq_divisors (n : ℕ) :
image (fun x : ℕ => n / x) n.divisors = n.divisors := by
by_cases hn : n = 0
· simp [hn]
ext a
constructor
· rw [mem_image]
rintro ⟨x, hx1, hx2⟩
rw [mem_divisors] at *
refine ⟨?_, hn⟩
rw [← hx2]
exact div_dvd_of_dvd hx1.1
· rw [mem_divisors, mem_image]
rintro ⟨h1, -⟩
exact ⟨n / a, mem_divisors.mpr ⟨div_dvd_of_dvd h1, hn⟩, Nat.div_div_self h1 hn⟩
@[to_additive (attr := simp) sum_div_divisors]
theorem prod_div_divisors {α : Type*} [CommMonoid α] (n : ℕ) (f : ℕ → α) :
(∏ d ∈ n.divisors, f (n / d)) = n.divisors.prod f := by
by_cases hn : n = 0; · simp [hn]
rw [← prod_image]
· exact prod_congr (image_div_divisors_eq_divisors n) (by simp)
· intro x hx y hy h
rw [mem_coe, mem_divisors] at hx hy
exact (div_eq_iff_eq_of_dvd_dvd hn hx.1 hy.1).mp h
theorem disjoint_divisors_filter_isPrimePow {a b : ℕ} (hab : a.Coprime b) :
Disjoint (a.divisors.filter IsPrimePow) (b.divisors.filter IsPrimePow) := by
simp only [Finset.disjoint_left, Finset.mem_filter, and_imp, Nat.mem_divisors, not_and]
rintro n han _ha hn hbn _hb -
exact hn.ne_one (Nat.eq_one_of_dvd_coprimes hab han hbn)
end Nat
namespace Int
variable {xy : ℤ × ℤ} {x y z : ℤ}
-- Local notation for the embeddings `n ↦ n, n ↦ -n : ℕ → ℤ`
local notation "natCast" => Nat.castEmbedding (R := ℤ)
local notation "negNatCast" =>
Function.Embedding.trans Nat.castEmbedding (Equiv.toEmbedding (Equiv.neg ℤ))
/-- Pairs of divisors of an integer as a finset.
`z.divisorsAntidiag` is the finset of pairs `(a, b) : ℤ × ℤ` such that `a * b = z`.
By convention, we set `Int.divisorsAntidiag 0 = ∅`.
O(|z|). Computed from `Nat.divisorsAntidiagonal`. -/
def divisorsAntidiag : (z : ℤ) → Finset (ℤ × ℤ)
| (n : ℕ) =>
let s : Finset (ℕ × ℕ) := n.divisorsAntidiagonal
(s.map <| .prodMap natCast natCast).disjUnion (s.map <| .prodMap negNatCast negNatCast) <| by
simp +contextual [s, disjoint_left, eq_comm]
| negSucc n =>
let s : Finset (ℕ × ℕ) := (n + 1).divisorsAntidiagonal
(s.map <| .prodMap natCast negNatCast).disjUnion (s.map <| .prodMap negNatCast natCast) <| by
simp +contextual [s, disjoint_left, eq_comm, forall_swap (α := _ * _ = _)]
@[simp]
lemma mem_divisorsAntidiag :
∀ {z} {xy : ℤ × ℤ}, xy ∈ divisorsAntidiag z ↔ xy.fst * xy.snd = z ∧ z ≠ 0
| (n : ℕ), ((x : ℕ), (y : ℕ)) => by
simp [divisorsAntidiag]
norm_cast
simp +contextual [eq_comm]
| (n : ℕ), (negSucc x, negSucc y) => by
simp [divisorsAntidiag, negSucc_eq, -neg_add_rev]
norm_cast
simp +contextual [eq_comm]
| (n : ℕ), ((x : ℕ), negSucc y) => by
simp [divisorsAntidiag, negSucc_eq, -neg_add_rev]
norm_cast
aesop
| (n : ℕ), (negSucc x, (y : ℕ)) => by
suffices (∃ a, (n = a * y ∧ ¬n = 0) ∧ (a:ℤ) = -1 + -↑x) ↔ (n:ℤ) = (-1 + -↑x) * ↑y ∧ ¬n = 0 by
simpa [divisorsAntidiag, eq_comm, negSucc_eq]
simp only [← Int.neg_add, Int.add_comm 1, Int.neg_mul, Int.add_mul]
norm_cast
match n with
| 0 => simp
| n + 1 => simp
| .negSucc n, ((x : ℕ), (y : ℕ)) => by
simp [divisorsAntidiag]
norm_cast
| .negSucc n, (negSucc x, negSucc y) => by
simp [divisorsAntidiag, negSucc_eq, -neg_add_rev]
norm_cast
simp +contextual
| .negSucc n, ((x : ℕ), negSucc y) => by
simp [divisorsAntidiag, negSucc_eq, -neg_add_rev]
norm_cast
aesop
| .negSucc n, (negSucc x, (y : ℕ)) => by
simp [divisorsAntidiag, negSucc_eq, -neg_add_rev]
norm_cast
simp +contextual [eq_comm]
@[simp] lemma divisorsAntidiag_zero : divisorsAntidiag 0 = ∅ := rfl
-- TODO Write a simproc instead of `divisorsAntidiagonal_one`, ..., `divisorsAntidiagonal_four` ...
@[simp]
theorem divisorsAntidiagonal_one :
Int.divisorsAntidiag 1 = {(1, 1), (-1, -1)} :=
rfl
@[simp]
theorem divisorsAntidiagonal_two :
Int.divisorsAntidiag 2 = {(1, 2), (2, 1), (-1, -2), (-2, -1)} :=
rfl
@[simp]
theorem divisorsAntidiagonal_three :
Int.divisorsAntidiag 3 = {(1, 3), (3, 1), (-1, -3), (-3, -1)} :=
rfl
@[simp]
theorem divisorsAntidiagonal_four :
Int.divisorsAntidiag 4 = {(1, 4), (2, 2), (4, 1), (-1, -4), (-2, -2), (-4, -1)} :=
rfl
lemma prodMk_mem_divisorsAntidiag (hz : z ≠ 0) : (x, y) ∈ z.divisorsAntidiag ↔ x * y = z := by
simp [hz]
@[simp high]
lemma swap_mem_divisorsAntidiag : xy.swap ∈ z.divisorsAntidiag ↔ xy ∈ z.divisorsAntidiag := by
simp [mul_comm]
lemma neg_mem_divisorsAntidiag : -xy ∈ z.divisorsAntidiag ↔ xy ∈ z.divisorsAntidiag := by simp
@[simp]
lemma map_prodComm_divisorsAntidiag :
z.divisorsAntidiag.map (Equiv.prodComm _ _).toEmbedding = z.divisorsAntidiag := by
ext; simp [mem_divisorsAntidiag]
@[simp]
lemma map_neg_divisorsAntidiag :
z.divisorsAntidiag.map (Equiv.neg _).toEmbedding = z.divisorsAntidiag := by
ext; simp [mem_divisorsAntidiag, mul_comm]
lemma divisorsAntidiag_neg :
(-z).divisorsAntidiag =
z.divisorsAntidiag.map (.prodMap (.refl _) (Equiv.neg _).toEmbedding) := by
ext; simp [mem_divisorsAntidiag, Prod.ext_iff, neg_eq_iff_eq_neg]
lemma divisorsAntidiag_natCast (n : ℕ) :
divisorsAntidiag n =
(n.divisorsAntidiagonal.map <| .prodMap natCast natCast).disjUnion
(n.divisorsAntidiagonal.map <| .prodMap negNatCast negNatCast) (by
simp +contextual [disjoint_left, eq_comm]) := rfl
lemma divisorsAntidiag_neg_natCast (n : ℕ) :
divisorsAntidiag (-n) =
(n.divisorsAntidiagonal.map <| .prodMap natCast negNatCast).disjUnion
(n.divisorsAntidiagonal.map <| .prodMap negNatCast natCast) (by
simp +contextual [disjoint_left, eq_comm]) := by cases n <;> rfl
lemma divisorsAntidiag_ofNat (n : ℕ) :
divisorsAntidiag ofNat(n) =
(n.divisorsAntidiagonal.map <| .prodMap natCast natCast).disjUnion
(n.divisorsAntidiagonal.map <| .prodMap negNatCast negNatCast) (by
simp +contextual [disjoint_left, eq_comm]) := rfl
/-- This lemma justifies its existence from its utility in crystallographic root system theory. -/
lemma mul_mem_one_two_three_iff {a b : ℤ} :
a * b ∈ ({1, 2, 3} : Set ℤ) ↔ (a, b) ∈ ({
(1, 1), (-1, -1),
(1, 2), (2, 1), (-1, -2), (-2, -1),
(1, 3), (3, 1), (-1, -3), (-3, -1)} : Set (ℤ × ℤ)) := by
simp only [← Int.prodMk_mem_divisorsAntidiag, Set.mem_insert_iff, Set.mem_singleton_iff, ne_eq,
one_ne_zero, not_false_eq_true, OfNat.ofNat_ne_zero]
aesop
/-- This lemma justifies its existence from its utility in crystallographic root system theory. -/
lemma mul_mem_zero_one_two_three_four_iff {a b : ℤ} (h₀ : a = 0 ↔ b = 0) :
a * b ∈ ({0, 1, 2, 3, 4} : Set ℤ) ↔ (a, b) ∈ ({
(0, 0),
(1, 1), (-1, -1),
(1, 2), (2, 1), (-1, -2), (-2, -1),
(1, 3), (3, 1), (-1, -3), (-3, -1),
(4, 1), (1, 4), (-4, -1), (-1, -4), (2, 2), (-2, -2)} : Set (ℤ × ℤ)) := by
simp only [← Int.prodMk_mem_divisorsAntidiag, Set.mem_insert_iff, Set.mem_singleton_iff, ne_eq,
one_ne_zero, not_false_eq_true, OfNat.ofNat_ne_zero]
aesop
end Int |
.lake/packages/mathlib/Mathlib/NumberTheory/FactorisationProperties.lean | import Mathlib.Algebra.Ring.GeomSum
import Mathlib.NumberTheory.Divisors
import Mathlib.Tactic.FinCases
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.NormNum.Prime
/-!
# Factorisation properties of natural numbers
This file defines abundant, pseudoperfect, deficient, and weird numbers and formalizes their
relations with prime and perfect numbers.
## Main Definitions
* `Nat.Abundant`: a natural number `n` is _abundant_ if the sum of its proper divisors is greater
than `n`
* `Nat.Pseudoperfect`: a natural number `n` is _pseudoperfect_ if the sum of a subset of its proper
divisors equals `n`
* `Nat.Deficient`: a natural number `n` is _deficient_ if the sum of its proper divisors is less
than `n`
* `Nat.Weird`: a natural number is _weird_ if it is abundant but not pseudoperfect
## Main Results
* `Nat.deficient_or_perfect_or_abundant`: A positive natural number is either deficient,
perfect, or abundant.
* `Nat.Prime.deficient`: All prime natural numbers are deficient.
* `Nat.infinite_deficient`: There are infinitely many deficient numbers.
* `Nat.Prime.deficient_pow`: Any natural number power of a prime is deficient.
## Implementation Notes
* Zero is not included in any of the definitions and these definitions only apply to natural
numbers greater than zero.
## References
* [R. W. Prielipp, *PERFECT NUMBERS, ABUNDANT NUMBERS, AND DEFICIENT NUMBERS*][Prielipp1970]
## Tags
abundant, deficient, weird, pseudoperfect
-/
open Finset
namespace Nat
variable {n m p : ℕ}
/-- `n : ℕ` is _abundant_ if the sum of the proper divisors of `n` is greater than `n`. -/
def Abundant (n : ℕ) : Prop := n < ∑ i ∈ properDivisors n, i
/-- `n : ℕ` is _deficient_ if the sum of the proper divisors of `n` is less than `n`. -/
def Deficient (n : ℕ) : Prop := ∑ i ∈ properDivisors n, i < n
/-- A positive natural number `n` is _pseudoperfect_ if there exists a subset of the proper
divisors of `n` such that the sum of that subset is equal to `n`. -/
def Pseudoperfect (n : ℕ) : Prop :=
0 < n ∧ ∃ s ⊆ properDivisors n, ∑ i ∈ s, i = n
/-- `n : ℕ` is a _weird_ number if and only if it is abundant but not pseudoperfect. -/
def Weird (n : ℕ) : Prop := Abundant n ∧ ¬ Pseudoperfect n
theorem not_pseudoperfect_iff_forall :
¬ Pseudoperfect n ↔ n = 0 ∨ ∀ s ⊆ properDivisors n, ∑ i ∈ s, i ≠ n := by
rw [Pseudoperfect, not_and_or]
simp only [not_lt, nonpos_iff_eq_zero, not_exists, not_and, ne_eq]
theorem deficient_one : Deficient 1 := zero_lt_one
theorem deficient_two : Deficient 2 := one_lt_two
theorem deficient_three : Deficient 3 := by norm_num [Deficient]
theorem abundant_twelve : Abundant 12 := by
rw [Abundant, show properDivisors 12 = {1,2,3,4,6} by rfl]
simp
theorem weird_seventy : Weird 70 := by
rw [Weird, Abundant, not_pseudoperfect_iff_forall]
have h : properDivisors 70 = {1, 2, 5, 7, 10, 14, 35} := by rfl
constructor
· rw [h]
repeat norm_num
· rw [h]
right
intro s hs
have hs' := mem_powerset.mpr hs
fin_cases hs' <;> decide
lemma deficient_iff_not_abundant_and_not_perfect (hn : n ≠ 0) :
Deficient n ↔ ¬ Abundant n ∧ ¬ Perfect n := by
dsimp only [Perfect, Abundant, Deficient]
cutsat
lemma perfect_iff_not_abundant_and_not_deficient (hn : 0 ≠ n) :
Perfect n ↔ ¬ Abundant n ∧ ¬ Deficient n := by
dsimp only [Perfect, Abundant, Deficient]
cutsat
lemma abundant_iff_not_perfect_and_not_deficient (hn : 0 ≠ n) :
Abundant n ↔ ¬ Perfect n ∧ ¬ Deficient n := by
dsimp only [Perfect, Abundant, Deficient]
cutsat
/-- A positive natural number is either deficient, perfect, or abundant -/
theorem deficient_or_perfect_or_abundant (hn : 0 ≠ n) :
Deficient n ∨ Abundant n ∨ Perfect n := by
dsimp only [Perfect, Abundant, Deficient]
cutsat
theorem Perfect.pseudoperfect (h : Perfect n) : Pseudoperfect n :=
⟨h.2, ⟨properDivisors n, ⟨fun ⦃_⦄ a ↦ a, h.1⟩⟩⟩
theorem Prime.not_abundant (h : Prime n) : ¬ Abundant n :=
fun h1 ↦ (h.one_lt.trans h1).ne' (sum_properDivisors_eq_one_iff_prime.mpr h)
theorem Prime.not_weird (h : Prime n) : ¬ Weird n := by
simp only [Nat.Weird, not_and_or]
left
exact h.not_abundant
theorem Prime.not_pseudoperfect (h : Prime p) : ¬ Pseudoperfect p := by
simp_rw [not_pseudoperfect_iff_forall, ← mem_powerset,
show p.properDivisors.powerset = {∅, {1}} by rw [Prime.properDivisors h]; rfl]
refine Or.inr (fun s hs ↦ ?_)
fin_cases hs <;>
simp only [sum_empty, sum_singleton] <;>
linarith [Prime.one_lt h]
theorem Prime.not_perfect (h : Prime p) : ¬ Perfect p := by
have h1 := Prime.not_pseudoperfect h
revert h1
exact not_imp_not.mpr (Perfect.pseudoperfect)
/-- Any natural number power of a prime is deficient -/
theorem Prime.deficient_pow (h : Prime n) : Deficient (n ^ m) := by
rcases Nat.eq_zero_or_pos m with (rfl | _)
· simpa using deficient_one
· have h1 : (n ^ m).properDivisors = image (n ^ ·) (range m) := by
apply subset_antisymm <;> intro a
· simp only [mem_properDivisors, mem_image, mem_range, dvd_prime_pow h]
rintro ⟨⟨t, ht, rfl⟩, ha'⟩
exact ⟨t, lt_of_le_of_ne ht (fun ht' ↦ lt_irrefl _ (ht' ▸ ha')), rfl⟩
· simp only [mem_image, mem_range, mem_properDivisors, forall_exists_index, and_imp]
intro x hx hy
constructor
· rw [← hy, dvd_prime_pow h]
exact ⟨x, Nat.le_of_succ_le hx, rfl⟩
· rw [← hy]
exact (Nat.pow_lt_pow_iff_right (Prime.two_le h)).mpr hx
have h2 : ∑ i ∈ image (fun x => n ^ x) (range m), i = ∑ i ∈ range m, n ^ i := by
rw [Finset.sum_image]
rintro x _ y _
apply pow_injective_of_not_isUnit h.not_isUnit <| Prime.ne_zero h
rw [Deficient, h1, h2]
calc
∑ i ∈ range m, n ^ i
= (n ^ m - 1) / (n - 1) := (Nat.geomSum_eq (Prime.two_le h) _)
_ ≤ (n ^ m - 1) := Nat.div_le_self (n ^ m - 1) (n - 1)
_ < n ^ m := sub_lt (pow_pos (Prime.pos h) m) (Nat.one_pos)
theorem _root_.IsPrimePow.deficient (h : IsPrimePow n) : Deficient n := by
obtain ⟨p, k, hp, -, rfl⟩ := h
exact hp.nat_prime.deficient_pow
theorem Prime.deficient (h : Prime n) : Deficient n := by
rw [← pow_one n]
exact h.deficient_pow
/-- There exists infinitely many deficient numbers -/
theorem infinite_deficient : {n : ℕ | n.Deficient}.Infinite := by
rw [Set.infinite_iff_exists_gt]
intro a
obtain ⟨b, h1, h2⟩ := exists_infinite_primes a.succ
exact ⟨b, h2.deficient, h1⟩
theorem infinite_even_deficient : {n : ℕ | Even n ∧ n.Deficient}.Infinite := by
rw [Set.infinite_iff_exists_gt]
intro n
use 2 ^ (n + 1)
constructor
· exact ⟨⟨2 ^ n, by rw [pow_succ, mul_two]⟩, prime_two.deficient_pow⟩
· calc
n ≤ 2 ^ n := Nat.le_of_lt n.lt_two_pow_self
_ < 2 ^ (n + 1) := (Nat.pow_lt_pow_iff_right (Nat.one_lt_two)).mpr (lt_add_one n)
theorem infinite_odd_deficient : {n : ℕ | Odd n ∧ n.Deficient}.Infinite := by
rw [Set.infinite_iff_exists_gt]
intro n
obtain ⟨p, ⟨_, h2⟩⟩ := exists_infinite_primes (max (n + 1) 3)
exact ⟨p, Set.mem_setOf.mpr ⟨Prime.odd_of_ne_two h2 (Ne.symm (ne_of_lt (by omega))),
Prime.deficient h2⟩, by omega⟩
end Nat |
.lake/packages/mathlib/Mathlib/NumberTheory/Fermat.lean | import Mathlib.NumberTheory.LegendreSymbol.QuadraticReciprocity
import Mathlib.NumberTheory.LucasPrimality
/-!
# Fermat numbers
The Fermat numbers are a sequence of natural numbers defined as `Nat.fermatNumber n = 2^(2^n) + 1`,
for all natural numbers `n`.
## Main theorems
- `Nat.coprime_fermatNumber_fermatNumber`: two distinct Fermat numbers are coprime.
- `Nat.pepin_primality`: For 0 < n, Fermat number Fₙ is prime if `3 ^ (2 ^ (2 ^ n - 1)) = -1 mod Fₙ`
- `fermat_primeFactors_one_lt`: For 1 < n, Prime factors the Fermat number Fₙ are of
form `k * 2 ^ (n + 2) + 1`.
-/
open Function
namespace Nat
open Finset Nat ZMod
open scoped BigOperators
/-- Fermat numbers: the `n`-th Fermat number is defined as `2^(2^n) + 1`. -/
def fermatNumber (n : ℕ) : ℕ := 2 ^ (2 ^ n) + 1
@[simp] theorem fermatNumber_zero : fermatNumber 0 = 3 := rfl
@[simp] theorem fermatNumber_one : fermatNumber 1 = 5 := rfl
@[simp] theorem fermatNumber_two : fermatNumber 2 = 17 := rfl
theorem fermatNumber_strictMono : StrictMono fermatNumber := by
intro m n
simp only [fermatNumber, add_lt_add_iff_right, Nat.pow_lt_pow_iff_right (one_lt_two : 1 < 2),
imp_self]
lemma fermatNumber_mono : Monotone fermatNumber := fermatNumber_strictMono.monotone
lemma fermatNumber_injective : Injective fermatNumber := fermatNumber_strictMono.injective
lemma three_le_fermatNumber (n : ℕ) : 3 ≤ fermatNumber n := fermatNumber_mono n.zero_le
lemma two_lt_fermatNumber (n : ℕ) : 2 < fermatNumber n := three_le_fermatNumber _
lemma fermatNumber_ne_one (n : ℕ) : fermatNumber n ≠ 1 := by have := three_le_fermatNumber n; cutsat
theorem odd_fermatNumber (n : ℕ) : Odd (fermatNumber n) :=
(even_pow.mpr ⟨even_two, (pow_pos two_pos n).ne'⟩).add_one
theorem prod_fermatNumber (n : ℕ) : ∏ k ∈ range n, fermatNumber k = fermatNumber n - 2 := by
induction n with | zero => rfl | succ n hn =>
rw [prod_range_succ, hn, fermatNumber, fermatNumber, mul_comm,
(show 2 ^ 2 ^ n + 1 - 2 = 2 ^ 2 ^ n - 1 by cutsat), ← sq_sub_sq]
ring_nf
cutsat
theorem fermatNumber_eq_prod_add_two (n : ℕ) :
fermatNumber n = ∏ k ∈ range n, fermatNumber k + 2 := by
rw [prod_fermatNumber, Nat.sub_add_cancel]
exact le_of_lt <| two_lt_fermatNumber _
theorem fermatNumber_succ (n : ℕ) : fermatNumber (n + 1) = (fermatNumber n - 1) ^ 2 + 1 := by
rw [fermatNumber, pow_succ, mul_comm, pow_mul', fermatNumber, add_tsub_cancel_right]
theorem two_mul_fermatNumber_sub_one_sq_le_fermatNumber_sq (n : ℕ) :
2 * (fermatNumber n - 1) ^ 2 ≤ (fermatNumber (n + 1)) ^ 2 := by
simp only [fermatNumber, add_tsub_cancel_right]
have : 0 ≤ 1 + 2 ^ (2 ^ n * 4) := le_add_left _ _
ring_nf
cutsat
theorem fermatNumber_eq_fermatNumber_sq_sub_two_mul_fermatNumber_sub_one_sq (n : ℕ) :
fermatNumber (n + 2) = (fermatNumber (n + 1)) ^ 2 - 2 * (fermatNumber n - 1) ^ 2 := by
simp only [fermatNumber, add_sub_self_right]
rw [← add_sub_self_right (2 ^ 2 ^ (n + 2) + 1) <| 2 * 2 ^ 2 ^ (n + 1)]
ring_nf
end Nat
open Nat
theorem Int.fermatNumber_eq_fermatNumber_sq_sub_two_mul_fermatNumber_sub_one_sq (n : ℕ) :
(fermatNumber (n + 2) : ℤ) = (fermatNumber (n + 1)) ^ 2 - 2 * (fermatNumber n - 1) ^ 2 := by
rw [Nat.fermatNumber_eq_fermatNumber_sq_sub_two_mul_fermatNumber_sub_one_sq,
Nat.cast_sub <| two_mul_fermatNumber_sub_one_sq_le_fermatNumber_sq n]
simp only [fermatNumber, push_cast, add_tsub_cancel_right]
namespace Nat
open Finset
/--
**Goldbach's theorem** : no two distinct Fermat numbers share a common factor greater than one.
From a letter to Euler, see page 37 in [juskevic2022].
-/
theorem coprime_fermatNumber_fermatNumber {m n : ℕ} (hmn : m ≠ n) :
Coprime (fermatNumber m) (fermatNumber n) := by
wlog hmn' : m < n
· simpa only [coprime_comm] using this hmn.symm (by cutsat)
let d := (fermatNumber m).gcd (fermatNumber n)
have h_n : d ∣ fermatNumber n := gcd_dvd_right ..
have h_m : d ∣ 2 := (Nat.dvd_add_right <| (gcd_dvd_left _ _).trans <| dvd_prod_of_mem _
<| mem_range.mpr hmn').mp <| fermatNumber_eq_prod_add_two _ ▸ h_n
refine ((dvd_prime prime_two).mp h_m).resolve_right fun h_two ↦ ?_
exact (odd_fermatNumber _).not_two_dvd_nat (h_two ▸ h_n)
lemma pairwise_coprime_fermatNumber :
Pairwise fun m n ↦ Coprime (fermatNumber m) (fermatNumber n) :=
fun _m _n ↦ coprime_fermatNumber_fermatNumber
open ZMod
/-- Prime `a ^ n + 1` implies `n` is a power of two (**Fermat primes**). -/
theorem pow_of_pow_add_prime {a n : ℕ} (ha : 1 < a) (hn : n ≠ 0) (hP : (a ^ n + 1).Prime) :
∃ m : ℕ, n = 2 ^ m := by
obtain ⟨k, m, hm, rfl⟩ := exists_eq_two_pow_mul_odd hn
rw [pow_mul] at hP
use k
replace ha : 1 < a ^ 2 ^ k := one_lt_pow (pow_ne_zero k two_ne_zero) ha
let h := hm.nat_add_dvd_pow_add_pow (a ^ 2 ^ k) 1
rw [one_pow, hP.dvd_iff_eq (Nat.lt_add_right 1 ha).ne', add_left_inj, pow_eq_self_iff ha] at h
rw [h, mul_one]
/-- `Fₙ = 2^(2^n)+1` is prime if `3^(2^(2^n-1)) = -1 mod Fₙ` (**Pépin's test**). -/
lemma pepin_primality (n : ℕ) (h : 3 ^ (2 ^ (2 ^ n - 1)) = (-1 : ZMod (fermatNumber n))) :
(fermatNumber n).Prime := by
have := Fact.mk (two_lt_fermatNumber n)
have key : 2 ^ n = 2 ^ n - 1 + 1 := (Nat.sub_add_cancel Nat.one_le_two_pow).symm
apply lucas_primality (p := 2 ^ (2 ^ n) + 1) (a := 3)
· rw [Nat.add_sub_cancel, key, pow_succ, pow_mul, ← pow_succ, ← key, h, neg_one_sq]
· intro p hp1 hp2
rw [Nat.add_sub_cancel, (Nat.prime_dvd_prime_iff_eq hp1 prime_two).mp (hp1.dvd_of_dvd_pow hp2),
key, pow_succ, Nat.mul_div_cancel _ two_pos, ← pow_succ, ← key, h]
exact neg_one_ne_one
/-- `Fₙ = 2^(2^n)+1` is prime if `3^((Fₙ - 1)/2) = -1 mod Fₙ` (**Pépin's test**). -/
lemma pepin_primality' (n : ℕ) (h : 3 ^ ((fermatNumber n - 1) / 2) = (-1 : ZMod (fermatNumber n))) :
(fermatNumber n).Prime := by
apply pepin_primality
rw [← h]
congr
rw [fermatNumber, add_tsub_cancel_right, Nat.pow_div Nat.one_le_two_pow Nat.zero_lt_two]
/-- Prime factors of `a ^ (2 ^ n) + 1` are of form `k * 2 ^ (n + 1) + 1`. -/
lemma pow_pow_add_primeFactors_one_lt {a n p : ℕ} (hp : p.Prime) (hp2 : p ≠ 2)
(hpdvd : p ∣ a ^ (2 ^ n) + 1) :
∃ k, p = k * 2 ^ (n + 1) + 1 := by
have : Fact (2 < p) := Fact.mk (lt_of_le_of_ne hp.two_le hp2.symm)
have : Fact p.Prime := Fact.mk hp
have ha1 : (a : ZMod p) ^ (2 ^ n) = -1 := by
rw [eq_neg_iff_add_eq_zero]
exact_mod_cast (natCast_eq_zero_iff (a ^ (2 ^ n) + 1) p).mpr hpdvd
have ha0 : (a : ZMod p) ≠ 0 := by
intro h
rw [h, zero_pow (pow_ne_zero n two_ne_zero), zero_eq_neg] at ha1
exact one_ne_zero ha1
have ha : orderOf (a : ZMod p) = 2 ^ (n + 1) := by
apply orderOf_eq_prime_pow
· rw [ha1]
exact neg_one_ne_one
· rw [pow_succ, pow_mul, ha1, neg_one_sq]
simpa [ha, dvd_def, Nat.sub_eq_iff_eq_add hp.one_le, mul_comm] using orderOf_dvd_card_sub_one ha0
-- Prime factors of `Fₙ = 2 ^ (2 ^ n) + 1`, `1 < n`, are of form `k * 2 ^ (n + 2) + 1`. -/
lemma fermat_primeFactors_one_lt (n p : ℕ) (hn : 1 < n) (hp : p.Prime)
(hpdvd : p ∣ fermatNumber n) :
∃ k, p = k * 2 ^ (n + 2) + 1 := by
have : Fact p.Prime := Fact.mk hp
have hp2 : p ≠ 2 := by
exact ((even_pow.mpr ⟨even_two, pow_ne_zero n two_ne_zero⟩).add_one).ne_two_of_dvd_nat hpdvd
have hp8 : p % 8 = 1 := by
obtain ⟨k, rfl⟩ := pow_pow_add_primeFactors_one_lt hp hp2 hpdvd
obtain ⟨n, rfl⟩ := Nat.exists_eq_add_of_le' hn
rw [add_assoc, pow_add, ← mul_assoc, ← mod_add_mod, mul_mod]
simp
obtain ⟨a, ha⟩ := (exists_sq_eq_two_iff hp2).mpr (Or.inl hp8)
suffices h : p ∣ a.val ^ (2 ^ (n + 1)) + 1 by
exact pow_pow_add_primeFactors_one_lt hp hp2 h
rw [fermatNumber] at hpdvd
rw [← natCast_eq_zero_iff, Nat.cast_add _ 1, Nat.cast_one, Nat.cast_pow] at hpdvd ⊢
rwa [natCast_val, ZMod.cast_id, pow_succ', pow_mul, sq, ← ha]
-- TODO: move to NumberTheory.Mersenne, once we have that.
/-!
### Primality of Mersenne numbers `Mₙ = a ^ n - 1`
-/
/-- Prime `a ^ n - 1` implies `a = 2` and prime `n`. -/
theorem prime_of_pow_sub_one_prime {a n : ℕ} (hn1 : n ≠ 1) (hP : (a ^ n - 1).Prime) :
a = 2 ∧ n.Prime := by
have han1 : 1 < a ^ n := tsub_pos_iff_lt.mp hP.pos
have hn0 : n ≠ 0 := fun h ↦ (h ▸ han1).ne' rfl
have ha1 : 1 < a := (Nat.one_lt_pow_iff hn0).mp han1
have ha0 : 0 < a := one_pos.trans ha1
have ha2 : a = 2 := by
contrapose! hn1
let h := Nat.sub_dvd_pow_sub_pow a 1 n
rw [one_pow, hP.dvd_iff_eq (mt (Nat.sub_eq_iff_eq_add ha1.le).mp hn1), eq_comm] at h
exact (pow_eq_self_iff ha1).mp (Nat.sub_one_cancel ha0 (pow_pos ha0 n) h).symm
subst ha2
refine ⟨rfl, Nat.prime_def.mpr ⟨(two_le_iff n).mpr ⟨hn0, hn1⟩, fun d hdn ↦ ?_⟩⟩
have hinj : ∀ x y, 2 ^ x - 1 = 2 ^ y - 1 → x = y :=
fun x y h ↦ Nat.pow_right_injective le_rfl (sub_one_cancel (pow_pos ha0 x) (pow_pos ha0 y) h)
let h := Nat.sub_dvd_pow_sub_pow (2 ^ d) 1 (n / d)
rw [one_pow, ← pow_mul, Nat.mul_div_cancel' hdn] at h
exact (hP.eq_one_or_self_of_dvd (2 ^ d - 1) h).imp (hinj d 1) (hinj d n)
end Nat |
.lake/packages/mathlib/Mathlib/NumberTheory/TsumDivsorsAntidiagonal.lean | import Mathlib.Analysis.SpecificLimits.Normed
import Mathlib.NumberTheory.ArithmeticFunction
/-!
# Lemmas on infinite sums over the antidiagonal of the divisors function
This file contains lemmas about the antidiagonal of the divisors function. It defines the map from
`Nat.divisorsAntidiagonal n` to `ℕ+ × ℕ+` given by sending `n = a * b` to `(a, b)`.
We then prove some identities about the infinite sums over this antidiagonal, such as
`∑' n : ℕ+, n ^ k * r ^ n / (1 - r ^ n) = ∑' n : ℕ+, σ k n * r ^ n`
which are used for Eisenstein series and their q-expansions. This is also a special case of
Lambert series.
-/
open Filter Complex ArithmeticFunction Nat Topology
/-- The map from `Nat.divisorsAntidiagonal n` to `ℕ+ × ℕ+` given by sending `n = a * b`
to `(a, b)`. -/
def divisorsAntidiagonalFactors (n : ℕ+) : Nat.divisorsAntidiagonal n → ℕ+ × ℕ+ := fun x ↦
⟨⟨x.1.1, Nat.pos_of_mem_divisors (Nat.fst_mem_divisors_of_mem_antidiagonal x.2)⟩,
(⟨x.1.2, Nat.pos_of_mem_divisors (Nat.snd_mem_divisors_of_mem_antidiagonal x.2)⟩ : ℕ+),
Nat.pos_of_mem_divisors (Nat.snd_mem_divisors_of_mem_antidiagonal x.2)⟩
lemma divisorsAntidiagonalFactors_eq {n : ℕ+} (x : Nat.divisorsAntidiagonal n) :
(divisorsAntidiagonalFactors n x).1.1 * (divisorsAntidiagonalFactors n x).2.1 = n := by
simp [divisorsAntidiagonalFactors, (Nat.mem_divisorsAntidiagonal.mp x.2).1]
lemma divisorsAntidiagonalFactors_one (x : Nat.divisorsAntidiagonal 1) :
(divisorsAntidiagonalFactors 1 x) = (1, 1) := by
have h := Nat.mem_divisorsAntidiagonal.mp x.2
simp only [mul_eq_one, ne_eq, one_ne_zero, not_false_eq_true, and_true] at h
simp [divisorsAntidiagonalFactors, h.1, h.2]
/-- The equivalence from the union over `n` of `Nat.divisorsAntidiagonal n` to `ℕ+ × ℕ+`
given by sending `n = a * b` to `(a, b)`. -/
def sigmaAntidiagonalEquivProd : (Σ n : ℕ+, Nat.divisorsAntidiagonal n) ≃ ℕ+ × ℕ+ where
toFun x := divisorsAntidiagonalFactors x.1 x.2
invFun x :=
⟨⟨x.1.val * x.2.val, mul_pos x.1.2 x.2.2⟩, ⟨x.1, x.2⟩, by simp [Nat.mem_divisorsAntidiagonal]⟩
left_inv := by
rintro ⟨n, ⟨k, l⟩, h⟩
rw [Nat.mem_divisorsAntidiagonal] at h
ext <;> simp [divisorsAntidiagonalFactors, ← PNat.coe_injective.eq_iff, h.1]
right_inv _ := rfl
lemma sigmaAntidiagonalEquivProd_symm_apply_fst (x : ℕ+ × ℕ+) :
(sigmaAntidiagonalEquivProd.symm x).1 = x.1.1 * x.2.1 := rfl
lemma sigmaAntidiagonalEquivProd_symm_apply_snd (x : ℕ+ × ℕ+) :
(sigmaAntidiagonalEquivProd.symm x).2 = (x.1.1, x.2.1) := rfl
section tsum
variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] [CompleteSpace 𝕜] [NormSMulClass ℤ 𝕜]
omit [NormSMulClass ℤ 𝕜] in
lemma summable_norm_pow_mul_geometric_div_one_sub (k : ℕ) {r : 𝕜} (hr : ‖r‖ < 1) :
Summable fun n : ℕ ↦ n ^ k * r ^ n / (1 - r ^ n) := by
simp only [div_eq_mul_one_div ( _ * _ ^ _)]
apply Summable.mul_tendsto_const (c := 1 / (1 - 0))
(by simpa using summable_norm_pow_mul_geometric_of_norm_lt_one k hr)
simpa only [Nat.cofinite_eq_atTop] using
tendsto_const_nhds.div ((tendsto_pow_atTop_nhds_zero_of_norm_lt_one hr).const_sub 1) (by simp)
private lemma summable_divisorsAntidiagonal_aux (k : ℕ) {r : 𝕜} (hr : ‖r‖ < 1) :
Summable fun c : (n : ℕ+) × {x // x ∈ (n : ℕ).divisorsAntidiagonal} ↦
(c.2.1.2) ^ k * (r ^ (c.2.1.1 * c.2.1.2)) := by
apply Summable.of_norm
rw [summable_sigma_of_nonneg (fun a ↦ by positivity)]
constructor
· exact fun n ↦ (hasSum_fintype _).summable
· simp only [norm_mul, norm_pow, tsum_fintype, Finset.univ_eq_attach]
apply Summable.of_nonneg_of_le (f := fun c : ℕ+ ↦ ‖(c : 𝕜) ^ (k + 1) * r ^ (c : ℕ)‖)
(fun b ↦ Finset.sum_nonneg (fun _ _ ↦ mul_nonneg (by simp) (by simp))) (fun b ↦ ?_)
(by apply (summable_norm_pow_mul_geometric_of_norm_lt_one (k + 1) hr).subtype)
transitivity ∑ _ ∈ (b : ℕ).divisors, ‖(b : 𝕜)‖ ^ k * ‖r ^ (b : ℕ)‖
· rw [(b : ℕ).divisorsAntidiagonal.sum_attach (fun x ↦ ‖(x.2 : 𝕜)‖ ^ _ * _ ^ (x.1 * x.2)),
sum_divisorsAntidiagonal ((fun x y ↦ ‖(y : 𝕜)‖ ^ k * _ ^ (x * y)))]
gcongr with i hi
· simpa using le_of_dvd b.2 (div_dvd_of_dvd (dvd_of_mem_divisors hi))
· rw [norm_pow, mul_comm, Nat.div_mul_cancel (dvd_of_mem_divisors hi)]
· simp only [norm_pow, Finset.sum_const, nsmul_eq_mul, ← mul_assoc, add_comm k 1, pow_add,
pow_one, norm_mul]
gcongr
simpa using Nat.card_divisors_le_self b
theorem summable_prod_mul_pow (k : ℕ) {r : 𝕜} (hr : ‖r‖ < 1) :
Summable fun c : (ℕ+ × ℕ+) ↦ c.2 ^ k * (r ^ (c.1 * c.2 : ℕ)) := by
simpa [sigmaAntidiagonalEquivProd.summable_iff.symm] using summable_divisorsAntidiagonal_aux k hr
-- access notation `σ`
open scoped sigma
theorem tsum_prod_pow_eq_tsum_sigma (k : ℕ) {r : 𝕜} (hr : ‖r‖ < 1) :
∑' d : ℕ+, ∑' c : ℕ+, c ^ k * r ^ (d * c : ℕ) = ∑' e : ℕ+, σ k e * r ^ (e : ℕ) := by
suffices ∑' c : ℕ+ × ℕ+, c.2 ^ k * r ^ (c.1 * c.2 : ℕ) =
∑' e : ℕ+, σ k e * r ^ (e : ℕ) by rwa [← (summable_prod_mul_pow k hr).tsum_prod]
simp only [← sigmaAntidiagonalEquivProd.tsum_eq, sigmaAntidiagonalEquivProd,
divisorsAntidiagonalFactors, PNat.mk_coe, Equiv.coe_fn_mk, sigma_eq_sum_div, cast_sum,
cast_pow, Summable.tsum_sigma (summable_divisorsAntidiagonal_aux k hr)]
refine tsum_congr fun n ↦ ?_
simpa [tsum_fintype, Finset.sum_mul,
(n : ℕ).divisorsAntidiagonal.sum_attach fun x : ℕ × ℕ ↦ x.2 ^ k * r ^ (x.1 * x.2),
sum_divisorsAntidiagonal fun x y ↦ y ^ k * r ^ (x * y)]
using Finset.sum_congr rfl fun i hi ↦ by rw [Nat.mul_div_cancel' (dvd_of_mem_divisors hi)]
lemma tsum_pow_div_one_sub_eq_tsum_sigma {r : 𝕜} (hr : ‖r‖ < 1) (k : ℕ) :
∑' n : ℕ+, n ^ k * r ^ (n : ℕ) / (1 - r ^ (n : ℕ)) = ∑' n : ℕ+, σ k n * r ^ (n : ℕ) := by
have (m : ℕ) [NeZero m] := tsum_geometric_of_norm_lt_one (ξ := r ^ m)
(by simpa using pow_lt_one₀ (by simp) hr (NeZero.ne _))
simp only [div_eq_mul_inv, ← this, ← tsum_mul_left, mul_assoc, ← _root_.pow_succ',
← fun (n : ℕ) ↦ tsum_pnat_eq_tsum_succ (f := fun m ↦ n ^ k * (r ^ n) ^ m)]
have h00 := tsum_prod_pow_eq_tsum_sigma k hr
rw [Summable.tsum_comm (by apply (summable_prod_mul_pow k hr).prod_symm)] at h00
rw [← h00]
exact tsum_congr₂ <| fun b c ↦ by simp [mul_comm c.val b.val, pow_mul]
end tsum |
.lake/packages/mathlib/Mathlib/NumberTheory/SelbergSieve.lean | import Mathlib.Data.Real.Basic
import Mathlib.NumberTheory.ArithmeticFunction
/-!
# The Selberg Sieve
We set up the working assumptions of the Selberg sieve, define the notion of an upper bound sieve
and show that every upper bound sieve yields an upper bound on the size of the sifted set. We also
define the Λ² sieve and prove that Λ² sieves are upper bound sieves. We then diagonalise the main
term of the Λ² sieve.
We mostly follow the treatment outlined by Heath-Brown in the notes to an old graduate course. One
minor notational difference is that we write $\nu(n)$ in place of $\frac{\omega(n)}{n}$.
## Results
* `siftedSum_le_mainSum_errSum_of_UpperBoundSieve` - Every upper bound sieve gives an upper bound
on the size of the sifted set in terms of `mainSum` and `errSum`
## References
* [Heath-Brown, *Lectures on sieves*][heathbrown2002lecturessieves]
* [Koukoulopoulos, *The Distribution of Prime Numbers*][MR3971232]
-/
noncomputable section
open scoped BigOperators ArithmeticFunction
open Finset Real Nat
/-- We set up a sieve problem as follows. Take a finite set of natural numbers `A`, whose elements
are weighted by a sequence `a n`. Also take a finite set of primes `P`, represented by a squarefree
natural number. These are the primes that we will sift from our set `A`. Suppose we can approximate
`∑ n ∈ {k ∈ A | d ∣ k}, a n = ν d * X + R d`, where `X` is an approximation to the total size of `A`
and `ν` is a multiplicative arithmetic function such that `0 < ν p < 1` for all primes `p ∣ P`.
Then a sieve-type theorem will give us an upper (or lower) bound on the size of the sifted sum
`∑ n ∈ {k ∈ support | k.Coprime P}, a n`, obtained by removing any elements of `A` that are a
multiple of a prime in `P`. -/
structure BoundingSieve where
/-- The set of natural numbers that is to be sifted. The fundamental lemma yields an upper bound
on the size of this set after the multiples of small primes have been removed. -/
support : Finset ℕ
/-- The finite set of prime numbers whose multiples are to be sifted from `support`. We work with
their product because it lets us treat `nu` as a multiplicative arithmetic function. It also
plays well with Moebius inversion. -/
prodPrimes : ℕ
prodPrimes_squarefree : Squarefree prodPrimes
/-- A sequence representing how much each element of `support` should be weighted. -/
weights : ℕ → ℝ
weights_nonneg : ∀ n : ℕ, 0 ≤ weights n
/-- An approximation to `∑ i in support, weights i`, i.e. the size of the unsifted set. A bad
approximation will yield a weak statement in the final theorem. -/
totalMass : ℝ
/-- `nu d` is an approximation to the proportion of elements of `support` that are a multiple of
`d` -/
nu : ArithmeticFunction ℝ
nu_mult : nu.IsMultiplicative
nu_pos_of_prime : ∀ p : ℕ, p.Prime → p ∣ prodPrimes → 0 < nu p
nu_lt_one_of_prime : ∀ p : ℕ, p.Prime → p ∣ prodPrimes → nu p < 1
/-- The Selberg upper bound sieve in particular introduces a parameter called the `level` which
gives the user control over the size of the error term. -/
structure SelbergSieve extends BoundingSieve where
/-- The `level` of the sieve controls how many terms we include in the inclusion-exclusion type
sum. A higher level will yield a tighter bound for the main term, but will also increase the
size of the error term. -/
level : ℝ
one_le_level : 1 ≤ level
attribute [arith_mult] BoundingSieve.nu_mult
namespace Mathlib.Meta.Positivity
open Lean Meta Qq
/-- Extension for the `positivity` tactic: `BoundingSieve.weights`. -/
@[positivity BoundingSieve.weights _ _]
def evalBoundingSieveWeights : PositivityExt where eval {u α} _zα _pα e := do
match u, α, e with
| 0, ~q(ℝ), ~q(@BoundingSieve.weights $s $n) =>
assertInstancesCommute
pure (.nonnegative q(BoundingSieve.weights_nonneg $s $n))
| _, _, _ => throwError "not BoundingSieve.weights"
end Mathlib.Meta.Positivity
namespace BoundingSieve
open SelbergSieve
theorem one_le_y {s : SelbergSieve} : 1 ≤ s.level := s.one_le_level
variable {s : BoundingSieve}
/-! Lemmas about $P$. -/
theorem prodPrimes_ne_zero : s.prodPrimes ≠ 0 :=
Squarefree.ne_zero s.prodPrimes_squarefree
theorem squarefree_of_dvd_prodPrimes {d : ℕ} (hd : d ∣ s.prodPrimes) : Squarefree d :=
Squarefree.squarefree_of_dvd hd s.prodPrimes_squarefree
theorem squarefree_of_mem_divisors_prodPrimes {d : ℕ} (hd : d ∈ divisors s.prodPrimes) :
Squarefree d := by
simp only [Nat.mem_divisors] at hd
exact Squarefree.squarefree_of_dvd hd.left s.prodPrimes_squarefree
/-! Lemmas about $\nu$. -/
theorem prod_primeFactors_nu {d : ℕ} (hd : d ∣ s.prodPrimes) :
∏ p ∈ d.primeFactors, s.nu p = s.nu d := by
rw [← s.nu_mult.map_prod_of_subset_primeFactors _ _ subset_rfl,
Nat.prod_primeFactors_of_squarefree <| Squarefree.squarefree_of_dvd hd s.prodPrimes_squarefree]
theorem nu_pos_of_dvd_prodPrimes {d : ℕ} (hd : d ∣ s.prodPrimes) : 0 < s.nu d := by
calc
0 < ∏ p ∈ d.primeFactors, s.nu p := by
apply prod_pos
intro p hpd
have hp_prime : p.Prime := prime_of_mem_primeFactors hpd
have hp_dvd : p ∣ s.prodPrimes := (dvd_of_mem_primeFactors hpd).trans hd
exact s.nu_pos_of_prime p hp_prime hp_dvd
_ = s.nu d := prod_primeFactors_nu hd
theorem nu_ne_zero {d : ℕ} (hd : d ∣ s.prodPrimes) : s.nu d ≠ 0 := by
apply _root_.ne_of_gt
exact nu_pos_of_dvd_prodPrimes hd
theorem nu_lt_one_of_dvd_prodPrimes {d : ℕ} (hdP : d ∣ s.prodPrimes) (hd_ne_one : d ≠ 1) :
s.nu d < 1 := by
have hd_sq : Squarefree d := Squarefree.squarefree_of_dvd hdP s.prodPrimes_squarefree
have := hd_sq.ne_zero
calc
s.nu d = ∏ p ∈ d.primeFactors, s.nu p := (prod_primeFactors_nu hdP).symm
_ < ∏ p ∈ d.primeFactors, 1 := by
apply prod_lt_prod_of_nonempty
· intro p hp
simp only [mem_primeFactors] at hp
apply s.nu_pos_of_prime p hp.1 (hp.2.1.trans hdP)
· intro p hpd; rw [mem_primeFactors_of_ne_zero hd_sq.ne_zero] at hpd
apply s.nu_lt_one_of_prime p hpd.left (hpd.2.trans hdP)
· simp only [nonempty_primeFactors, show 1 < d by cutsat]
_ = 1 := by
simp
/-- The weight of all the elements that are a multiple of `d`. -/
@[simp]
def multSum (d : ℕ) : ℝ := ∑ n ∈ s.support, if d ∣ n then s.weights n else 0
/-- The remainder term in the approximation A_d = ν (d) X + R_d. This is the degree to which `nu`
fails to approximate the proportion of the weight that is a multiple of `d`. -/
@[simp]
def rem (d : ℕ) : ℝ := s.multSum d - s.nu d * s.totalMass
/-- The weight of all the elements that are not a multiple of any of our finite set of primes. -/
def siftedSum : ℝ := ∑ d ∈ s.support, if Coprime s.prodPrimes d then s.weights d else 0
/-- `X * mainSum μ⁺` is the main term in the upper bound on `sifted_sum`. -/
def mainSum (muPlus : ℕ → ℝ) : ℝ := ∑ d ∈ divisors s.prodPrimes, muPlus d * s.nu d
/-- `errSum μ⁺` is the error term in the upper bound on `sifted_sum`. -/
def errSum (muPlus : ℕ → ℝ) : ℝ := ∑ d ∈ divisors s.prodPrimes, |muPlus d| * |s.rem d|
theorem multSum_eq_main_err (d : ℕ) : s.multSum d = s.nu d * s.totalMass + s.rem d := by
dsimp [rem]
ring
theorem siftedSum_eq_sum_support_mul_ite :
s.siftedSum = ∑ d ∈ s.support, s.weights d * if Nat.gcd s.prodPrimes d = 1 then 1 else 0 := by
dsimp only [siftedSum]
simp_rw [mul_ite, mul_one, mul_zero]
@[deprecated (since := "2025-07-27")]
alias siftedsum_eq_sum_support_mul_ite := siftedSum_eq_sum_support_mul_ite
omit s in
/-- A sequence of coefficients $\mu^{+}$ is upper Moebius if $\mu * \zeta ≤ \mu^{+} * \zeta$. These
coefficients then yield an upper bound on the sifted sum. -/
def IsUpperMoebius (muPlus : ℕ → ℝ) : Prop :=
∀ n : ℕ, (if n = 1 then 1 else 0) ≤ ∑ d ∈ n.divisors, muPlus d
theorem siftedSum_le_sum_of_upperMoebius (muPlus : ℕ → ℝ) (h : IsUpperMoebius muPlus) :
s.siftedSum ≤ ∑ d ∈ divisors s.prodPrimes, muPlus d * s.multSum d := by
have hμ : ∀ n, (if n = 1 then 1 else 0) ≤ ∑ d ∈ n.divisors, muPlus d := h
calc siftedSum ≤
∑ n ∈ s.support, s.weights n * ∑ d ∈ (Nat.gcd s.prodPrimes n).divisors, muPlus d := ?caseA
_ = ∑ n ∈ s.support, ∑ d ∈ divisors s.prodPrimes,
if d ∣ n then s.weights n * muPlus d else 0 := ?caseB
_ = ∑ d ∈ divisors s.prodPrimes, muPlus d * multSum d := ?caseC
case caseA =>
rw [siftedSum_eq_sum_support_mul_ite]
gcongr with n
exact hμ (Nat.gcd s.prodPrimes n)
case caseB =>
simp_rw [mul_sum, ← sum_filter]
congr with n
congr
· rw [← divisors_filter_dvd_of_dvd prodPrimes_ne_zero (Nat.gcd_dvd_left _ _)]
ext x; simp +contextual [dvd_gcd_iff]
case caseC =>
rw [sum_comm]
simp_rw [multSum, ← sum_filter, mul_sum, mul_comm]
theorem siftedSum_le_mainSum_errSum_of_upperMoebius (muPlus : ℕ → ℝ) (h : IsUpperMoebius muPlus) :
s.siftedSum ≤ s.totalMass * s.mainSum muPlus + s.errSum muPlus := calc
s.siftedSum ≤ ∑ d ∈ divisors s.prodPrimes, muPlus d * multSum d :=
siftedSum_le_sum_of_upperMoebius _ h
_ = s.totalMass * mainSum muPlus + ∑ d ∈ divisors s.prodPrimes, muPlus d * s.rem d := by
rw [mainSum, mul_sum, ← sum_add_distrib]
congr with d
dsimp only [rem]; ring
_ ≤ s.totalMass * mainSum muPlus + errSum muPlus := by
rw [errSum]
gcongr _ + ∑ d ∈ _, ?_ with d
rw [← abs_mul]
exact le_abs_self (muPlus d * s.rem d)
end BoundingSieve |
.lake/packages/mathlib/Mathlib/NumberTheory/Wilson.lean | import Mathlib.FieldTheory.Finite.Basic
/-!
# Wilson's theorem.
This file contains a proof of Wilson's theorem.
The heavy lifting is mostly done by the previous `wilsons_lemma`,
but here we also prove the other logical direction.
This could be generalized to similar results about finite abelian groups.
## References
* [Wilson's Theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem)
## TODO
* Give `wilsons_lemma` a descriptive name.
-/
assert_not_exists legendreSym.quadratic_reciprocity
open Finset Nat FiniteField ZMod
open scoped Nat
namespace ZMod
variable (p : ℕ) [Fact p.Prime]
/-- **Wilson's Lemma**: the product of `1`, ..., `p-1` is `-1` modulo `p`. -/
@[simp]
theorem wilsons_lemma : ((p - 1)! : ZMod p) = -1 := by
refine
calc
((p - 1)! : ZMod p) = ∏ x ∈ Ico 1 (succ (p - 1)), (x : ZMod p) := by
rw [← Finset.prod_Ico_id_eq_factorial, prod_natCast]
_ = ∏ x : (ZMod p)ˣ, (x : ZMod p) := ?_
_ = -1 := by
simp_rw [← Units.coeHom_apply, ← map_prod (Units.coeHom (ZMod p)),
prod_univ_units_id_eq_neg_one, Units.coeHom_apply, Units.val_neg, Units.val_one]
have hp : 0 < p := (Fact.out (p := p.Prime)).pos
symm
refine prod_bij (fun a _ => (a : ZMod p).val) ?_ ?_ ?_ ?_
· intro a ha
rw [mem_Ico, ← Nat.succ_sub hp, Nat.add_one_sub_one]
constructor
· apply Nat.pos_of_ne_zero; rw [← @val_zero p]
intro h; apply Units.ne_zero a (val_injective p h)
· exact val_lt _
· intro _ _ _ _ h; rw [Units.ext_iff]; exact val_injective p h
· intro b hb
rw [mem_Ico, Nat.succ_le_iff, ← succ_sub hp, Nat.add_one_sub_one, pos_iff_ne_zero] at hb
refine ⟨Units.mk0 b ?_, Finset.mem_univ _, ?_⟩
· intro h; apply hb.1; apply_fun val at h
simpa only [val_cast_of_lt hb.right, val_zero] using h
· simp only [val_cast_of_lt hb.right, Units.val_mk0]
· rintro a -; simp only [cast_id, natCast_val]
@[simp]
theorem prod_Ico_one_prime : ∏ x ∈ Ico 1 p, (x : ZMod p) = -1 := by
-- Porting note: was `conv in Ico 1 p =>`
conv =>
congr
congr
rw [← Nat.add_one_sub_one p, succ_sub (Fact.out (p := p.Prime)).pos]
rw [← prod_natCast, Finset.prod_Ico_id_eq_factorial, wilsons_lemma]
end ZMod
namespace Nat
variable {n : ℕ}
/-- For `n ≠ 1`, `(n-1)!` is congruent to `-1` modulo `n` only if n is prime. -/
theorem prime_of_fac_equiv_neg_one (h : ((n - 1)! : ZMod n) = -1) (h1 : n ≠ 1) : Prime n := by
rcases eq_or_ne n 0 with (rfl | h0)
· norm_num at h
replace h1 : 1 < n := n.two_le_iff.mpr ⟨h0, h1⟩
by_contra h2
obtain ⟨m, hm1, hm2 : 1 < m, hm3⟩ := exists_dvd_of_not_prime2 h1 h2
have hm : m ∣ (n - 1)! := Nat.dvd_factorial (pos_of_gt hm2) (le_pred_of_lt hm3)
refine hm2.ne' (Nat.dvd_one.mp ((Nat.dvd_add_right hm).mp (hm1.trans ?_)))
rw [← ZMod.natCast_eq_zero_iff, cast_add, cast_one, h, neg_add_cancel]
/-- **Wilson's Theorem**: For `n ≠ 1`, `(n-1)!` is congruent to `-1` modulo `n` iff n is prime. -/
theorem prime_iff_fac_equiv_neg_one (h : n ≠ 1) : Prime n ↔ ((n - 1)! : ZMod n) = -1 := by
refine ⟨fun h1 => ?_, fun h2 => prime_of_fac_equiv_neg_one h2 h⟩
haveI := Fact.mk h1
exact ZMod.wilsons_lemma n
end Nat |
.lake/packages/mathlib/Mathlib/NumberTheory/FermatPsp.lean | import Mathlib.Algebra.Order.Archimedean.Basic
import Mathlib.FieldTheory.Finite.Basic
import Mathlib.Order.Filter.Cofinite
import Mathlib.Tactic.GCongr
/-!
# Fermat Pseudoprimes
In this file we define Fermat pseudoprimes: composite numbers that pass the Fermat primality test.
A natural number `n` passes the Fermat primality test to base `b` (and is therefore deemed a
"probable prime") if `n` divides `b ^ (n - 1) - 1`. `n` is a Fermat pseudoprime to base `b` if `n`
is a composite number that passes the Fermat primality test to base `b` and is coprime with `b`.
Fermat pseudoprimes can also be seen as composite numbers for which Fermat's little theorem holds
true.
Numbers which are Fermat pseudoprimes to all bases are known as Carmichael numbers (not yet defined
in this file).
## Main Results
The main definitions for this file are
- `Nat.ProbablePrime`: A number `n` is a probable prime to base `b` if it passes the Fermat
primality test; that is, if `n` divides `b ^ (n - 1) - 1`
- `Nat.FermatPsp`: A number `n` is a pseudoprime to base `b` if it is a probable prime to base `b`,
is composite, and is coprime with `b` (this last condition is automatically true if `n` divides
`b ^ (n - 1) - 1`, but some sources include it in the definition).
Note that all composite numbers are pseudoprimes to base 0 and 1, and that the definition of
`Nat.ProbablePrime` in this file implies that all numbers are probable primes to bases 0 and 1, and
that 0 and 1 are probable primes to any base.
The main theorems are
- `Nat.exists_infinite_pseudoprimes`: there are infinite pseudoprimes to any base `b ≥ 1`
-/
namespace Nat
/--
`n` is a probable prime to base `b` if `n` passes the Fermat primality test; that is, `n` divides
`b ^ (n - 1) - 1`.
This definition implies that all numbers are probable primes to base 0 or 1, and that 0 and 1 are
probable primes to any base.
-/
def ProbablePrime (n b : ℕ) : Prop :=
n ∣ b ^ (n - 1) - 1
/--
`n` is a Fermat pseudoprime to base `b` if `n` is a probable prime to base `b` and is composite. By
this definition, all composite natural numbers are pseudoprimes to base 0 and 1. This definition
also permits `n` to be less than `b`, so that 4 is a pseudoprime to base 5, for example.
-/
def FermatPsp (n b : ℕ) : Prop :=
ProbablePrime n b ∧ ¬n.Prime ∧ 1 < n
instance decidableProbablePrime (n b : ℕ) : Decidable (ProbablePrime n b) :=
Nat.decidable_dvd _ _
instance decidablePsp (n b : ℕ) : Decidable (FermatPsp n b) :=
inferInstanceAs (Decidable (_ ∧ _))
/-- If `n` passes the Fermat primality test to base `b`, then `n` is coprime with `b`, assuming that
`n` and `b` are both positive.
-/
theorem coprime_of_probablePrime {n b : ℕ} (h : ProbablePrime n b) (h₁ : 1 ≤ n) (h₂ : 1 ≤ b) :
Nat.Coprime n b := by
by_cases h₃ : 2 ≤ n
· -- To prove that `n` is coprime with `b`, we need to show that for all prime factors of `n`,
-- we can derive a contradiction if `n` divides `b`.
apply Nat.coprime_of_dvd
-- If `k` is a prime number that divides both `n` and `b`, then we know that `n = m * k` and
-- `b = j * k` for some natural numbers `m` and `j`. We substitute these into the hypothesis.
rintro k hk ⟨m, rfl⟩ ⟨j, rfl⟩
-- Because prime numbers do not divide 1, it suffices to show that `k ∣ 1` to prove a
-- contradiction
apply Nat.Prime.not_dvd_one hk
-- Since `n` divides `b ^ (n - 1) - 1`, `k` also divides `b ^ (n - 1) - 1`
replace h := dvd_of_mul_right_dvd h
-- Because `k` divides `b ^ (n - 1) - 1`, if we can show that `k` also divides `b ^ (n - 1)`,
-- then we know `k` divides 1.
rw [Nat.dvd_add_iff_right h, Nat.sub_add_cancel (Nat.one_le_pow _ _ h₂)]
-- Since `k` divides `b`, `k` also divides any power of `b` except `b ^ 0`. Therefore, it
-- suffices to show that `n - 1` isn't zero. However, we know that `n - 1` isn't zero because we
-- assumed `2 ≤ n` when doing `by_cases`.
refine dvd_of_mul_right_dvd (dvd_pow_self (k * j) ?_)
cutsat
-- If `n = 1`, then it follows trivially that `n` is coprime with `b`.
· rw [show n = 1 by cutsat]
simp
theorem probablePrime_iff_modEq (n : ℕ) {b : ℕ} (h : 1 ≤ b) :
ProbablePrime n b ↔ b ^ (n - 1) ≡ 1 [MOD n] := by
have : 1 ≤ b ^ (n - 1) := one_le_pow₀ h
-- For exact mod_cast
rw [Nat.ModEq.comm]
constructor
· intro h₁
apply Nat.modEq_of_dvd
exact mod_cast h₁
· intro h₁
exact mod_cast Nat.ModEq.dvd h₁
/-- If `n` is a Fermat pseudoprime to base `b`, then `n` is coprime with `b`, assuming that `b` is
positive.
This lemma is a small wrapper based on `coprime_of_probablePrime`
-/
theorem coprime_of_fermatPsp {n b : ℕ} (h : FermatPsp n b) (h₁ : 1 ≤ b) : Nat.Coprime n b := by
rcases h with ⟨hp, _, hn₂⟩
exact coprime_of_probablePrime hp (by cutsat) h₁
/-- All composite numbers are Fermat pseudoprimes to base 1.
-/
theorem fermatPsp_base_one {n : ℕ} (h₁ : 1 < n) (h₂ : ¬n.Prime) : FermatPsp n 1 := by
refine ⟨show n ∣ 1 ^ (n - 1) - 1 from ?_, h₂, h₁⟩
exact show 0 = 1 ^ (n - 1) - 1 by simp ▸ dvd_zero n
-- Lemmas that are needed to prove statements in this file, but aren't directly related to Fermat
-- pseudoprimes
section HelperLemmas
private theorem a_id_helper {a b : ℕ} (ha : 2 ≤ a) (hb : 2 ≤ b) : 2 ≤ (a ^ b - 1) / (a - 1) := by
change 1 < _
have h₁ : a - 1 ∣ a ^ b - 1 := by simpa only [one_pow] using Nat.sub_dvd_pow_sub_pow a 1 b
rw [Nat.lt_div_iff_mul_lt' h₁, mul_one, tsub_lt_tsub_iff_right (Nat.le_of_succ_le ha)]
exact lt_self_pow₀ (Nat.lt_of_succ_le ha) hb
private theorem b_id_helper {a b : ℕ} (ha : 2 ≤ a) (hb : 2 < b) : 2 ≤ (a ^ b + 1) / (a + 1) := by
rw [Nat.le_div_iff_mul_le (Nat.zero_lt_succ _)]
apply Nat.succ_le_succ
calc
2 * a + 1 ≤ a ^ 2 * a := by nlinarith
_ = a ^ 3 := by rw [Nat.pow_succ a 2]
_ ≤ a ^ b := pow_right_mono₀ (Nat.le_of_succ_le ha) hb
private theorem AB_id_helper (b p : ℕ) (_ : 2 ≤ b) (hp : Odd p) :
(b ^ p - 1) / (b - 1) * ((b ^ p + 1) / (b + 1)) = (b ^ (2 * p) - 1) / (b ^ 2 - 1) := by
have q₁ : b - 1 ∣ b ^ p - 1 := by simpa only [one_pow] using Nat.sub_dvd_pow_sub_pow b 1 p
have q₂ : b + 1 ∣ b ^ p + 1 := by simpa only [one_pow] using hp.nat_add_dvd_pow_add_pow b 1
convert Nat.div_mul_div_comm q₁ q₂ using 2 <;> rw [mul_comm (_ - 1), ← Nat.sq_sub_sq]
ring_nf
/-- Used in the proof of `psp_from_prime_psp`
-/
private theorem bp_helper {b p : ℕ} (hb : 0 < b) (hp : 1 ≤ p) :
b ^ (2 * p) - 1 - (b ^ 2 - 1) = b * (b ^ (p - 1) - 1) * (b ^ p + b) :=
have hi_bsquared : 1 ≤ b ^ 2 := Nat.one_le_pow _ _ hb
calc
b ^ (2 * p) - 1 - (b ^ 2 - 1) = b ^ (2 * p) - (1 + (b ^ 2 - 1)) := by rw [Nat.sub_sub]
_ = b ^ (2 * p) - (1 + b ^ 2 - 1) := by rw [Nat.add_sub_assoc hi_bsquared]
_ = b ^ (2 * p) - b ^ 2 := by rw [Nat.add_sub_cancel_left]
_ = b ^ (p * 2) - b ^ 2 := by rw [mul_comm]
_ = (b ^ p) ^ 2 - b ^ 2 := by rw [pow_mul]
_ = (b ^ p + b) * (b ^ p - b) := by rw [Nat.sq_sub_sq]
_ = (b ^ p - b) * (b ^ p + b) := by rw [mul_comm]
_ = (b ^ (p - 1 + 1) - b) * (b ^ p + b) := by rw [Nat.sub_add_cancel hp]
_ = (b * b ^ (p - 1) - b) * (b ^ p + b) := by rw [pow_succ']
_ = (b * b ^ (p - 1) - b * 1) * (b ^ p + b) := by rw [mul_one]
_ = b * (b ^ (p - 1) - 1) * (b ^ p + b) := by rw [Nat.mul_sub_left_distrib]
end HelperLemmas
/-- Given a prime `p` which does not divide `b * (b ^ 2 - 1)`, we can produce a number `n` which is
larger than `p` and pseudoprime to base `b`. We do this by defining
`n = ((b ^ p - 1) / (b - 1)) * ((b ^ p + 1) / (b + 1))`
The primary purpose of this definition is to help prove `exists_infinite_pseudoprimes`. For a proof
that `n` is actually pseudoprime to base `b`, see `psp_from_prime_psp`, and for a proof that `n` is
greater than `p`, see `psp_from_prime_gt_p`.
This lemma is intended to be used when `2 ≤ b`, `2 < p`, `p` is prime, and `¬p ∣ b * (b ^ 2 - 1)`,
because those are the hypotheses for `psp_from_prime_psp`.
-/
private def psp_from_prime (b : ℕ) (p : ℕ) : ℕ :=
(b ^ p - 1) / (b - 1) * ((b ^ p + 1) / (b + 1))
/--
This is a proof that the number produced using `psp_from_prime` is actually pseudoprime to base `b`.
The primary purpose of this lemma is to help prove `exists_infinite_pseudoprimes`.
We use <https://primes.utm.edu/notes/proofs/a_pseudoprimes.html> as a rough outline of the proof.
-/
private theorem psp_from_prime_psp {b : ℕ} (b_ge_two : 2 ≤ b) {p : ℕ} (p_prime : p.Prime)
(p_gt_two : 2 < p) (not_dvd : ¬p ∣ b * (b ^ 2 - 1)) : FermatPsp (psp_from_prime b p) b := by
unfold psp_from_prime
set A := (b ^ p - 1) / (b - 1)
set B := (b ^ p + 1) / (b + 1)
-- Inequalities
have hi_A : 1 < A := a_id_helper (Nat.succ_le_iff.mp b_ge_two) (Nat.Prime.one_lt p_prime)
have hi_B : 1 < B := b_id_helper (Nat.succ_le_iff.mp b_ge_two) p_gt_two
have hi_AB : 1 < A * B := one_lt_mul'' hi_A hi_B
have hi_b : 0 < b := by omega
have hi_p : 1 ≤ p := Nat.one_le_of_lt p_gt_two
have hi_bsquared : 0 < b ^ 2 - 1 := by
have := Nat.pow_le_pow_left b_ge_two 2
omega
have hi_bpowtwop : 1 ≤ b ^ (2 * p) := Nat.one_le_pow (2 * p) b hi_b
have hi_bpowpsubone : 1 ≤ b ^ (p - 1) := Nat.one_le_pow (p - 1) b hi_b
-- Other useful facts
have p_odd : Odd p := p_prime.odd_of_ne_two p_gt_two.ne.symm
have AB_not_prime : ¬Nat.Prime (A * B) := Nat.not_prime_mul hi_A.ne' hi_B.ne'
have AB_id : A * B = (b ^ (2 * p) - 1) / (b ^ 2 - 1) := AB_id_helper _ _ b_ge_two p_odd
have hd : b ^ 2 - 1 ∣ b ^ (2 * p) - 1 := by
simpa only [one_pow, pow_mul] using Nat.sub_dvd_pow_sub_pow _ 1 p
-- We know that `A * B` is not prime, and that `1 < A * B`. Since two conditions of being
-- pseudoprime are satisfied, we only need to show that `A * B` is probable prime to base `b`
refine ⟨?_, AB_not_prime, hi_AB⟩
-- Used to prove that `2 * p * (b ^ 2 - 1) ∣ (b ^ 2 - 1) * (A * B - 1)`.
have ha₁ : (b ^ 2 - 1) * (A * B - 1) = b * (b ^ (p - 1) - 1) * (b ^ p + b) := by
apply_fun fun x => x * (b ^ 2 - 1) at AB_id
rw [Nat.div_mul_cancel hd] at AB_id
apply_fun fun x => x - (b ^ 2 - 1) at AB_id
nth_rw 2 [← one_mul (b ^ 2 - 1)] at AB_id
rw [← Nat.mul_sub_right_distrib, mul_comm] at AB_id
rw [AB_id]
exact bp_helper hi_b hi_p
-- If `b` is even, then `b^p` is also even, so `2 ∣ b^p + b`
-- If `b` is odd, then `b^p` is also odd, so `2 ∣ b^p + b`
have ha₂ : 2 ∣ b ^ p + b := by
rw [← even_iff_two_dvd, Nat.even_add, Nat.even_pow' p_prime.ne_zero]
-- Since `b` isn't divisible by `p`, `b` is coprime with `p`. we can use Fermat's Little Theorem
-- to prove this.
have ha₃ : p ∣ b ^ (p - 1) - 1 := by
have : ¬p ∣ b := mt (fun h : p ∣ b => dvd_mul_of_dvd_left h _) not_dvd
have : p.Coprime b := Or.resolve_right (Nat.coprime_or_dvd_of_prime p_prime b) this
have : IsCoprime (b : ℤ) ↑p := this.symm.isCoprime
have : ↑b ^ (p - 1) ≡ 1 [ZMOD ↑p] := Int.ModEq.pow_card_sub_one_eq_one p_prime this
have : ↑p ∣ ↑b ^ (p - 1) - ↑1 := mod_cast Int.ModEq.dvd (Int.ModEq.symm this)
exact mod_cast this
-- Because `p - 1` is even, there is a `c` such that `2 * c = p - 1`. `Nat.sub_dvd_pow_sub_pow`
-- implies that `b ^ c - 1 ∣ (b ^ c) ^ 2 - 1`, and `(b ^ c) ^ 2 = b ^ (p - 1)`.
have ha₄ : b ^ 2 - 1 ∣ b ^ (p - 1) - 1 := by
obtain ⟨k, hk⟩ := p_odd
have : 2 ∣ p - 1 := ⟨k, by simp [hk]⟩
obtain ⟨c, hc⟩ := this
have : b ^ 2 - 1 ∣ (b ^ 2) ^ c - 1 := by
simpa only [one_pow] using Nat.sub_dvd_pow_sub_pow _ 1 c
have : b ^ 2 - 1 ∣ b ^ (2 * c) - 1 := by rwa [← pow_mul] at this
rwa [← hc] at this
-- Used to prove that `2 * p` divides `A * B - 1`
have ha₅ : 2 * p * (b ^ 2 - 1) ∣ (b ^ 2 - 1) * (A * B - 1) := by
suffices q : 2 * p * (b ^ 2 - 1) ∣ b * (b ^ (p - 1) - 1) * (b ^ p + b) by rwa [ha₁]
-- We already proved that `b ^ 2 - 1 ∣ b ^ (p - 1) - 1`.
-- Since `2 ∣ b ^ p + b` and `p ∣ b ^ p + b`, if we show that 2 and p are coprime, then we
-- know that `2 * p ∣ b ^ p + b`
have q₁ : Nat.Coprime p (b ^ 2 - 1) :=
haveI q₂ : ¬p ∣ b ^ 2 - 1 := by
rw [mul_comm] at not_dvd
exact mt (fun h : p ∣ b ^ 2 - 1 => dvd_mul_of_dvd_left h _) not_dvd
(Nat.Prime.coprime_iff_not_dvd p_prime).mpr q₂
have q₂ : p * (b ^ 2 - 1) ∣ b ^ (p - 1) - 1 := Nat.Coprime.mul_dvd_of_dvd_of_dvd q₁ ha₃ ha₄
have q₃ : p * (b ^ 2 - 1) * 2 ∣ (b ^ (p - 1) - 1) * (b ^ p + b) := mul_dvd_mul q₂ ha₂
have q₄ : p * (b ^ 2 - 1) * 2 ∣ b * ((b ^ (p - 1) - 1) * (b ^ p + b)) :=
dvd_mul_of_dvd_right q₃ _
rwa [mul_assoc, mul_comm, mul_assoc b]
have ha₆ : 2 * p ∣ A * B - 1 := by
rw [mul_comm] at ha₅
exact Nat.dvd_of_mul_dvd_mul_left hi_bsquared ha₅
-- `A * B` divides `b ^ (2 * p) - 1` because `A * B * (b ^ 2 - 1) = b ^ (2 * p) - 1`.
-- This can be proven by multiplying both sides of `AB_id` by `b ^ 2 - 1`.
have ha₇ : A * B ∣ b ^ (2 * p) - 1 := by
use b ^ 2 - 1
have : A * B * (b ^ 2 - 1) = (b ^ (2 * p) - 1) / (b ^ 2 - 1) * (b ^ 2 - 1) :=
congr_arg (fun x : ℕ => x * (b ^ 2 - 1)) AB_id
simpa only [add_comm, Nat.div_mul_cancel hd, Nat.sub_add_cancel hi_bpowtwop] using this.symm
-- Since `2 * p ∣ A * B - 1`, there is a number `q` such that `2 * p * q = A * B - 1`.
-- By `Nat.sub_dvd_pow_sub_pow`, we know that `b ^ (2 * p) - 1 ∣ b ^ (2 * p * q) - 1`.
-- This means that `b ^ (2 * p) - 1 ∣ b ^ (A * B - 1) - 1`.
obtain ⟨q, hq⟩ := ha₆
have ha₈ : b ^ (2 * p) - 1 ∣ b ^ (A * B - 1) - 1 := by
simpa only [one_pow, pow_mul, hq] using Nat.sub_dvd_pow_sub_pow _ 1 q
-- We have proved that `A * B ∣ b ^ (2 * p) - 1` and `b ^ (2 * p) - 1 ∣ b ^ (A * B - 1) - 1`.
-- Therefore, `A * B ∣ b ^ (A * B - 1) - 1`.
exact dvd_trans ha₇ ha₈
/--
This is a proof that the number produced using `psp_from_prime` is greater than the prime `p` used
to create it. The primary purpose of this lemma is to help prove `exists_infinite_pseudoprimes`.
-/
private theorem psp_from_prime_gt_p {b : ℕ} (b_ge_two : 2 ≤ b) {p : ℕ} (p_prime : p.Prime)
(p_gt_two : 2 < p) : p < psp_from_prime b p := by
unfold psp_from_prime
set A := (b ^ p - 1) / (b - 1)
set B := (b ^ p + 1) / (b + 1)
rw [show A * B = (b ^ (2 * p) - 1) / (b ^ 2 - 1) from
AB_id_helper _ _ b_ge_two (p_prime.odd_of_ne_two p_gt_two.ne.symm)]
have AB_dvd : b ^ 2 - 1 ∣ b ^ (2 * p) - 1 := by
simpa only [one_pow, pow_mul] using Nat.sub_dvd_pow_sub_pow _ 1 p
suffices h : p * (b ^ 2 - 1) < b ^ (2 * p) - 1 by
have h₁ : p * (b ^ 2 - 1) / (b ^ 2 - 1) < (b ^ (2 * p) - 1) / (b ^ 2 - 1) :=
Nat.div_lt_div_of_lt_of_dvd AB_dvd h
have h₂ : 0 < b ^ 2 - 1 := by
linarith [show 3 ≤ b ^ 2 - 1 from le_tsub_of_add_le_left (show 4 ≤ b ^ 2 by nlinarith)]
rwa [Nat.mul_div_cancel _ h₂] at h₁
rw [Nat.mul_sub_left_distrib, mul_one, pow_mul]
conv_rhs => rw [← Nat.sub_add_cancel (show 1 ≤ p by cutsat)]
rw [Nat.pow_succ (b ^ 2)]
suffices h : p * b ^ 2 < (b ^ 2) ^ (p - 1) * b ^ 2 by
apply lt_of_le_of_lt'
· exact tsub_le_tsub_left (one_le_of_lt p_gt_two) ((b ^ 2) ^ (p - 1) * b ^ 2)
· have : p ≤ p * b ^ 2 := Nat.le_mul_of_pos_right _ (show 0 < b ^ 2 by positivity)
exact tsub_lt_tsub_right_of_le this h
suffices h : p < (b ^ 2) ^ (p - 1) by gcongr
rw [← pow_mul, Nat.mul_sub_left_distrib, mul_one]
have : 2 ≤ 2 * p - 2 := le_tsub_of_add_le_left (show 4 ≤ 2 * p by cutsat)
have : 2 + p ≤ 2 * p := by omega
have : p ≤ 2 * p - 2 := le_tsub_of_add_le_left this
exact this.trans_lt (Nat.lt_pow_self b_ge_two)
/-- For all positive bases, there exist infinite **Fermat pseudoprimes** to that base.
Given in this form: for all numbers `b ≥ 1` and `m`, there exists a pseudoprime `n` to base `b` such
that `m ≤ n`. This form is similar to `Nat.exists_infinite_primes`.
-/
theorem exists_infinite_pseudoprimes {b : ℕ} (h : 1 ≤ b) (m : ℕ) :
∃ n : ℕ, FermatPsp n b ∧ m ≤ n := by
by_cases b_ge_two : 2 ≤ b
-- If `2 ≤ b`, then because there exist infinite prime numbers, there is a prime number p with
-- `m ≤ p` and `¬p ∣ b*(b^2 - 1)`. We pick a prime number `b*(b^2 - 1) + 1 + m ≤ p` because we
-- automatically know that `p` is greater than m and that it does not divide `b*(b^2 - 1)`
-- (because `p` can't divide a number less than `p`).
-- From `p`, we can use the lemmas we proved earlier to show that
-- `((b^p - 1)/(b - 1)) * ((b^p + 1)/(b + 1))` is a pseudoprime to base `b`.
· have h := Nat.exists_infinite_primes (b * (b ^ 2 - 1) + 1 + m)
obtain ⟨p, ⟨hp₁, hp₂⟩⟩ := h
have h₁ : 0 < b := pos_of_gt (Nat.succ_le_iff.mp b_ge_two)
have h₂ : 4 ≤ b ^ 2 := pow_le_pow_left' b_ge_two 2
have h₃ : 0 < b ^ 2 - 1 := tsub_pos_of_lt (lt_of_lt_of_le (by simp) h₂)
have h₄ : 0 < b * (b ^ 2 - 1) := mul_pos h₁ h₃
have h₅ : b * (b ^ 2 - 1) < p := by omega
have h₆ : ¬p ∣ b * (b ^ 2 - 1) := Nat.not_dvd_of_pos_of_lt h₄ h₅
have h₇ : b ≤ b * (b ^ 2 - 1) := Nat.le_mul_of_pos_right _ h₃
have h₈ : 2 ≤ b * (b ^ 2 - 1) := le_trans b_ge_two h₇
have h₉ : 2 < p := lt_of_le_of_lt h₈ h₅
have h₁₀ := psp_from_prime_gt_p b_ge_two hp₂ h₉
use psp_from_prime b p
constructor
· exact psp_from_prime_psp b_ge_two hp₂ h₉ h₆
· exact le_trans (show m ≤ p by cutsat) (le_of_lt h₁₀)
-- If `¬2 ≤ b`, then `b = 1`. Since all composite numbers are pseudoprimes to base 1, we can pick
-- any composite number greater than m. We choose `2 * (m + 2)` because it is greater than `m` and
-- is composite for all natural numbers `m`.
· have h₁ : b = 1 := by omega
rw [h₁]
use 2 * (m + 2)
have : ¬Nat.Prime (2 * (m + 2)) := Nat.not_prime_mul (by cutsat) (by cutsat)
exact ⟨fermatPsp_base_one (by cutsat) this, by cutsat⟩
theorem frequently_atTop_fermatPsp {b : ℕ} (h : 1 ≤ b) : ∃ᶠ n in Filter.atTop, FermatPsp n b := by
-- Based on the proof of `Nat.frequently_atTop_modEq_one`
refine Filter.frequently_atTop.2 fun n => ?_
obtain ⟨p, hp⟩ := exists_infinite_pseudoprimes h n
exact ⟨p, hp.2, hp.1⟩
/-- Infinite set variant of `Nat.exists_infinite_pseudoprimes`
-/
theorem infinite_setOf_pseudoprimes {b : ℕ} (h : 1 ≤ b) :
Set.Infinite { n : ℕ | FermatPsp n b } :=
Nat.frequently_atTop_iff_infinite.mp (frequently_atTop_fermatPsp h)
end Nat |
.lake/packages/mathlib/Mathlib/NumberTheory/EllipticDivisibilitySequence.lean | import Mathlib.Data.Nat.EvenOddRec
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.LinearCombination
/-!
# Elliptic divisibility sequences
This file defines the type of an elliptic divisibility sequence (EDS) and a few examples.
## Mathematical background
Let `R` be a commutative ring. An elliptic sequence is a sequence `W : ℤ → R` satisfying
`W(m + n)W(m - n)W(r)² = W(m + r)W(m - r)W(n)² - W(n + r)W(n - r)W(m)²` for any `m, n, r ∈ ℤ`.
A divisibility sequence is a sequence `W : ℤ → R` satisfying `W(m) ∣ W(n)` for any `m, n ∈ ℤ` such
that `m ∣ n`. An elliptic divisibility sequence is simply a divisibility sequence that is elliptic.
Some examples of EDSs include
* the identity sequence,
* certain terms of Lucas sequences, and
* division polynomials of elliptic curves.
## Main definitions
* `IsEllSequence`: a sequence indexed by integers is an elliptic sequence.
* `IsDivSequence`: a sequence indexed by integers is a divisibility sequence.
* `IsEllDivSequence`: a sequence indexed by integers is an EDS.
* `preNormEDS'`: the auxiliary sequence for a normalised EDS indexed by `ℕ`.
* `preNormEDS`: the auxiliary sequence for a normalised EDS indexed by `ℤ`.
* `complEDS₂`: the 2-complement sequence for a normalised EDS indexed by `ℕ`.
* `normEDS`: the canonical example of a normalised EDS indexed by `ℤ`.
* `complEDS'`: the complement sequence for a normalised EDS indexed by `ℕ`.
* `complEDS`: the complement sequence for a normalised EDS indexed by `ℤ`.
## Main statements
* TODO: prove that `normEDS` satisfies `IsEllDivSequence`.
* TODO: prove that a normalised sequence satisfying `IsEllDivSequence` can be given by `normEDS`.
## Implementation notes
The normalised EDS `normEDS b c d n` is defined in terms of the auxiliary sequence
`preNormEDS (b ^ 4) c d n`, which are equal when `n` is odd, and which differ by a factor of `b`
when `n` is even. This coincides with the definition in the references since both agree for
`normEDS b c d 2` and for `normEDS b c d 4`, and the correct factors of `b` are removed in
`normEDS b c d (2 * (m + 2) + 1)` and in `normEDS b c d (2 * (m + 3))`.
One reason is to avoid the necessity for ring division by `b` in the inductive definition of
`normEDS b c d (2 * (m + 3))`. The idea is that, it can be shown that `normEDS b c d (2 * (m + 3))`
always contains a factor of `b`, so it is possible to remove a factor of `b` *a posteriori*, but
stating this lemma requires first defining `normEDS b c d (2 * (m + 3))`, which requires having this
factor of `b` *a priori*. Another reason is to allow the definition of univariate `n`-division
polynomials of elliptic curves, omitting a factor of the bivariate `2`-division polynomial.
## References
M Ward, *Memoir on Elliptic Divisibility Sequences*
## Tags
elliptic, divisibility, sequence
-/
universe u v
variable {R : Type u} [CommRing R]
section IsEllDivSequence
variable (W : ℤ → R)
/-- The proposition that a sequence indexed by integers is an elliptic sequence. -/
def IsEllSequence : Prop :=
∀ m n r : ℤ, W (m + n) * W (m - n) * W r ^ 2 =
W (m + r) * W (m - r) * W n ^ 2 - W (n + r) * W (n - r) * W m ^ 2
/-- The proposition that a sequence indexed by integers is a divisibility sequence. -/
def IsDivSequence : Prop :=
∀ m n : ℕ, m ∣ n → W m ∣ W n
/-- The proposition that a sequence indexed by integers is an EDS. -/
def IsEllDivSequence : Prop :=
IsEllSequence W ∧ IsDivSequence W
lemma isEllSequence_id : IsEllSequence id :=
fun _ _ _ => by simp_rw [id_eq]; ring1
lemma isDivSequence_id : IsDivSequence id :=
fun _ _ => Int.ofNat_dvd.mpr
/-- The identity sequence is an EDS. -/
theorem isEllDivSequence_id : IsEllDivSequence id :=
⟨isEllSequence_id, isDivSequence_id⟩
variable {W}
lemma IsEllSequence.smul (h : IsEllSequence W) (x : R) : IsEllSequence (x • W) :=
fun m n r => by
linear_combination (norm := (simp_rw [Pi.smul_apply, smul_eq_mul]; ring1)) x ^ 4 * h m n r
lemma IsDivSequence.smul (h : IsDivSequence W) (x : R) : IsDivSequence (x • W) :=
fun m n r => mul_dvd_mul_left x <| h m n r
lemma IsEllDivSequence.smul (h : IsEllDivSequence W) (x : R) : IsEllDivSequence (x • W) :=
⟨h.left.smul x, h.right.smul x⟩
end IsEllDivSequence
variable (b c d : R)
section PreNormEDS
/-- The auxiliary sequence for a normalised EDS `W : ℕ → R`, with initial values
`W(0) = 0`, `W(1) = 1`, `W(2) = 1`, `W(3) = c`, and `W(4) = d` and extra parameter `b`. -/
def preNormEDS' : ℕ → R
| 0 => 0
| 1 => 1
| 2 => 1
| 3 => c
| 4 => d
| (n + 5) => let m := n / 2
if hn : Even n then
preNormEDS' (m + 4) * preNormEDS' (m + 2) ^ 3 * (if Even m then b else 1) -
preNormEDS' (m + 1) * preNormEDS' (m + 3) ^ 3 * (if Even m then 1 else b)
else
have : m + 5 < n + 5 := by
gcongr; exact Nat.div_lt_self (Nat.not_even_iff_odd.mp hn).pos one_lt_two
preNormEDS' (m + 2) ^ 2 * preNormEDS' (m + 3) * preNormEDS' (m + 5) -
preNormEDS' (m + 1) * preNormEDS' (m + 3) * preNormEDS' (m + 4) ^ 2
@[simp]
lemma preNormEDS'_zero : preNormEDS' b c d 0 = 0 := by
rw [preNormEDS']
@[simp]
lemma preNormEDS'_one : preNormEDS' b c d 1 = 1 := by
rw [preNormEDS']
@[simp]
lemma preNormEDS'_two : preNormEDS' b c d 2 = 1 := by
rw [preNormEDS']
@[simp]
lemma preNormEDS'_three : preNormEDS' b c d 3 = c := by
rw [preNormEDS']
@[simp]
lemma preNormEDS'_four : preNormEDS' b c d 4 = d := by
rw [preNormEDS']
lemma preNormEDS'_even (m : ℕ) : preNormEDS' b c d (2 * (m + 3)) =
preNormEDS' b c d (m + 2) ^ 2 * preNormEDS' b c d (m + 3) * preNormEDS' b c d (m + 5) -
preNormEDS' b c d (m + 1) * preNormEDS' b c d (m + 3) * preNormEDS' b c d (m + 4) ^ 2 := by
rw [show 2 * (m + 3) = 2 * m + 1 + 5 by rfl, preNormEDS', dif_neg m.not_even_two_mul_add_one]
simpa only [Nat.mul_add_div two_pos] using by rfl
lemma preNormEDS'_odd (m : ℕ) : preNormEDS' b c d (2 * (m + 2) + 1) =
preNormEDS' b c d (m + 4) * preNormEDS' b c d (m + 2) ^ 3 * (if Even m then b else 1) -
preNormEDS' b c d (m + 1) * preNormEDS' b c d (m + 3) ^ 3 * (if Even m then 1 else b) := by
rw [show 2 * (m + 2) + 1 = 2 * m + 5 by rfl, preNormEDS', dif_pos <| even_two_mul m,
m.mul_div_cancel_left two_pos]
/-- The auxiliary sequence for a normalised EDS `W : ℤ → R`, with initial values
`W(0) = 0`, `W(1) = 1`, `W(2) = 1`, `W(3) = c`, and `W(4) = d` and extra parameter `b`.
This extends `preNormEDS'` by defining its values at negative integers. -/
def preNormEDS (n : ℤ) : R :=
n.sign * preNormEDS' b c d n.natAbs
@[simp]
lemma preNormEDS_ofNat (n : ℕ) : preNormEDS b c d n = preNormEDS' b c d n := by
by_cases hn : n = 0
· simp [hn, preNormEDS]
· simp [preNormEDS, Int.sign_natCast_of_ne_zero hn]
@[simp]
lemma preNormEDS_zero : preNormEDS b c d 0 = 0 := by
simp [preNormEDS]
@[simp]
lemma preNormEDS_one : preNormEDS b c d 1 = 1 := by
simp [preNormEDS]
@[simp]
lemma preNormEDS_two : preNormEDS b c d 2 = 1 := by
simp [preNormEDS, Int.sign_eq_one_of_pos]
@[simp]
lemma preNormEDS_three : preNormEDS b c d 3 = c := by
simp [preNormEDS, Int.sign_eq_one_of_pos]
@[simp]
lemma preNormEDS_four : preNormEDS b c d 4 = d := by
simp [preNormEDS, Int.sign_eq_one_of_pos]
@[simp]
lemma preNormEDS_neg (n : ℤ) : preNormEDS b c d (-n) = -preNormEDS b c d n := by
simp [preNormEDS]
lemma preNormEDS_even (m : ℤ) : preNormEDS b c d (2 * m) =
preNormEDS b c d (m - 1) ^ 2 * preNormEDS b c d m * preNormEDS b c d (m + 2) -
preNormEDS b c d (m - 2) * preNormEDS b c d m * preNormEDS b c d (m + 1) ^ 2 := by
induction m using Int.negInduction with
| nat m =>
rcases m with _ | _ | _ | m
iterate 3 simp
simp_rw [Nat.cast_succ, Int.add_sub_cancel, show (m : ℤ) + 1 + 1 + 1 = m + 1 + 2 by rfl,
Int.add_sub_cancel]
norm_cast
simpa only [preNormEDS_ofNat] using preNormEDS'_even ..
| neg ih m =>
simp_rw [mul_neg, ← sub_neg_eq_add, ← neg_sub', ← neg_add', preNormEDS_neg, ih]
ring1
@[deprecated (since := "2025-05-15")] alias preNormEDS_even_ofNat := preNormEDS_even
lemma preNormEDS_odd (m : ℤ) : preNormEDS b c d (2 * m + 1) =
preNormEDS b c d (m + 2) * preNormEDS b c d m ^ 3 * (if Even m then b else 1) -
preNormEDS b c d (m - 1) * preNormEDS b c d (m + 1) ^ 3 * (if Even m then 1 else b) := by
induction m using Int.negInduction with
| nat m =>
rcases m with _ | _ | _
iterate 2 simp
simp_rw [Nat.cast_succ, Int.add_sub_cancel, Int.even_add_one, not_not, Int.even_coe_nat]
norm_cast
simpa only [preNormEDS_ofNat] using preNormEDS'_odd ..
| neg ih m =>
rcases m with _ | m
· simp
simp_rw [Nat.cast_succ, show 2 * -(m + 1 : ℤ) + 1 = -(2 * m + 1) by rfl,
show -(m + 1 : ℤ) + 2 = -(m - 1) by ring1, show -(m + 1 : ℤ) - 1 = -(m + 2) by rfl,
show -(m + 1 : ℤ) + 1 = -m by ring1, preNormEDS_neg, even_neg, Int.even_add_one, ite_not, ih]
ring1
@[deprecated (since := "2025-05-15")] alias preNormEDS_odd_ofNat := preNormEDS_odd
/-- The 2-complement sequence `Wᶜ₂ : ℤ → R` for a normalised EDS `W : ℤ → R` that witnesses
`W(k) ∣ W(2 * k)`. In other words, `W(k) * Wᶜ₂(k) = W(2 * k)` for any `k ∈ ℤ`.
This is defined in terms of `preNormEDS`. -/
def complEDS₂ (k : ℤ) : R :=
(preNormEDS (b ^ 4) c d (k - 1) ^ 2 * preNormEDS (b ^ 4) c d (k + 2) -
preNormEDS (b ^ 4) c d (k - 2) * preNormEDS (b ^ 4) c d (k + 1) ^ 2) * if Even k then 1 else b
@[simp]
lemma complEDS₂_zero : complEDS₂ b c d 0 = 2 := by
simp [complEDS₂, one_add_one_eq_two]
@[simp]
lemma complEDS₂_one : complEDS₂ b c d 1 = b := by
simp [complEDS₂]
@[simp]
lemma complEDS₂_two : complEDS₂ b c d 2 = d := by
simp [complEDS₂]
@[simp]
lemma complEDS₂_three : complEDS₂ b c d 3 = preNormEDS (b ^ 4) c d 5 * b - d ^ 2 * b := by
simp [complEDS₂, if_neg (by decide : ¬Even (3 : ℤ)), sub_mul]
@[simp]
lemma complEDS₂_four : complEDS₂ b c d 4 =
c ^ 2 * preNormEDS (b ^ 4) c d 6 - preNormEDS (b ^ 4) c d 5 ^ 2 := by
simp [complEDS₂, if_pos (by decide : Even (4 : ℤ))]
@[simp]
lemma complEDS₂_neg (k : ℤ) : complEDS₂ b c d (-k) = complEDS₂ b c d k := by
simp_rw [complEDS₂, ← neg_add', ← sub_neg_eq_add, ← neg_sub', preNormEDS_neg, even_neg]
ring1
lemma preNormEDS_mul_complEDS₂ (k : ℤ) : preNormEDS (b ^ 4) c d k * complEDS₂ b c d k =
preNormEDS (b ^ 4) c d (2 * k) * if Even k then 1 else b := by
rw [complEDS₂, preNormEDS_even]
ring1
end PreNormEDS
section NormEDS
/-- The canonical example of a normalised EDS `W : ℤ → R`, with initial values
`W(0) = 0`, `W(1) = 1`, `W(2) = b`, `W(3) = c`, and `W(4) = d * b`.
This is defined in terms of `preNormEDS` whose even terms differ by a factor of `b`. -/
def normEDS (n : ℤ) : R :=
preNormEDS (b ^ 4) c d n * if Even n then b else 1
@[simp]
lemma normEDS_ofNat (n : ℕ) :
normEDS b c d n = preNormEDS' (b ^ 4) c d n * if Even n then b else 1 := by
simp [normEDS]
@[simp]
lemma normEDS_zero : normEDS b c d 0 = 0 := by
simp [normEDS]
@[simp]
lemma normEDS_one : normEDS b c d 1 = 1 := by
simp [normEDS]
@[simp]
lemma normEDS_two : normEDS b c d 2 = b := by
simp [normEDS]
@[simp]
lemma normEDS_three : normEDS b c d 3 = c := by
simp [normEDS, show ¬Even (3 : ℤ) by decide]
@[simp]
lemma normEDS_four : normEDS b c d 4 = d * b := by
simp [normEDS, show ¬Odd (4 : ℤ) by decide]
@[simp]
lemma normEDS_neg (n : ℤ) : normEDS b c d (-n) = -normEDS b c d n := by
simp_rw [normEDS, preNormEDS_neg, even_neg, neg_mul]
lemma normEDS_mul_complEDS₂ (k : ℤ) :
normEDS b c d k * complEDS₂ b c d k = normEDS b c d (2 * k) := by
simp_rw [normEDS, mul_right_comm, preNormEDS_mul_complEDS₂, mul_assoc, apply_ite₂, one_mul,
mul_one, ite_self, if_pos <| even_two_mul k]
lemma normEDS_dvd_normEDS_two_mul (k : ℤ) : normEDS b c d k ∣ normEDS b c d (2 * k) :=
⟨complEDS₂ .., (normEDS_mul_complEDS₂ ..).symm⟩
lemma complEDS₂_mul_b (k : ℤ) : complEDS₂ b c d k * b =
normEDS b c d (k - 1) ^ 2 * normEDS b c d (k + 2) -
normEDS b c d (k - 2) * normEDS b c d (k + 1) ^ 2 := by
induction k using Int.negInduction with
| nat k =>
simp_rw [complEDS₂, normEDS, Int.even_add, Int.even_sub, even_two, iff_true, Int.not_even_one,
iff_false]
split_ifs <;> ring1
| neg ih =>
simp_rw [complEDS₂_neg, ← sub_neg_eq_add, ← neg_sub', ← neg_add', normEDS_neg, ih]
ring1
lemma normEDS_even (m : ℤ) : normEDS b c d (2 * m) * b =
normEDS b c d (m - 1) ^ 2 * normEDS b c d m * normEDS b c d (m + 2) -
normEDS b c d (m - 2) * normEDS b c d m * normEDS b c d (m + 1) ^ 2 := by
rw [← normEDS_mul_complEDS₂, mul_assoc, complEDS₂_mul_b]
ring1
@[deprecated (since := "2025-05-15")] alias normEDS_even_ofNat := normEDS_even
lemma normEDS_odd (m : ℤ) : normEDS b c d (2 * m + 1) =
normEDS b c d (m + 2) * normEDS b c d m ^ 3 -
normEDS b c d (m - 1) * normEDS b c d (m + 1) ^ 3 := by
simp_rw [normEDS, preNormEDS_odd, if_neg m.not_even_two_mul_add_one, Int.even_add, Int.even_sub,
even_two, iff_true, Int.not_even_one, iff_false]
split_ifs <;> ring1
@[deprecated (since := "2025-05-15")] alias normEDS_odd_ofNat := normEDS_odd
/--
Strong recursion principle for a normalised EDS: if we have
* `P 0`, `P 1`, `P 2`, `P 3`, and `P 4`,
* for all `m : ℕ` we can prove `P (2 * (m + 3))` from `P k` for all `k < 2 * (m + 3)`, and
* for all `m : ℕ` we can prove `P (2 * (m + 2) + 1)` from `P k` for all `k < 2 * (m + 2) + 1`,
then we have `P n` for all `n : ℕ`.
-/
@[elab_as_elim]
noncomputable def normEDSRec' {P : ℕ → Sort u}
(zero : P 0) (one : P 1) (two : P 2) (three : P 3) (four : P 4)
(even : ∀ m : ℕ, (∀ k < 2 * (m + 3), P k) → P (2 * (m + 3)))
(odd : ∀ m : ℕ, (∀ k < 2 * (m + 2) + 1, P k) → P (2 * (m + 2) + 1)) (n : ℕ) : P n :=
n.evenOddStrongRec (by rintro (_ | _ | _ | _) h; exacts [zero, two, four, even _ h])
(by rintro (_ | _ | _) h; exacts [one, three, odd _ h])
/-- Recursion principle for a normalised EDS: if we have
* `P 0`, `P 1`, `P 2`, `P 3`, and `P 4`,
* for all `m : ℕ` we can prove `P (2 * (m + 3))` from `P (m + 1)`, `P (m + 2)`, `P (m + 3)`,
`P (m + 4)`, and `P (m + 5)`, and
* for all `m : ℕ` we can prove `P (2 * (m + 2) + 1)` from `P (m + 1)`, `P (m + 2)`, `P (m + 3)`,
and `P (m + 4)`,
then we have `P n` for all `n : ℕ`. -/
@[elab_as_elim]
noncomputable def normEDSRec {P : ℕ → Sort u}
(zero : P 0) (one : P 1) (two : P 2) (three : P 3) (four : P 4)
(even : ∀ m : ℕ, P (m + 1) → P (m + 2) → P (m + 3) → P (m + 4) → P (m + 5) → P (2 * (m + 3)))
(odd : ∀ m : ℕ, P (m + 1) → P (m + 2) → P (m + 3) → P (m + 4) → P (2 * (m + 2) + 1)) (n : ℕ) :
P n :=
normEDSRec' zero one two three four (fun _ ih => by apply even <;> exact ih _ <| by linarith only)
(fun _ ih => by apply odd <;> exact ih _ <| by linarith only) n
end NormEDS
section ComplEDS
variable (k : ℤ)
/-- The complement sequence `Wᶜ : ℤ × ℕ → R` for a normalised EDS `W : ℤ → R` that witnesses
`W(k) ∣ W(n * k)`. In other words, `W(k) * Wᶜ(k, n) = W(n * k)` for any `k, n ∈ ℤ`.
This is defined in terms of `normEDS` and agrees with `complEDS₂` when `n = 2`. -/
def complEDS' : ℕ → R
| 0 => 0
| 1 => 1
| (n + 2) => let m := n / 2 + 1
if hn : Even n then complEDS' m * complEDS₂ b c d (m * k) else
have : m + 1 < n + 2 :=
add_lt_add_right (Nat.div_lt_self (Nat.not_even_iff_odd.mp hn).pos one_lt_two) 2
complEDS' m ^ 2 * normEDS b c d ((m + 1) * k + 1) * normEDS b c d ((m + 1) * k - 1) -
complEDS' (m + 1) ^ 2 * normEDS b c d (m * k + 1) * normEDS b c d (m * k - 1)
@[simp]
lemma complEDS'_zero : complEDS' b c d k 0 = 0 := by
rw [complEDS']
@[simp]
lemma complEDS'_one : complEDS' b c d k 1 = 1 := by
rw [complEDS']
lemma complEDS'_even (m : ℕ) : complEDS' b c d k (2 * (m + 1)) =
complEDS' b c d k (m + 1) * complEDS₂ b c d ((m + 1) * k) := by
rw [show 2 * (m + 1) = 2 * m + 2 by rfl, complEDS', dif_pos <| even_two_mul m,
m.mul_div_cancel_left two_pos, Nat.cast_succ]
lemma complEDS'_odd (m : ℕ) : complEDS' b c d k (2 * (m + 1) + 1) =
complEDS' b c d k (m + 1) ^ 2
* normEDS b c d ((m + 2) * k + 1) * normEDS b c d ((m + 2) * k - 1) -
complEDS' b c d k (m + 2) ^ 2
* normEDS b c d ((m + 1) * k + 1) * normEDS b c d ((m + 1) * k - 1) := by
rw [show 2 * (m + 1) + 1 = 2 * m + 3 by rfl, complEDS', dif_neg m.not_even_two_mul_add_one]
simpa only [Nat.mul_add_div two_pos] using by rfl
/-- The complement sequence `Wᶜ : ℤ × ℤ → R` for a normalised EDS `W : ℤ → R` that witnesses
`W(k) ∣ W(n * k)`. In other words, `W(k) * Wᶜ(k, n) = W(n * k)` for any `k, n ∈ ℤ`.
This extends `complEDS'` by defining its values at negative integers. -/
def complEDS (n : ℤ) : R :=
n.sign * complEDS' b c d k n.natAbs
@[simp]
lemma complEDS_ofNat (n : ℕ) : complEDS b c d k n = complEDS' b c d k n := by
by_cases hn : n = 0
· simp [hn, complEDS]
· simp [complEDS, Int.sign_natCast_of_ne_zero hn]
@[simp]
lemma complEDS_zero : complEDS b c d k 0 = 0 := by
simp [complEDS]
@[simp]
lemma complEDS_one : complEDS b c d k 1 = 1 := by
simp [complEDS]
@[simp]
lemma complEDS_neg (n : ℤ) : complEDS b c d k (-n) = -complEDS b c d k n := by
simp [complEDS]
lemma complEDS_even (m : ℤ) :
complEDS b c d k (2 * m) = complEDS b c d k m * complEDS₂ b c d (m * k) := by
induction m using Int.negInduction with
| nat m =>
rcases m with _ | _
· simp
norm_cast
simpa only [complEDS_ofNat] using complEDS'_even ..
| neg ih => simp_rw [mul_neg, complEDS_neg, ih, neg_mul, complEDS₂_neg]
lemma complEDS_odd (m : ℤ) : complEDS b c d k (2 * m + 1) =
complEDS b c d k m ^ 2 * normEDS b c d ((m + 1) * k + 1) * normEDS b c d ((m + 1) * k - 1) -
complEDS b c d k (m + 1) ^ 2 * normEDS b c d (m * k + 1) * normEDS b c d (m * k - 1) := by
induction m using Int.negInduction with
| nat m =>
rcases m with _ | _
· simp
norm_cast
simpa only [complEDS_ofNat] using complEDS'_odd ..
| neg ih m =>
rcases m with _ | m
· simp
simp_rw [Nat.cast_succ, show 2 * -(m + 1 : ℤ) + 1 = -(2 * m + 1) by rfl,
show (-(m + 1 : ℤ) + 1) = -m by ring1, neg_mul, ← sub_neg_eq_add, ← neg_sub', sub_neg_eq_add,
← neg_add', complEDS_neg, normEDS_neg, ih]
ring1
/-- Strong recursion principle for the complement sequence for a normalised EDS: if we have
* `P 0`, `P 1`,
* for all `m : ℕ` we can prove `P (2 * (m + 3))` from `P k` for all `k < 2 * (m + 3)`, and
* for all `m : ℕ` we can prove `P (2 * (m + 2) + 1)` from `P k` for all `k < 2 * (m + 2) + 1`,
then we have `P n` for all `n : ℕ`. -/
@[elab_as_elim]
noncomputable def complEDSRec' {P : ℕ → Sort u} (zero : P 0) (one : P 1)
(even : ∀ m : ℕ, (∀ k < 2 * (m + 1), P k) → P (2 * (m + 1)))
(odd : ∀ m : ℕ, (∀ k < 2 * (m + 1) + 1, P k) → P (2 * (m + 1) + 1)) (n : ℕ) : P n :=
n.evenOddStrongRec (by rintro (_ | _) h; exacts [zero, even _ h])
(by rintro (_ | _) h; exacts [one, odd _ h])
/-- Recursion principle for the complement sequence for a normalised EDS: if we have
* `P 0`, `P 1`,
* for all `m : ℕ` we can prove `P (2 * (m + 3))` from `P (m + 1)`, `P (m + 2)`, `P (m + 3)`,
`P (m + 4)`, and `P (m + 5)`, and
* for all `m : ℕ` we can prove `P (2 * (m + 2) + 1)` from `P (m + 1)`, `P (m + 2)`, `P (m + 3)`,
and `P (m + 4)`,
then we have `P n` for all `n : ℕ`. -/
@[elab_as_elim]
noncomputable def complEDSRec {P : ℕ → Sort u} (zero : P 0) (one : P 1)
(even : ∀ m : ℕ, P (m + 1) → P (2 * (m + 1)))
(odd : ∀ m : ℕ, P (m + 1) → P (m + 2) → P (2 * (m + 1) + 1)) (n : ℕ) : P n :=
complEDSRec' zero one (fun _ ih => even _ <| ih _ <| by linarith only)
(fun _ ih => odd _ (ih _ <| by linarith only) <| ih _ <| by linarith only) n
end ComplEDS
section Map
variable {S : Type v} [CommRing S] (f : R →+* S)
@[simp]
lemma map_preNormEDS' (n : ℕ) : f (preNormEDS' b c d n) = preNormEDS' (f b) (f c) (f d) n := by
induction n using normEDSRec' with
| zero => simp
| one => simp
| two => simp
| three => simp
| four => simp
| _ _ ih =>
simp only [preNormEDS'_even, preNormEDS'_odd, apply_ite f, map_pow, map_mul, map_sub, map_one]
repeat rw [ih _ <| by linarith only]
@[simp]
lemma map_preNormEDS (n : ℤ) : f (preNormEDS b c d n) = preNormEDS (f b) (f c) (f d) n := by
simp [preNormEDS]
@[simp]
lemma map_complEDS₂ (n : ℤ) : f (complEDS₂ b c d n) = complEDS₂ (f b) (f c) (f d) n := by
simp [complEDS₂, apply_ite f]
@[simp]
lemma map_normEDS (n : ℤ) : f (normEDS b c d n) = normEDS (f b) (f c) (f d) n := by
simp [normEDS, apply_ite f]
@[simp]
lemma map_complEDS' (k : ℤ) (n : ℕ) :
f (complEDS' b c d k n) = complEDS' (f b) (f c) (f d) k n := by
induction n using complEDSRec' with
| zero => simp
| one => simp
| _ _ ih =>
simp only [complEDS'_even, complEDS'_odd, map_normEDS, map_complEDS₂, map_pow, map_mul, map_sub]
repeat rw [ih _ <| by linarith only]
@[simp]
lemma map_complEDS (k n : ℤ) : f (complEDS b c d k n) = complEDS (f b) (f c) (f d) k n := by
simp [complEDS]
end Map |
.lake/packages/mathlib/Mathlib/NumberTheory/AbelSummation.lean | import Mathlib.MeasureTheory.Function.Floor
import Mathlib.MeasureTheory.Integral.Asymptotics
import Mathlib.MeasureTheory.Integral.IntegralEqImproper
import Mathlib.Topology.Order.IsLocallyClosed
/-!
# Abel's summation formula
We prove several versions of Abel's summation formula.
## Results
* `sum_mul_eq_sub_sub_integral_mul`: general statement of the formula for a sum between two
(nonnegative) reals `a` and `b`.
* `sum_mul_eq_sub_integral_mul`: a specialized version of `sum_mul_eq_sub_sub_integral_mul` for
the case `a = 0`.
* `sum_mul_eq_sub_integral_mul₀`: a specialized version of `sum_mul_eq_sub_integral_mul` for
when the first coefficient of the sequence is `0`. This is useful for `ArithmeticFunction`.
Primed versions of the three results above are also stated for when the endpoints are `Nat`.
* `tendsto_sum_mul_atTop_nhds_one_sub_integral`: limit version of `sum_mul_eq_sub_integral_mul`
when `a` tends to `∞`.
* `tendsto_sum_mul_atTop_nhds_one_sub_integral₀`: limit version of `sum_mul_eq_sub_integral_mul₀`
when `a` tends to `∞`.
* `summable_mul_of_bigO_atTop`: let `c : ℕ → 𝕜` and `f : ℝ → 𝕜` with `𝕜 = ℝ` or `ℂ`, prove the
summability of `n ↦ (c n) * (f n)` using Abel's formula under some `bigO` assumptions at infinity.
## References
* <https://en.wikipedia.org/wiki/Abel%27s_summation_formula>
-/
noncomputable section
open Finset MeasureTheory
variable {𝕜 : Type*} [RCLike 𝕜] (c : ℕ → 𝕜) {f : ℝ → 𝕜} {a b : ℝ}
namespace abelSummationProof
open intervalIntegral IntervalIntegrable
private theorem sumlocc {m : ℕ} (n : ℕ) :
∀ᵐ t, t ∈ Set.Icc (n : ℝ) (n + 1) → ∑ k ∈ Icc m ⌊t⌋₊, c k = ∑ k ∈ Icc m n, c k := by
filter_upwards [Ico_ae_eq_Icc] with t h ht
rw [Nat.floor_eq_on_Ico _ _ (h.mpr ht)]
open scoped Interval in
private theorem integralmulsum (hf_diff : ∀ t ∈ Set.Icc a b, DifferentiableAt ℝ f t)
(hf_int : IntegrableOn (deriv f) (Set.Icc a b)) (t₁ t₂ : ℝ) (n : ℕ) (h : t₁ ≤ t₂)
(h₁ : n ≤ t₁) (h₂ : t₂ ≤ n + 1) (h₃ : a ≤ t₁) (h₄ : t₂ ≤ b) :
∫ t in t₁..t₂, deriv f t * ∑ k ∈ Icc 0 ⌊t⌋₊, c k =
(f t₂ - f t₁) * ∑ k ∈ Icc 0 n, c k := by
have h_inc₁ : Ι t₁ t₂ ⊆ Set.Icc n (n + 1) :=
Set.uIoc_of_le h ▸ Set.Ioc_subset_Icc_self.trans <| Set.Icc_subset_Icc h₁ h₂
have h_inc₂ : Set.uIcc t₁ t₂ ⊆ Set.Icc a b := Set.uIcc_of_le h ▸ Set.Icc_subset_Icc h₃ h₄
rw [← integral_deriv_eq_sub (fun t ht ↦ hf_diff t (h_inc₂ ht)),
← intervalIntegral.integral_mul_const]
· refine integral_congr_ae ?_
filter_upwards [sumlocc c n] with t h h'
rw [h (h_inc₁ h')]
· refine (intervalIntegrable_iff_integrableOn_Icc_of_le h).mpr (hf_int.mono_set ?_)
rwa [← Set.uIcc_of_le h]
private theorem ineqofmemIco {k : ℕ} (hk : k ∈ Set.Ico (⌊a⌋₊ + 1) ⌊b⌋₊) :
a ≤ k ∧ k + 1 ≤ b := by
constructor
· have := (Set.mem_Ico.mp hk).1
exact le_of_lt <| (Nat.floor_lt' (by cutsat)).mp this
· rw [← Nat.cast_add_one, ← Nat.le_floor_iff' (Nat.succ_ne_zero k)]
exact (Set.mem_Ico.mp hk).2
private theorem ineqofmemIco' {k : ℕ} (hk : k ∈ Ico (⌊a⌋₊ + 1) ⌊b⌋₊) :
a ≤ k ∧ k + 1 ≤ b :=
ineqofmemIco (by rwa [← Finset.coe_Ico])
theorem _root_.integrableOn_mul_sum_Icc {m : ℕ} (ha : 0 ≤ a) {g : ℝ → 𝕜}
(hg_int : IntegrableOn g (Set.Icc a b)) :
IntegrableOn (fun t ↦ g t * ∑ k ∈ Icc m ⌊t⌋₊, c k) (Set.Icc a b) := by
obtain hab | hab := le_or_gt a b
· obtain hb | hb := eq_or_lt_of_le (Nat.floor_le_floor hab)
· have : ∀ᵐ t, t ∈ Set.Icc a b → ∑ k ∈ Icc m ⌊a⌋₊, c k = ∑ k ∈ Icc m ⌊t⌋₊, c k := by
filter_upwards [sumlocc c ⌊a⌋₊] with t ht₁ ht₂
rw [ht₁ ⟨(Nat.floor_le ha).trans ht₂.1, hb ▸ ht₂.2.trans (Nat.lt_floor_add_one b).le⟩]
rw [← ae_restrict_iff' measurableSet_Icc] at this
exact IntegrableOn.congr_fun_ae
(hg_int.mul_const _) ((Filter.EventuallyEq.refl _ g).mul this)
· have h_locint {t₁ t₂ : ℝ} {n : ℕ} (h : t₁ ≤ t₂) (h₁ : n ≤ t₁) (h₂ : t₂ ≤ n + 1)
(h₃ : a ≤ t₁) (h₄ : t₂ ≤ b) :
IntervalIntegrable (fun t ↦ g t * ∑ k ∈ Icc m ⌊t⌋₊, c k) volume t₁ t₂ := by
rw [intervalIntegrable_iff_integrableOn_Icc_of_le h]
exact (IntegrableOn.mono_set (hg_int.mul_const _) (Set.Icc_subset_Icc h₃ h₄)).congr
<| ae_restrict_of_ae_restrict_of_subset (Set.Icc_subset_Icc h₁ h₂)
<| (ae_restrict_iff' measurableSet_Icc).mpr
(by filter_upwards [sumlocc c n] with t h ht using by rw [h ht])
have aux1 : 0 ≤ b := (Nat.pos_of_floor_pos <| (Nat.zero_le _).trans_lt hb).le
have aux2 : ⌊a⌋₊ + 1 ≤ b := by rwa [← Nat.cast_add_one, ← Nat.le_floor_iff aux1]
have aux3 : a ≤ ⌊a⌋₊ + 1 := (Nat.lt_floor_add_one _).le
have aux4 : a ≤ ⌊b⌋₊ := le_of_lt (by rwa [← Nat.floor_lt ha])
-- now break up into 3 subintervals
rw [← intervalIntegrable_iff_integrableOn_Icc_of_le (aux3.trans aux2)]
have I1 : IntervalIntegrable _ volume a ↑(⌊a⌋₊ + 1) :=
h_locint (mod_cast aux3) (Nat.floor_le ha) (mod_cast le_rfl) le_rfl (mod_cast aux2)
have I2 : IntervalIntegrable _ volume ↑(⌊a⌋₊ + 1) ⌊b⌋₊ :=
trans_iterate_Ico hb fun k hk ↦ h_locint (mod_cast k.le_succ)
le_rfl (mod_cast le_rfl) (ineqofmemIco hk).1 (mod_cast (ineqofmemIco hk).2)
have I3 : IntervalIntegrable _ volume ⌊b⌋₊ b :=
h_locint (Nat.floor_le aux1) le_rfl (Nat.lt_floor_add_one _).le aux4 le_rfl
exact (I1.trans I2).trans I3
· rw [Set.Icc_eq_empty_of_lt hab]
exact integrableOn_empty
/-- Abel's summation formula. -/
theorem _root_.sum_mul_eq_sub_sub_integral_mul (ha : 0 ≤ a) (hab : a ≤ b)
(hf_diff : ∀ t ∈ Set.Icc a b, DifferentiableAt ℝ f t)
(hf_int : IntegrableOn (deriv f) (Set.Icc a b)) :
∑ k ∈ Ioc ⌊a⌋₊ ⌊b⌋₊, f k * c k =
f b * (∑ k ∈ Icc 0 ⌊b⌋₊, c k) - f a * (∑ k ∈ Icc 0 ⌊a⌋₊, c k) -
∫ t in Set.Ioc a b, deriv f t * ∑ k ∈ Icc 0 ⌊t⌋₊, c k := by
rw [← integral_of_le hab]
have aux1 : ⌊a⌋₊ ≤ a := Nat.floor_le ha
have aux2 : b ≤ ⌊b⌋₊ + 1 := (Nat.lt_floor_add_one _).le
-- We consider two cases depending on whether the sum is empty or not
obtain hb | hb := eq_or_lt_of_le (Nat.floor_le_floor hab)
· rw [hb, Ioc_eq_empty_of_le le_rfl, sum_empty, ← sub_mul,
integralmulsum c hf_diff hf_int _ _ ⌊b⌋₊ hab (hb ▸ aux1) aux2 le_rfl le_rfl, sub_self]
have aux3 : a ≤ ⌊a⌋₊ + 1 := (Nat.lt_floor_add_one _).le
have aux4 : ⌊a⌋₊ + 1 ≤ b := by rwa [← Nat.cast_add_one, ← Nat.le_floor_iff (ha.trans hab)]
have aux5 : ⌊b⌋₊ ≤ b := Nat.floor_le (ha.trans hab)
have aux6 : a ≤ ⌊b⌋₊ := Nat.floor_lt ha |>.mp hb |>.le
simp_rw [← smul_eq_mul, sum_Ioc_by_parts (fun k ↦ f k) _ hb, range_eq_Ico,
Ico_add_one_right_eq_Icc, smul_eq_mul]
have : ∑ k ∈ Ioc ⌊a⌋₊ (⌊b⌋₊ - 1), (f ↑(k + 1) - f k) * ∑ n ∈ Icc 0 k, c n =
∑ k ∈ Ico (⌊a⌋₊ + 1) ⌊b⌋₊, ∫ t in k..↑(k + 1), deriv f t * ∑ n ∈ Icc 0 ⌊t⌋₊, c n := by
rw [← Ico_add_one_add_one_eq_Ioc, Nat.sub_add_cancel (by cutsat), Eq.comm]
exact sum_congr rfl fun k hk ↦ (integralmulsum c hf_diff hf_int _ _ _ (mod_cast k.le_succ)
le_rfl (mod_cast le_rfl) (ineqofmemIco' hk).1 <| mod_cast (ineqofmemIco' hk).2)
rw [this, sum_integral_adjacent_intervals_Ico hb, Nat.cast_add, Nat.cast_one,
← integral_interval_sub_left (a := a) (c := ⌊a⌋₊ + 1),
← integral_add_adjacent_intervals (b := ⌊b⌋₊) (c := b),
integralmulsum c hf_diff hf_int _ _ _ aux3 aux1 le_rfl le_rfl aux4,
integralmulsum c hf_diff hf_int _ _ _ aux5 le_rfl aux2 aux6 le_rfl]
· ring
-- now deal with the integrability side goals
-- (Note we have 5 goals, but the 1st and 3rd are identical. TODO: find a non-hacky way of dealing
-- with both at once.)
· rw [intervalIntegrable_iff_integrableOn_Icc_of_le aux6]
exact (integrableOn_mul_sum_Icc c ha hf_int).mono_set (Set.Icc_subset_Icc_right aux5)
· rw [intervalIntegrable_iff_integrableOn_Icc_of_le aux5]
exact (integrableOn_mul_sum_Icc c ha hf_int).mono_set (Set.Icc_subset_Icc_left aux6)
· rw [intervalIntegrable_iff_integrableOn_Icc_of_le aux6]
exact (integrableOn_mul_sum_Icc c ha hf_int).mono_set (Set.Icc_subset_Icc_right aux5)
· rw [intervalIntegrable_iff_integrableOn_Icc_of_le aux3]
exact (integrableOn_mul_sum_Icc c ha hf_int).mono_set (Set.Icc_subset_Icc_right aux4)
· exact fun k hk ↦ (intervalIntegrable_iff_integrableOn_Icc_of_le (mod_cast k.le_succ)).mpr
<| (integrableOn_mul_sum_Icc c ha hf_int).mono_set
<| (Set.Icc_subset_Icc_iff (mod_cast k.le_succ)).mpr <| mod_cast (ineqofmemIco hk)
/-- A version of `sum_mul_eq_sub_sub_integral_mul` where the endpoints are `Nat`. -/
theorem _root_.sum_mul_eq_sub_sub_integral_mul' {n m : ℕ} (h : n ≤ m)
(hf_diff : ∀ t ∈ Set.Icc (n : ℝ) m, DifferentiableAt ℝ f t)
(hf_int : IntegrableOn (deriv f) (Set.Icc (n : ℝ) m)) :
∑ k ∈ Ioc n m, f k * c k =
f m * (∑ k ∈ Icc 0 m, c k) - f n * (∑ k ∈ Icc 0 n, c k) -
∫ t in Set.Ioc (n : ℝ) m, deriv f t * ∑ k ∈ Icc 0 ⌊t⌋₊, c k := by
convert sum_mul_eq_sub_sub_integral_mul c n.cast_nonneg (Nat.cast_le.mpr h) hf_diff hf_int
all_goals rw [Nat.floor_natCast]
end abelSummationProof
section specialversions
/-- Specialized version of `sum_mul_eq_sub_sub_integral_mul` for the case `a = 0` -/
theorem sum_mul_eq_sub_integral_mul {b : ℝ} (hb : 0 ≤ b)
(hf_diff : ∀ t ∈ Set.Icc 0 b, DifferentiableAt ℝ f t)
(hf_int : IntegrableOn (deriv f) (Set.Icc 0 b)) :
∑ k ∈ Icc 0 ⌊b⌋₊, f k * c k =
f b * (∑ k ∈ Icc 0 ⌊b⌋₊, c k) - ∫ t in Set.Ioc 0 b, deriv f t * ∑ k ∈ Icc 0 ⌊t⌋₊, c k := by
nth_rewrite 1 [Icc_eq_cons_Ioc (Nat.zero_le _)]
rw [sum_cons, ← Nat.floor_zero (R := ℝ), sum_mul_eq_sub_sub_integral_mul c le_rfl hb hf_diff
hf_int, Nat.floor_zero, Nat.cast_zero, Icc_self, sum_singleton]
ring
/-- A version of `sum_mul_eq_sub_integral_mul` where the endpoint is a `Nat`. -/
theorem sum_mul_eq_sub_integral_mul' (m : ℕ)
(hf_diff : ∀ t ∈ Set.Icc (0 : ℝ) m, DifferentiableAt ℝ f t)
(hf_int : IntegrableOn (deriv f) (Set.Icc (0 : ℝ) m)) :
∑ k ∈ Icc 0 m, f k * c k =
f m * (∑ k ∈ Icc 0 m, c k) -
∫ t in Set.Ioc (0 : ℝ) m, deriv f t * ∑ k ∈ Icc 0 ⌊t⌋₊, c k := by
convert sum_mul_eq_sub_integral_mul c m.cast_nonneg hf_diff hf_int
all_goals rw [Nat.floor_natCast]
/-- Specialized version of `sum_mul_eq_sub_integral_mul` when the first coefficient of the sequence
`c` is equal to `0`. -/
theorem sum_mul_eq_sub_integral_mul₀ (hc : c 0 = 0) (b : ℝ)
(hf_diff : ∀ t ∈ Set.Icc 1 b, DifferentiableAt ℝ f t)
(hf_int : IntegrableOn (deriv f) (Set.Icc 1 b)) :
∑ k ∈ Icc 0 ⌊b⌋₊, f k * c k =
f b * (∑ k ∈ Icc 0 ⌊b⌋₊, c k) - ∫ t in Set.Ioc 1 b, deriv f t * ∑ k ∈ Icc 0 ⌊t⌋₊, c k := by
obtain hb | hb := le_or_gt 1 b
· have : 1 ≤ ⌊b⌋₊ := (Nat.one_le_floor_iff _).mpr hb
nth_rewrite 1 [Icc_eq_cons_Ioc (Nat.zero_le _), sum_cons, ← Icc_add_one_left_eq_Ioc,
Icc_eq_cons_Ioc (by cutsat), sum_cons]
rw [zero_add, ← Nat.floor_one (R := ℝ),
sum_mul_eq_sub_sub_integral_mul c zero_le_one hb hf_diff hf_int, Nat.floor_one, Nat.cast_one,
Icc_eq_cons_Ioc zero_le_one, sum_cons, show 1 = 0 + 1 by rfl, Nat.Ioc_succ_singleton,
zero_add, sum_singleton, hc, mul_zero, zero_add]
ring
· simp_rw [Nat.floor_eq_zero.mpr hb, Icc_self, sum_singleton, Nat.cast_zero, hc, mul_zero,
Set.Ioc_eq_empty_of_le hb.le, Measure.restrict_empty, integral_zero_measure, sub_self]
/-- A version of `sum_mul_eq_sub_integral_mul₀` where the endpoint is a `Nat`. -/
theorem sum_mul_eq_sub_integral_mul₀' (hc : c 0 = 0) (m : ℕ)
(hf_diff : ∀ t ∈ Set.Icc (1 : ℝ) m, DifferentiableAt ℝ f t)
(hf_int : IntegrableOn (deriv f) (Set.Icc (1 : ℝ) m)) :
∑ k ∈ Icc 0 m, f k * c k =
f m * (∑ k ∈ Icc 0 m, c k) -
∫ t in Set.Ioc (1 : ℝ) m, deriv f t * ∑ k ∈ Icc 0 ⌊t⌋₊, c k := by
convert sum_mul_eq_sub_integral_mul₀ c hc m hf_diff hf_int
all_goals rw [Nat.floor_natCast]
end specialversions
section limit
open Filter Topology abelSummationProof intervalIntegral
theorem locallyIntegrableOn_mul_sum_Icc {m : ℕ} (ha : 0 ≤ a) {g : ℝ → 𝕜}
(hg : LocallyIntegrableOn g (Set.Ici a)) :
LocallyIntegrableOn (fun t ↦ g t * ∑ k ∈ Icc m ⌊t⌋₊, c k) (Set.Ici a) := by
refine (locallyIntegrableOn_iff isLocallyClosed_Ici).mpr fun K hK₁ hK₂ ↦ ?_
by_cases hK₃ : K.Nonempty
· have h_inf : a ≤ sInf K := (hK₁ (hK₂.sInf_mem hK₃))
refine IntegrableOn.mono_set ?_ (Bornology.IsBounded.subset_Icc_sInf_sSup hK₂.isBounded)
refine integrableOn_mul_sum_Icc _ (ha.trans h_inf) ?_
refine hg.integrableOn_compact_subset ?_ isCompact_Icc
exact (Set.Icc_subset_Ici_iff (Real.sInf_le_sSup _ hK₂.bddBelow hK₂.bddAbove)).mpr h_inf
· rw [Set.not_nonempty_iff_eq_empty.mp hK₃]
exact integrableOn_empty
theorem tendsto_sum_mul_atTop_nhds_one_sub_integral
(hf_diff : ∀ t ∈ Set.Ici 0, DifferentiableAt ℝ f t)
(hf_int : LocallyIntegrableOn (deriv f) (Set.Ici 0)) {l : 𝕜}
(h_lim : Tendsto (fun n : ℕ ↦ f n * ∑ k ∈ Icc 0 n, c k) atTop (𝓝 l))
{g : ℝ → 𝕜} (hg_dom : (fun t ↦ deriv f t * ∑ k ∈ Icc 0 ⌊t⌋₊, c k) =O[atTop] g)
(hg_int : IntegrableAtFilter g atTop) :
Tendsto (fun n : ℕ ↦ ∑ k ∈ Icc 0 n, f k * c k) atTop
(𝓝 (l - ∫ t in Set.Ioi 0, deriv f t * ∑ k ∈ Icc 0 ⌊t⌋₊, c k)) := by
have h_lim' : Tendsto (fun n : ℕ ↦ ∫ t in Set.Ioc (0 : ℝ) n, deriv f t * ∑ k ∈ Icc 0 ⌊t⌋₊, c k)
atTop (𝓝 (∫ t in Set.Ioi 0, deriv f t * ∑ k ∈ Icc 0 ⌊t⌋₊, c k)) := by
refine Tendsto.congr (fun _ ↦ by rw [← integral_of_le (Nat.cast_nonneg _)]) ?_
refine intervalIntegral_tendsto_integral_Ioi _ ?_ tendsto_natCast_atTop_atTop
exact Iff.mp integrableOn_Ici_iff_integrableOn_Ioi
<| (locallyIntegrableOn_mul_sum_Icc c le_rfl hf_int).integrableOn_of_isBigO_atTop
hg_dom hg_int
refine (h_lim.sub h_lim').congr (fun _ ↦ ?_)
rw [sum_mul_eq_sub_integral_mul' _ _ (fun t ht ↦ hf_diff _ ht.1)]
exact hf_int.integrableOn_compact_subset Set.Icc_subset_Ici_self isCompact_Icc
theorem tendsto_sum_mul_atTop_nhds_one_sub_integral₀ (hc : c 0 = 0)
(hf_diff : ∀ t ∈ Set.Ici 1, DifferentiableAt ℝ f t)
(hf_int : LocallyIntegrableOn (deriv f) (Set.Ici 1)) {l : 𝕜}
(h_lim : Tendsto (fun n : ℕ ↦ f n * ∑ k ∈ Icc 0 n, c k) atTop (𝓝 l))
{g : ℝ → ℝ} (hg_dom : (fun t ↦ deriv f t * ∑ k ∈ Icc 0 ⌊t⌋₊, c k) =O[atTop] g)
(hg_int : IntegrableAtFilter g atTop) :
Tendsto (fun n : ℕ ↦ ∑ k ∈ Icc 0 n, f k * c k) atTop
(𝓝 (l - ∫ t in Set.Ioi 1, deriv f t * ∑ k ∈ Icc 0 ⌊t⌋₊, c k)) := by
have h : (fun n : ℕ ↦ ∫ (x : ℝ) in (1 : ℝ)..n, deriv f x * ∑ k ∈ Icc 0 ⌊x⌋₊, c k) =ᶠ[atTop]
(fun n : ℕ ↦ ∫ (t : ℝ) in Set.Ioc 1 ↑n, deriv f t * ∑ k ∈ Icc 0 ⌊t⌋₊, c k) := by
filter_upwards [eventually_ge_atTop 1] with _ h
rw [← integral_of_le (Nat.one_le_cast.mpr h)]
have h_lim' : Tendsto (fun n : ℕ ↦ ∫ t in Set.Ioc (1 : ℝ) n, deriv f t * ∑ k ∈ Icc 0 ⌊t⌋₊, c k)
atTop (𝓝 (∫ t in Set.Ioi 1, deriv f t * ∑ k ∈ Icc 0 ⌊t⌋₊, c k)) := by
refine Tendsto.congr' h (intervalIntegral_tendsto_integral_Ioi _ ?_ tendsto_natCast_atTop_atTop)
exact Iff.mp integrableOn_Ici_iff_integrableOn_Ioi
<| (locallyIntegrableOn_mul_sum_Icc c zero_le_one hf_int).integrableOn_of_isBigO_atTop
hg_dom hg_int
refine (h_lim.sub h_lim').congr (fun _ ↦ ?_)
rw [sum_mul_eq_sub_integral_mul₀' _ hc _ (fun t ht ↦ hf_diff _ ht.1)]
exact hf_int.integrableOn_compact_subset Set.Icc_subset_Ici_self isCompact_Icc
end limit
section summable
open Filter abelSummationProof
private theorem summable_mul_of_bigO_atTop_aux (m : ℕ)
(h_bdd : (fun n : ℕ ↦ ‖f n‖ * ∑ k ∈ Icc 0 n, ‖c k‖) =O[atTop] fun _ ↦ (1 : ℝ))
(hf_int : LocallyIntegrableOn (deriv (fun t ↦ ‖f t‖)) (Set.Ici (m : ℝ)))
(hf : ∀ n : ℕ, ∑ k ∈ Icc 0 n, ‖f k‖ * ‖c k‖ =
‖f n‖ * ∑ k ∈ Icc 0 n, ‖c k‖ -
∫ (t : ℝ) in Set.Ioc ↑m ↑n, deriv (fun t ↦ ‖f t‖) t * ∑ k ∈ Icc 0 ⌊t⌋₊, ‖c k‖)
{g : ℝ → ℝ}
(hg₁ : (fun t ↦ deriv (fun t ↦ ‖f t‖) t * ∑ k ∈ Icc 0 ⌊t⌋₊, ‖c k‖) =O[atTop] g)
(hg₂ : IntegrableAtFilter g atTop) :
Summable (fun n : ℕ ↦ f n * c n) := by
obtain ⟨C₁, hC₁⟩ := Asymptotics.isBigO_one_nat_atTop_iff.mp h_bdd
let C₂ := ∫ t in Set.Ioi (m : ℝ), ‖deriv (fun t ↦ ‖f t‖) t * ∑ k ∈ Icc 0 ⌊t⌋₊, ‖c k‖‖
refine summable_of_sum_range_norm_le (c := max (C₁ + C₂) 1) fun n ↦ ?_
cases n with
| zero => simp only [range_zero, norm_mul, sum_empty, le_sup_iff, zero_le_one, or_true]
| succ n =>
have h_mes : Measurable fun t ↦ deriv (fun t ↦ ‖f t‖) t * ∑ k ∈ Icc 0 ⌊t⌋₊, ‖c k‖ :=
(measurable_deriv _).mul <| Measurable.comp' (g := fun n : ℕ ↦ ∑ k ∈ Icc 0 n, ‖c k‖)
(fun _ _ ↦ trivial) Nat.measurable_floor
rw [Nat.range_eq_Icc_zero_sub_one _ n.add_one_ne_zero, add_tsub_cancel_right]
calc
_ = ∑ k ∈ Icc 0 n, ‖f k‖ * ‖c k‖ := by simp_rw [norm_mul]
_ = ‖f n‖ * ∑ k ∈ Icc 0 n, ‖c k‖ -
∫ t in Set.Ioc ↑m ↑n, deriv (fun t ↦ ‖f t‖) t * ∑ k ∈ Icc 0 ⌊t⌋₊, ‖c k‖ := ?_
_ ≤ C₁ - ∫ t in Set.Ioc ↑m ↑n, deriv (fun t ↦ ‖f t‖) t * ∑ k ∈ Icc 0 ⌊t⌋₊, ‖c k‖ := ?_
_ ≤ C₁ + ∫ t in Set.Ioc ↑m ↑n, ‖deriv (fun t ↦ ‖f t‖) t * ∑ k ∈ Icc 0 ⌊t⌋₊, ‖c k‖‖ := ?_
_ ≤ C₁ + C₂ := ?_
_ ≤ max (C₁ + C₂) 1 := le_max_left _ _
· exact hf _
· refine tsub_le_tsub_right (le_of_eq_of_le (Real.norm_of_nonneg ?_).symm (hC₁ n)) _
exact mul_nonneg (norm_nonneg _) (sum_nonneg fun _ _ ↦ norm_nonneg _)
· grw [sub_eq_add_neg, neg_le_abs, abs_integral_le_integral_abs]
simp
· unfold C₂
grw [setIntegral_mono_set ?_ (.of_forall fun _ ↦ norm_nonneg _)
Set.Ioc_subset_Ioi_self.eventuallyLE]
rw [← integrableOn_Ici_iff_integrableOn_Ioi, IntegrableOn,
integrable_norm_iff h_mes.aestronglyMeasurable]
exact (locallyIntegrableOn_mul_sum_Icc _ m.cast_nonneg hf_int).integrableOn_of_isBigO_atTop
hg₁ hg₂
theorem summable_mul_of_bigO_atTop
(hf_diff : ∀ t ∈ Set.Ici 0, DifferentiableAt ℝ (fun x ↦ ‖f x‖) t)
(hf_int : LocallyIntegrableOn (deriv (fun t ↦ ‖f t‖)) (Set.Ici 0))
(h_bdd : (fun n : ℕ ↦ ‖f n‖ * ∑ k ∈ Icc 0 n, ‖c k‖) =O[atTop] fun _ ↦ (1 : ℝ))
{g : ℝ → ℝ} (hg₁ : (fun t ↦ deriv (fun t ↦ ‖f t‖) t * ∑ k ∈ Icc 0 ⌊t⌋₊, ‖c k‖) =O[atTop] g)
(hg₂ : IntegrableAtFilter g atTop) :
Summable (fun n : ℕ ↦ f n * c n) := by
refine summable_mul_of_bigO_atTop_aux c 0 h_bdd (by rwa [Nat.cast_zero]) (fun n ↦ ?_) hg₁ hg₂
exact_mod_cast sum_mul_eq_sub_integral_mul' _ _ (fun _ ht ↦ hf_diff _ ht.1)
(hf_int.integrableOn_compact_subset Set.Icc_subset_Ici_self isCompact_Icc)
/-- A version of `summable_mul_of_bigO_atTop` that can be useful to avoid difficulties near zero. -/
theorem summable_mul_of_bigO_atTop'
(hf_diff : ∀ t ∈ Set.Ici 1, DifferentiableAt ℝ (fun x ↦ ‖f x‖) t)
(hf_int : LocallyIntegrableOn (deriv (fun t ↦ ‖f t‖)) (Set.Ici 1))
(h_bdd : (fun n : ℕ ↦ ‖f n‖ * ∑ k ∈ Icc 1 n, ‖c k‖) =O[atTop] fun _ ↦ (1 : ℝ))
{g : ℝ → ℝ} (hg₁ : (fun t ↦ deriv (fun t ↦ ‖f t‖) t * ∑ k ∈ Icc 1 ⌊t⌋₊, ‖c k‖) =O[atTop] g)
(hg₂ : IntegrableAtFilter g atTop) :
Summable (fun n : ℕ ↦ f n * c n) := by
have h : ∀ n, ∑ k ∈ Icc 1 n, ‖c k‖ = ∑ k ∈ Icc 0 n, ‖(fun n ↦ if n = 0 then 0 else c n) k‖ := by
intro n
rw [Icc_eq_cons_Ioc n.zero_le, sum_cons, ← Icc_add_one_left_eq_Ioc, zero_add]
simp_rw [if_pos, norm_zero, zero_add]
exact Finset.sum_congr rfl fun _ h ↦ by rw [if_neg (zero_lt_one.trans_le (mem_Icc.mp h).1).ne']
simp_rw [h] at h_bdd hg₁
refine Summable.congr_atTop (summable_mul_of_bigO_atTop_aux (fun n ↦ if n = 0 then 0 else c n) 1
h_bdd (by rwa [Nat.cast_one]) (fun n ↦ ?_) hg₁ hg₂) ?_
· exact_mod_cast sum_mul_eq_sub_integral_mul₀' _ (by simp only [reduceIte, norm_zero]) n
(fun _ ht ↦ hf_diff _ ht.1)
(hf_int.integrableOn_compact_subset Set.Icc_subset_Ici_self isCompact_Icc)
· filter_upwards [eventually_ne_atTop 0] with k hk
simp_rw [if_neg hk]
end summable |
.lake/packages/mathlib/Mathlib/NumberTheory/FrobeniusNumber.lean | import Mathlib.RingTheory.Ideal.NatInt
/-!
# Frobenius Number
In this file we first define a predicate for Frobenius numbers, then solve the 2-variable variant
of this problem. We also show the Frobenius number exists for any set of coprime natural numbers
that doesn't contain 1. This is closely related to the fact that all ideals of ℕ are finitely
generated, which we also prove in this file.
## Theorem Statement
Given a finite set of relatively prime integers all greater than 1, their Frobenius number is the
largest positive integer that cannot be expressed as a sum of nonnegative multiples of these
integers. Here we show the Frobenius number of two relatively prime integers `m` and `n` greater
than 1 is `m * n - m - n`. This result is also known as the Chicken McNugget Theorem.
## Implementation Notes
First we define Frobenius numbers in general using `IsGreatest` and `AddSubmonoid.closure`. Then
we proceed to compute the Frobenius number of `m` and `n`.
For the upper bound, we begin with an auxiliary lemma showing `m * n` is not attainable, then show
`m * n - m - n` is not attainable. Then for the construction, we create a `k_1` which is `k mod n`
and `0 mod m`, then show it is at most `k`. Then `k_1` is a multiple of `m`, so `(k-k_1)`
is a multiple of n, and we're done.
## Tags
frobenius number, chicken mcnugget, chinese remainder theorem, AddSubmonoid.closure
-/
open Nat
/-- A natural number `n` is the **Frobenius number** of a set of natural numbers `s` if it is an
upper bound on the complement of the additive submonoid generated by `s`.
In other words, it is the largest number that cannot be expressed as a sum of numbers in `s`. -/
def FrobeniusNumber (n : ℕ) (s : Set ℕ) : Prop :=
IsGreatest { k | k ∉ AddSubmonoid.closure s } n
theorem frobeniusNumber_iff {n : ℕ} {s : Set ℕ} :
FrobeniusNumber n s ↔ n ∉ AddSubmonoid.closure s ∧ ∀ k > n, k ∈ AddSubmonoid.closure s := by
simp_rw [FrobeniusNumber, IsGreatest, upperBounds, Set.mem_setOf, not_imp_comm, not_le]
variable {m n : ℕ}
/-- The **Chicken McNugget theorem** stating that the Frobenius number
of positive numbers `m` and `n` is `m * n - m - n`. -/
theorem frobeniusNumber_pair (cop : Coprime m n) (hm : 1 < m) (hn : 1 < n) :
FrobeniusNumber (m * n - m - n) {m, n} := by
simp_rw [FrobeniusNumber, AddSubmonoid.mem_closure_pair]
have hmn : m + n ≤ m * n := add_le_mul hm hn
constructor
· push_neg
intro a b h
apply cop.mul_add_mul_ne_mul (add_one_ne_zero a) (add_one_ne_zero b)
simp only [Nat.sub_sub, smul_eq_mul] at h
zify [hmn] at h ⊢
rw [← sub_eq_zero] at h ⊢
rw [← h]
ring
· intro k hk
dsimp at hk
contrapose! hk
let x := chineseRemainder cop 0 k
have hx : x.val < m * n := chineseRemainder_lt_mul cop 0 k (ne_bot_of_gt hm) (ne_bot_of_gt hn)
suffices key : x.1 ≤ k by
obtain ⟨a, ha⟩ := modEq_zero_iff_dvd.mp x.2.1
obtain ⟨b, hb⟩ := (modEq_iff_dvd' key).mp x.2.2
exact ⟨a, b, by rw [mul_comm, ← ha, mul_comm, ← hb, Nat.add_sub_of_le key]⟩
refine ModEq.le_of_lt_add x.2.2 (lt_of_le_of_lt ?_ (add_lt_add_right hk n))
rw [Nat.sub_add_cancel (le_tsub_of_add_le_left hmn)]
exact
ModEq.le_of_lt_add
(x.2.1.trans (modEq_zero_iff_dvd.mpr (Nat.dvd_sub (dvd_mul_right m n) dvd_rfl)).symm)
(lt_of_lt_of_le hx le_tsub_add)
namespace Nat
open Submodule.IsPrincipal
/-- The gcd of a set of natural numbers is defined to be the nonnegative generator
of the ideal of `ℤ` generated by them. -/
noncomputable def setGcd (s : Set ℕ) : ℕ :=
(generator <| Ideal.span <| ((↑) : ℕ → ℤ) '' s).natAbs
variable {s t : Set ℕ} {n : ℕ}
lemma setGcd_dvd_of_mem (h : n ∈ s) : setGcd s ∣ n := by
rw [setGcd, ← Int.dvd_natCast, ← mem_iff_generator_dvd]
exact Ideal.subset_span ⟨n, h, rfl⟩
lemma setGcd_dvd_of_mem_closure (h : n ∈ AddSubmonoid.closure s) : setGcd s ∣ n :=
AddSubmonoid.closure_induction (fun _ ↦ setGcd_dvd_of_mem) (dvd_zero _) (fun _ _ _ _ ↦ dvd_add) h
/-- The characterizing property of `Nat.setGcd`. -/
lemma dvd_setGcd_iff : n ∣ setGcd s ↔ ∀ m ∈ s, n ∣ m := by
simp_rw [setGcd, ← Int.natCast_dvd, dvd_generator_span_iff,
Set.forall_mem_image, Int.natCast_dvd_natCast]
lemma setGcd_mono (h : s ⊆ t) : setGcd t ∣ setGcd s :=
dvd_setGcd_iff.mpr fun _m hm ↦ setGcd_dvd_of_mem (h hm)
lemma dvdNotUnit_setGcd_insert (h : ¬ setGcd s ∣ n) :
DvdNotUnit (setGcd (insert n s)) (setGcd s) :=
dvdNotUnit_of_dvd_of_not_dvd (setGcd_mono <| Set.subset_insert ..)
fun dvd ↦ h <| dvd_setGcd_iff.mp dvd _ (Set.mem_insert ..)
lemma setGcd_insert_of_dvd (h : setGcd s ∣ n) : setGcd (insert n s) = setGcd s :=
(setGcd_mono <| Set.subset_insert ..).antisymm <| dvd_setGcd_iff.mpr
fun m ↦ by rintro (rfl | hm); exacts [h, setGcd_dvd_of_mem hm]
lemma setGcd_eq_zero_iff : setGcd s = 0 ↔ s ⊆ {0} := by
simp_rw [setGcd, Int.natAbs_eq_zero, ← eq_bot_iff_generator_eq_zero, Ideal.span_eq_bot,
Set.forall_mem_image, Int.natCast_eq_zero, Set.subset_def, Set.mem_singleton_iff]
lemma exists_ne_zero_of_setGcd_ne_zero (hs : setGcd s ≠ 0) : ∃ n ∈ s, n ≠ 0 := by
contrapose! hs
exact setGcd_eq_zero_iff.mpr hs
variable (s)
lemma span_singleton_setGcd : Ideal.span {(setGcd s : ℤ)} = Ideal.span (((↑) : ℕ → ℤ) '' s) := by
rw [setGcd, ← Ideal.span_singleton_eq_span_singleton.mpr (Int.associated_natAbs _),
Ideal.span, span_singleton_generator]
lemma subset_span_setGcd : s ⊆ Ideal.span {setGcd s} :=
fun _x hx ↦ Ideal.mem_span_singleton.mpr (setGcd_dvd_of_mem hx)
open Ideal in
theorem exists_mem_span_nat_finset_of_ge :
∃ (t : Finset ℕ) (n : ℕ), ↑t ⊆ s ∧ ∀ m ≥ n, setGcd s ∣ m → m ∈ Ideal.span t := by
by_cases h0 : setGcd s = 0
· refine ⟨∅, 0, by simp, fun _ _ dvd ↦ by cases zero_dvd_iff.mp (h0 ▸ dvd); exact zero_mem _⟩
-- Write the gcd of `s` as a ℤ-linear combination of a finite subset `t`.
have ⟨t, hts, a, eq⟩ := (Submodule.mem_span_image_iff_exists_fun _).mp
(span_singleton_setGcd s ▸ mem_span_singleton_self _)
-- Let `x` be an arbitrary nonzero element in `s`.
have ⟨x, hxs, hx⟩ := exists_ne_zero_of_setGcd_ne_zero h0
let n := (x / setGcd s) * ∑ i, (-a i).toNat * i
refine ⟨insert x t, n, by simpa [Set.insert_subset_iff] using ⟨hxs, hts⟩, fun m ge dvd ↦ ?_⟩
-- For `m ≥ n`, write `m = q * x + (r + n)` with 0 ≤ r < x.
obtain ⟨c, rfl⟩ := exists_add_of_le ge
rw [← c.div_add_mod' x]
set q := c / x
set r := c % x
rw [add_comm, add_assoc]
refine add_mem (mul_mem_left _ q (subset_span (Finset.mem_insert_self ..)))
(Submodule.span_mono (s := t) (Finset.subset_insert ..) ?_)
-- It suffices to show `r + n` lies in the ℕ-span of `t`.
obtain ⟨rx, hrx⟩ : setGcd s ∣ r := (dvd_mod_iff (setGcd_dvd_of_mem hxs)).mpr <|
(Nat.dvd_add_right <| dvd_mul_of_dvd_right (Finset.dvd_sum fun i _ ↦
dvd_mul_of_dvd_right (setGcd_dvd_of_mem (hts i.2)) _) _).mp dvd
convert (sum_mem fun i _ ↦ mul_mem_left _ _ (subset_span i.2) :
-- an explicit ℕ-linear combination of elements of `t` that is equal to `r + n`
∑ i : t, (if 0 ≤ a i then rx else x / setGcd s - rx) * (a i).natAbs * i ∈ span t)
simp_rw [← Int.natCast_inj, hrx, n, Finset.mul_sum, mul_comm _ rx, cast_add, cast_sum, cast_mul,
← eq, Finset.mul_sum, smul_eq_mul, ← mul_assoc, ← Finset.sum_add_distrib, ← add_mul]
congr! 2 with i
split_ifs with hai
· rw [Int.toNat_eq_zero.mpr (by cutsat), cast_zero, mul_zero, add_zero,
Int.natCast_natAbs, abs_eq_self.mpr hai]
· rw [cast_sub, Int.natCast_natAbs, abs_eq_neg_self.mpr (by cutsat), sub_mul,
← Int.eq_natCast_toNat.mpr (by cutsat), mul_neg (rx : ℤ), sub_neg_eq_add, add_comm]
rw [← Nat.mul_le_mul_left_iff (pos_of_ne_zero h0), ← hrx,
Nat.mul_div_cancel' (setGcd_dvd_of_mem hxs)]
exact (c.mod_lt (pos_of_ne_zero hx)).le
theorem exists_mem_closure_of_ge : ∃ n, ∀ m ≥ n, setGcd s ∣ m → m ∈ AddSubmonoid.closure s :=
have ⟨_t, n, hts, hn⟩ := exists_mem_span_nat_finset_of_ge s
⟨n, fun m ge dvd ↦ (Submodule.span_nat_eq_addSubmonoidClosure s).le
(Submodule.span_mono hts (hn m ge dvd))⟩
theorem finite_setOf_setGcd_dvd_and_mem_span :
{n | setGcd s ∣ n ∧ n ∉ Ideal.span s}.Finite :=
have ⟨n, hn⟩ := exists_mem_closure_of_ge s
(Finset.range n).finite_toSet.subset fun m h ↦ Finset.mem_range.mpr <|
lt_of_not_ge fun ge ↦ h.2 <| (Submodule.span_nat_eq_addSubmonoidClosure s).ge (hn m ge h.1)
/-- `ℕ` is a Noetherian `ℕ`-module, i.e., `ℕ` is a Noetherian semiring. -/
instance : IsNoetherian ℕ ℕ where
noetherian s := by
have ⟨t, n, hts, hn⟩ := exists_mem_span_nat_finset_of_ge s
classical
refine ⟨t ∪ {m ∈ Finset.range n | m ∈ s}, (Submodule.span_le.mpr ?_).antisymm fun m hm ↦ ?_⟩
· simpa using ⟨hts, fun _ ↦ And.right⟩
obtain le | gt := le_or_gt n m
· exact Submodule.span_mono (by simp) (hn m le (setGcd_dvd_of_mem hm))
· exact Submodule.subset_span (by simpa using .inr ⟨gt, hm⟩)
theorem addSubmonoid_fg (s : AddSubmonoid ℕ) : s.FG := by
rw [← s.toNatSubmodule_toAddSubmonoid, ← Submodule.fg_iff_addSubmonoid_fg]
apply IsNoetherian.noetherian
end Nat
/-- A set of natural numbers has a Frobenius number iff their gcd is 1; if 1 is in the set,
the Frobenius number is -1, so the Frobenius number doesn't exist as a natural number.
[Wikipedia](https://en.wikipedia.org/wiki/Coin_problem#Statement) seems to attribute this to
Issai Schur, but [Schur's theorem](https://en.wikipedia.org/wiki/Schur%27s_theorem#Combinatorics)
is a more precise statement about asymptotics of the number of ℕ-linear combinations, and the
existence of the Frobenius number for a set with gcd 1 is probably well known before that. -/
theorem exists_frobeniusNumber_iff {s : Set ℕ} :
(∃ n, FrobeniusNumber n s) ↔ setGcd s = 1 ∧ 1 ∉ s where
mp := fun ⟨n, hn⟩ ↦ by
rw [frobeniusNumber_iff] at hn
exact ⟨dvd_one.mp <| Nat.dvd_add_iff_right (setGcd_dvd_of_mem_closure (hn.2 (n + 1)
(by omega))) (n := 1) |>.mpr (setGcd_dvd_of_mem_closure (hn.2 (n + 2) (by omega))),
fun h ↦ hn.1 <| AddSubmonoid.closure_mono (Set.singleton_subset_iff.mpr h)
(addSubmonoidClosure_one.ge ⟨⟩)⟩
mpr h := by
have ⟨n, hn⟩ := exists_mem_closure_of_ge s
let P n := n ∉ AddSubmonoid.closure s
have : P 1 := h.2 ∘ one_mem_closure_iff.mp
classical
refine ⟨findGreatest P n, frobeniusNumber_iff.mpr ⟨findGreatest_spec (P := P) (m := 1)
(le_of_not_gt fun lt ↦ this (hn _ lt.le h.1.dvd)) this, fun k gt ↦ ?_⟩⟩
obtain le | le := le_total k n
· exact of_not_not (findGreatest_is_greatest gt le)
· exact hn k le (h.1.dvd.trans <| one_dvd k) |
.lake/packages/mathlib/Mathlib/NumberTheory/LucasLehmer.lean | import Mathlib.NumberTheory.Fermat
import Mathlib.RingTheory.Fintype
/-!
# The Lucas-Lehmer test for Mersenne primes
We define `lucasLehmerResidue : Π p : ℕ, ZMod (2^p - 1)`, and
prove `lucasLehmerResidue p = 0 ↔ Prime (mersenne p)`.
We construct a `norm_num` extension to calculate this residue to certify primality of Mersenne
primes using `lucas_lehmer_sufficiency`.
## TODO
- Speed up the calculations using `n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1]`.
- Find some bigger primes!
## History
This development began as a student project by Ainsley Pahljina,
and was then cleaned up for mathlib by Kim Morrison.
The tactic for certified computation of Lucas-Lehmer residues was provided by Mario Carneiro.
This tactic was ported by Thomas Murrills to Lean 4, and then it was converted to a `norm_num`
extension and made to use kernel reductions by Kyle Miller.
-/
/-- The Mersenne numbers, 2^p - 1. -/
def mersenne (p : ℕ) : ℕ :=
2 ^ p - 1
theorem strictMono_mersenne : StrictMono mersenne := fun m n h ↦
(Nat.sub_lt_sub_iff_right <| Nat.one_le_pow _ _ two_pos).2 <| by gcongr; norm_num1
@[simp]
theorem mersenne_lt_mersenne {p q : ℕ} : mersenne p < mersenne q ↔ p < q :=
strictMono_mersenne.lt_iff_lt
@[gcongr] protected alias ⟨_, GCongr.mersenne_lt_mersenne⟩ := mersenne_lt_mersenne
@[simp]
theorem mersenne_le_mersenne {p q : ℕ} : mersenne p ≤ mersenne q ↔ p ≤ q :=
strictMono_mersenne.le_iff_le
@[gcongr] protected alias ⟨_, GCongr.mersenne_le_mersenne⟩ := mersenne_le_mersenne
@[simp] theorem mersenne_zero : mersenne 0 = 0 := rfl
@[simp] lemma mersenne_odd : ∀ {p : ℕ}, Odd (mersenne p) ↔ p ≠ 0
| 0 => by simp
| p + 1 => by
simpa using Nat.Even.sub_odd (one_le_pow₀ one_le_two)
(even_two.pow_of_ne_zero p.succ_ne_zero) odd_one
@[simp] theorem mersenne_pos {p : ℕ} : 0 < mersenne p ↔ 0 < p := mersenne_lt_mersenne (p := 0)
lemma mersenne_succ (n : ℕ) : mersenne (n + 1) = 2 * mersenne n + 1 := by
dsimp [mersenne]
have := Nat.one_le_pow n 2 two_pos
cutsat
/-- If `2 ^ p - 1` is prime, then `p` is prime. -/
lemma Nat.Prime.of_mersenne {p : ℕ} (h : (mersenne p).Prime) : Nat.Prime p := by
apply Nat.prime_of_pow_sub_one_prime _ h |>.2
rintro rfl
apply Nat.not_prime_one h
namespace Mathlib.Meta.Positivity
open Lean Meta Qq Function
alias ⟨_, mersenne_pos_of_pos⟩ := mersenne_pos
/-- Extension for the `positivity` tactic: `mersenne`. -/
@[positivity mersenne _]
def evalMersenne : PositivityExt where eval {u α} _zα _pα e := do
match u, α, e with
| 0, ~q(ℕ), ~q(mersenne $a) =>
let ra ← core q(inferInstance) q(inferInstance) a
assertInstancesCommute
match ra with
| .positive pa => pure (.positive q(mersenne_pos_of_pos $pa))
| _ => pure (.nonnegative q(Nat.zero_le (mersenne $a)))
| _, _, _ => throwError "not mersenne"
end Mathlib.Meta.Positivity
@[simp]
theorem one_lt_mersenne {p : ℕ} : 1 < mersenne p ↔ 1 < p :=
mersenne_lt_mersenne (p := 1)
@[simp]
theorem succ_mersenne (k : ℕ) : mersenne k + 1 = 2 ^ k := by
rw [mersenne, tsub_add_cancel_of_le]
exact one_le_pow₀ (by simp)
lemma mersenne_mod_four {n : ℕ} (h : 2 ≤ n) : mersenne n % 4 = 3 := by
induction n, h using Nat.le_induction with
| base => rfl
| succ _ _ _ => rw [mersenne_succ]; cutsat
lemma mersenne_mod_three {n : ℕ} (odd : Odd n) (h : 3 ≤ n) : mersenne n % 3 = 1 := by
obtain ⟨k, rfl⟩ := odd
replace h : 1 ≤ k := by omega
induction k, h using Nat.le_induction with
| base => rfl
| succ j _ _ =>
rw [mersenne_succ, show 2 * (j + 1) = 2 * j + 1 + 1 by cutsat, mersenne_succ]
cutsat
lemma mersenne_mod_eight {n : ℕ} (h : 3 ≤ n) : mersenne n % 8 = 7 := by
induction n, h using Nat.le_induction with
| base => rfl
| succ _ _ _ => rw [mersenne_succ]; cutsat
/-- If `2^p - 1` is prime then 2 is a square mod `2^p - 1`. -/
lemma legendreSym_mersenne_two {p : ℕ} [Fact (mersenne p).Prime] (hp : 3 ≤ p) :
legendreSym (mersenne p) 2 = 1 := by
have := mersenne_mod_eight hp
rw [legendreSym.at_two (by cutsat), ZMod.χ₈_nat_eq_if_mod_eight]
cutsat
/-- If `2^p - 1` is prime then 3 is not a square mod `2^p - 1`. -/
lemma legendreSym_mersenne_three {p : ℕ} [Fact (mersenne p).Prime] (hp : 3 ≤ p) (odd : Odd p) :
legendreSym (mersenne p) 3 = -1 := by
rw [(by rfl : (3 : ℤ) = (3 : ℕ)), legendreSym.quadratic_reciprocity_three_mod_four (by norm_num)
(mersenne_mod_four (by cutsat)),
legendreSym.mod]
rw_mod_cast [mersenne_mod_three odd hp]
simp
namespace LucasLehmer
open Nat
/-!
We now define three(!) different versions of the recurrence
`s (i+1) = (s i)^2 - 2`.
These versions take values either in `ℤ`, in `ZMod (2^p - 1)`, or
in `ℤ` but applying `% (2^p - 1)` at each step.
They are each useful at different points in the proof,
so we take a moment setting up the lemmas relating them.
-/
/-- The recurrence `s (i+1) = (s i)^2 - 2` in `ℤ`. -/
def s : ℕ → ℤ
| 0 => 4
| i + 1 => s i ^ 2 - 2
/-- The recurrence `s (i+1) = (s i)^2 - 2` in `ZMod (2^p - 1)`. -/
def sZMod (p : ℕ) : ℕ → ZMod (2 ^ p - 1)
| 0 => 4
| i + 1 => sZMod p i ^ 2 - 2
/-- The recurrence `s (i+1) = ((s i)^2 - 2) % (2^p - 1)` in `ℤ`. -/
def sMod (p : ℕ) : ℕ → ℤ
| 0 => 4 % (2 ^ p - 1)
| i + 1 => (sMod p i ^ 2 - 2) % (2 ^ p - 1)
theorem mersenne_int_pos {p : ℕ} (hp : p ≠ 0) : (0 : ℤ) < 2 ^ p - 1 :=
sub_pos.2 <| mod_cast Nat.one_lt_two_pow hp
theorem mersenne_int_ne_zero (p : ℕ) (hp : p ≠ 0) : (2 ^ p - 1 : ℤ) ≠ 0 :=
(mersenne_int_pos hp).ne'
theorem sMod_nonneg (p : ℕ) (hp : p ≠ 0) (i : ℕ) : 0 ≤ sMod p i := by
cases i <;> dsimp [sMod]
· exact sup_eq_right.mp rfl
· apply Int.emod_nonneg
exact mersenne_int_ne_zero p hp
theorem sMod_mod (p i : ℕ) : sMod p i % (2 ^ p - 1) = sMod p i := by cases i <;> simp [sMod]
theorem sMod_lt (p : ℕ) (hp : p ≠ 0) (i : ℕ) : sMod p i < 2 ^ p - 1 := by
rw [← sMod_mod]
refine (Int.emod_lt_abs _ (mersenne_int_ne_zero p hp)).trans_eq ?_
exact abs_of_nonneg (mersenne_int_pos hp).le
theorem sZMod_eq_s (p' : ℕ) (i : ℕ) : sZMod (p' + 2) i = (s i : ZMod (2 ^ (p' + 2) - 1)) := by
induction i with
| zero => dsimp [s, sZMod]; simp
| succ i ih => push_cast [s, sZMod, ih]; rfl
-- These next two don't make good `norm_cast` lemmas.
theorem Int.natCast_pow_pred (b p : ℕ) (w : 0 < b) : ((b ^ p - 1 : ℕ) : ℤ) = (b : ℤ) ^ p - 1 := by
have : 1 ≤ b ^ p := Nat.one_le_pow p b w
norm_cast
theorem Int.coe_nat_two_pow_pred (p : ℕ) : ((2 ^ p - 1 : ℕ) : ℤ) = (2 ^ p - 1 : ℤ) :=
Int.natCast_pow_pred 2 p (by decide)
theorem sZMod_eq_sMod (p : ℕ) (i : ℕ) : sZMod p i = (sMod p i : ZMod (2 ^ p - 1)) := by
induction i <;> push_cast [← Int.coe_nat_two_pow_pred p, sMod, sZMod, *] <;> rfl
/-- The Lucas-Lehmer residue is `s p (p-2)` in `ZMod (2^p - 1)`. -/
def lucasLehmerResidue (p : ℕ) : ZMod (2 ^ p - 1) :=
sZMod p (p - 2)
theorem residue_eq_zero_iff_sMod_eq_zero (p : ℕ) (w : 1 < p) :
lucasLehmerResidue p = 0 ↔ sMod p (p - 2) = 0 := by
dsimp [lucasLehmerResidue]
rw [sZMod_eq_sMod p]
constructor
· -- We want to use that fact that `0 ≤ s_mod p (p-2) < 2^p - 1`
-- and `lucas_lehmer_residue p = 0 → 2^p - 1 ∣ s_mod p (p-2)`.
intro h
apply Int.eq_zero_of_dvd_of_nonneg_of_lt _ _
(by simpa [ZMod.intCast_zmod_eq_zero_iff_dvd] using h) <;> clear h
· exact sMod_nonneg _ (by positivity) _
· exact sMod_lt _ (by positivity) _
· intro h
rw [h]
simp
/-- **Lucas-Lehmer Test**: a Mersenne number `2^p-1` is prime if and only if
the Lucas-Lehmer residue `s p (p-2) % (2^p - 1)` is zero.
-/
def LucasLehmerTest (p : ℕ) : Prop :=
lucasLehmerResidue p = 0
/-- `q` is defined as the minimum factor of `mersenne p`, bundled as an `ℕ+`. -/
def q (p : ℕ) : ℕ+ :=
⟨Nat.minFac (mersenne p), Nat.minFac_pos (mersenne p)⟩
-- It would be nice to define this as (ℤ/qℤ)[x] / (x^2 - 3),
-- obtaining the ring structure for free,
-- but that seems to be more trouble than it's worth;
-- if it were easy to make the definition,
-- cardinality calculations would be somewhat more involved, too.
/-- We construct the ring `X q` as ℤ/qℤ + √3 ℤ/qℤ. -/
def X (q : ℕ) : Type :=
ZMod q × ZMod q
namespace X
variable {q : ℕ}
instance : Inhabited (X q) := inferInstanceAs (Inhabited (ZMod q × ZMod q))
instance : DecidableEq (X q) := inferInstanceAs (DecidableEq (ZMod q × ZMod q))
instance : AddCommGroup (X q) := inferInstanceAs (AddCommGroup (ZMod q × ZMod q))
@[ext]
theorem ext {x y : X q} (h₁ : x.1 = y.1) (h₂ : x.2 = y.2) : x = y := by
cases x; cases y; congr
@[simp] theorem zero_fst : (0 : X q).1 = 0 := rfl
@[simp] theorem zero_snd : (0 : X q).2 = 0 := rfl
@[simp]
theorem add_fst (x y : X q) : (x + y).1 = x.1 + y.1 :=
rfl
@[simp]
theorem add_snd (x y : X q) : (x + y).2 = x.2 + y.2 :=
rfl
@[simp]
theorem neg_fst (x : X q) : (-x).1 = -x.1 :=
rfl
@[simp]
theorem neg_snd (x : X q) : (-x).2 = -x.2 :=
rfl
instance : Mul (X q) where mul x y := (x.1 * y.1 + 3 * x.2 * y.2, x.1 * y.2 + x.2 * y.1)
@[simp]
theorem mul_fst (x y : X q) : (x * y).1 = x.1 * y.1 + 3 * x.2 * y.2 :=
rfl
@[simp]
theorem mul_snd (x y : X q) : (x * y).2 = x.1 * y.2 + x.2 * y.1 :=
rfl
instance : One (X q) where one := ⟨1, 0⟩
@[simp]
theorem one_fst : (1 : X q).1 = 1 :=
rfl
@[simp]
theorem one_snd : (1 : X q).2 = 0 :=
rfl
instance : Monoid (X q) :=
{ inferInstanceAs (Mul (X q)), inferInstanceAs (One (X q)) with
mul_assoc := fun x y z => by ext <;> dsimp <;> ring
one_mul := fun x => by ext <;> simp
mul_one := fun x => by ext <;> simp }
instance : NatCast (X q) where
natCast := fun n => ⟨n, 0⟩
@[simp] theorem fst_natCast (n : ℕ) : (n : X q).fst = (n : ZMod q) := rfl
@[simp] theorem snd_natCast (n : ℕ) : (n : X q).snd = (0 : ZMod q) := rfl
@[simp] theorem ofNat_fst (n : ℕ) [n.AtLeastTwo] :
(ofNat(n) : X q).fst = OfNat.ofNat n :=
rfl
@[simp] theorem ofNat_snd (n : ℕ) [n.AtLeastTwo] :
(ofNat(n) : X q).snd = 0 :=
rfl
instance : AddGroupWithOne (X q) :=
{ inferInstanceAs (Monoid (X q)), inferInstanceAs (AddCommGroup (X q)),
inferInstanceAs (NatCast (X q)) with
natCast_zero := by ext <;> simp
natCast_succ := fun _ ↦ by ext <;> simp
intCast := fun n => ⟨n, 0⟩
intCast_ofNat := fun n => by ext <;> simp
intCast_negSucc := fun n => by ext <;> simp }
theorem left_distrib (x y z : X q) : x * (y + z) = x * y + x * z := by
ext <;> dsimp <;> ring
theorem right_distrib (x y z : X q) : (x + y) * z = x * z + y * z := by
ext <;> dsimp <;> ring
instance : Ring (X q) :=
{ inferInstanceAs (AddGroupWithOne (X q)), inferInstanceAs (AddCommGroup (X q)),
inferInstanceAs (Monoid (X q)) with
left_distrib := left_distrib
right_distrib := right_distrib
mul_zero := fun _ ↦ by ext <;> simp
zero_mul := fun _ ↦ by ext <;> simp }
instance : CommRing (X q) :=
{ inferInstanceAs (Ring (X q)) with
mul_comm := fun _ _ ↦ by ext <;> dsimp <;> ring }
instance [Fact (1 < (q : ℕ))] : Nontrivial (X q) :=
⟨⟨0, 1, ne_of_apply_ne Prod.fst zero_ne_one⟩⟩
@[simp]
theorem fst_intCast (n : ℤ) : (n : X q).fst = (n : ZMod q) :=
rfl
@[simp]
theorem snd_intCast (n : ℤ) : (n : X q).snd = (0 : ZMod q) :=
rfl
@[norm_cast]
theorem coe_mul (n m : ℤ) : ((n * m : ℤ) : X q) = (n : X q) * (m : X q) := by ext <;> simp
@[norm_cast]
theorem coe_natCast (n : ℕ) : ((n : ℤ) : X q) = (n : X q) := by ext <;> simp
/-- We define `ω = 2 + √3`. -/
def ω : X q := (2, 1)
/-- We define `ωb = 2 - √3`, which is the inverse of `ω`. -/
def ωb : X q := (2, -1)
theorem ω_mul_ωb : (ω : X q) * ωb = 1 := by
dsimp [ω, ωb]
ext <;> simp; ring
theorem ωb_mul_ω : (ωb : X q) * ω = 1 := by
rw [mul_comm, ω_mul_ωb]
/-- A closed form for the recurrence relation. -/
theorem closed_form (i : ℕ) : (s i : X q) = (ω : X q) ^ 2 ^ i + (ωb : X q) ^ 2 ^ i := by
induction i with
| zero =>
dsimp [s, ω, ωb]
ext <;> norm_num
| succ i ih =>
calc
(s (i + 1) : X q) = (s i ^ 2 - 2 : ℤ) := rfl
_ = (s i : X q) ^ 2 - 2 := by push_cast; rfl
_ = (ω ^ 2 ^ i + ωb ^ 2 ^ i) ^ 2 - 2 := by rw [ih]
_ = (ω ^ 2 ^ i) ^ 2 + (ωb ^ 2 ^ i) ^ 2 + 2 * (ωb ^ 2 ^ i * ω ^ 2 ^ i) - 2 := by ring
_ = (ω ^ 2 ^ i) ^ 2 + (ωb ^ 2 ^ i) ^ 2 := by
rw [← mul_pow ωb ω, ωb_mul_ω, one_pow, mul_one, add_sub_cancel_right]
_ = ω ^ 2 ^ (i + 1) + ωb ^ 2 ^ (i + 1) := by rw [← pow_mul, ← pow_mul, _root_.pow_succ]
/-- We define `α = √3`. -/
def α : X q := (0, 1)
@[simp] lemma α_sq : (α ^ 2 : X q) = 3 := by
ext <;> simp [α, sq]
@[simp] lemma one_add_α_sq : ((1 + α) ^ 2 : X q) = 2 * ω := by
ext <;> simpa [α, ω, sq] using by norm_num
lemma α_pow (i : ℕ) : (α : X q) ^ (2 * i + 1) = 3 ^ i * α := by
rw [pow_succ, pow_mul, α_sq]
/-! We show that `X q` has characteristic `q`, so that we can apply the binomial theorem. -/
instance : CharP (X q) q where
cast_eq_zero_iff x := by
convert ZMod.natCast_eq_zero_iff _ _
exact ⟨congr_arg Prod.fst, fun hx ↦ ext hx (by simp)⟩
instance : Coe (ZMod ↑q) (X q) where
coe := ZMod.castHom dvd_rfl (X q)
/-- If `3` is not a square mod `q` then `(1 + α) ^ q = 1 - α` -/
lemma one_add_α_pow_q [Fact q.Prime] (odd : Odd q) (leg3 : legendreSym q 3 = -1) :
(1 + α : X q) ^ q = 1 - α := by
obtain ⟨k, rfl⟩ := odd
let q := 2 * k + 1
have : (3 ^ k : ZMod q) = -1 := by
simpa [leg3, mul_add_div, eq_comm] using legendreSym.eq_pow (2 * k + 1) 3
rw [add_pow_expChar, α_pow, show (3 : X q) = (3 : ZMod q) by rw [map_ofNat], ← map_pow, this,
map_neg]
simp [sub_eq_add_neg]
/-- If `3` is not a square then `(1 + α) ^ (q + 1) = -2`. -/
lemma one_add_α_pow_q_succ [Fact q.Prime] (odd : Odd q) (leg3 : legendreSym q 3 = -1) :
(1 + α : X q) ^ (q + 1) = -2 := by
rw [pow_succ, one_add_α_pow_q odd leg3, mul_comm, ← _root_.sq_sub_sq, α_sq]
norm_num
/-- If `3` is not a square then `(2 * ω) ^ ((q + 1) / 2) = -2`. -/
lemma two_mul_ω_pow [Fact q.Prime] (odd : Odd q) (leg3 : legendreSym q 3 = -1) :
(2 * ω : X q) ^ ((q + 1) / 2) = -2 := by
rw [← one_add_α_sq, ← pow_mul]
have : 2 * ((q + 1) / 2) = q + 1 := by
apply Nat.mul_div_cancel'
rw [← even_iff_two_dvd]
exact Odd.add_one odd
rw [this, one_add_α_pow_q_succ odd leg3]
/-- If 3 is not a square and 2 is square then $\omega^{(q+1)/2}=-1$. -/
lemma pow_ω [Fact q.Prime] (odd : Odd q)
(leg3 : legendreSym q 3 = -1)
(leg2 : legendreSym q 2 = 1) :
(ω : X q) ^ ((q + 1) / 2) = -1 := by
have pow2 : (2 : ZMod q) ^ ((q + 1) / 2) = 2 := by
obtain ⟨_, _⟩ := odd
rw [(by cutsat : (q + 1) / 2 = q / 2 + 1), pow_succ]
have leg := legendreSym.eq_pow q 2
have : (2 : ZMod q) = ((2 : ℤ) : ZMod q) := by norm_cast
rw [this, ← leg, leg2]
ring
have := two_mul_ω_pow odd leg3
rw [mul_pow] at this
have coe : (2 : X q) = (2 : ZMod q) := by rw [map_ofNat]
rw [coe, ← RingHom.map_pow, pow2, ← coe,
(by ring : (-2 : X q) = 2 * -1)] at this
refine (IsUnit.of_mul_eq_one (M := X q) ↑((q + 1) / 2) ?_).mul_left_cancel this
norm_cast
simp [Nat.mul_div_cancel' odd.add_one.two_dvd]
/-- The final evaluation needed to establish the Lucas-Lehmer necessity. -/
lemma ω_pow_trace [Fact q.Prime] (odd : Odd q)
(leg3 : legendreSym q 3 = -1)
(leg2 : legendreSym q 2 = 1)
(hq4 : 4 ∣ q + 1) :
(ω : X q) ^ ((q + 1) / 4) + ωb ^ ((q + 1) / 4) = 0 := by
have : (ω : X q) ^ ((q + 1) / 2) * ωb ^ ((q + 1) / 4) = -ωb ^ ((q + 1) / 4) := by
rw [pow_ω odd leg3 leg2]
ring
have div4 : (q + 1) / 2 = (q + 1) / 4 + (q + 1) / 4 := by rcases hq4 with ⟨k, hk⟩; omega
rw [div4, pow_add, mul_assoc, ← mul_pow, ω_mul_ωb, one_pow, mul_one] at this
rw [this]
ring
variable [NeZero q]
instance : Fintype (X q) := inferInstanceAs (Fintype (ZMod q × ZMod q))
/-- The cardinality of `X` is `q^2`. -/
theorem card_eq : Fintype.card (X q) = q ^ 2 := by
dsimp [X]
rw [Fintype.card_prod, ZMod.card q, sq]
/-- There are strictly fewer than `q^2` units, since `0` is not a unit. -/
nonrec theorem card_units_lt (w : 1 < q) : Fintype.card (X q)ˣ < q ^ 2 := by
have : Fact (1 < (q : ℕ)) := ⟨w⟩
convert card_units_lt (X q)
rw [card_eq]
end X
open X
/-!
Here and below, we introduce `p' = p - 2`, in order to avoid using subtraction in `ℕ`.
-/
/-- If `1 < p`, then `q p`, the smallest prime factor of `mersenne p`, is more than 2. -/
theorem two_lt_q (p' : ℕ) : 2 < q (p' + 2) := by
refine (minFac_prime (one_lt_mersenne.2 ?_).ne').two_le.lt_of_ne' ?_
· exact le_add_left _ _
· rw [Ne, minFac_eq_two_iff, mersenne, Nat.pow_succ']
exact Nat.two_not_dvd_two_mul_sub_one Nat.one_le_two_pow
theorem ω_pow_formula (p' : ℕ) (h : lucasLehmerResidue (p' + 2) = 0) :
∃ k : ℤ,
(ω : X (q (p' + 2))) ^ 2 ^ (p' + 1) =
k * mersenne (p' + 2) * (ω : X (q (p' + 2))) ^ 2 ^ p' - 1 := by
dsimp [lucasLehmerResidue] at h
rw [sZMod_eq_s p'] at h
replace h : 2 ^ (p' + 2) - 1 ∣ s p' := by simpa [ZMod.intCast_zmod_eq_zero_iff_dvd] using h
obtain ⟨k, h⟩ := h
use k
replace h := congr_arg (fun n : ℤ => (n : X (q (p' + 2)))) h
-- coercion from ℤ to X q
dsimp at h
rw [closed_form] at h
replace h := congr_arg (fun x => ω ^ 2 ^ p' * x) h
dsimp at h
have t : 2 ^ p' + 2 ^ p' = 2 ^ (p' + 1) := by ring
rw [mul_add, ← pow_add ω, t, ← mul_pow ω ωb (2 ^ p'), ω_mul_ωb, one_pow] at h
rw [mul_comm, coe_mul] at h
rw [mul_comm _ (k : X (q (p' + 2)))] at h
replace h := eq_sub_of_add_eq h
have : 1 ≤ 2 ^ (p' + 2) := Nat.one_le_pow _ _ (by decide)
exact mod_cast h
/-- `q` is the minimum factor of `mersenne p`, so `M p = 0` in `X q`. -/
theorem mersenne_coe_X (p : ℕ) : (mersenne p : X (q p)) = 0 := by
ext <;> simp [mersenne, q, ZMod.natCast_eq_zero_iff, -pow_pos]
apply Nat.minFac_dvd
theorem ω_pow_eq_neg_one (p' : ℕ) (h : lucasLehmerResidue (p' + 2) = 0) :
(ω : X (q (p' + 2))) ^ 2 ^ (p' + 1) = -1 := by
obtain ⟨k, w⟩ := ω_pow_formula p' h
rw [mersenne_coe_X] at w
simpa using w
theorem ω_pow_eq_one (p' : ℕ) (h : lucasLehmerResidue (p' + 2) = 0) :
(ω : X (q (p' + 2))) ^ 2 ^ (p' + 2) = 1 :=
calc
(ω : X (q (p' + 2))) ^ 2 ^ (p' + 2) = (ω ^ 2 ^ (p' + 1)) ^ 2 := by
rw [← pow_mul, ← Nat.pow_succ]
_ = (-1) ^ 2 := by rw [ω_pow_eq_neg_one p' h]
_ = 1 := by simp
/-- `ω` as an element of the group of units. -/
def ωUnit (p : ℕ) : Units (X (q p)) where
val := ω
inv := ωb
val_inv := ω_mul_ωb
inv_val := ωb_mul_ω
@[simp]
theorem ωUnit_coe (p : ℕ) : (ωUnit p : X (q p)) = ω :=
rfl
/-- The order of `ω` in the unit group is exactly `2^p`. -/
theorem order_ω (p' : ℕ) (h : lucasLehmerResidue (p' + 2) = 0) :
orderOf (ωUnit (p' + 2)) = 2 ^ (p' + 2) := by
apply Nat.eq_prime_pow_of_dvd_least_prime_pow
-- the order of ω divides 2^p
· exact Nat.prime_two
· intro o
have ω_pow :=
congr_arg (Units.coeHom (X (q (p' + 2))) : Units (X (q (p' + 2))) → X (q (p' + 2))) <|
orderOf_dvd_iff_pow_eq_one.1 o
have h : (1 : ZMod (q (p' + 2))) = -1 :=
congr_arg Prod.fst (ω_pow.symm.trans (ω_pow_eq_neg_one p' h))
haveI : Fact (2 < (q (p' + 2) : ℕ)) := ⟨two_lt_q _⟩
apply ZMod.neg_one_ne_one h.symm
· apply orderOf_dvd_iff_pow_eq_one.2
apply Units.ext
push_cast
exact ω_pow_eq_one p' h
theorem order_ineq (p' : ℕ) (h : lucasLehmerResidue (p' + 2) = 0) :
2 ^ (p' + 2) < (q (p' + 2) : ℕ) ^ 2 :=
calc
2 ^ (p' + 2) = orderOf (ωUnit (p' + 2)) := (order_ω p' h).symm
_ ≤ Fintype.card (X (q (p' + 2)))ˣ := orderOf_le_card_univ
_ < q (p' + 2) ^ 2 := card_units_lt (Nat.lt_of_succ_lt (two_lt_q _))
end LucasLehmer
export LucasLehmer (LucasLehmerTest lucasLehmerResidue)
open LucasLehmer
theorem lucas_lehmer_sufficiency (p : ℕ) (w : 1 < p) : LucasLehmerTest p → (mersenne p).Prime := by
set p' := p - 2 with hp'
clear_value p'
obtain rfl : p = p' + 2 := by cutsat
have w : 1 < p' + 2 := Nat.lt_of_sub_eq_succ rfl
contrapose
intro a t
have h₁ := order_ineq p' t
have h₂ := Nat.minFac_sq_le_self (mersenne_pos.2 (Nat.lt_of_succ_lt w)) a
have h := lt_of_lt_of_le h₁ h₂
exact not_lt_of_ge (Nat.sub_le _ _) h
/-- If `2^p-1` is prime then the Lucas-Lehmer test holds, `s(p-2) % (2^p-1) = 0. -/
theorem lucas_lehmer_necessity (p : ℕ) (w : 3 ≤ p) (hp : (mersenne p).Prime) :
LucasLehmerTest p := by
have : Fact (mersenne p).Prime := ⟨‹_›⟩
set p' := p - 2 with hp'
clear_value p'
obtain rfl : p = p' + 2 := by cutsat
dsimp [LucasLehmerTest, lucasLehmerResidue]
rw [sZMod_eq_s p', ← X.fst_intCast, X.closed_form, add_tsub_cancel_right]
have := X.ω_pow_trace (q := mersenne (p' + 2)) (by simp)
(legendreSym_mersenne_three w <| hp.of_mersenne.odd_of_ne_two (by cutsat))
(legendreSym_mersenne_two w) (by simp [pow_add])
rw [succ_mersenne, pow_add, show 2 ^ 2 = 4 by norm_num, mul_div_cancel_right₀ _ (by norm_num)]
at this
simp [this]
namespace LucasLehmer
/-!
### `norm_num` extension
Next we define a `norm_num` extension that calculates `LucasLehmerTest p` for `1 < p`.
It makes use of a version of `sMod` that is specifically written to be reducible by the
Lean 4 kernel, which has the capability of efficiently reducing natural number expressions.
With this reduction in hand, it's a simple matter of applying the lemma
`LucasLehmer.residue_eq_zero_iff_sMod_eq_zero`.
See [Archive/Examples/MersennePrimes.lean] for certifications of all Mersenne primes
up through `mersenne 4423`.
-/
namespace norm_num_ext
open Qq Lean Elab.Tactic Mathlib.Meta.NormNum
/-- Version of `sMod` that is `ℕ`-valued. One should have `q = 2 ^ p - 1`.
This can be reduced by the kernel. -/
def sModNat (q : ℕ) : ℕ → ℕ
| 0 => 4 % q
| i + 1 => (sModNat q i ^ 2 + (q - 2)) % q
theorem sModNat_eq_sMod (p k : ℕ) (hp : 2 ≤ p) : (sModNat (2 ^ p - 1) k : ℤ) = sMod p k := by
have h1 := calc
4 = 2 ^ 2 := by simp
_ ≤ 2 ^ p := Nat.pow_le_pow_right (by simp) hp
have h2 : 1 ≤ 2 ^ p := by omega
induction k with
| zero =>
rw [sModNat, sMod, Int.natCast_emod]
simp [h2]
| succ k ih =>
rw [sModNat, sMod, ← ih]
have h3 : 2 ≤ 2 ^ p - 1 := by
zify [h2]
calc
(2 : Int) ≤ 4 - 1 := by simp
_ ≤ 2 ^ p - 1 := by zify at h1; exact Int.sub_le_sub_right h1 _
zify [h2, h3]
rw [← add_sub_assoc, sub_eq_add_neg, add_assoc, add_comm _ (-2), ← add_assoc,
Int.add_emod_right, ← sub_eq_add_neg]
/-- Tail-recursive version of `sModNat`. -/
def sModNatTR (q k : ℕ) : ℕ :=
go k (4 % q)
where
/-- Helper function for `sMod''`. -/
go : ℕ → ℕ → ℕ
| 0, acc => acc
| n + 1, acc => go n ((acc ^ 2 + (q - 2)) % q)
/--
Generalization of `sModNat` with arbitrary base case,
useful for proving `sModNatTR` and `sModNat` agree.
-/
def sModNat_aux (b q : ℕ) : ℕ → ℕ
| 0 => b
| i + 1 => (sModNat_aux b q i ^ 2 + (q - 2)) % q
theorem sModNat_aux_eq (q k : ℕ) : sModNat_aux (4 % q) q k = sModNat q k := by
induction k with
| zero => rfl
| succ k ih => rw [sModNat_aux, ih, sModNat, ← ih]
theorem sModNatTR_eq_sModNat (q i : ℕ) : sModNatTR q i = sModNat q i := by
rw [sModNatTR, helper, sModNat_aux_eq]
where
helper b q k : sModNatTR.go q k b = sModNat_aux b q k := by
induction k generalizing b with
| zero => rfl
| succ k ih =>
rw [sModNatTR.go, ih, sModNat_aux]
clear ih
induction k with
| zero => rfl
| succ k ih =>
rw [sModNat_aux, ih, sModNat_aux]
lemma testTrueHelper (p : ℕ) (hp : Nat.blt 1 p = true) (h : sModNatTR (2 ^ p - 1) (p - 2) = 0) :
LucasLehmerTest p := by
rw [Nat.blt_eq] at hp
rw [LucasLehmerTest, LucasLehmer.residue_eq_zero_iff_sMod_eq_zero p hp, ← sModNat_eq_sMod p _ hp,
← sModNatTR_eq_sModNat, h]
rfl
lemma testFalseHelper (p : ℕ) (hp : Nat.blt 1 p = true)
(h : Nat.ble 1 (sModNatTR (2 ^ p - 1) (p - 2))) : ¬ LucasLehmerTest p := by
rw [Nat.blt_eq] at hp
rw [Nat.ble_eq, Nat.succ_le, Nat.pos_iff_ne_zero] at h
rw [LucasLehmerTest, LucasLehmer.residue_eq_zero_iff_sMod_eq_zero p hp, ← sModNat_eq_sMod p _ hp,
← sModNatTR_eq_sModNat]
simpa using h
theorem isNat_lucasLehmerTest : {p np : ℕ} →
IsNat p np → LucasLehmerTest np → LucasLehmerTest p
| _, _, ⟨rfl⟩, h => h
theorem isNat_not_lucasLehmerTest : {p np : ℕ} →
IsNat p np → ¬ LucasLehmerTest np → ¬ LucasLehmerTest p
| _, _, ⟨rfl⟩, h => h
/-- Calculate `LucasLehmer.LucasLehmerTest p` for `2 ≤ p` by using kernel reduction for the
`sMod'` function. -/
@[norm_num LucasLehmer.LucasLehmerTest (_ : ℕ)]
def evalLucasLehmerTest : NormNumExt where eval {_ _} e := do
let .app _ (p : Q(ℕ)) ← Meta.whnfR e | failure
let ⟨ep, hp⟩ ← deriveNat p _
let np := ep.natLit!
unless 1 < np do
failure
haveI' h1ltp : Nat.blt 1 $ep =Q true := ⟨⟩
if sModNatTR (2 ^ np - 1) (np - 2) = 0 then
haveI' hs : sModNatTR (2 ^ $ep - 1) ($ep - 2) =Q 0 := ⟨⟩
have pf : Q(LucasLehmerTest $ep) := q(testTrueHelper $ep $h1ltp $hs)
have pf' : Q(LucasLehmerTest $p) := q(isNat_lucasLehmerTest $hp $pf)
return .isTrue pf'
else
haveI' hs : Nat.ble 1 (sModNatTR (2 ^ $ep - 1) ($ep - 2)) =Q true := ⟨⟩
have pf : Q(¬ LucasLehmerTest $ep) := q(testFalseHelper $ep $h1ltp $hs)
have pf' : Q(¬ LucasLehmerTest $p) := q(isNat_not_lucasLehmerTest $hp $pf)
return .isFalse pf'
end norm_num_ext
end LucasLehmer
/-!
This implementation works successfully to prove `(2^4423 - 1).Prime`,
and all the Mersenne primes up to this point appear in [Archive/Examples/MersennePrimes.lean].
These can be calculated nearly instantly, and `(2^9689 - 1).Prime` only fails due to deep
recursion.
(Note by kmill: the following notes were for the Lean 3 version. They seem like they could still
be useful, so I'm leaving them here.)
There's still low hanging fruit available to do faster computations
based on the formula
```
n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1]
```
and the fact that `% 2^p` and `/ 2^p` can be very efficient on the binary representation.
Someone should do this, too!
-/
theorem modEq_mersenne (n k : ℕ) : k ≡ k / 2 ^ n + k % 2 ^ n [MOD 2 ^ n - 1] :=
-- See https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/help.20finding.20a.20lemma/near/177698446
calc
k = 2 ^ n * (k / 2 ^ n) + k % 2 ^ n := (Nat.div_add_mod k (2 ^ n)).symm
_ ≡ 1 * (k / 2 ^ n) + k % 2 ^ n [MOD 2 ^ n - 1] :=
((Nat.modEq_sub <| Nat.succ_le_of_lt <| pow_pos zero_lt_two _).mul_right _).add_right _
_ = k / 2 ^ n + k % 2 ^ n := by rw [one_mul]
-- It's hard to know what the limiting factor for large Mersenne primes would be.
-- In the purely computational world, I think it's the squaring operation in `s`. |
.lake/packages/mathlib/Mathlib/NumberTheory/ADEInequality.lean | import Mathlib.Algebra.Order.Ring.Rat
import Mathlib.Data.Multiset.Sort
import Mathlib.Data.PNat.Basic
import Mathlib.Data.PNat.Interval
import Mathlib.Tactic.NormNum
import Mathlib.Tactic.IntervalCases
/-!
# The inequality `p⁻¹ + q⁻¹ + r⁻¹ > 1`
In this file we classify solutions to the inequality
`(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`, for positive natural numbers `p`, `q`, and `r`.
The solutions are exactly of the form.
* `A' q r := {1,q,r}`
* `D' r := {2,2,r}`
* `E6 := {2,3,3}`, or `E7 := {2,3,4}`, or `E8 := {2,3,5}`
This inequality shows up in Lie theory,
in the classification of Dynkin diagrams, root systems, and semisimple Lie algebras.
## Main declarations
* `pqr.A' q r`, the multiset `{1,q,r}`
* `pqr.D' r`, the multiset `{2,2,r}`
* `pqr.E6`, the multiset `{2,3,3}`
* `pqr.E7`, the multiset `{2,3,4}`
* `pqr.E8`, the multiset `{2,3,5}`
* `pqr.classification`, the classification of solutions to `p⁻¹ + q⁻¹ + r⁻¹ > 1`
-/
namespace ADEInequality
open Multiset
/-- `A' q r := {1,q,r}` is a `Multiset ℕ+`
that is a solution to the inequality
`(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`. -/
def A' (q r : ℕ+) : Multiset ℕ+ :=
{1, q, r}
/-- `A r := {1,1,r}` is a `Multiset ℕ+`
that is a solution to the inequality
`(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`.
These solutions are related to the Dynkin diagrams $A_r$. -/
def A (r : ℕ+) : Multiset ℕ+ :=
A' 1 r
/-- `D' r := {2,2,r}` is a `Multiset ℕ+`
that is a solution to the inequality
`(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`.
These solutions are related to the Dynkin diagrams $D_{r+2}$. -/
def D' (r : ℕ+) : Multiset ℕ+ :=
{2, 2, r}
/-- `E' r := {2,3,r}` is a `Multiset ℕ+`.
For `r ∈ {3,4,5}` is a solution to the inequality
`(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`.
These solutions are related to the Dynkin diagrams $E_{r+3}$. -/
def E' (r : ℕ+) : Multiset ℕ+ :=
{2, 3, r}
/-- `E6 := {2,3,3}` is a `Multiset ℕ+`
that is a solution to the inequality
`(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`.
This solution is related to the Dynkin diagrams $E_6$. -/
def E6 : Multiset ℕ+ :=
E' 3
/-- `E7 := {2,3,4}` is a `Multiset ℕ+`
that is a solution to the inequality
`(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`.
This solution is related to the Dynkin diagrams $E_7$. -/
def E7 : Multiset ℕ+ :=
E' 4
/-- `E8 := {2,3,5}` is a `Multiset ℕ+`
that is a solution to the inequality
`(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`.
This solution is related to the Dynkin diagrams $E_8$. -/
def E8 : Multiset ℕ+ :=
E' 5
/-- `sum_inv pqr` for a `pqr : Multiset ℕ+` is the sum of the inverses
of the elements of `pqr`, as rational number.
The intended argument is a multiset `{p,q,r}` of cardinality `3`. -/
def sumInv (pqr : Multiset ℕ+) : ℚ :=
Multiset.sum (pqr.map fun (x : ℕ+) => x⁻¹)
theorem sumInv_pqr (p q r : ℕ+) : sumInv {p, q, r} = (p : ℚ)⁻¹ + (q : ℚ)⁻¹ + (r : ℚ)⁻¹ := by
simp only [sumInv, insert_eq_cons, add_assoc, map_cons, sum_cons,
map_singleton, sum_singleton]
/-- A multiset `pqr` of positive natural numbers is `admissible`
if it is equal to `A' q r`, or `D' r`, or one of `E6`, `E7`, or `E8`. -/
def Admissible (pqr : Multiset ℕ+) : Prop :=
(∃ q r, A' q r = pqr) ∨ (∃ r, D' r = pqr) ∨ E' 3 = pqr ∨ E' 4 = pqr ∨ E' 5 = pqr
theorem admissible_A' (q r : ℕ+) : Admissible (A' q r) :=
Or.inl ⟨q, r, rfl⟩
theorem admissible_D' (n : ℕ+) : Admissible (D' n) :=
Or.inr <| Or.inl ⟨n, rfl⟩
theorem admissible_E'3 : Admissible (E' 3) :=
Or.inr <| Or.inr <| Or.inl rfl
theorem admissible_E'4 : Admissible (E' 4) :=
Or.inr <| Or.inr <| Or.inr <| Or.inl rfl
theorem admissible_E'5 : Admissible (E' 5) :=
Or.inr <| Or.inr <| Or.inr <| Or.inr rfl
theorem admissible_E6 : Admissible E6 :=
admissible_E'3
theorem admissible_E7 : Admissible E7 :=
admissible_E'4
theorem admissible_E8 : Admissible E8 :=
admissible_E'5
theorem Admissible.one_lt_sumInv {pqr : Multiset ℕ+} : Admissible pqr → 1 < sumInv pqr := by
rw [Admissible]
rintro (⟨p', q', H⟩ | ⟨n, H⟩ | H | H | H)
· rw [← H, A', sumInv_pqr, add_assoc]
simp only [lt_add_iff_pos_right, PNat.one_coe, inv_one, Nat.cast_one]
apply add_pos <;> simp only [PNat.pos, Nat.cast_pos, inv_pos]
· rw [← H, D', sumInv_pqr]
norm_num
all_goals
rw [← H, E', sumInv_pqr]
norm_num
theorem lt_three {p q r : ℕ+} (hpq : p ≤ q) (hqr : q ≤ r) (H : 1 < sumInv {p, q, r}) : p < 3 := by
have h3 : (0 : ℚ) < 3 := by simp
contrapose! H
rw [sumInv_pqr]
have h3q := H.trans hpq
have h3r := h3q.trans hqr
have hp : (p : ℚ)⁻¹ ≤ 3⁻¹ := by
rw [inv_le_inv₀ _ h3]
· assumption_mod_cast
· simp
have hq : (q : ℚ)⁻¹ ≤ 3⁻¹ := by
rw [inv_le_inv₀ _ h3]
· assumption_mod_cast
· simp
have hr : (r : ℚ)⁻¹ ≤ 3⁻¹ := by
rw [inv_le_inv₀ _ h3]
· assumption_mod_cast
· simp
calc
(p : ℚ)⁻¹ + (q : ℚ)⁻¹ + (r : ℚ)⁻¹ ≤ 3⁻¹ + 3⁻¹ + 3⁻¹ := add_le_add (add_le_add hp hq) hr
_ = 1 := by norm_num
theorem lt_four {q r : ℕ+} (hqr : q ≤ r) (H : 1 < sumInv {2, q, r}) : q < 4 := by
have h4 : (0 : ℚ) < 4 := by simp
contrapose! H
rw [sumInv_pqr]
have h4r := H.trans hqr
have hq : (q : ℚ)⁻¹ ≤ 4⁻¹ := by
rw [inv_le_inv₀ _ h4]
· assumption_mod_cast
· simp
have hr : (r : ℚ)⁻¹ ≤ 4⁻¹ := by
rw [inv_le_inv₀ _ h4]
· assumption_mod_cast
· simp
calc
(2⁻¹ + (q : ℚ)⁻¹ + (r : ℚ)⁻¹) ≤ 2⁻¹ + 4⁻¹ + 4⁻¹ := add_le_add (add_le_add le_rfl hq) hr
_ = 1 := by norm_num
theorem lt_six {r : ℕ+} (H : 1 < sumInv {2, 3, r}) : r < 6 := by
have h6 : (0 : ℚ) < 6 := by simp
contrapose! H
rw [sumInv_pqr]
have hr : (r : ℚ)⁻¹ ≤ 6⁻¹ := by
rw [inv_le_inv₀ _ h6]
· assumption_mod_cast
· simp
calc
(2⁻¹ + 3⁻¹ + (r : ℚ)⁻¹ : ℚ) ≤ 2⁻¹ + 3⁻¹ + 6⁻¹ := add_le_add (add_le_add le_rfl le_rfl) hr
_ = 1 := by norm_num
theorem admissible_of_one_lt_sumInv_aux' {p q r : ℕ+} (hpq : p ≤ q) (hqr : q ≤ r)
(H : 1 < sumInv {p, q, r}) : Admissible {p, q, r} := by
have hp3 : p < 3 := lt_three hpq hqr H
-- Porting note: `interval_cases` doesn't support `ℕ+` yet.
replace hp3 := Finset.mem_Iio.mpr hp3
conv at hp3 => change p ∈ ({1, 2} : Multiset ℕ+)
fin_cases hp3
· exact admissible_A' q r
have hq4 : q < 4 := lt_four hqr H
replace hq4 := Finset.mem_Ico.mpr ⟨hpq, hq4⟩; clear hpq
conv at hq4 => change q ∈ ({2, 3} : Multiset ℕ+)
fin_cases hq4
· exact admissible_D' r
have hr6 : r < 6 := lt_six H
replace hr6 := Finset.mem_Ico.mpr ⟨hqr, hr6⟩; clear hqr
conv at hr6 => change r ∈ ({3, 4, 5} : Multiset ℕ+)
fin_cases hr6
· exact admissible_E6
· exact admissible_E7
· exact admissible_E8
theorem admissible_of_one_lt_sumInv_aux :
∀ {pqr : List ℕ+} (_ : pqr.Sorted (· ≤ ·)) (_ : pqr.length = 3) (_ : 1 < sumInv pqr),
Admissible pqr
| [p, q, r], hs, _, H => by
obtain ⟨⟨hpq, -⟩, hqr⟩ : (p ≤ q ∧ p ≤ r) ∧ q ≤ r := by simpa using hs
exact admissible_of_one_lt_sumInv_aux' hpq hqr H
theorem admissible_of_one_lt_sumInv {p q r : ℕ+} (H : 1 < sumInv {p, q, r}) :
Admissible {p, q, r} := by
simp only [Admissible]
let S := sort (α := ℕ+) {p, q, r}
have hS : S.Sorted (· ≤ ·) := sort_sorted _ _
have hpqr : ({p, q, r} : Multiset ℕ+) = S := (sort_eq {p, q, r} LE.le).symm
rw [hpqr]
rw [hpqr] at H
apply admissible_of_one_lt_sumInv_aux hS _ H
simp only [S, insert_eq_cons, length_sort, card_cons, card_singleton]
/-- A multiset `{p,q,r}` of positive natural numbers
is a solution to `(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1` if and only if
it is `admissible` which means it is one of:
* `A' q r := {1,q,r}`
* `D' r := {2,2,r}`
* `E6 := {2,3,3}`, or `E7 := {2,3,4}`, or `E8 := {2,3,5}`
-/
theorem classification (p q r : ℕ+) : 1 < sumInv {p, q, r} ↔ Admissible {p, q, r} :=
⟨admissible_of_one_lt_sumInv, Admissible.one_lt_sumInv⟩
end ADEInequality |
.lake/packages/mathlib/Mathlib/NumberTheory/WellApproximable.lean | import Mathlib.Dynamics.Ergodic.AddCircle
import Mathlib.MeasureTheory.Covering.LiminfLimsup
/-!
# Well-approximable numbers and Gallagher's ergodic theorem
Gallagher's ergodic theorem is a result in metric number theory. It thus belongs to that branch of
mathematics concerning arithmetic properties of real numbers which hold almost everywhere with
respect to the Lebesgue measure.
Gallagher's theorem concerns the approximation of real numbers by rational numbers. The input is a
sequence of distances `δ₁, δ₂, ...`, and the theorem concerns the set of real numbers `x` for which
there is an infinity of solutions to:
$$
|x - m/n| < δₙ,
$$
where the rational number `m/n` is in lowest terms. The result is that for any `δ`, this set is
either almost all `x` or almost no `x`.
This result was proved by Gallagher in 1959
[P. Gallagher, *Approximation by reduced fractions*][Gallagher1961]. It is formalised here as
`AddCircle.addWellApproximable_ae_empty_or_univ` except with `x` belonging to the circle `ℝ ⧸ ℤ`
since this turns out to be more natural.
Given a particular `δ`, the Duffin-Schaeffer conjecture (now a theorem) gives a criterion for
deciding which of the two cases in the conclusion of Gallagher's theorem actually occurs. It was
proved by Koukoulopoulos and Maynard in 2019
[D. Koukoulopoulos, J. Maynard, *On the Duffin-Schaeffer conjecture*][KoukoulopoulosMaynard2020].
We do *not* include a formalisation of the Koukoulopoulos-Maynard result here.
## Main definitions and results:
* `approxOrderOf`: in a seminormed group `A`, given `n : ℕ` and `δ : ℝ`, `approxOrderOf A n δ`
is the set of elements within a distance `δ` of a point of order `n`.
* `wellApproximable`: in a seminormed group `A`, given a sequence of distances `δ₁, δ₂, ...`,
`wellApproximable A δ` is the limsup as `n → ∞` of the sets `approxOrderOf A n δₙ`. Thus, it
is the set of points that lie in infinitely many of the sets `approxOrderOf A n δₙ`.
* `AddCircle.addWellApproximable_ae_empty_or_univ`: *Gallagher's ergodic theorem* says that for
the (additive) circle `𝕊`, for any sequence of distances `δ`, the set
`addWellApproximable 𝕊 δ` is almost empty or almost full.
* `NormedAddCommGroup.exists_norm_nsmul_le`: a general version of Dirichlet's approximation theorem
* `AddCircle.exists_norm_nsmul_le`: Dirichlet's approximation theorem
## TODO
The hypothesis `hδ` in `AddCircle.addWellApproximable_ae_empty_or_univ` can be dropped.
An elementary (non-measure-theoretic) argument shows that if `¬ hδ` holds then
`addWellApproximable 𝕊 δ = univ` (provided `δ` is non-negative).
Use `AddCircle.exists_norm_nsmul_le` to prove:
`addWellApproximable 𝕊 (fun n ↦ 1 / n^2) = { ξ | ¬ IsOfFinAddOrder ξ }`
(which is equivalent to `Real.infinite_rat_abs_sub_lt_one_div_den_sq_iff_irrational`).
-/
open Set Filter Function Metric MeasureTheory
open scoped MeasureTheory Topology Pointwise
/-- In a seminormed group `A`, given `n : ℕ` and `δ : ℝ`, `approxOrderOf A n δ` is the set of
elements within a distance `δ` of a point of order `n`. -/
@[to_additive /-- In a seminormed additive group `A`, given `n : ℕ` and `δ : ℝ`,
`approxAddOrderOf A n δ` is the set of elements within a distance `δ` of a point of order `n`. -/]
def approxOrderOf (A : Type*) [SeminormedGroup A] (n : ℕ) (δ : ℝ) : Set A :=
thickening δ {y | orderOf y = n}
@[to_additive mem_approx_add_orderOf_iff]
theorem mem_approxOrderOf_iff {A : Type*} [SeminormedGroup A] {n : ℕ} {δ : ℝ} {a : A} :
a ∈ approxOrderOf A n δ ↔ ∃ b : A, orderOf b = n ∧ a ∈ ball b δ := by
simp only [approxOrderOf, thickening_eq_biUnion_ball, mem_iUnion₂, mem_setOf_eq, exists_prop]
/-- In a seminormed group `A`, given a sequence of distances `δ₁, δ₂, ...`, `wellApproximable A δ`
is the limsup as `n → ∞` of the sets `approxOrderOf A n δₙ`. Thus, it is the set of points that
lie in infinitely many of the sets `approxOrderOf A n δₙ`. -/
@[to_additive addWellApproximable /-- In a seminormed additive group `A`, given a sequence of
distances `δ₁, δ₂, ...`, `addWellApproximable A δ` is the limsup as `n → ∞` of the sets
`approxAddOrderOf A n δₙ`. Thus, it is the set of points that lie in infinitely many of the sets
`approxAddOrderOf A n δₙ`. -/]
def wellApproximable (A : Type*) [SeminormedGroup A] (δ : ℕ → ℝ) : Set A :=
blimsup (fun n => approxOrderOf A n (δ n)) atTop fun n => 0 < n
@[to_additive mem_add_wellApproximable_iff]
theorem mem_wellApproximable_iff {A : Type*} [SeminormedGroup A] {δ : ℕ → ℝ} {a : A} :
a ∈ wellApproximable A δ ↔
a ∈ blimsup (fun n => approxOrderOf A n (δ n)) atTop fun n => 0 < n :=
Iff.rfl
namespace approxOrderOf
variable {A : Type*} [SeminormedCommGroup A] {a : A} {m n : ℕ} (δ : ℝ)
@[to_additive]
theorem image_pow_subset_of_coprime (hm : 0 < m) (hmn : n.Coprime m) :
(fun (y : A) => y ^ m) '' approxOrderOf A n δ ⊆ approxOrderOf A n (m * δ) := by
rintro - ⟨a, ha, rfl⟩
obtain ⟨b, hb, hab⟩ := mem_approxOrderOf_iff.mp ha
replace hb : b ^ m ∈ {u : A | orderOf u = n} := by
rw [← hb] at hmn ⊢; exact hmn.orderOf_pow
apply ball_subset_thickening hb ((m : ℝ) • δ)
convert pow_mem_ball hm hab using 1
simp only [nsmul_eq_mul, Algebra.id.smul_eq_mul]
@[to_additive]
theorem image_pow_subset (n : ℕ) (hm : 0 < m) :
(fun (y : A) => y ^ m) '' approxOrderOf A (n * m) δ ⊆ approxOrderOf A n (m * δ) := by
rintro - ⟨a, ha, rfl⟩
obtain ⟨b, hb : orderOf b = n * m, hab : a ∈ ball b δ⟩ := mem_approxOrderOf_iff.mp ha
replace hb : b ^ m ∈ {y : A | orderOf y = n} := by
rw [mem_setOf_eq, orderOf_pow' b hm.ne', hb, Nat.gcd_mul_left_left, n.mul_div_cancel hm]
apply ball_subset_thickening hb (m * δ)
convert pow_mem_ball hm hab using 1
simp only [nsmul_eq_mul]
@[to_additive]
theorem smul_subset_of_coprime (han : (orderOf a).Coprime n) :
a • approxOrderOf A n δ ⊆ approxOrderOf A (orderOf a * n) δ := by
simp_rw [approxOrderOf, thickening_eq_biUnion_ball, ← image_smul, image_iUnion₂, image_smul,
smul_ball'', smul_eq_mul, mem_setOf_eq]
refine iUnion₂_subset_iff.mpr fun b hb c hc => ?_
simp only [mem_iUnion, exists_prop]
refine ⟨a * b, ?_, hc⟩
rw [← hb] at han ⊢
exact (Commute.all a b).orderOf_mul_eq_mul_orderOf_of_coprime han
@[to_additive vadd_eq_of_mul_dvd]
theorem smul_eq_of_mul_dvd (hn : 0 < n) (han : orderOf a ^ 2 ∣ n) :
a • approxOrderOf A n δ = approxOrderOf A n δ := by
simp_rw [approxOrderOf, thickening_eq_biUnion_ball, ← image_smul, image_iUnion₂, image_smul,
smul_ball'', smul_eq_mul, mem_setOf_eq]
replace han : ∀ {b : A}, orderOf b = n → orderOf (a * b) = n := by
intro b hb
rw [← hb] at han hn
rw [sq] at han
rwa [(Commute.all a b).orderOf_mul_eq_right_of_forall_prime_mul_dvd (orderOf_pos_iff.mp hn)
fun p _ hp' => dvd_trans (mul_dvd_mul_right hp' <| orderOf a) han]
let f : {b : A | orderOf b = n} → {b : A | orderOf b = n} := fun b => ⟨a * b, han b.property⟩
have hf : Surjective f := by
rintro ⟨b, hb⟩
refine ⟨⟨a⁻¹ * b, ?_⟩, ?_⟩
· rw [mem_setOf_eq, ← orderOf_inv, mul_inv_rev, inv_inv, mul_comm]
apply han
simpa
· simp only [f, mul_inv_cancel_left]
simpa only [mem_setOf_eq, Subtype.coe_mk, iUnion_coe_set] using
hf.iUnion_comp fun b => ball (b : A) δ
end approxOrderOf
namespace UnitAddCircle
theorem mem_approxAddOrderOf_iff {δ : ℝ} {x : UnitAddCircle} {n : ℕ} (hn : 0 < n) :
x ∈ approxAddOrderOf UnitAddCircle n δ ↔ ∃ m < n, gcd m n = 1 ∧ ‖x - ↑((m : ℝ) / n)‖ < δ := by
simp only [mem_approx_add_orderOf_iff, mem_setOf_eq, ball, dist_eq_norm,
AddCircle.addOrderOf_eq_pos_iff hn, mul_one]
constructor
· rintro ⟨y, ⟨m, hm₁, hm₂, rfl⟩, hx⟩; exact ⟨m, hm₁, hm₂, hx⟩
· rintro ⟨m, hm₁, hm₂, hx⟩; exact ⟨↑((m : ℝ) / n), ⟨m, hm₁, hm₂, rfl⟩, hx⟩
theorem mem_addWellApproximable_iff (δ : ℕ → ℝ) (x : UnitAddCircle) :
x ∈ addWellApproximable UnitAddCircle δ ↔
{n : ℕ | ∃ m < n, gcd m n = 1 ∧ ‖x - ↑((m : ℝ) / n)‖ < δ n}.Infinite := by
simp only [mem_add_wellApproximable_iff, ← Nat.cofinite_eq_atTop, cofinite.blimsup_set_eq,
mem_setOf_eq]
refine iff_of_eq (congr_arg Set.Infinite <| ext fun n => ⟨fun hn => ?_, fun hn => ?_⟩)
· exact (mem_approxAddOrderOf_iff hn.1).mp hn.2
· have h : 0 < n := by obtain ⟨m, hm₁, _, _⟩ := hn; exact pos_of_gt hm₁
exact ⟨h, (mem_approxAddOrderOf_iff h).mpr hn⟩
end UnitAddCircle
namespace AddCircle
variable {T : ℝ} [hT : Fact (0 < T)]
local notation a "∤" b => ¬a ∣ b
local notation a "∣∣" b => a ∣ b ∧ (a * a)∤b
local notation "𝕊" => AddCircle T
/-- **Gallagher's ergodic theorem** on Diophantine approximation. -/
theorem addWellApproximable_ae_empty_or_univ (δ : ℕ → ℝ) (hδ : Tendsto δ atTop (𝓝 0)) :
(∀ᵐ x, ¬addWellApproximable 𝕊 δ x) ∨ ∀ᵐ x, addWellApproximable 𝕊 δ x := by
/- Sketch of proof:
Let `E := addWellApproximable 𝕊 δ`. For each prime `p : ℕ`, we can partition `E` into three
pieces `E = (A p) ∪ (B p) ∪ (C p)` where:
`A p = blimsup (approxAddOrderOf 𝕊 n (δ n)) atTop (fun n => 0 < n ∧ (p ∤ n))`
`B p = blimsup (approxAddOrderOf 𝕊 n (δ n)) atTop (fun n => 0 < n ∧ (p ∣∣ n))`
`C p = blimsup (approxAddOrderOf 𝕊 n (δ n)) atTop (fun n => 0 < n ∧ (p*p ∣ n))`.
In other words, `A p` is the set of points `x` for which there exist infinitely-many `n` such
that `x` is within a distance `δ n` of a point of order `n` and `p ∤ n`. Similarly for `B`, `C`.
These sets have the following key properties:
1. `A p` is almost invariant under the ergodic map `y ↦ p • y`
2. `B p` is almost invariant under the ergodic map `y ↦ p • y + 1/p`
3. `C p` is invariant under the map `y ↦ y + 1/p`
To prove 1 and 2 we need the key result `blimsup_thickening_mul_ae_eq` but 3 is elementary.
It follows from `AddCircle.ergodic_nsmul_add` and `Ergodic.ae_empty_or_univ_of_image_ae_le` that
if either `A p` or `B p` is not almost empty for any `p`, then it is almost full and thus so is
`E`. We may therefore assume that `A p` and `B p` are almost empty for all `p`. We thus have
`E` is almost equal to `C p` for every prime. Combining this with 3 we find that `E` is almost
invariant under the map `y ↦ y + 1/p` for every prime `p`. The required result then follows from
`AddCircle.ae_empty_or_univ_of_forall_vadd_ae_eq_self`. -/
letI : SemilatticeSup Nat.Primes := Nat.Subtype.semilatticeSup _
set μ : Measure 𝕊 := volume
set u : Nat.Primes → 𝕊 := fun p => ↑((↑(1 : ℕ) : ℝ) / ((p : ℕ) : ℝ) * T)
have hu₀ : ∀ p : Nat.Primes, addOrderOf (u p) = (p : ℕ) := by
rintro ⟨p, hp⟩; exact addOrderOf_div_of_gcd_eq_one hp.pos (gcd_one_left p)
have hu : Tendsto (addOrderOf ∘ u) atTop atTop := by
rw [(funext hu₀ : addOrderOf ∘ u = (↑))]
have h_mono : Monotone ((↑) : Nat.Primes → ℕ) := fun p q hpq => hpq
refine h_mono.tendsto_atTop_atTop fun n => ?_
obtain ⟨p, hp, hp'⟩ := n.exists_infinite_primes
exact ⟨⟨p, hp'⟩, hp⟩
set E := addWellApproximable 𝕊 δ
set X : ℕ → Set 𝕊 := fun n => approxAddOrderOf 𝕊 n (δ n)
set A : ℕ → Set 𝕊 := fun p => blimsup X atTop fun n => 0 < n ∧ p∤n
set B : ℕ → Set 𝕊 := fun p => blimsup X atTop fun n => 0 < n ∧ p∣∣n
set C : ℕ → Set 𝕊 := fun p => blimsup X atTop fun n => 0 < n ∧ p ^ 2 ∣ n
have hA₀ : ∀ p, MeasurableSet (A p) := fun p =>
MeasurableSet.measurableSet_blimsup fun n _ => isOpen_thickening.measurableSet
have hB₀ : ∀ p, MeasurableSet (B p) := fun p =>
MeasurableSet.measurableSet_blimsup fun n _ => isOpen_thickening.measurableSet
have hE₀ : NullMeasurableSet E μ := by
refine (MeasurableSet.measurableSet_blimsup fun n hn =>
IsOpen.measurableSet ?_).nullMeasurableSet
exact isOpen_thickening
have hE₁ : ∀ p, E = A p ∪ B p ∪ C p := by
intro p
simp only [E, A, B, C, addWellApproximable, ← blimsup_or_eq_sup, ← and_or_left, ← sup_eq_union,
sq]
congr
ext n
tauto
have hE₂ : ∀ p : Nat.Primes, A p =ᵐ[μ] (∅ : Set 𝕊) ∧ B p =ᵐ[μ] (∅ : Set 𝕊) → E =ᵐ[μ] C p := by
rintro p ⟨hA, hB⟩
rw [hE₁ p]
exact union_ae_eq_right_of_ae_eq_empty ((union_ae_eq_right_of_ae_eq_empty hA).trans hB)
have hA : ∀ p : Nat.Primes, A p =ᵐ[μ] (∅ : Set 𝕊) ∨ A p =ᵐ[μ] univ := by
rintro ⟨p, hp⟩
let f : 𝕊 → 𝕊 := fun y => (p : ℕ) • y
suffices
f '' A p ⊆ blimsup (fun n => approxAddOrderOf 𝕊 n (p * δ n)) atTop fun n => 0 < n ∧ p∤n by
apply (ergodic_nsmul hp.one_lt).ae_empty_or_univ_of_image_ae_le (hA₀ p).nullMeasurableSet
apply (HasSubset.Subset.eventuallyLE this).congr EventuallyEq.rfl
exact blimsup_thickening_mul_ae_eq μ (fun n => 0 < n ∧ p∤n) (fun n => {y | addOrderOf y = n})
(Nat.cast_pos.mpr hp.pos) _ hδ
refine (sSupHom.setImage f).apply_blimsup_le.trans (mono_blimsup fun n hn => ?_)
replace hn := Nat.coprime_comm.mp (hp.coprime_iff_not_dvd.2 hn.2)
exact approxAddOrderOf.image_nsmul_subset_of_coprime (δ n) hp.pos hn
have hB : ∀ p : Nat.Primes, B p =ᵐ[μ] (∅ : Set 𝕊) ∨ B p =ᵐ[μ] univ := by
rintro ⟨p, hp⟩
let x := u ⟨p, hp⟩
let f : 𝕊 → 𝕊 := fun y => p • y + x
suffices
f '' B p ⊆ blimsup (fun n => approxAddOrderOf 𝕊 n (p * δ n)) atTop fun n => 0 < n ∧ p∣∣n by
apply (ergodic_nsmul_add x hp.one_lt).ae_empty_or_univ_of_image_ae_le
(hB₀ p).nullMeasurableSet
apply (HasSubset.Subset.eventuallyLE this).congr EventuallyEq.rfl
exact blimsup_thickening_mul_ae_eq μ (fun n => 0 < n ∧ p∣∣n) (fun n => {y | addOrderOf y = n})
(Nat.cast_pos.mpr hp.pos) _ hδ
refine (sSupHom.setImage f).apply_blimsup_le.trans (mono_blimsup ?_)
rintro n ⟨hn, h_div, h_ndiv⟩
have h_cop : (addOrderOf x).Coprime (n / p) := by
obtain ⟨q, rfl⟩ := h_div
rw [hu₀, Subtype.coe_mk, hp.coprime_iff_not_dvd, q.mul_div_cancel_left hp.pos]
exact fun contra => h_ndiv (mul_dvd_mul_left p contra)
replace h_div : n / p * p = n := Nat.div_mul_cancel h_div
have hf : f = (fun y => x + y) ∘ fun y => p • y := by
ext; simp [f, add_comm x]
simp_rw [Function.comp_apply, le_eq_subset]
rw [sSupHom.setImage_toFun, hf, image_comp]
have := @monotone_image 𝕊 𝕊 fun y => x + y
specialize this (approxAddOrderOf.image_nsmul_subset (δ n) (n / p) hp.pos)
simp only [h_div] at this ⊢
refine this.trans ?_
convert approxAddOrderOf.vadd_subset_of_coprime (p * δ n) h_cop
rw [hu₀, Subtype.coe_mk, mul_comm p, h_div]
change (∀ᵐ x, x ∉ E) ∨ E ∈ ae volume
rw [← eventuallyEq_empty, ← eventuallyEq_univ]
have hC : ∀ p : Nat.Primes, u p +ᵥ C p = C p := by
intro p
let e := (AddAction.toPerm (u p) : Equiv.Perm 𝕊).toOrderIsoSet
change e (C p) = C p
rw [OrderIso.apply_blimsup e, ← hu₀ p]
exact blimsup_congr (Eventually.of_forall fun n hn =>
approxAddOrderOf.vadd_eq_of_mul_dvd (δ n) hn.1 hn.2)
set_option push_neg.use_distrib true in
by_cases! h : ∀ p : Nat.Primes, A p =ᵐ[μ] (∅ : Set 𝕊) ∧ B p =ᵐ[μ] (∅ : Set 𝕊)
· replace h : ∀ p : Nat.Primes, (u p +ᵥ E : Set _) =ᵐ[μ] E := by
intro p
replace hE₂ : E =ᵐ[μ] C p := hE₂ p (h p)
have h_qmp : Measure.QuasiMeasurePreserving (-u p +ᵥ ·) μ μ :=
(measurePreserving_vadd _ μ).quasiMeasurePreserving
refine (h_qmp.vadd_ae_eq_of_ae_eq (u p) hE₂).trans (ae_eq_trans ?_ hE₂.symm)
rw [hC]
exact ae_empty_or_univ_of_forall_vadd_ae_eq_self hE₀ h hu
· right
obtain ⟨p, hp⟩ := h
rw [hE₁ p]
cases hp
· rcases hA p with _ | h; · contradiction
simp only [μ, h, union_ae_eq_univ_of_ae_eq_univ_left]
· rcases hB p with _ | h; · contradiction
simp only [μ, h, union_ae_eq_univ_of_ae_eq_univ_left,
union_ae_eq_univ_of_ae_eq_univ_right]
/-- A general version of **Dirichlet's approximation theorem**.
See also `AddCircle.exists_norm_nsmul_le`. -/
lemma _root_.NormedAddCommGroup.exists_norm_nsmul_le {A : Type*}
[NormedAddCommGroup A] [CompactSpace A] [PreconnectedSpace A]
[MeasurableSpace A] [BorelSpace A] {μ : Measure A} [μ.IsAddHaarMeasure]
(ξ : A) {n : ℕ} (hn : 0 < n) (δ : ℝ) (hδ : μ univ ≤ (n + 1) • μ (closedBall (0 : A) (δ / 2))) :
∃ j ∈ Icc 1 n, ‖j • ξ‖ ≤ δ := by
have : IsFiniteMeasure μ := CompactSpace.isFiniteMeasure
let B : Icc 0 n → Set A := fun j ↦ closedBall ((j : ℕ) • ξ) (δ / 2)
have hB : ∀ j, IsClosed (B j) := fun j ↦ isClosed_closedBall
suffices ¬ Pairwise (Disjoint on B) by
obtain ⟨i, j, hij, x, hx⟩ := exists_lt_mem_inter_of_not_pairwise_disjoint this
refine ⟨j - i, ⟨le_tsub_of_add_le_left hij, ?_⟩, ?_⟩
· simpa only [tsub_le_iff_right] using j.property.2.trans le_self_add
· rw [sub_nsmul _ (Subtype.coe_le_coe.mpr hij.le), ← sub_eq_add_neg, ← dist_eq_norm]
exact (dist_triangle ((j : ℕ) • ξ) x ((i : ℕ) • ξ)).trans (by
linarith [mem_closedBall.mp hx.1, mem_closedBall'.mp hx.2])
by_contra h
apply hn.ne'
have h' : ⋃ j, B j = univ := by
rw [← (isClosed_iUnion_of_finite hB).measure_eq_univ_iff_eq (μ := μ)]
refine le_antisymm (μ.mono (subset_univ _)) ?_
simp_rw [measure_iUnion h (fun _ ↦ measurableSet_closedBall), tsum_fintype,
B, μ.addHaar_closedBall_center, Finset.sum_const, Finset.card_univ, Fintype.card_Icc,
Nat.card_Icc, tsub_zero]
exact hδ
replace hδ : 0 ≤ δ/2 := by
by_contra contra
suffices μ (closedBall 0 (δ/2)) = 0 by
apply isOpen_univ.measure_ne_zero μ univ_nonempty <| le_zero_iff.mp <| le_trans hδ _
simp [this]
rw [not_le, ← closedBall_eq_empty (x := (0 : A))] at contra
simp [contra]
have h'' : ∀ j, (B j).Nonempty := by intro j; rwa [nonempty_closedBall]
simpa using subsingleton_of_disjoint_isClosed_iUnion_eq_univ h'' h hB h'
/-- **Dirichlet's approximation theorem**
See also `Real.exists_rat_abs_sub_le_and_den_le`. -/
lemma exists_norm_nsmul_le (ξ : 𝕊) {n : ℕ} (hn : 0 < n) :
∃ j ∈ Icc 1 n, ‖j • ξ‖ ≤ T / ↑(n + 1) := by
apply NormedAddCommGroup.exists_norm_nsmul_le (μ := volume) ξ hn
rw [AddCircle.measure_univ, volume_closedBall, ← ENNReal.ofReal_nsmul,
mul_div_cancel₀ _ two_ne_zero, min_eq_right (div_le_self hT.out.le <| by simp), nsmul_eq_mul,
mul_div_cancel₀ _ (Nat.cast_ne_zero.mpr n.succ_ne_zero)]
end AddCircle |
.lake/packages/mathlib/Mathlib/NumberTheory/SmoothNumbers.lean | import Mathlib.Data.Nat.Factorization.Defs
import Mathlib.Data.Nat.Squarefree
/-!
# Smooth numbers
For `s : Finset ℕ` we define the set `Nat.factoredNumbers s` of "`s`-factored numbers"
consisting of the positive natural numbers all of whose prime factors are in `s`, and
we provide some API for this.
We then define the set `Nat.smoothNumbers n` consisting of the positive natural numbers all of
whose prime factors are strictly less than `n`. This is the special case `s = Finset.range n`
of the set of `s`-factored numbers.
We also define the finite set `Nat.primesBelow n` to be the set of prime numbers less than `n`.
The main definition `Nat.equivProdNatSmoothNumbers` establishes the bijection between
`ℕ × (smoothNumbers p)` and `smoothNumbers (p+1)` given by sending `(e, n)` to `p^e * n`.
Here `p` is a prime number. It is obtained from the more general bijection between
`ℕ × (factoredNumbers s)` and `factoredNumbers (s ∪ {p})`; see `Nat.equivProdNatFactoredNumbers`.
Additionally, we define `Nat.smoothNumbersUpTo N n` as the `Finset` of `n`-smooth numbers
up to and including `N`, and similarly `Nat.roughNumbersUpTo` for its complement in `{1, ..., N}`,
and we provide some API, in particular bounds for their cardinalities; see
`Nat.smoothNumbersUpTo_card_le` and `Nat.roughNumbersUpTo_card_le`.
-/
open scoped Finset
namespace Nat
/-- `primesBelow n` is the set of primes less than `n` as a `Finset`. -/
def primesBelow (n : ℕ) : Finset ℕ := {p ∈ Finset.range n | p.Prime}
@[simp]
lemma primesBelow_zero : primesBelow 0 = ∅ := by
rw [primesBelow, Finset.range_zero, Finset.filter_empty]
lemma mem_primesBelow {k n : ℕ} :
n ∈ primesBelow k ↔ n < k ∧ n.Prime := by simp [primesBelow]
lemma prime_of_mem_primesBelow {p n : ℕ} (h : p ∈ n.primesBelow) : p.Prime :=
(Finset.mem_filter.mp h).2
lemma lt_of_mem_primesBelow {p n : ℕ} (h : p ∈ n.primesBelow) : p < n :=
Finset.mem_range.mp <| Finset.mem_of_mem_filter p h
lemma primesBelow_succ (n : ℕ) :
primesBelow (n + 1) = if n.Prime then insert n (primesBelow n) else primesBelow n := by
rw [primesBelow, primesBelow, Finset.range_add_one, Finset.filter_insert]
lemma notMem_primesBelow (n : ℕ) : n ∉ primesBelow n :=
fun hn ↦ (lt_of_mem_primesBelow hn).false
@[deprecated (since := "2025-05-23")] alias not_mem_primesBelow := notMem_primesBelow
/-!
### `s`-factored numbers
-/
/-- `factoredNumbers s`, for a finite set `s` of natural numbers, is the set of positive natural
numbers all of whose prime factors are in `s`. -/
def factoredNumbers (s : Finset ℕ) : Set ℕ := {m | m ≠ 0 ∧ ∀ p ∈ primeFactorsList m, p ∈ s}
lemma mem_factoredNumbers {s : Finset ℕ} {m : ℕ} :
m ∈ factoredNumbers s ↔ m ≠ 0 ∧ ∀ p ∈ primeFactorsList m, p ∈ s :=
Iff.rfl
/-- Membership in `Nat.factoredNumbers n` is decidable. -/
instance (s : Finset ℕ) : DecidablePred (· ∈ factoredNumbers s) :=
inferInstanceAs <| DecidablePred fun x ↦ x ∈ {m | m ≠ 0 ∧ ∀ p ∈ primeFactorsList m, p ∈ s}
/-- A number that divides an `s`-factored number is itself `s`-factored. -/
lemma mem_factoredNumbers_of_dvd {s : Finset ℕ} {m k : ℕ} (h : m ∈ factoredNumbers s)
(h' : k ∣ m) :
k ∈ factoredNumbers s := by
obtain ⟨h₁, h₂⟩ := h
have hk := ne_zero_of_dvd_ne_zero h₁ h'
refine ⟨hk, fun p hp ↦ h₂ p ?_⟩
rw [mem_primeFactorsList <| by assumption] at hp ⊢
exact ⟨hp.1, hp.2.trans h'⟩
/-- `m` is `s`-factored if and only if `m` is nonzero and all prime divisors `≤ m` of `m`
are in `s`. -/
lemma mem_factoredNumbers_iff_forall_le {s : Finset ℕ} {m : ℕ} :
m ∈ factoredNumbers s ↔ m ≠ 0 ∧ ∀ p ≤ m, p.Prime → p ∣ m → p ∈ s := by
simp_rw [mem_factoredNumbers, mem_primeFactorsList']
exact ⟨fun ⟨H₀, H₁⟩ ↦ ⟨H₀, fun p _ hp₂ hp₃ ↦ H₁ p ⟨hp₂, hp₃, H₀⟩⟩,
fun ⟨H₀, H₁⟩ ↦
⟨H₀, fun p ⟨hp₁, hp₂, hp₃⟩ ↦ H₁ p (le_of_dvd (Nat.pos_of_ne_zero hp₃) hp₂) hp₁ hp₂⟩⟩
/-- `m` is `s`-factored if and only if all prime divisors of `m` are in `s`. -/
lemma mem_factoredNumbers' {s : Finset ℕ} {m : ℕ} :
m ∈ factoredNumbers s ↔ ∀ p, p.Prime → p ∣ m → p ∈ s := by
obtain ⟨p, hp₁, hp₂⟩ := exists_infinite_primes (1 + Finset.sup s id)
rw [mem_factoredNumbers_iff_forall_le]
refine ⟨fun ⟨H₀, H₁⟩ ↦ fun p hp₁ hp₂ ↦ H₁ p (le_of_dvd (Nat.pos_of_ne_zero H₀) hp₂) hp₁ hp₂,
fun H ↦ ⟨fun h ↦ lt_irrefl p ?_, fun p _ ↦ H p⟩⟩
calc
p ≤ s.sup id := Finset.le_sup (f := @id ℕ) <| H p hp₂ <| h.symm ▸ dvd_zero p
_ < 1 + s.sup id := lt_one_add _
_ ≤ p := hp₁
lemma ne_zero_of_mem_factoredNumbers {s : Finset ℕ} {m : ℕ} (h : m ∈ factoredNumbers s) : m ≠ 0 :=
h.1
/-- The `Finset` of prime factors of an `s`-factored number is contained in `s`. -/
lemma primeFactors_subset_of_mem_factoredNumbers {s : Finset ℕ} {m : ℕ}
(hm : m ∈ factoredNumbers s) :
m.primeFactors ⊆ s := by
rw [mem_factoredNumbers] at hm
exact fun n hn ↦ hm.2 n (mem_primeFactors_iff_mem_primeFactorsList.mp hn)
/-- If `m ≠ 0` and the `Finset` of prime factors of `m` is contained in `s`, then `m`
is `s`-factored. -/
lemma mem_factoredNumbers_of_primeFactors_subset {s : Finset ℕ} {m : ℕ} (hm : m ≠ 0)
(hp : m.primeFactors ⊆ s) :
m ∈ factoredNumbers s := by
rw [mem_factoredNumbers]
exact ⟨hm, fun p hp' ↦ hp <| mem_primeFactors_iff_mem_primeFactorsList.mpr hp'⟩
/-- `m` is `s`-factored if and only if `m ≠ 0` and its `Finset` of prime factors
is contained in `s`. -/
lemma mem_factoredNumbers_iff_primeFactors_subset {s : Finset ℕ} {m : ℕ} :
m ∈ factoredNumbers s ↔ m ≠ 0 ∧ m.primeFactors ⊆ s :=
⟨fun h ↦ ⟨ne_zero_of_mem_factoredNumbers h, primeFactors_subset_of_mem_factoredNumbers h⟩,
fun ⟨h₁, h₂⟩ ↦ mem_factoredNumbers_of_primeFactors_subset h₁ h₂⟩
@[simp]
lemma factoredNumbers_empty : factoredNumbers ∅ = {1} := by
ext m
simp only [mem_factoredNumbers, Finset.notMem_empty, ← List.eq_nil_iff_forall_not_mem,
primeFactorsList_eq_nil, and_or_left, not_and_self_iff, ne_and_eq_iff_right zero_ne_one,
false_or, Set.mem_singleton_iff]
/-- The product of two `s`-factored numbers is again `s`-factored. -/
lemma mul_mem_factoredNumbers {s : Finset ℕ} {m n : ℕ} (hm : m ∈ factoredNumbers s)
(hn : n ∈ factoredNumbers s) :
m * n ∈ factoredNumbers s := by
have hm' := primeFactors_subset_of_mem_factoredNumbers hm
have hn' := primeFactors_subset_of_mem_factoredNumbers hn
exact mem_factoredNumbers_of_primeFactors_subset (mul_ne_zero hm.1 hn.1)
<| primeFactors_mul hm.1 hn.1 ▸ Finset.union_subset hm' hn'
/-- The product of the prime factors of `n` that are in `s` is an `s`-factored number. -/
lemma prod_mem_factoredNumbers (s : Finset ℕ) (n : ℕ) :
(n.primeFactorsList.filter (· ∈ s)).prod ∈ factoredNumbers s := by
have h₀ : (n.primeFactorsList.filter (· ∈ s)).prod ≠ 0 :=
List.prod_ne_zero fun h ↦ (pos_of_mem_primeFactorsList (List.mem_of_mem_filter h)).false
refine ⟨h₀, fun p hp ↦ ?_⟩
obtain ⟨H₁, H₂⟩ := (mem_primeFactorsList h₀).mp hp
simpa only [decide_eq_true_eq] using List.of_mem_filter <| mem_list_primes_of_dvd_prod H₁.prime
(fun _ hq ↦ (prime_of_mem_primeFactorsList (List.mem_of_mem_filter hq)).prime) H₂
/-- The sets of `s`-factored and of `s ∪ {N}`-factored numbers are the same when `N` is not prime.
See `Nat.equivProdNatFactoredNumbers` for when `N` is prime. -/
lemma factoredNumbers_insert (s : Finset ℕ) {N : ℕ} (hN : ¬ N.Prime) :
factoredNumbers (insert N s) = factoredNumbers s := by
ext m
refine ⟨fun hm ↦ ⟨hm.1, fun p hp ↦ ?_⟩,
fun hm ↦ ⟨hm.1, fun p hp ↦ Finset.mem_insert_of_mem <| hm.2 p hp⟩⟩
exact Finset.mem_of_mem_insert_of_ne (hm.2 p hp)
fun h ↦ hN <| h ▸ prime_of_mem_primeFactorsList hp
@[gcongr] lemma factoredNumbers_mono {s t : Finset ℕ} (hst : s ≤ t) :
factoredNumbers s ⊆ factoredNumbers t :=
fun _ hx ↦ ⟨hx.1, fun p hp ↦ hst <| hx.2 p hp⟩
/-- The non-zero non-`s`-factored numbers are `≥ N` when `s` contains all primes less than `N`. -/
lemma factoredNumbers_compl {N : ℕ} {s : Finset ℕ} (h : primesBelow N ≤ s) :
(factoredNumbers s)ᶜ \ {0} ⊆ {n | N ≤ n} := by
intro n hn
simp only [Set.mem_compl_iff, mem_factoredNumbers, Set.mem_diff, ne_eq, not_and, not_forall,
exists_prop, Set.mem_singleton_iff] at hn
simp only [Set.mem_setOf_eq]
obtain ⟨p, hp₁, hp₂⟩ := hn.1 hn.2
have : N ≤ p := by
contrapose! hp₂
exact h <| mem_primesBelow.mpr ⟨hp₂, prime_of_mem_primeFactorsList hp₁⟩
exact this.trans <| le_of_mem_primeFactorsList hp₁
/-- If `p` is a prime and `n` is `s`-factored, then every product `p^e * n`
is `s ∪ {p}`-factored. -/
lemma pow_mul_mem_factoredNumbers {s : Finset ℕ} {p n : ℕ} (hp : p.Prime) (e : ℕ)
(hn : n ∈ factoredNumbers s) :
p ^ e * n ∈ factoredNumbers (insert p s) := by
have hp' := pow_ne_zero e hp.ne_zero
refine ⟨mul_ne_zero hp' hn.1, fun q hq ↦ ?_⟩
rcases (mem_primeFactorsList_mul hp' hn.1).mp hq with H | H
· rw [mem_primeFactorsList hp'] at H
rw [(prime_dvd_prime_iff_eq H.1 hp).mp <| H.1.dvd_of_dvd_pow H.2]
exact Finset.mem_insert_self p s
· exact Finset.mem_insert_of_mem <| hn.2 _ H
/-- If `p ∉ s` is a prime and `n` is `s`-factored, then `p` and `n` are coprime. -/
lemma Prime.factoredNumbers_coprime {s : Finset ℕ} {p n : ℕ} (hp : p.Prime) (hs : p ∉ s)
(hn : n ∈ factoredNumbers s) :
Nat.Coprime p n := by
rw [hp.coprime_iff_not_dvd, ← mem_primeFactorsList_iff_dvd hn.1 hp]
exact fun H ↦ hs <| hn.2 p H
/-- If `f : ℕ → F` is multiplicative on coprime arguments, `p ∉ s` is a prime and `m`
is `s`-factored, then `f (p^e * m) = f (p^e) * f m`. -/
lemma factoredNumbers.map_prime_pow_mul {F : Type*} [Mul F] {f : ℕ → F}
(hmul : ∀ {m n}, Coprime m n → f (m * n) = f m * f n) {s : Finset ℕ} {p : ℕ}
(hp : p.Prime) (hs : p ∉ s) (e : ℕ) {m : factoredNumbers s} :
f (p ^ e * m) = f (p ^ e) * f m :=
hmul <| Coprime.pow_left _ <| hp.factoredNumbers_coprime hs <| Subtype.mem m
open List Perm in
/-- We establish the bijection from `ℕ × factoredNumbers s` to `factoredNumbers (s ∪ {p})`
given by `(e, n) ↦ p^e * n` when `p ∉ s` is a prime. See `Nat.factoredNumbers_insert` for
when `p` is not prime. -/
def equivProdNatFactoredNumbers {s : Finset ℕ} {p : ℕ} (hp : p.Prime) (hs : p ∉ s) :
ℕ × factoredNumbers s ≃ factoredNumbers (insert p s) where
toFun := fun ⟨e, n⟩ ↦ ⟨p ^ e * n, pow_mul_mem_factoredNumbers hp e n.2⟩
invFun := fun ⟨m, _⟩ ↦ (m.factorization p,
⟨(m.primeFactorsList.filter (· ∈ s)).prod, prod_mem_factoredNumbers ..⟩)
left_inv := by
rintro ⟨e, m, hm₀, hm⟩
simp (etaStruct := .all) only [Prod.mk.injEq, Subtype.mk.injEq]
constructor
· rw [factorization_mul (pos_iff_ne_zero.mp <| Nat.pow_pos hp.pos) hm₀]
simp only [factorization_pow, Finsupp.coe_add, Finsupp.coe_smul, nsmul_eq_mul,
Pi.natCast_def, cast_id, Pi.add_apply, Pi.mul_apply, hp.factorization_self,
mul_one, add_eq_left]
rw [← primeFactorsList_count_eq, count_eq_zero]
exact fun H ↦ hs (hm p H)
· nth_rewrite 2 [← prod_primeFactorsList hm₀]
refine prod_eq <|
(filter _ <| perm_primeFactorsList_mul (pow_ne_zero e hp.ne_zero) hm₀).trans ?_
rw [filter_append, hp.primeFactorsList_pow,
filter_eq_nil_iff.mpr fun q hq ↦ by rw [mem_replicate] at hq; simp [hq.2, hs],
nil_append, filter_eq_self.mpr fun q hq ↦ by simp only [hm q hq, decide_true]]
right_inv := by
rintro ⟨m, hm₀, hm⟩
simp only [Subtype.mk.injEq]
rw [← primeFactorsList_count_eq, ← prod_replicate, ← prod_append]
nth_rewrite 3 [← prod_primeFactorsList hm₀]
have : m.primeFactorsList.filter (· = p) = m.primeFactorsList.filter (· ∉ s) := by
refine (filter_congr fun q hq ↦ ?_).symm
simp only [decide_not]
rcases Finset.mem_insert.mp <| hm _ hq with h | h
· simp only [h, hs, decide_false, Bool.not_false, decide_true]
· simp only [h, decide_true, Bool.not_true, false_eq_decide_iff]
exact fun H ↦ hs <| H ▸ h
refine prod_eq <| (filter_eq p).symm ▸ this ▸ perm_append_comm.trans ?_
simp only [decide_not]
exact filter_append_perm (· ∈ s) (primeFactorsList m)
@[simp]
lemma equivProdNatFactoredNumbers_apply {s : Finset ℕ} {p e m : ℕ} (hp : p.Prime) (hs : p ∉ s)
(hm : m ∈ factoredNumbers s) :
equivProdNatFactoredNumbers hp hs (e, ⟨m, hm⟩) = p ^ e * m := rfl
@[simp]
lemma equivProdNatFactoredNumbers_apply' {s : Finset ℕ} {p : ℕ} (hp : p.Prime) (hs : p ∉ s)
(x : ℕ × factoredNumbers s) :
equivProdNatFactoredNumbers hp hs x = p ^ x.1 * x.2 := rfl
/-!
### `n`-smooth numbers
-/
/-- `smoothNumbers n` is the set of *`n`-smooth positive natural numbers*, i.e., the
positive natural numbers all of whose prime factors are less than `n`. -/
def smoothNumbers (n : ℕ) : Set ℕ := {m | m ≠ 0 ∧ ∀ p ∈ primeFactorsList m, p < n}
lemma mem_smoothNumbers {n m : ℕ} : m ∈ smoothNumbers n ↔ m ≠ 0 ∧ ∀ p ∈ primeFactorsList m, p < n :=
Iff.rfl
/-- The `n`-smooth numbers agree with the `Finset.range n`-factored numbers. -/
lemma smoothNumbers_eq_factoredNumbers (n : ℕ) :
smoothNumbers n = factoredNumbers (Finset.range n) := by
simp only [smoothNumbers, ne_eq, mem_primeFactorsList', and_imp, factoredNumbers,
Finset.mem_range]
/-- The `n`-smooth numbers agree with the `primesBelow n`-factored numbers. -/
lemma smoothNumbers_eq_factoredNumbers_primesBelow (n : ℕ) :
smoothNumbers n = factoredNumbers n.primesBelow := by
rw [smoothNumbers_eq_factoredNumbers]
refine Set.Subset.antisymm (fun m hm ↦ ?_) <| factoredNumbers_mono Finset.mem_of_mem_filter
simp_rw [mem_factoredNumbers'] at hm ⊢
exact fun p hp hp' ↦ mem_primesBelow.mpr ⟨Finset.mem_range.mp <| hm p hp hp', hp⟩
@[deprecated (since := "2025-07-08")]
alias smmoothNumbers_eq_factoredNumbers_primesBelow := smoothNumbers_eq_factoredNumbers_primesBelow
/-- Membership in `Nat.smoothNumbers n` is decidable. -/
instance (n : ℕ) : DecidablePred (· ∈ smoothNumbers n) :=
inferInstanceAs <| DecidablePred fun x ↦ x ∈ {m | m ≠ 0 ∧ ∀ p ∈ primeFactorsList m, p < n}
/-- A number that divides an `n`-smooth number is itself `n`-smooth. -/
lemma mem_smoothNumbers_of_dvd {n m k : ℕ} (h : m ∈ smoothNumbers n) (h' : k ∣ m) :
k ∈ smoothNumbers n := by
simp only [smoothNumbers_eq_factoredNumbers] at h ⊢
exact mem_factoredNumbers_of_dvd h h'
/-- `m` is `n`-smooth if and only if `m` is nonzero and all prime divisors `≤ m` of `m`
are less than `n`. -/
lemma mem_smoothNumbers_iff_forall_le {n m : ℕ} :
m ∈ smoothNumbers n ↔ m ≠ 0 ∧ ∀ p ≤ m, p.Prime → p ∣ m → p < n := by
simp only [smoothNumbers_eq_factoredNumbers, mem_factoredNumbers_iff_forall_le, Finset.mem_range]
/-- `m` is `n`-smooth if and only if all prime divisors of `m` are less than `n`. -/
lemma mem_smoothNumbers' {n m : ℕ} : m ∈ smoothNumbers n ↔ ∀ p, p.Prime → p ∣ m → p < n := by
simp only [smoothNumbers_eq_factoredNumbers, mem_factoredNumbers', Finset.mem_range]
/-- The `Finset` of prime factors of an `n`-smooth number is contained in the `Finset`
of primes below `n`. -/
lemma primeFactors_subset_of_mem_smoothNumbers {m n : ℕ} (hms : m ∈ n.smoothNumbers) :
m.primeFactors ⊆ n.primesBelow :=
primeFactors_subset_of_mem_factoredNumbers <|
smoothNumbers_eq_factoredNumbers_primesBelow n ▸ hms
/-- `m` is an `n`-smooth number if the `Finset` of its prime factors consists of numbers `< n`. -/
lemma mem_smoothNumbers_of_primeFactors_subset {m n : ℕ} (hm : m ≠ 0)
(hp : m.primeFactors ⊆ Finset.range n) : m ∈ n.smoothNumbers :=
smoothNumbers_eq_factoredNumbers n ▸ mem_factoredNumbers_of_primeFactors_subset hm hp
/-- `m` is an `n`-smooth number if and only if `m ≠ 0` and the `Finset` of its prime factors
is contained in the `Finset` of primes below `n` -/
lemma mem_smoothNumbers_iff_primeFactors_subset {m n : ℕ} :
m ∈ n.smoothNumbers ↔ m ≠ 0 ∧ m.primeFactors ⊆ n.primesBelow :=
⟨fun h ↦ ⟨h.1, primeFactors_subset_of_mem_smoothNumbers h⟩,
fun h ↦ mem_smoothNumbers_of_primeFactors_subset h.1 <| h.2.trans <| Finset.filter_subset ..⟩
/-- Zero is never a smooth number -/
lemma ne_zero_of_mem_smoothNumbers {n m : ℕ} (h : m ∈ smoothNumbers n) : m ≠ 0 := h.1
@[simp]
lemma smoothNumbers_zero : smoothNumbers 0 = {1} := by
simp only [smoothNumbers_eq_factoredNumbers, Finset.range_zero, factoredNumbers_empty]
/-- The product of two `n`-smooth numbers is an `n`-smooth number. -/
theorem mul_mem_smoothNumbers {m₁ m₂ n : ℕ}
(hm1 : m₁ ∈ n.smoothNumbers) (hm2 : m₂ ∈ n.smoothNumbers) : m₁ * m₂ ∈ n.smoothNumbers := by
rw [smoothNumbers_eq_factoredNumbers] at hm1 hm2 ⊢
exact mul_mem_factoredNumbers hm1 hm2
/-- The product of the prime factors of `n` that are less than `N` is an `N`-smooth number. -/
lemma prod_mem_smoothNumbers (n N : ℕ) :
(n.primeFactorsList.filter (· < N)).prod ∈ smoothNumbers N := by
simp only [smoothNumbers_eq_factoredNumbers, ← Finset.mem_range, prod_mem_factoredNumbers]
/-- The sets of `N`-smooth and of `(N+1)`-smooth numbers are the same when `N` is not prime.
See `Nat.equivProdNatSmoothNumbers` for when `N` is prime. -/
lemma smoothNumbers_succ {N : ℕ} (hN : ¬ N.Prime) : (N + 1).smoothNumbers = N.smoothNumbers := by
simp only [smoothNumbers_eq_factoredNumbers, Finset.range_add_one, factoredNumbers_insert _ hN]
@[simp] lemma smoothNumbers_one : smoothNumbers 1 = {1} := by
simp +decide only [not_false_eq_true, smoothNumbers_succ, smoothNumbers_zero]
@[gcongr] lemma smoothNumbers_mono {N M : ℕ} (hNM : N ≤ M) : N.smoothNumbers ⊆ M.smoothNumbers :=
fun _ hx ↦ ⟨hx.1, fun p hp => (hx.2 p hp).trans_le hNM⟩
/-- All `m`, `0 < m < n` are `n`-smooth numbers -/
lemma mem_smoothNumbers_of_lt {m n : ℕ} (hm : 0 < m) (hmn : m < n) : m ∈ n.smoothNumbers :=
smoothNumbers_eq_factoredNumbers _ ▸ ⟨ne_zero_of_lt hm,
fun _ h => Finset.mem_range.mpr <| lt_of_le_of_lt (le_of_mem_primeFactorsList h) hmn⟩
/-- The non-zero non-`N`-smooth numbers are `≥ N`. -/
lemma smoothNumbers_compl (N : ℕ) : (N.smoothNumbers)ᶜ \ {0} ⊆ {n | N ≤ n} := by
simpa only [smoothNumbers_eq_factoredNumbers]
using factoredNumbers_compl <| Finset.filter_subset _ (Finset.range N)
/-- If `p` is positive and `n` is `p`-smooth, then every product `p^e * n` is `(p+1)`-smooth. -/
lemma pow_mul_mem_smoothNumbers {p n : ℕ} (hp : p ≠ 0) (e : ℕ) (hn : n ∈ smoothNumbers p) :
p ^ e * n ∈ smoothNumbers (succ p) := by
-- This cannot be easily reduced to `pow_mul_mem_factoredNumbers`, as there `p.Prime` is needed.
have : NoZeroDivisors ℕ := inferInstance -- this is needed twice --> speed-up
have hp' := pow_ne_zero e hp
refine ⟨mul_ne_zero hp' hn.1, fun q hq ↦ ?_⟩
rcases (mem_primeFactorsList_mul hp' hn.1).mp hq with H | H
· rw [mem_primeFactorsList hp'] at H
exact lt_succ.mpr <| le_of_dvd hp.bot_lt <| H.1.dvd_of_dvd_pow H.2
· exact (hn.2 q H).trans <| lt_succ_self p
/-- If `p` is a prime and `n` is `p`-smooth, then `p` and `n` are coprime. -/
lemma Prime.smoothNumbers_coprime {p n : ℕ} (hp : p.Prime) (hn : n ∈ smoothNumbers p) :
Nat.Coprime p n := by
simp only [smoothNumbers_eq_factoredNumbers] at hn
exact hp.factoredNumbers_coprime Finset.notMem_range_self hn
/-- If `f : ℕ → F` is multiplicative on coprime arguments, `p` is a prime and `m` is `p`-smooth,
then `f (p^e * m) = f (p^e) * f m`. -/
lemma map_prime_pow_mul {F : Type*} [Mul F] {f : ℕ → F}
(hmul : ∀ {m n}, Nat.Coprime m n → f (m * n) = f m * f n) {p : ℕ} (hp : p.Prime) (e : ℕ)
{m : p.smoothNumbers} :
f (p ^ e * m) = f (p ^ e) * f m :=
hmul <| Coprime.pow_left _ <| hp.smoothNumbers_coprime <| Subtype.mem m
open List Perm Equiv in
/-- We establish the bijection from `ℕ × smoothNumbers p` to `smoothNumbers (p+1)`
given by `(e, n) ↦ p^e * n` when `p` is a prime. See `Nat.smoothNumbers_succ` for
when `p` is not prime. -/
def equivProdNatSmoothNumbers {p : ℕ} (hp : p.Prime) :
ℕ × smoothNumbers p ≃ smoothNumbers (p + 1) :=
((prodCongrRight fun _ ↦ setCongr <| smoothNumbers_eq_factoredNumbers p).trans <|
equivProdNatFactoredNumbers hp Finset.notMem_range_self).trans <|
setCongr <| (smoothNumbers_eq_factoredNumbers (p + 1)) ▸ Finset.range_add_one ▸ rfl
@[simp]
lemma equivProdNatSmoothNumbers_apply {p e m : ℕ} (hp : p.Prime) (hm : m ∈ p.smoothNumbers) :
equivProdNatSmoothNumbers hp (e, ⟨m, hm⟩) = p ^ e * m := rfl
@[simp]
lemma equivProdNatSmoothNumbers_apply' {p : ℕ} (hp : p.Prime) (x : ℕ × p.smoothNumbers) :
equivProdNatSmoothNumbers hp x = p ^ x.1 * x.2 := rfl
/-!
### Smooth and rough numbers up to a bound
We consider the sets of smooth and non-smooth ("rough") positive natural numbers `≤ N`
and prove bounds for their sizes.
-/
/-- The `k`-smooth numbers up to and including `N` as a `Finset` -/
def smoothNumbersUpTo (N k : ℕ) : Finset ℕ :=
{n ∈ Finset.range (N + 1) | n ∈ smoothNumbers k}
lemma mem_smoothNumbersUpTo {N k n : ℕ} :
n ∈ smoothNumbersUpTo N k ↔ n ≤ N ∧ n ∈ smoothNumbers k := by
simp [smoothNumbersUpTo, lt_succ]
/-- The positive non-`k`-smooth (so "`k`-rough") numbers up to and including `N` as a `Finset` -/
def roughNumbersUpTo (N k : ℕ) : Finset ℕ :=
{n ∈ Finset.range (N + 1) | n ≠ 0 ∧ n ∉ smoothNumbers k}
lemma smoothNumbersUpTo_card_add_roughNumbersUpTo_card (N k : ℕ) :
#(smoothNumbersUpTo N k) + #(roughNumbersUpTo N k) = N := by
rw [smoothNumbersUpTo, roughNumbersUpTo,
← Finset.card_union_of_disjoint <| Finset.disjoint_filter.mpr fun n _ hn₂ h ↦ h.2 hn₂,
Finset.filter_union_right]
suffices #{x ∈ Finset.range (N + 1) | x ≠ 0} = N by
have hn' (n) : n ∈ smoothNumbers k ∨ n ≠ 0 ∧ n ∉ smoothNumbers k ↔ n ≠ 0 := by
have : n ∈ smoothNumbers k → n ≠ 0 := ne_zero_of_mem_smoothNumbers
refine ⟨fun H ↦ Or.elim H this fun H ↦ H.1, fun H ↦ ?_⟩
simp only [ne_eq, H, not_false_eq_true, true_and, or_not]
rwa [Finset.filter_congr (s := Finset.range (succ N)) fun n _ ↦ hn' n]
rw [Finset.filter_ne', Finset.card_erase_of_mem <| Finset.mem_range_succ_iff.mpr <| zero_le N]
simp only [Finset.card_range, succ_sub_succ_eq_sub, tsub_zero]
/-- A `k`-smooth number can be written as a square times a product of distinct primes `< k`. -/
lemma eq_prod_primes_mul_sq_of_mem_smoothNumbers {n k : ℕ} (h : n ∈ smoothNumbers k) :
∃ s ∈ k.primesBelow.powerset, ∃ m, n = m ^ 2 * (s.prod id) := by
obtain ⟨l, m, H₁, H₂⟩ := sq_mul_squarefree n
have hl : l ∈ smoothNumbers k := mem_smoothNumbers_of_dvd h (Dvd.intro_left (m ^ 2) H₁)
refine ⟨l.primeFactorsList.toFinset, ?_, m, ?_⟩
· simp only [toFinset_factors, Finset.mem_powerset]
refine fun p hp ↦ mem_primesBelow.mpr ⟨?_, (mem_primeFactors.mp hp).1⟩
rw [mem_primeFactors] at hp
exact mem_smoothNumbers'.mp hl p hp.1 hp.2.1
rw [← H₁]
congr
simp only [toFinset_factors]
exact (prod_primeFactors_of_squarefree H₂).symm
/-- The set of `k`-smooth numbers `≤ N` is contained in the set of numbers of the form `m^2 * P`,
where `m ≤ √N` and `P` is a product of distinct primes `< k`. -/
lemma smoothNumbersUpTo_subset_image (N k : ℕ) :
smoothNumbersUpTo N k ⊆ Finset.image (fun (s, m) ↦ m ^ 2 * (s.prod id))
(k.primesBelow.powerset ×ˢ (Finset.range (N.sqrt + 1)).erase 0) := by
intro n hn
obtain ⟨hn₁, hn₂⟩ := mem_smoothNumbersUpTo.mp hn
obtain ⟨s, hs, m, hm⟩ := eq_prod_primes_mul_sq_of_mem_smoothNumbers hn₂
simp only [id_eq, Finset.mem_range, Finset.mem_image,
Finset.mem_product, Finset.mem_powerset, Finset.mem_erase, Prod.exists]
refine ⟨s, m, ⟨Finset.mem_powerset.mp hs, ?_, ?_⟩, hm.symm⟩
· have := hm ▸ ne_zero_of_mem_smoothNumbers hn₂
simp only [ne_eq, _root_.mul_eq_zero, sq_eq_zero_iff, not_or] at this
exact this.1
· rw [lt_succ, le_sqrt']
refine LE.le.trans ?_ (hm ▸ hn₁)
nth_rw 1 [← mul_one (m ^ 2)]
gcongr
exact Finset.one_le_prod' fun p hp ↦
(prime_of_mem_primesBelow <| Finset.mem_powerset.mp hs hp).one_le
/-- The cardinality of the set of `k`-smooth numbers `≤ N` is bounded by `2^π(k-1) * √N`. -/
lemma smoothNumbersUpTo_card_le (N k : ℕ) :
#(smoothNumbersUpTo N k) ≤ 2 ^ #k.primesBelow * N.sqrt := by
convert (Finset.card_le_card <| smoothNumbersUpTo_subset_image N k).trans <|
Finset.card_image_le
simp only [Finset.card_product, Finset.card_powerset, Finset.mem_range, zero_lt_succ,
Finset.card_erase_of_mem, Finset.card_range, succ_sub_succ_eq_sub, tsub_zero]
/-- The set of `k`-rough numbers `≤ N` can be written as the union of the sets of multiples `≤ N`
of primes `k ≤ p ≤ N`. -/
lemma roughNumbersUpTo_eq_biUnion (N k) :
roughNumbersUpTo N k =
((N + 1).primesBelow \ k.primesBelow).biUnion
fun p ↦ {m ∈ Finset.range (N + 1) | m ≠ 0 ∧ p ∣ m} := by
ext m
simp only [roughNumbersUpTo, mem_smoothNumbers_iff_forall_le, not_and, not_forall,
not_lt, exists_prop, Finset.mem_range, Finset.mem_filter,
Finset.mem_biUnion, Finset.mem_sdiff, mem_primesBelow,
show ∀ P Q : Prop, P ∧ (P → Q) ↔ P ∧ Q by tauto]
simp_rw [← exists_and_left, ← not_lt]
refine exists_congr fun p ↦ ?_
have H₁ : m ≠ 0 → p ∣ m → m < N + 1 → p < N + 1 :=
fun h₁ h₂ h₃ ↦ (le_of_dvd (Nat.pos_of_ne_zero h₁) h₂).trans_lt h₃
have H₂ : m ≠ 0 → p ∣ m → ¬ m < p :=
fun h₁ h₂ ↦ not_lt.mpr <| le_of_dvd (Nat.pos_of_ne_zero h₁) h₂
grind
/-- The cardinality of the set of `k`-rough numbers `≤ N` is bounded by the sum of `⌊N/p⌋`
over the primes `k ≤ p ≤ N`. -/
lemma roughNumbersUpTo_card_le (N k : ℕ) :
#(roughNumbersUpTo N k) ≤ ((N + 1).primesBelow \ k.primesBelow).sum (fun p ↦ N / p) := by
rw [roughNumbersUpTo_eq_biUnion]
exact Finset.card_biUnion_le.trans <| Finset.sum_le_sum fun p _ ↦ (card_multiples' N p).le
end Nat |
.lake/packages/mathlib/Mathlib/NumberTheory/FunctionField.lean | import Mathlib.FieldTheory.RatFunc.Degree
import Mathlib.RingTheory.DedekindDomain.IntegralClosure
import Mathlib.RingTheory.IntegralClosure.IntegrallyClosed
import Mathlib.Topology.Algebra.Valued.ValuedField
/-!
# Function fields
This file defines a function field and the ring of integers corresponding to it.
## Main definitions
- `FunctionField Fq F` states that `F` is a function field over the (finite) field `Fq`,
i.e. it is a finite extension of the field of rational functions in one variable over `Fq`.
- `FunctionField.ringOfIntegers` defines the ring of integers corresponding to a function field
as the integral closure of `Fq[X]` in the function field.
- `FunctionField.inftyValuation` : The place at infinity on `Fq(t)` is the nonarchimedean
valuation on `Fq(t)` with uniformizer `1/t`.
- `FunctionField.FqtInfty` : The completion `Fq((t⁻¹))` of `Fq(t)` with respect to the
valuation at infinity.
## Implementation notes
The definitions that involve a field of fractions choose a canonical field of fractions,
but are independent of that choice. We also omit assumptions like `Finite Fq` or
`IsScalarTower Fq[X] (FractionRing Fq[X]) F` in definitions,
adding them back in lemmas when they are needed.
## References
* [D. Marcus, *Number Fields*][marcus1977number]
* [J.W.S. Cassels, A. Fröhlich, *Algebraic Number Theory*][cassels1967algebraic]
* [P. Samuel, *Algebraic Theory of Numbers*][samuel1967]
## Tags
function field, ring of integers
-/
noncomputable section
open scoped nonZeroDivisors Polynomial WithZero
variable (Fq F : Type*) [Field Fq] [Field F]
/-- `F` is a function field over the finite field `Fq` if it is a finite
extension of the field of rational functions in one variable over `Fq`.
Note that `F` can be a function field over multiple, non-isomorphic, `Fq`.
-/
abbrev FunctionField [Algebra (RatFunc Fq) F] : Prop :=
FiniteDimensional (RatFunc Fq) F
/-- `F` is a function field over `Fq` iff it is a finite extension of `Fq(t)`. -/
theorem functionField_iff (Fqt : Type*) [Field Fqt] [Algebra Fq[X] Fqt]
[IsFractionRing Fq[X] Fqt] [Algebra (RatFunc Fq) F] [Algebra Fqt F] [Algebra Fq[X] F]
[IsScalarTower Fq[X] Fqt F] [IsScalarTower Fq[X] (RatFunc Fq) F] :
FunctionField Fq F ↔ FiniteDimensional Fqt F := by
let e := IsLocalization.algEquiv Fq[X]⁰ (RatFunc Fq) Fqt
have : ∀ (c) (x : F), e c • x = c • x := by
intro c x
rw [Algebra.smul_def, Algebra.smul_def]
congr
refine congr_fun (f := fun c => algebraMap Fqt F (e c)) ?_ c
refine IsLocalization.ext (nonZeroDivisors Fq[X]) _ _ ?_ ?_ ?_ ?_ ?_ <;> intros <;>
simp only [map_one, map_mul, AlgEquiv.commutes, ← IsScalarTower.algebraMap_apply]
constructor <;> intro h
· let b := Module.finBasis (RatFunc Fq) F
exact (b.mapCoeffs e this).finiteDimensional_of_finite
· let b := Module.finBasis Fqt F
refine (b.mapCoeffs e.symm ?_).finiteDimensional_of_finite
intro c x; convert (this (e.symm c) x).symm; simp only [e.apply_symm_apply]
namespace FunctionField
theorem algebraMap_injective [Algebra Fq[X] F] [Algebra (RatFunc Fq) F]
[IsScalarTower Fq[X] (RatFunc Fq) F] : Function.Injective (⇑(algebraMap Fq[X] F)) := by
rw [IsScalarTower.algebraMap_eq Fq[X] (RatFunc Fq) F]
exact (algebraMap (RatFunc Fq) F).injective.comp (IsFractionRing.injective Fq[X] (RatFunc Fq))
/-- The function field analogue of `NumberField.ringOfIntegers`:
`FunctionField.ringOfIntegers Fq Fqt F` is the integral closure of `Fq[t]` in `F`.
We don't actually assume `F` is a function field over `Fq` in the definition,
only when proving its properties.
-/
def ringOfIntegers [Algebra Fq[X] F] :=
integralClosure Fq[X] F
namespace ringOfIntegers
variable [Algebra Fq[X] F]
instance : IsDomain (ringOfIntegers Fq F) :=
(ringOfIntegers Fq F).isDomain
instance : IsIntegralClosure (ringOfIntegers Fq F) Fq[X] F :=
integralClosure.isIntegralClosure _ _
variable [Algebra (RatFunc Fq) F] [IsScalarTower Fq[X] (RatFunc Fq) F]
theorem algebraMap_injective : Function.Injective (⇑(algebraMap Fq[X] (ringOfIntegers Fq F))) := by
have hinj : Function.Injective (⇑(algebraMap Fq[X] F)) := by
rw [IsScalarTower.algebraMap_eq Fq[X] (RatFunc Fq) F]
exact (algebraMap (RatFunc Fq) F).injective.comp (IsFractionRing.injective Fq[X] (RatFunc Fq))
rw [injective_iff_map_eq_zero (algebraMap Fq[X] (↥(ringOfIntegers Fq F)))]
intro p hp
rw [← Subtype.coe_inj, Subalgebra.coe_zero] at hp
rw [injective_iff_map_eq_zero (algebraMap Fq[X] F)] at hinj
exact hinj p hp
theorem not_isField : ¬IsField (ringOfIntegers Fq F) := by
simpa [← (IsIntegralClosure.isIntegral_algebra Fq[X] F).isField_iff_isField
(algebraMap_injective Fq F)] using
Polynomial.not_isField Fq
variable [FunctionField Fq F]
instance : IsFractionRing (ringOfIntegers Fq F) F :=
integralClosure.isFractionRing_of_finite_extension (RatFunc Fq) F
instance : IsIntegrallyClosed (ringOfIntegers Fq F) :=
integralClosure.isIntegrallyClosedOfFiniteExtension (RatFunc Fq)
instance [Algebra.IsSeparable (RatFunc Fq) F] : IsNoetherian Fq[X] (ringOfIntegers Fq F) :=
IsIntegralClosure.isNoetherian _ (RatFunc Fq) F _
instance [Algebra.IsSeparable (RatFunc Fq) F] : IsDedekindDomain (ringOfIntegers Fq F) :=
IsIntegralClosure.isDedekindDomain Fq[X] (RatFunc Fq) F _
end ringOfIntegers
/-! ### The place at infinity on Fq(t) -/
section InftyValuation
open Multiplicative WithZero
variable [DecidableEq (RatFunc Fq)]
/-- The valuation at infinity is the nonarchimedean valuation on `Fq(t)` with uniformizer `1/t`.
Explicitly, if `f/g ∈ Fq(t)` is a nonzero quotient of polynomials, its valuation at infinity is
`exp (degree(f) - degree(g))`. -/
def inftyValuationDef (r : RatFunc Fq) : ℤᵐ⁰ :=
if r = 0 then 0 else exp r.intDegree
theorem InftyValuation.map_zero' : inftyValuationDef Fq 0 = 0 :=
if_pos rfl
theorem InftyValuation.map_one' : inftyValuationDef Fq 1 = 1 :=
(if_neg one_ne_zero).trans <| by simp
theorem InftyValuation.map_mul' (x y : RatFunc Fq) :
inftyValuationDef Fq (x * y) = inftyValuationDef Fq x * inftyValuationDef Fq y := by
rw [inftyValuationDef, inftyValuationDef, inftyValuationDef]
by_cases hx : x = 0
· rw [hx, zero_mul, if_pos (Eq.refl _), zero_mul]
· by_cases hy : y = 0
· rw [hy, mul_zero, if_pos (Eq.refl _), mul_zero]
· simp_all [RatFunc.intDegree_mul]
theorem InftyValuation.map_add_le_max' (x y : RatFunc Fq) :
inftyValuationDef Fq (x + y) ≤ max (inftyValuationDef Fq x) (inftyValuationDef Fq y) := by
by_cases hx : x = 0
· rw [hx, zero_add]
conv_rhs => rw [inftyValuationDef, if_pos (Eq.refl _)]
rw [max_eq_right (WithZero.zero_le (inftyValuationDef Fq y))]
· by_cases hy : y = 0
· rw [hy, add_zero]
conv_rhs => rw [max_comm, inftyValuationDef, if_pos (Eq.refl _)]
rw [max_eq_right (WithZero.zero_le (inftyValuationDef Fq x))]
· by_cases hxy : x + y = 0
· rw [inftyValuationDef, if_pos hxy]; exact zero_le'
· rw [inftyValuationDef, inftyValuationDef, inftyValuationDef, if_neg hx, if_neg hy,
if_neg hxy]
simpa using RatFunc.intDegree_add_le hy hxy
@[simp]
theorem inftyValuation_of_nonzero {x : RatFunc Fq} (hx : x ≠ 0) :
inftyValuationDef Fq x = exp x.intDegree := by
rw [inftyValuationDef, if_neg hx]
/-- The valuation at infinity on `Fq(t)`. -/
def inftyValuation : Valuation (RatFunc Fq) ℤᵐ⁰ where
toFun := inftyValuationDef Fq
map_zero' := InftyValuation.map_zero' Fq
map_one' := InftyValuation.map_one' Fq
map_mul' := InftyValuation.map_mul' Fq
map_add_le_max' := InftyValuation.map_add_le_max' Fq
theorem inftyValuation_apply {x : RatFunc Fq} : inftyValuation Fq x = inftyValuationDef Fq x :=
rfl
@[simp]
theorem inftyValuation.C {k : Fq} (hk : k ≠ 0) :
inftyValuation Fq (RatFunc.C k) = 1 := by
simp [inftyValuation_apply, hk]
@[simp]
theorem inftyValuation.X : inftyValuation Fq RatFunc.X = exp 1 := by
simp [inftyValuation_apply, inftyValuationDef, if_neg RatFunc.X_ne_zero, RatFunc.intDegree_X]
lemma inftyValuation.X_zpow (m : ℤ) : inftyValuation Fq (RatFunc.X ^ m) = exp m := by simp
theorem inftyValuation.X_inv : inftyValuation Fq (1 / RatFunc.X) = exp (-1) := by
rw [one_div, ← zpow_neg_one, inftyValuation.X_zpow]
-- Dropped attribute `@[simp]` due to issue described here:
-- https://leanprover.zulipchat.com/#narrow/channel/287929-mathlib4/topic/.60synthInstance.2EmaxHeartbeats.60.20error.20but.20only.20in.20.60simpNF.60
theorem inftyValuation.polynomial {p : Fq[X]} (hp : p ≠ 0) :
inftyValuationDef Fq (algebraMap Fq[X] (RatFunc Fq) p) = exp (p.natDegree : ℤ) := by
rw [inftyValuationDef, if_neg (by simpa), RatFunc.intDegree_polynomial]
/-- The valued field `Fq(t)` with the valuation at infinity. -/
def inftyValuedFqt : Valued (RatFunc Fq) ℤᵐ⁰ :=
Valued.mk' <| inftyValuation Fq
theorem inftyValuedFqt.def {x : RatFunc Fq} :
(inftyValuedFqt Fq).v x = inftyValuationDef Fq x :=
rfl
/-- The completion `Fq((t⁻¹))` of `Fq(t)` with respect to the valuation at infinity. -/
def FqtInfty :=
@UniformSpace.Completion (RatFunc Fq) <| (inftyValuedFqt Fq).toUniformSpace
instance : Field (FqtInfty Fq) :=
letI := inftyValuedFqt Fq
UniformSpace.Completion.instField
instance : Inhabited (FqtInfty Fq) :=
⟨(0 : FqtInfty Fq)⟩
/-- The valuation at infinity on `k(t)` extends to a valuation on `FqtInfty`. -/
instance valuedFqtInfty : Valued (FqtInfty Fq) ℤᵐ⁰ := (inftyValuedFqt Fq).valuedCompletion
theorem valuedFqtInfty.def {x : FqtInfty Fq} : Valued.v x = (inftyValuedFqt Fq).extension x := rfl
end InftyValuation
end FunctionField |
.lake/packages/mathlib/Mathlib/NumberTheory/PellMatiyasevic.lean | import Mathlib.Data.Nat.ModEq
import Mathlib.Data.Nat.Prime.Basic
import Mathlib.NumberTheory.Zsqrtd.Basic
/-!
# Pell's equation and Matiyasevic's theorem
This file solves Pell's equation, i.e. integer solutions to `x ^ 2 - d * y ^ 2 = 1`
*in the special case that `d = a ^ 2 - 1`*.
This is then applied to prove Matiyasevic's theorem that the power
function is Diophantine, which is the last key ingredient in the solution to Hilbert's tenth
problem. For the definition of Diophantine function, see `NumberTheory.Dioph`.
For results on Pell's equation for arbitrary (positive, non-square) `d`, see
`NumberTheory.Pell`.
## Main definition
* `pell` is a function assigning to a natural number `n` the `n`-th solution to Pell's equation
constructed recursively from the initial solution `(0, 1)`.
## Main statements
* `eq_pell` shows that every solution to Pell's equation is recursively obtained using `pell`
* `matiyasevic` shows that a certain system of Diophantine equations has a solution if and only if
the first variable is the `x`-component in a solution to Pell's equation - the key step towards
Hilbert's tenth problem in Davis' version of Matiyasevic's theorem.
* `eq_pow_of_pell` shows that the power function is Diophantine.
## Implementation notes
The proof of Matiyasevic's theorem doesn't follow Matiyasevic's original account of using Fibonacci
numbers but instead Davis' variant of using solutions to Pell's equation.
## References
* [M. Carneiro, _A Lean formalization of Matiyasevič's theorem_][carneiro2018matiyasevic]
* [M. Davis, _Hilbert's tenth problem is unsolvable_][MR317916]
## Tags
Pell's equation, Matiyasevic's theorem, Hilbert's tenth problem
-/
namespace Pell
open Nat
section
variable {d : ℤ}
/-- The property of being a solution to the Pell equation, expressed
as a property of elements of `ℤ√d`. -/
def IsPell : ℤ√d → Prop
| ⟨x, y⟩ => x * x - d * y * y = 1
theorem isPell_norm : ∀ {b : ℤ√d}, IsPell b ↔ b * star b = 1
| ⟨x, y⟩ => by simp [Zsqrtd.ext_iff, IsPell, mul_comm]; ring_nf
theorem isPell_iff_mem_unitary : ∀ {b : ℤ√d}, IsPell b ↔ b ∈ unitary (ℤ√d)
| ⟨x, y⟩ => by rw [Unitary.mem_iff, isPell_norm, mul_comm (star _), and_self_iff]
theorem isPell_mul {b c : ℤ√d} (hb : IsPell b) (hc : IsPell c) : IsPell (b * c) :=
isPell_norm.2 (by simp [mul_comm, mul_left_comm c, mul_assoc,
star_mul, isPell_norm.1 hb, isPell_norm.1 hc])
theorem isPell_star : ∀ {b : ℤ√d}, IsPell b ↔ IsPell (star b)
| ⟨x, y⟩ => by simp [IsPell]
end
section
variable {a : ℕ} (a1 : 1 < a)
private def d (_a1 : 1 < a) :=
a * a - 1
@[simp]
theorem d_pos : 0 < d a1 :=
tsub_pos_of_lt (mul_lt_mul a1 (le_of_lt a1) (by decide) (Nat.zero_le _) : 1 * 1 < a * a)
-- TODO(lint): Fix double namespace issue
/-- The Pell sequences, i.e. the sequence of integer solutions to `x ^ 2 - d * y ^ 2 = 1`, where
`d = a ^ 2 - 1`, defined together in mutual recursion. -/
--@[nolint dup_namespace]
def pell : ℕ → ℕ × ℕ
| 0 => (1, 0)
| n + 1 => ((pell n).1 * a + d a1 * (pell n).2, (pell n).1 + (pell n).2 * a)
/-- The Pell `x` sequence. -/
def xn (n : ℕ) : ℕ :=
(pell a1 n).1
/-- The Pell `y` sequence. -/
def yn (n : ℕ) : ℕ :=
(pell a1 n).2
@[simp]
theorem pell_val (n : ℕ) : pell a1 n = (xn a1 n, yn a1 n) :=
show pell a1 n = ((pell a1 n).1, (pell a1 n).2) from
match pell a1 n with
| (_, _) => rfl
@[simp]
theorem xn_zero : xn a1 0 = 1 :=
rfl
@[simp]
theorem yn_zero : yn a1 0 = 0 :=
rfl
@[simp]
theorem xn_succ (n : ℕ) : xn a1 (n + 1) = xn a1 n * a + d a1 * yn a1 n :=
rfl
@[simp]
theorem yn_succ (n : ℕ) : yn a1 (n + 1) = xn a1 n + yn a1 n * a :=
rfl
theorem xn_one : xn a1 1 = a := by simp
theorem yn_one : yn a1 1 = 1 := by simp
/-- The Pell `x` sequence, considered as an integer sequence. -/
def xz (n : ℕ) : ℤ :=
xn a1 n
/-- The Pell `y` sequence, considered as an integer sequence. -/
def yz (n : ℕ) : ℤ :=
yn a1 n
section
/-- The element `a` such that `d = a ^ 2 - 1`, considered as an integer. -/
def az (a : ℕ) : ℤ :=
a
end
include a1 in
theorem asq_pos : 0 < a * a :=
le_trans (le_of_lt a1)
(by have := @Nat.mul_le_mul_left 1 a a (le_of_lt a1); rwa [mul_one] at this)
theorem dz_val : ↑(d a1) = az a * az a - 1 :=
have : 1 ≤ a * a := asq_pos a1
by rw [Pell.d, Int.ofNat_sub this]; rfl
@[simp]
theorem xz_succ (n : ℕ) : (xz a1 (n + 1)) = xz a1 n * az a + d a1 * yz a1 n :=
rfl
@[simp]
theorem yz_succ (n : ℕ) : yz a1 (n + 1) = xz a1 n + yz a1 n * az a :=
rfl
/-- The Pell sequence can also be viewed as an element of `ℤ√d` -/
def pellZd (n : ℕ) : ℤ√(d a1) :=
⟨xn a1 n, yn a1 n⟩
@[simp]
theorem re_pellZd (n : ℕ) : (pellZd a1 n).re = xn a1 n :=
rfl
@[deprecated (since := "2025-08-31")] alias pellZd_re := re_pellZd
@[simp]
theorem im_pellZd (n : ℕ) : (pellZd a1 n).im = yn a1 n :=
rfl
@[deprecated (since := "2025-08-31")] alias pellZd_im := im_pellZd
theorem isPell_nat {x y : ℕ} : IsPell (⟨x, y⟩ : ℤ√(d a1)) ↔ x * x - d a1 * y * y = 1 :=
⟨fun h =>
(Nat.cast_inj (R := ℤ)).1
(by rw [Int.ofNat_sub (Int.le_of_ofNat_le_ofNat <| Int.le.intro_sub _ h)]; exact h),
fun h =>
show ((x * x : ℕ) - (d a1 * y * y : ℕ) : ℤ) = 1 by
rw [← Int.ofNat_sub <| le_of_lt <| Nat.lt_of_sub_eq_succ h, h]; rfl⟩
@[simp]
theorem pellZd_succ (n : ℕ) : pellZd a1 (n + 1) = pellZd a1 n * ⟨a, 1⟩ := by ext <;> simp
theorem isPell_one : IsPell (⟨a, 1⟩ : ℤ√(d a1)) :=
show az a * az a - d a1 * 1 * 1 = 1 by simp [dz_val]
theorem isPell_pellZd : ∀ n : ℕ, IsPell (pellZd a1 n)
| 0 => rfl
| n + 1 => by
let o := isPell_one a1
simpa using Pell.isPell_mul (isPell_pellZd n) o
@[simp]
theorem pell_eqz (n : ℕ) : xz a1 n * xz a1 n - d a1 * yz a1 n * yz a1 n = 1 :=
isPell_pellZd a1 n
@[simp]
theorem pell_eq (n : ℕ) : xn a1 n * xn a1 n - d a1 * yn a1 n * yn a1 n = 1 :=
let pn := pell_eqz a1 n
have h : (↑(xn a1 n * xn a1 n) : ℤ) - ↑(d a1 * yn a1 n * yn a1 n) = 1 := by
repeat' rw [Int.natCast_mul]; exact pn
have hl : d a1 * yn a1 n * yn a1 n ≤ xn a1 n * xn a1 n :=
Nat.cast_le.1 <| Int.le.intro _ <| add_eq_of_eq_sub' <| Eq.symm h
(Nat.cast_inj (R := ℤ)).1 (by rw [Int.ofNat_sub hl]; exact h)
instance dnsq : Zsqrtd.Nonsquare (d a1) :=
⟨fun n h =>
have : n * n + 1 = a * a := by rw [← h]; exact Nat.succ_pred_eq_of_pos (asq_pos a1)
have na : n < a := Nat.mul_self_lt_mul_self_iff.1 (by rw [← this]; exact Nat.lt_succ_self _)
have : (n + 1) * (n + 1) ≤ n * n + 1 := by rw [this]; exact Nat.mul_self_le_mul_self na
have : n + n ≤ 0 :=
@Nat.le_of_add_le_add_right _ (n * n + 1) _ (by ring_nf at this ⊢; assumption)
Nat.ne_of_gt (d_pos a1) <| by
rwa [Nat.eq_zero_of_le_zero ((Nat.le_add_left _ _).trans this)] at h⟩
theorem xn_ge_a_pow : ∀ n : ℕ, a ^ n ≤ xn a1 n
| 0 => le_refl 1
| n + 1 => by
simp only [_root_.pow_succ, xn_succ]
exact le_trans (Nat.mul_le_mul_right _ (xn_ge_a_pow n)) (Nat.le_add_right _ _)
theorem n_lt_xn (n) : n < xn a1 n :=
lt_of_lt_of_le (Nat.lt_pow_self a1) (xn_ge_a_pow a1 n)
theorem x_pos (n) : 0 < xn a1 n :=
lt_of_le_of_lt (Nat.zero_le n) (n_lt_xn a1 n)
theorem eq_pell_lem : ∀ (n) (b : ℤ√(d a1)), 1 ≤ b → IsPell b →
b ≤ pellZd a1 n → ∃ n, b = pellZd a1 n
| 0, _ => fun h1 _ hl => ⟨0, @Zsqrtd.le_antisymm _ (dnsq a1) _ _ hl h1⟩
| n + 1, b => fun h1 hp h =>
have a1p : (0 : ℤ√(d a1)) ≤ ⟨a, 1⟩ := trivial
have am1p : (0 : ℤ√(d a1)) ≤ ⟨a, -1⟩ := show (_ : Nat) ≤ _ by simp; exact Nat.pred_le _
have a1m : (⟨a, 1⟩ * ⟨a, -1⟩ : ℤ√(d a1)) = 1 := isPell_norm.1 (isPell_one a1)
if ha : (⟨↑a, 1⟩ : ℤ√(d a1)) ≤ b then
let ⟨m, e⟩ :=
eq_pell_lem n (b * ⟨a, -1⟩) (by rw [← a1m]; exact mul_le_mul_of_nonneg_right ha am1p)
(isPell_mul hp (isPell_star.1 (isPell_one a1)))
(by
have t := mul_le_mul_of_nonneg_right h am1p
rwa [pellZd_succ, mul_assoc, a1m, mul_one] at t)
⟨m + 1, by
rw [show b = b * ⟨a, -1⟩ * ⟨a, 1⟩ by rw [mul_assoc, Eq.trans (mul_comm _ _) a1m]; simp,
pellZd_succ, e]⟩
else
suffices ¬1 < b from ⟨0, show b = 1 from (Or.resolve_left (lt_or_eq_of_le h1) this).symm⟩
fun h1l => by
obtain ⟨x, y⟩ := b
exact by
have bm : (_ * ⟨_, _⟩ : ℤ√d a1) = 1 := Pell.isPell_norm.1 hp
have y0l : (0 : ℤ√d a1) < ⟨x - x, y - -y⟩ :=
sub_lt_sub h1l fun hn : (1 : ℤ√d a1) ≤ ⟨x, -y⟩ => by
have t := mul_le_mul_of_nonneg_left hn (le_trans zero_le_one h1)
rw [bm, mul_one] at t
exact h1l t
have yl2 : (⟨_, _⟩ : ℤ√_) < ⟨_, _⟩ :=
show (⟨x, y⟩ - ⟨x, -y⟩ : ℤ√d a1) < ⟨a, 1⟩ - ⟨a, -1⟩ from
sub_lt_sub ha fun hn : (⟨x, -y⟩ : ℤ√d a1) ≤ ⟨a, -1⟩ => by
have t := mul_le_mul_of_nonneg_right
(mul_le_mul_of_nonneg_left hn (le_trans zero_le_one h1)) a1p
rw [bm, one_mul, mul_assoc, Eq.trans (mul_comm _ _) a1m, mul_one] at t
exact ha t
simp only [sub_self, sub_neg_eq_add] at y0l; simp only [Zsqrtd.re_neg, add_neg_cancel,
Zsqrtd.im_neg, neg_neg] at yl2
exact
match y, y0l, (yl2 : (⟨_, _⟩ : ℤ√_) < ⟨_, _⟩) with
| 0, y0l, _ => y0l (le_refl 0)
| (y + 1 : ℕ), _, yl2 =>
yl2
(Zsqrtd.le_of_le_le (by simp)
(let t := Int.ofNat_le_ofNat_of_le (Nat.succ_pos y)
add_le_add t t))
| Int.negSucc _, y0l, _ => y0l trivial
theorem eq_pellZd (b : ℤ√(d a1)) (b1 : 1 ≤ b) (hp : IsPell b) : ∃ n, b = pellZd a1 n :=
let ⟨n, h⟩ := @Zsqrtd.le_arch (d a1) b
eq_pell_lem a1 n b b1 hp <|
h.trans <| by
rw [Zsqrtd.natCast_val]
exact
Zsqrtd.le_of_le_le (Int.ofNat_le_ofNat_of_le <| le_of_lt <| n_lt_xn _ _)
(Int.ofNat_zero_le _)
/-- Every solution to **Pell's equation** is recursively obtained from the initial solution
`(1,0)` using the recursion `pell`. -/
theorem eq_pell {x y : ℕ} (hp : x * x - d a1 * y * y = 1) : ∃ n, x = xn a1 n ∧ y = yn a1 n :=
have : (1 : ℤ√(d a1)) ≤ ⟨x, y⟩ :=
match x, hp with
| 0, (hp : 0 - _ = 1) => by rw [zero_tsub] at hp; contradiction
| x + 1, _hp =>
Zsqrtd.le_of_le_le (Int.ofNat_le_ofNat_of_le <| Nat.succ_pos x) (Int.ofNat_zero_le _)
let ⟨m, e⟩ := eq_pellZd a1 ⟨x, y⟩ this ((isPell_nat a1).2 hp)
⟨m,
match x, y, e with
| _, _, rfl => ⟨rfl, rfl⟩⟩
theorem pellZd_add (m) : ∀ n, pellZd a1 (m + n) = pellZd a1 m * pellZd a1 n
| 0 => (mul_one _).symm
| n + 1 => by rw [← add_assoc, pellZd_succ, pellZd_succ, pellZd_add _ n, ← mul_assoc]
theorem xn_add (m n) : xn a1 (m + n) = xn a1 m * xn a1 n + d a1 * yn a1 m * yn a1 n := by
injection pellZd_add a1 m n with h _
zify
rw [h]
simp [pellZd]
theorem yn_add (m n) : yn a1 (m + n) = xn a1 m * yn a1 n + yn a1 m * xn a1 n := by
injection pellZd_add a1 m n with _ h
zify
rw [h]
simp [pellZd]
theorem pellZd_sub {m n} (h : n ≤ m) : pellZd a1 (m - n) = pellZd a1 m * star (pellZd a1 n) := by
let t := pellZd_add a1 n (m - n)
rw [add_tsub_cancel_of_le h] at t
rw [t, mul_comm (pellZd _ n) _, mul_assoc, isPell_norm.1 (isPell_pellZd _ _), mul_one]
theorem xz_sub {m n} (h : n ≤ m) :
xz a1 (m - n) = xz a1 m * xz a1 n - d a1 * yz a1 m * yz a1 n := by
rw [sub_eq_add_neg, ← mul_neg]
exact congr_arg Zsqrtd.re (pellZd_sub a1 h)
theorem yz_sub {m n} (h : n ≤ m) : yz a1 (m - n) = xz a1 n * yz a1 m - xz a1 m * yz a1 n := by
rw [sub_eq_add_neg, ← mul_neg, mul_comm, add_comm]
exact congr_arg Zsqrtd.im (pellZd_sub a1 h)
theorem xy_coprime (n) : (xn a1 n).Coprime (yn a1 n) :=
Nat.coprime_of_dvd' fun k _ kx ky => by
let p := pell_eq a1 n
rw [← p]
exact Nat.dvd_sub (kx.mul_left _) (ky.mul_left _)
theorem strictMono_y : StrictMono (yn a1)
| _, 0, h => absurd h <| Nat.not_lt_zero _
| m, n + 1, h => by
have : yn a1 m ≤ yn a1 n :=
Or.elim (lt_or_eq_of_le <| Nat.le_of_succ_le_succ h) (fun hl => le_of_lt <| strictMono_y hl)
fun e => by rw [e]
simp only [yn_succ, gt_iff_lt]; refine lt_of_le_of_lt ?_ (Nat.lt_add_of_pos_left <| x_pos a1 n)
rw [← mul_one (yn a1 m)]
exact mul_le_mul this (le_of_lt a1) (Nat.zero_le _) (Nat.zero_le _)
theorem strictMono_x : StrictMono (xn a1)
| _, 0, h => absurd h <| Nat.not_lt_zero _
| m, n + 1, h => by
have : xn a1 m ≤ xn a1 n :=
Or.elim (lt_or_eq_of_le <| Nat.le_of_succ_le_succ h) (fun hl => le_of_lt <| strictMono_x hl)
fun e => by rw [e]
simp only [xn_succ, gt_iff_lt]
refine lt_of_lt_of_le (lt_of_le_of_lt this ?_) (Nat.le_add_right _ _)
have t := Nat.mul_lt_mul_of_pos_left a1 (x_pos a1 n)
rwa [mul_one] at t
theorem yn_ge_n : ∀ n, n ≤ yn a1 n
| 0 => Nat.zero_le _
| n + 1 =>
show n < yn a1 (n + 1) from lt_of_le_of_lt (yn_ge_n n) (strictMono_y a1 <| Nat.lt_succ_self n)
theorem y_mul_dvd (n) : ∀ k, yn a1 n ∣ yn a1 (n * k)
| 0 => dvd_zero _
| k + 1 => by
rw [Nat.mul_succ, yn_add]; exact dvd_add (dvd_mul_left _ _) ((y_mul_dvd _ k).mul_right _)
theorem y_dvd_iff (m n) : yn a1 m ∣ yn a1 n ↔ m ∣ n :=
⟨fun h =>
Nat.dvd_of_mod_eq_zero <|
(Nat.eq_zero_or_pos _).resolve_right fun hp => by
have co : Nat.Coprime (yn a1 m) (xn a1 (m * (n / m))) :=
Nat.Coprime.symm <| (xy_coprime a1 _).coprime_dvd_right (y_mul_dvd a1 m (n / m))
have m0 : 0 < m :=
m.eq_zero_or_pos.resolve_left fun e => by
rw [e, Nat.mod_zero] at hp;rw [e] at h
exact _root_.ne_of_lt (strictMono_y a1 hp) (eq_zero_of_zero_dvd h).symm
rw [← Nat.mod_add_div n m, yn_add] at h
exact
not_le_of_gt (strictMono_y _ <| Nat.mod_lt n m0)
(Nat.le_of_dvd (strictMono_y _ hp) <|
co.dvd_of_dvd_mul_right <|
(Nat.dvd_add_iff_right <| (y_mul_dvd _ _ _).mul_left _).2 h),
fun ⟨k, e⟩ => by rw [e]; apply y_mul_dvd⟩
theorem xy_modEq_yn (n) :
∀ k, xn a1 (n * k) ≡ xn a1 n ^ k [MOD yn a1 n ^ 2] ∧ yn a1 (n * k) ≡
k * xn a1 n ^ (k - 1) * yn a1 n [MOD yn a1 n ^ 3]
| 0 => by simp [Nat.ModEq.refl]
| k + 1 => by
let ⟨hx, hy⟩ := xy_modEq_yn n k
have L : xn a1 (n * k) * xn a1 n + d a1 * yn a1 (n * k) * yn a1 n ≡
xn a1 n ^ k * xn a1 n + 0 [MOD yn a1 n ^ 2] := by
gcongr
rw [modEq_zero_iff_dvd, sq]
gcongr
apply dvd_mul_of_dvd_right
rw [← modEq_zero_iff_dvd]
refine (hy.of_dvd <| dvd_pow_self _ <| by decide).trans ?_
simp [modEq_zero_iff_dvd]
have R : xn a1 (n * k) * yn a1 n + yn a1 (n * k) * xn a1 n ≡
xn a1 n ^ k * yn a1 n + k * xn a1 n ^ k * yn a1 n [MOD yn a1 n ^ 3] := by
gcongr ?_ + ?_
· rw [_root_.pow_succ]
exact hx.mul_right' _
· have : k * xn a1 n ^ (k - 1) * yn a1 n * xn a1 n = k * xn a1 n ^ k * yn a1 n := by
rcases k with - | k <;> simp [_root_.pow_succ]; ring_nf
rw [← this]
gcongr
rw [add_tsub_cancel_right, Nat.mul_succ, xn_add, yn_add, pow_succ (xn _ n), Nat.succ_mul,
add_comm (k * xn _ n ^ k) (xn _ n ^ k), right_distrib]
exact ⟨L, R⟩
theorem ysq_dvd_yy (n) : yn a1 n * yn a1 n ∣ yn a1 (n * yn a1 n) :=
modEq_zero_iff_dvd.1 <|
((xy_modEq_yn a1 n (yn a1 n)).right.of_dvd <| by simp [_root_.pow_succ]).trans
(modEq_zero_iff_dvd.2 <| by simp [mul_dvd_mul_left, mul_assoc])
theorem dvd_of_ysq_dvd {n t} (h : yn a1 n * yn a1 n ∣ yn a1 t) : yn a1 n ∣ t :=
have nt : n ∣ t := (y_dvd_iff a1 n t).1 <| dvd_of_mul_left_dvd h
n.eq_zero_or_pos.elim (fun n0 => by rwa [n0] at nt ⊢) fun n0l : 0 < n => by
let ⟨k, ke⟩ := nt
have : yn a1 n ∣ k * xn a1 n ^ (k - 1) :=
Nat.dvd_of_mul_dvd_mul_right (strictMono_y a1 n0l) <|
modEq_zero_iff_dvd.1 <| by
have xm := (xy_modEq_yn a1 n k).right; rw [← ke] at xm
exact (xm.of_dvd <| by simp [_root_.pow_succ]).symm.trans h.modEq_zero_nat
rw [ke]
exact dvd_mul_of_dvd_right (((xy_coprime _ _).pow_left _).symm.dvd_of_dvd_mul_right this) _
theorem pellZd_succ_succ (n) :
pellZd a1 (n + 2) + pellZd a1 n = (2 * a : ℕ) * pellZd a1 (n + 1) := by
have : (1 : ℤ√(d a1)) + ⟨a, 1⟩ * ⟨a, 1⟩ = ⟨a, 1⟩ * (2 * a) := by
rw [Zsqrtd.natCast_val]
change (⟨_, _⟩ : ℤ√(d a1)) = ⟨_, _⟩
rw [dz_val]
dsimp [az]
ext <;> dsimp <;> ring_nf
simpa [mul_add, mul_comm, mul_left_comm, add_comm] using congr_arg (· * pellZd a1 n) this
theorem xy_succ_succ (n) :
xn a1 (n + 2) + xn a1 n =
2 * a * xn a1 (n + 1) ∧ yn a1 (n + 2) + yn a1 n = 2 * a * yn a1 (n + 1) := by
have := pellZd_succ_succ a1 n; unfold pellZd at this
rw [Zsqrtd.nsmul_val (2 * a : ℕ)] at this
injection this with h₁ h₂
grind
theorem xn_succ_succ (n) : xn a1 (n + 2) + xn a1 n = 2 * a * xn a1 (n + 1) :=
(xy_succ_succ a1 n).1
theorem yn_succ_succ (n) : yn a1 (n + 2) + yn a1 n = 2 * a * yn a1 (n + 1) :=
(xy_succ_succ a1 n).2
theorem xz_succ_succ (n) : xz a1 (n + 2) = (2 * a : ℕ) * xz a1 (n + 1) - xz a1 n :=
eq_sub_of_add_eq <| by delta xz; rw [← Int.natCast_add, ← Int.natCast_mul, xn_succ_succ]
theorem yz_succ_succ (n) : yz a1 (n + 2) = (2 * a : ℕ) * yz a1 (n + 1) - yz a1 n :=
eq_sub_of_add_eq <| by delta yz; rw [← Int.natCast_add, ← Int.natCast_mul, yn_succ_succ]
theorem yn_modEq_a_sub_one : ∀ n, yn a1 n ≡ n [MOD a - 1]
| 0 => by simp [Nat.ModEq.refl]
| 1 => by simp [Nat.ModEq.refl]
| n + 2 =>
(yn_modEq_a_sub_one n).add_right_cancel <| by
rw [yn_succ_succ, (by ring : n + 2 + n = 2 * (n + 1))]
exact ((modEq_sub a1.le).mul_left 2).mul (yn_modEq_a_sub_one (n + 1))
theorem yn_modEq_two : ∀ n, yn a1 n ≡ n [MOD 2]
| 0 => by rfl
| 1 => by simp [Nat.ModEq.refl]
| n + 2 =>
(yn_modEq_two n).add_right_cancel <| by
rw [yn_succ_succ, mul_assoc, (by ring : n + 2 + n = 2 * (n + 1))]
exact (dvd_mul_right 2 _).modEq_zero_nat.trans (dvd_mul_right 2 _).zero_modEq_nat
section
theorem x_sub_y_dvd_pow_lem (y2 y1 y0 yn1 yn0 xn1 xn0 ay a2 : ℤ) :
(a2 * yn1 - yn0) * ay + y2 - (a2 * xn1 - xn0) =
y2 - a2 * y1 + y0 + a2 * (yn1 * ay + y1 - xn1) - (yn0 * ay + y0 - xn0) := by
ring
end
theorem x_sub_y_dvd_pow (y : ℕ) :
∀ n, (2 * a * y - y * y - 1 : ℤ) ∣ yz a1 n * (a - y) + ↑(y ^ n) - xz a1 n
| 0 => by simp [xz, yz]
| 1 => by simp [xz, yz]
| n + 2 => by
have : (2 * a * y - y * y - 1 : ℤ) ∣ ↑(y ^ (n + 2)) - ↑(2 * a) * ↑(y ^ (n + 1)) + ↑(y ^ n) :=
⟨-↑(y ^ n), by
simp [_root_.pow_succ, mul_comm,
mul_left_comm]
ring⟩
rw [xz_succ_succ, yz_succ_succ, x_sub_y_dvd_pow_lem ↑(y ^ (n + 2)) ↑(y ^ (n + 1)) ↑(y ^ n)]
exact _root_.dvd_sub (dvd_add this <| (x_sub_y_dvd_pow _ (n + 1)).mul_left _)
(x_sub_y_dvd_pow _ n)
theorem xn_modEq_x2n_add_lem (n j) : xn a1 n ∣ d a1 * yn a1 n * (yn a1 n * xn a1 j) + xn a1 j := by
have h1 : d a1 * yn a1 n * (yn a1 n * xn a1 j) + xn a1 j =
(d a1 * yn a1 n * yn a1 n + 1) * xn a1 j := by
simp [add_mul, mul_assoc]
have h2 : d a1 * yn a1 n * yn a1 n + 1 = xn a1 n * xn a1 n := by
zify at *
apply add_eq_of_eq_sub' (Eq.symm (pell_eqz a1 n))
rw [h2] at h1; rw [h1, mul_assoc]; exact dvd_mul_right _ _
theorem xn_modEq_x2n_add (n j) : xn a1 (2 * n + j) + xn a1 j ≡ 0 [MOD xn a1 n] := by
rw [two_mul, add_assoc, xn_add, add_assoc, ← zero_add 0]
refine (dvd_mul_right (xn a1 n) (xn a1 (n + j))).modEq_zero_nat.add ?_
rw [yn_add, left_distrib, add_assoc, ← zero_add 0]
exact
((dvd_mul_right _ _).mul_left _).modEq_zero_nat.add (xn_modEq_x2n_add_lem _ _ _).modEq_zero_nat
theorem xn_modEq_x2n_sub_lem {n j} (h : j ≤ n) : xn a1 (2 * n - j) + xn a1 j ≡ 0 [MOD xn a1 n] := by
have h1 : xz a1 n ∣ d a1 * yz a1 n * yz a1 (n - j) + xz a1 j := by
rw [yz_sub _ h, mul_sub_left_distrib, sub_add_eq_add_sub]
exact
dvd_sub
(by
delta xz; delta yz
rw [mul_comm (xn _ _ : ℤ)]
exact mod_cast (xn_modEq_x2n_add_lem _ n j))
((dvd_mul_right _ _).mul_left _)
rw [two_mul, add_tsub_assoc_of_le h, xn_add, add_assoc, ← zero_add 0]
exact
(dvd_mul_right _ _).modEq_zero_nat.add
(Int.natCast_dvd_natCast.1 <| by simpa [xz, yz] using h1).modEq_zero_nat
theorem xn_modEq_x2n_sub {n j} (h : j ≤ 2 * n) : xn a1 (2 * n - j) + xn a1 j ≡ 0 [MOD xn a1 n] :=
(le_total j n).elim (xn_modEq_x2n_sub_lem a1) fun jn => by
have : 2 * n - j + j ≤ n + j := by
rw [tsub_add_cancel_of_le h, two_mul]; exact Nat.add_le_add_left jn _
let t := xn_modEq_x2n_sub_lem a1 (Nat.le_of_add_le_add_right this)
rwa [tsub_tsub_cancel_of_le h, add_comm] at t
theorem xn_modEq_x4n_add (n j) : xn a1 (4 * n + j) ≡ xn a1 j [MOD xn a1 n] :=
ModEq.add_right_cancel' (xn a1 (2 * n + j)) <| by
refine @ModEq.trans _ _ 0 _ ?_ (by rw [add_comm]; exact (xn_modEq_x2n_add _ _ _).symm)
rw [show 4 * n = 2 * n + 2 * n from right_distrib 2 2 n, add_assoc]
apply xn_modEq_x2n_add
theorem xn_modEq_x4n_sub {n j} (h : j ≤ 2 * n) : xn a1 (4 * n - j) ≡ xn a1 j [MOD xn a1 n] :=
have h' : j ≤ 2 * n := le_trans h (by rw [Nat.succ_mul])
ModEq.add_right_cancel' (xn a1 (2 * n - j)) <| by
refine @ModEq.trans _ _ 0 _ ?_ (by rw [add_comm]; exact (xn_modEq_x2n_sub _ h).symm)
rw [show 4 * n = 2 * n + 2 * n from right_distrib 2 2 n, add_tsub_assoc_of_le h']
apply xn_modEq_x2n_add
theorem eq_of_xn_modEq_lem1 {i n} : ∀ {j}, i < j → j < n → xn a1 i % xn a1 n < xn a1 j % xn a1 n
| 0, ij, _ => absurd ij (Nat.not_lt_zero _)
| j + 1, ij, jn => by
suffices xn a1 j % xn a1 n < xn a1 (j + 1) % xn a1 n from
(lt_or_eq_of_le (Nat.le_of_succ_le_succ ij)).elim
(fun h => lt_trans (eq_of_xn_modEq_lem1 h (le_of_lt jn)) this) fun h => by
rw [h]; exact this
rw [Nat.mod_eq_of_lt (strictMono_x _ (Nat.lt_of_succ_lt jn)),
Nat.mod_eq_of_lt (strictMono_x _ jn)]
exact strictMono_x _ (Nat.lt_succ_self _)
theorem eq_of_xn_modEq_lem2 {n} (h : 2 * xn a1 n = xn a1 (n + 1)) : a = 2 ∧ n = 0 := by
rw [xn_succ, mul_comm] at h
have : n = 0 :=
n.eq_zero_or_pos.resolve_right fun np =>
_root_.ne_of_lt
(lt_of_le_of_lt (Nat.mul_le_mul_left _ a1)
(Nat.lt_add_of_pos_right <| mul_pos (d_pos a1) (strictMono_y a1 np)))
h
cases this; simp at h; exact ⟨h.symm, rfl⟩
theorem eq_of_xn_modEq_lem3 {i n} (npos : 0 < n) :
∀ {j}, i < j → j ≤ 2 * n → j ≠ n → ¬(a = 2 ∧ n = 1 ∧ i = 0 ∧ j = 2) →
xn a1 i % xn a1 n < xn a1 j % xn a1 n
| 0, ij, _, _, _ => absurd ij (Nat.not_lt_zero _)
| j + 1, ij, j2n, jnn, ntriv =>
have lem2 : ∀ k > n, k ≤ 2 * n → (↑(xn a1 k % xn a1 n) : ℤ) =
xn a1 n - xn a1 (2 * n - k) := fun k kn k2n => by
let k2nl : 2 * n - k < n := by cutsat
have xle : xn a1 (2 * n - k) ≤ xn a1 n := le_of_lt <| strictMono_x a1 k2nl
suffices xn a1 k % xn a1 n = xn a1 n - xn a1 (2 * n - k) by rw [this, Int.ofNat_sub xle]
rw [← Nat.mod_eq_of_lt (Nat.sub_lt (x_pos a1 n) (x_pos a1 (2 * n - k)))]
apply ModEq.add_right_cancel' (xn a1 (2 * n - k))
rw [tsub_add_cancel_of_le xle]
have t := xn_modEq_x2n_sub_lem a1 k2nl.le
rw [tsub_tsub_cancel_of_le k2n] at t
exact t.trans dvd_rfl.zero_modEq_nat
(lt_trichotomy j n).elim (fun jn : j < n => eq_of_xn_modEq_lem1 _ ij (lt_of_le_of_ne jn jnn))
fun o =>
o.elim
(fun jn : j = n => by
cases jn
apply Int.lt_of_ofNat_lt_ofNat
rw [lem2 (n + 1) (Nat.lt_succ_self _) j2n,
show 2 * n - (n + 1) = n - 1 by
rw [two_mul, tsub_add_eq_tsub_tsub, add_tsub_cancel_right]]
refine lt_sub_left_of_add_lt (Int.ofNat_lt_ofNat_of_lt ?_)
rcases lt_or_eq_of_le <| Nat.le_of_succ_le_succ ij with lin | ein
· rw [Nat.mod_eq_of_lt (strictMono_x _ lin)]
have ll : xn a1 (n - 1) + xn a1 (n - 1) ≤ xn a1 n := by
rw [← two_mul, mul_comm,
show xn a1 n = xn a1 (n - 1 + 1) by rw [tsub_add_cancel_of_le (succ_le_of_lt npos)],
xn_succ]
exact le_trans (Nat.mul_le_mul_left _ a1) (Nat.le_add_right _ _)
have npm : (n - 1).succ = n := Nat.succ_pred_eq_of_pos npos
have il : i ≤ n - 1 := by
apply Nat.le_of_succ_le_succ
rw [npm]
exact lin
rcases lt_or_eq_of_le il with ill | ile
· exact lt_of_lt_of_le (Nat.add_lt_add_left (strictMono_x a1 ill) _) ll
· rw [ile]
apply lt_of_le_of_ne ll
rw [← two_mul]
exact fun e =>
ntriv <| by
let ⟨a2, s1⟩ :=
@eq_of_xn_modEq_lem2 _ a1 (n - 1)
(by rwa [tsub_add_cancel_of_le (succ_le_of_lt npos)])
have n1 : n = 1 := le_antisymm (tsub_eq_zero_iff_le.mp s1) npos
rw [ile, a2, n1]; exact ⟨rfl, rfl, rfl, rfl⟩
· rw [ein, Nat.mod_self, add_zero]
exact strictMono_x _ (Nat.pred_lt npos.ne'))
fun jn : j > n =>
have lem1 : j ≠ n → xn a1 j % xn a1 n < xn a1 (j + 1) % xn a1 n →
xn a1 i % xn a1 n < xn a1 (j + 1) % xn a1 n :=
fun jn s =>
(lt_or_eq_of_le (Nat.le_of_succ_le_succ ij)).elim
(fun h =>
lt_trans
(eq_of_xn_modEq_lem3 npos h (le_of_lt (Nat.lt_of_succ_le j2n)) jn
fun ⟨_, n1, _, j2⟩ => by
rw [n1, j2] at j2n; exact absurd j2n (by decide))
s)
fun h => by rw [h]; exact s
lem1 (_root_.ne_of_gt jn) <|
Int.lt_of_ofNat_lt_ofNat <| by
rw [lem2 j jn (le_of_lt j2n), lem2 (j + 1) (Nat.le_succ_of_le jn) j2n]
refine sub_lt_sub_left (Int.ofNat_lt_ofNat_of_lt <| strictMono_x _ ?_) _
rw [Nat.sub_succ]
exact Nat.pred_lt (_root_.ne_of_gt <| tsub_pos_of_lt j2n)
theorem eq_of_xn_modEq_le {i j n} (ij : i ≤ j) (j2n : j ≤ 2 * n)
(h : xn a1 i ≡ xn a1 j [MOD xn a1 n])
(ntriv : ¬(a = 2 ∧ n = 1 ∧ i = 0 ∧ j = 2)) : i = j :=
if npos : n = 0 then by simp_all
else
(lt_or_eq_of_le ij).resolve_left fun ij' =>
if jn : j = n then by
refine _root_.ne_of_gt ?_ h
rw [jn, Nat.mod_self]
have x0 : 0 < xn a1 0 % xn a1 n := by
rw [Nat.mod_eq_of_lt (strictMono_x a1 (Nat.pos_of_ne_zero npos))]
exact Nat.succ_pos _
rcases i with - | i
· exact x0
rw [jn] at ij'
exact
x0.trans
(eq_of_xn_modEq_lem3 _ (Nat.pos_of_ne_zero npos) (Nat.succ_pos _) (le_trans ij j2n)
(_root_.ne_of_lt ij') fun ⟨_, n1, _, i2⟩ => by
rw [n1, i2] at ij'; exact absurd ij' (by decide))
else _root_.ne_of_lt (eq_of_xn_modEq_lem3 a1 (Nat.pos_of_ne_zero npos) ij' j2n jn ntriv) h
theorem eq_of_xn_modEq {i j n} (i2n : i ≤ 2 * n) (j2n : j ≤ 2 * n)
(h : xn a1 i ≡ xn a1 j [MOD xn a1 n])
(ntriv : a = 2 → n = 1 → (i = 0 → j ≠ 2) ∧ (i = 2 → j ≠ 0)) : i = j :=
(le_total i j).elim
(fun ij => eq_of_xn_modEq_le a1 ij j2n h fun ⟨a2, n1, i0, j2⟩ => (ntriv a2 n1).left i0 j2)
fun ij =>
(eq_of_xn_modEq_le a1 ij i2n h.symm fun ⟨a2, n1, j0, i2⟩ => (ntriv a2 n1).right i2 j0).symm
theorem eq_of_xn_modEq' {i j n} (ipos : 0 < i) (hin : i ≤ n) (j4n : j ≤ 4 * n)
(h : xn a1 j ≡ xn a1 i [MOD xn a1 n]) : j = i ∨ j + i = 4 * n :=
have i2n : i ≤ 2 * n := by apply le_trans hin; rw [two_mul]; apply Nat.le_add_left
(le_or_gt j (2 * n)).imp
(fun j2n : j ≤ 2 * n =>
eq_of_xn_modEq a1 j2n i2n h fun _ n1 =>
⟨fun _ i2 => by rw [n1, i2] at hin; exact absurd hin (by decide), fun _ i0 =>
_root_.ne_of_gt ipos i0⟩)
fun j2n : 2 * n < j =>
suffices i = 4 * n - j by rw [this, add_tsub_cancel_of_le j4n]
have j42n : 4 * n - j ≤ 2 * n := by cutsat
eq_of_xn_modEq a1 i2n j42n
(h.symm.trans <| by
let t := xn_modEq_x4n_sub a1 j42n
rwa [tsub_tsub_cancel_of_le j4n] at t)
(by cutsat)
theorem modEq_of_xn_modEq {i j n} (ipos : 0 < i) (hin : i ≤ n)
(h : xn a1 j ≡ xn a1 i [MOD xn a1 n]) :
j ≡ i [MOD 4 * n] ∨ j + i ≡ 0 [MOD 4 * n] :=
let j' := j % (4 * n)
have n4 : 0 < 4 * n := mul_pos (by decide) (ipos.trans_le hin)
have jl : j' < 4 * n := Nat.mod_lt _ n4
have jj : j ≡ j' [MOD 4 * n] := by delta ModEq; rw [Nat.mod_eq_of_lt jl]
have : ∀ j q, xn a1 (j + 4 * n * q) ≡ xn a1 j [MOD xn a1 n] := by
intro j q; induction q with
| zero => simp [ModEq.refl]
| succ q IH =>
rw [Nat.mul_succ, ← add_assoc, add_comm]
exact (xn_modEq_x4n_add _ _ _).trans IH
Or.imp (fun ji : j' = i => by rwa [← ji])
(fun ji : j' + i = 4 * n =>
(jj.add_right _).trans <| by
rw [ji]
exact dvd_rfl.modEq_zero_nat)
(eq_of_xn_modEq' a1 ipos hin jl.le <|
(h.symm.trans <| by
rw [← Nat.mod_add_div j (4 * n)]
exact this j' _).symm)
end
theorem xy_modEq_of_modEq {a b c} (a1 : 1 < a) (b1 : 1 < b) (h : a ≡ b [MOD c]) :
∀ n, xn a1 n ≡ xn b1 n [MOD c] ∧ yn a1 n ≡ yn b1 n [MOD c]
| 0 => by simp [Nat.ModEq.refl]
| 1 => by simpa [Nat.ModEq.refl]
| n + 2 =>
⟨(xy_modEq_of_modEq a1 b1 h n).left.add_right_cancel <| by
rw [xn_succ_succ a1, xn_succ_succ b1]
exact (h.mul_left _).mul (xy_modEq_of_modEq _ _ h (n + 1)).left,
(xy_modEq_of_modEq a1 b1 h n).right.add_right_cancel <| by
rw [yn_succ_succ a1, yn_succ_succ b1]
exact (h.mul_left _).mul (xy_modEq_of_modEq _ _ h (n + 1)).right⟩
theorem matiyasevic {a k x y} :
(∃ a1 : 1 < a, xn a1 k = x ∧ yn a1 k = y) ↔
1 < a ∧ k ≤ y ∧ (x = 1 ∧ y = 0 ∨
∃ u v s t b : ℕ,
x * x - (a * a - 1) * y * y = 1 ∧ u * u - (a * a - 1) * v * v = 1 ∧
s * s - (b * b - 1) * t * t = 1 ∧ 1 < b ∧ b ≡ 1 [MOD 4 * y] ∧
b ≡ a [MOD u] ∧ 0 < v ∧ y * y ∣ v ∧ s ≡ x [MOD u] ∧ t ≡ k [MOD 4 * y]) :=
⟨fun ⟨a1, hx, hy⟩ => by
rw [← hx, ← hy]
refine ⟨a1,
(Nat.eq_zero_or_pos k).elim (fun k0 => by rw [k0]; exact ⟨le_rfl, Or.inl ⟨rfl, rfl⟩⟩)
fun kpos => ?_⟩
exact
let x := xn a1 k
let y := yn a1 k
let m := 2 * (k * y)
let u := xn a1 m
let v := yn a1 m
have ky : k ≤ y := yn_ge_n a1 k
have yv : y * y ∣ v := (ysq_dvd_yy a1 k).trans <| (y_dvd_iff _ _ _).2 <| dvd_mul_left _ _
have uco : Nat.Coprime u (4 * y) :=
have : 2 ∣ v :=
modEq_zero_iff_dvd.1 <| (yn_modEq_two _ _).trans (dvd_mul_right _ _).modEq_zero_nat
have : Nat.Coprime u 2 := (xy_coprime a1 m).coprime_dvd_right this
(this.mul_right this).mul_right <|
(xy_coprime _ _).coprime_dvd_right (dvd_of_mul_left_dvd yv)
let ⟨b, ba, bm1⟩ := chineseRemainder uco a 1
have m1 : 1 < m :=
have : 0 < k * y := mul_pos kpos (strictMono_y a1 kpos)
Nat.mul_le_mul_left 2 this
have vp : 0 < v := strictMono_y a1 (lt_trans zero_lt_one m1)
have b1 : 1 < b :=
have : xn a1 1 < u := strictMono_x a1 m1
have : a < u := by simpa using this
lt_of_lt_of_le a1 <| by
delta ModEq at ba; rw [Nat.mod_eq_of_lt this] at ba; rw [← ba]
apply Nat.mod_le
let s := xn b1 k
let t := yn b1 k
have sx : s ≡ x [MOD u] := (xy_modEq_of_modEq b1 a1 ba k).left
have tk : t ≡ k [MOD 4 * y] :=
have : 4 * y ∣ b - 1 :=
Int.natCast_dvd_natCast.1 <| by rw [Int.ofNat_sub (le_of_lt b1)]; exact bm1.symm.dvd
(yn_modEq_a_sub_one _ _).of_dvd this
⟨ky,
Or.inr
⟨u, v, s, t, b, pell_eq _ _, pell_eq _ _, pell_eq _ _, b1, bm1, ba, vp, yv, sx, tk⟩⟩,
fun ⟨a1, ky, o⟩ =>
⟨a1,
match o with
| Or.inl ⟨x1, y0⟩ => by
rw [y0] at ky; rw [Nat.eq_zero_of_le_zero ky, x1, y0]; exact ⟨rfl, rfl⟩
| Or.inr ⟨u, v, s, t, b, xy, uv, st, b1, rem⟩ =>
match x, y, eq_pell a1 xy, u, v, eq_pell a1 uv, s, t, eq_pell b1 st, rem, ky with
| _, _, ⟨i, rfl, rfl⟩, _, _, ⟨n, rfl, rfl⟩, _, _, ⟨j, rfl, rfl⟩,
⟨(bm1 : b ≡ 1 [MOD 4 * yn a1 i]), (ba : b ≡ a [MOD xn a1 n]), (vp : 0 < yn a1 n),
(yv : yn a1 i * yn a1 i ∣ yn a1 n), (sx : xn b1 j ≡ xn a1 i [MOD xn a1 n]),
(tk : yn b1 j ≡ k [MOD 4 * yn a1 i])⟩,
(ky : k ≤ yn a1 i) =>
(Nat.eq_zero_or_pos i).elim
(fun i0 => by
simp only [i0, yn_zero, nonpos_iff_eq_zero] at ky; rw [i0, ky]; exact ⟨rfl, rfl⟩)
fun ipos => by
suffices i = k by rw [this]; exact ⟨rfl, rfl⟩
clear o rem xy uv st
have iln : i ≤ n :=
le_of_not_gt fun hin =>
not_lt_of_ge (Nat.le_of_dvd vp (dvd_of_mul_left_dvd yv)) (strictMono_y a1 hin)
have yd : 4 * yn a1 i ∣ 4 * n := by gcongr; exact dvd_of_ysq_dvd a1 yv
have jk : j ≡ k [MOD 4 * yn a1 i] :=
have : 4 * yn a1 i ∣ b - 1 :=
Int.natCast_dvd_natCast.1 <| by rw [Int.ofNat_sub (le_of_lt b1)]; exact bm1.symm.dvd
((yn_modEq_a_sub_one b1 _).of_dvd this).symm.trans tk
have ki : k + i < 4 * yn a1 i :=
lt_of_le_of_lt (_root_.add_le_add ky (yn_ge_n a1 i)) <| by
rw [← two_mul]
exact Nat.mul_lt_mul_of_pos_right (by decide) (strictMono_y a1 ipos)
have ji : j ≡ i [MOD 4 * n] :=
have : xn a1 j ≡ xn a1 i [MOD xn a1 n] :=
(xy_modEq_of_modEq b1 a1 ba j).left.symm.trans sx
(modEq_of_xn_modEq a1 ipos iln this).resolve_right
fun ji : j + i ≡ 0 [MOD 4 * n] =>
not_le_of_gt ki <|
Nat.le_of_dvd (lt_of_lt_of_le ipos <| Nat.le_add_left _ _) <|
modEq_zero_iff_dvd.1 <| (jk.symm.add_right i).trans <| ji.of_dvd yd
have : i % (4 * yn a1 i) = k % (4 * yn a1 i) := (ji.of_dvd yd).symm.trans jk
rwa [Nat.mod_eq_of_lt (lt_of_le_of_lt (Nat.le_add_left _ _) ki),
Nat.mod_eq_of_lt (lt_of_le_of_lt (Nat.le_add_right _ _) ki)] at this⟩⟩
theorem eq_pow_of_pell_lem {a y k : ℕ} (hy0 : y ≠ 0) (hk0 : k ≠ 0) (hyk : y ^ k < a) :
(↑(y ^ k) : ℤ) < 2 * a * y - y * y - 1 :=
have hya : y < a := (Nat.le_self_pow hk0 _).trans_lt hyk
calc
(↑(y ^ k) : ℤ) < a := Nat.cast_lt.2 hyk
_ ≤ (a : ℤ) ^ 2 - (a - 1 : ℤ) ^ 2 - 1 := by
rw [sub_sq, mul_one, one_pow, sub_add, sub_sub_cancel, two_mul, sub_sub, ← add_sub,
le_add_iff_nonneg_right, sub_nonneg, Int.add_one_le_iff]
norm_cast
exact lt_of_le_of_lt (Nat.succ_le_of_lt (Nat.pos_of_ne_zero hy0)) hya
_ ≤ (a : ℤ) ^ 2 - (a - y : ℤ) ^ 2 - 1 := by
have := hya.le
gcongr <;> norm_cast <;> omega
_ = 2 * a * y - y * y - 1 := by ring
theorem eq_pow_of_pell {m n k} :
n ^ k = m ↔ k = 0 ∧ m = 1 ∨ 0 < k ∧ (n = 0 ∧ m = 0 ∨
0 < n ∧ ∃ (w a t z : ℕ) (a1 : 1 < a), xn a1 k ≡ yn a1 k * (a - n) + m [MOD t] ∧
2 * a * n = t + (n * n + 1) ∧ m < t ∧
n ≤ w ∧ k ≤ w ∧ a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1) := by
constructor
· rintro rfl
refine k.eq_zero_or_pos.imp (fun k0 : k = 0 => k0.symm ▸ ⟨rfl, rfl⟩) fun hk => ⟨hk, ?_⟩
refine n.eq_zero_or_pos.imp (fun n0 : n = 0 ↦ n0.symm ▸ ⟨rfl, zero_pow hk.ne'⟩)
fun hn ↦ ⟨hn, ?_⟩
set w := max n k
have nw : n ≤ w := le_max_left _ _
have kw : k ≤ w := le_max_right _ _
have wpos : 0 < w := hn.trans_le nw
have w1 : 1 < w + 1 := Nat.succ_lt_succ wpos
set a := xn w1 w
have a1 : 1 < a := strictMono_x w1 wpos
have na : n ≤ a := nw.trans (n_lt_xn w1 w).le
set x := xn a1 k
set y := yn a1 k
obtain ⟨z, ze⟩ : w ∣ yn w1 w :=
modEq_zero_iff_dvd.1 ((yn_modEq_a_sub_one w1 w).trans dvd_rfl.modEq_zero_nat)
have nt : (↑(n ^ k) : ℤ) < 2 * a * n - n * n - 1 := by
refine eq_pow_of_pell_lem hn.ne' hk.ne' ?_
calc
n ^ k ≤ n ^ w := Nat.pow_le_pow_right hn kw
_ < (w + 1) ^ w := Nat.pow_lt_pow_left (Nat.lt_succ_of_le nw) wpos.ne'
_ ≤ a := xn_ge_a_pow w1 w
lift (2 * a * n - n * n - 1 : ℤ) to ℕ using (Nat.cast_nonneg _).trans nt.le with t te
have tm : x ≡ y * (a - n) + n ^ k [MOD t] := by
apply modEq_of_dvd
rw [Int.natCast_add, Int.natCast_mul, Int.ofNat_sub na, te]
exact x_sub_y_dvd_pow a1 n k
have ta : 2 * a * n = t + (n * n + 1) := by
zify
omega
have zp : a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1 := ze ▸ pell_eq w1 w
exact ⟨w, a, t, z, a1, tm, ta, Nat.cast_lt.1 nt, nw, kw, zp⟩
· rintro (⟨rfl, rfl⟩ | ⟨hk0, ⟨rfl, rfl⟩ | ⟨hn0, w, a, t, z, a1, tm, ta, mt, nw, kw, zp⟩⟩)
· exact _root_.pow_zero n
· exact zero_pow hk0.ne'
have hw0 : 0 < w := hn0.trans_le nw
have hw1 : 1 < w + 1 := Nat.succ_lt_succ hw0
rcases eq_pell hw1 zp with ⟨j, rfl, yj⟩
have hj0 : 0 < j := by
apply Nat.pos_of_ne_zero
rintro rfl
exact lt_irrefl 1 a1
have wj : w ≤ j :=
Nat.le_of_dvd hj0
(modEq_zero_iff_dvd.1 <|
(yn_modEq_a_sub_one hw1 j).symm.trans <| modEq_zero_iff_dvd.2 ⟨z, yj.symm⟩)
have hnka : n ^ k < xn hw1 j := calc
n ^ k ≤ n ^ j := Nat.pow_le_pow_right hn0 (le_trans kw wj)
_ < (w + 1) ^ j := Nat.pow_lt_pow_left (Nat.lt_succ_of_le nw) hj0.ne'
_ ≤ xn hw1 j := xn_ge_a_pow hw1 j
have nt : (↑(n ^ k) : ℤ) < 2 * xn hw1 j * n - n * n - 1 :=
eq_pow_of_pell_lem hn0.ne' hk0.ne' hnka
have na : n ≤ xn hw1 j := (Nat.le_self_pow hk0.ne' _).trans hnka.le
have te : (t : ℤ) = 2 * xn hw1 j * n - n * n - 1 := by
rw [sub_sub, eq_sub_iff_add_eq]
exact mod_cast ta.symm
have : xn a1 k ≡ yn a1 k * (xn hw1 j - n) + n ^ k [MOD t] := by
apply modEq_of_dvd
rw [te, Nat.cast_add, Nat.cast_mul, Int.ofNat_sub na]
exact x_sub_y_dvd_pow a1 n k
have : n ^ k % t = m % t := (this.symm.trans tm).add_left_cancel' _
rw [← te] at nt
rwa [Nat.mod_eq_of_lt (Nat.cast_lt.1 nt), Nat.mod_eq_of_lt mt] at this
end Pell |
.lake/packages/mathlib/Mathlib/NumberTheory/Ostrowski.lean | import Mathlib.Analysis.AbsoluteValue.Equivalence
import Mathlib.Analysis.SpecialFunctions.Log.Base
import Mathlib.Analysis.SpecialFunctions.Pow.Continuity
import Mathlib.NumberTheory.Padics.PadicNorm
/-!
# Ostrowski’s Theorem
Ostrowski's Theorem for the field `ℚ`: every absolute value on `ℚ` is equivalent to either a
`p`-adic absolute value or to the standard Archimedean (Euclidean) absolute value.
## Main results
- `Rat.AbsoluteValue.equiv_real_or_padic`: given an absolute value on `ℚ`, it is equivalent
to the standard Archimedean (Euclidean) absolute value `Rat.AbsoluteValue.real` or to a `p`-adic
absolute value `Rat.AbsoluteValue.padic p` for a unique prime number `p`.
## TODO
Extend to arbitrary number fields.
## References
* [K. Conrad, *Ostrowski's Theorem for Q*][conradQ]
* [K. Conrad, *Ostrowski for number fields*][conradnumbfield]
* [J. W. S. Cassels, *Local fields*][cassels1986local]
## Tags
absolute value, Ostrowski's theorem
-/
open Filter Nat Real Topology
-- For any `C > 0`, the limit of `C ^ (1/k)` is 1 as `k → ∞`
private lemma tendsto_const_rpow_inv {C : ℝ} (hC : 0 < C) :
Tendsto (fun k : ℕ ↦ C ^ (k : ℝ)⁻¹) atTop (𝓝 1) :=
((continuous_iff_continuousAt.mpr fun _ ↦ continuousAt_const_rpow hC.ne').tendsto'
0 1 (rpow_zero C)).comp <| tendsto_inv_atTop_zero.comp tendsto_natCast_atTop_atTop
--extends the lemma `tendsto_rpow_div` when the function has natural input
private lemma tendsto_nat_rpow_inv :
Tendsto (fun k : ℕ ↦ (k : ℝ) ^ (k : ℝ)⁻¹) atTop (𝓝 1) := by
simp_rw [← one_div]
exact Tendsto.comp tendsto_rpow_div tendsto_natCast_atTop_atTop
-- Multiplication by a constant moves in a List.sum
private lemma list_mul_sum {R : Type*} [Semiring R] {T : Type*} (l : List T) (y : R) (x : R) :
(l.mapIdx fun i _ => x * y ^ i).sum = x * (l.mapIdx fun i _ => y ^ i).sum := by
simp_rw [← smul_eq_mul, List.smul_sum, List.mapIdx_eq_zipIdx_map]
congr 1
simp
-- Geometric sum for lists
private lemma list_geom {T : Type*} {F : Type*} [DivisionRing F] (l : List T) {y : F} (hy : y ≠ 1) :
(l.mapIdx fun i _ => y ^ i).sum = (y ^ l.length - 1) / (y - 1) := by
rw [← geom_sum_eq hy l.length, List.mapIdx_eq_zipIdx_map, Finset.sum_range,
← Fin.sum_univ_fun_getElem]
simp only
let e : Fin l.zipIdx.length ≃ Fin l.length := finCongr List.length_zipIdx
exact Fintype.sum_bijective e e.bijective _ _ fun _ ↦ by simp [e]
open AbsoluteValue -- does not work as intended after `namespace Rat.AbsoluteValue`
namespace Rat.AbsoluteValue
/-!
### Preliminary lemmas
-/
open Int
variable {f g : AbsoluteValue ℚ ℝ}
/-- Values of an absolute value on the rationals are determined by the values on the natural
numbers. -/
lemma eq_on_nat_iff_eq : (∀ n : ℕ, f n = g n) ↔ f = g := by
refine ⟨fun h ↦ ?_, fun h n ↦ congrFun (congrArg DFunLike.coe h) ↑n⟩
ext1 z
rw [← Rat.num_div_den z, map_div₀, map_div₀, h, eq_on_nat_iff_eq_on_int.mp h]
/-- The equivalence class of an absolute value on the rationals is determined by its values on
the natural numbers. -/
lemma exists_nat_rpow_iff_isEquiv : (∃ c : ℝ, 0 < c ∧ ∀ n : ℕ, f n ^ c = g n) ↔ f.IsEquiv g := by
rw [isEquiv_iff_exists_rpow_eq]
refine ⟨fun ⟨c, hc, h⟩ ↦ ⟨c, hc, ?_⟩, fun ⟨c, hc, h⟩ ↦ ⟨c, hc, (congrFun h ·)⟩⟩
ext1 x
rw [← Rat.num_div_den x, map_div₀, map_div₀, div_rpow (by positivity) (by positivity), h x.den,
← apply_natAbs_eq, ← apply_natAbs_eq, h (natAbs x.num)]
@[deprecated (since := "2025-09-12")]
alias equiv_on_nat_iff_equiv := exists_nat_rpow_iff_isEquiv
section Non_archimedean
/-!
### The non-archimedean case
Every bounded absolute value on `ℚ` is equivalent to a `p`-adic absolute value.
-/
/-- The real-valued `AbsoluteValue` corresponding to the p-adic norm on `ℚ`. -/
def padic (p : ℕ) [Fact p.Prime] : AbsoluteValue ℚ ℝ where
toFun x := (padicNorm p x : ℝ)
map_mul' := by simp only [padicNorm.mul, Rat.cast_mul, forall_const]
nonneg' x := cast_nonneg.mpr <| padicNorm.nonneg x
eq_zero' x :=
⟨fun H ↦ padicNorm.zero_of_padicNorm_eq_zero <| cast_eq_zero.mp H,
fun H ↦ cast_eq_zero.mpr <| H ▸ padicNorm.zero (p := p)⟩
add_le' x y := by exact_mod_cast padicNorm.triangle_ineq x y
@[simp] lemma padic_eq_padicNorm (p : ℕ) [Fact p.Prime] (r : ℚ) :
padic p r = padicNorm p r := rfl
lemma padic_le_one (p : ℕ) [Fact p.Prime] (n : ℤ) : padic p n ≤ 1 := by
simp only [padic_eq_padicNorm]
exact_mod_cast padicNorm.of_int n
-- ## Step 1: define `p = minimal n s. t. 0 < f n < 1`
variable (hf_nontriv : f.IsNontrivial) (bdd : ∀ n : ℕ, f n ≤ 1)
include hf_nontriv bdd in
/-- There exists a minimal positive integer with absolute value smaller than 1. -/
lemma exists_minimal_nat_zero_lt_and_lt_one :
∃ p : ℕ, (0 < f p ∧ f p < 1) ∧ ∀ m : ℕ, 0 < f m ∧ f m < 1 → p ≤ m := by
-- There is a positive integer with absolute value different from one.
obtain ⟨n, hn1, hn2⟩ : ∃ n : ℕ, n ≠ 0 ∧ f n ≠ 1 := by
contrapose! hf_nontriv
refine (isNontrivial_iff_ne_trivial f).not_left.mpr <| eq_on_nat_iff_eq.mp fun n ↦ ?_
rcases eq_or_ne n 0 with rfl | hn
· simp
· simp [hf_nontriv, hn]
set P := {m : ℕ | 0 < f ↑m ∧ f ↑m < 1} -- p is going to be the minimum of this set.
have hP : P.Nonempty :=
⟨n, map_pos_of_ne_zero f (Nat.cast_ne_zero.mpr hn1), lt_of_le_of_ne (bdd n) hn2⟩
exact ⟨sInf P, Nat.sInf_mem hP, fun m hm ↦ Nat.sInf_le hm⟩
-- ## Step 2: p is prime
variable {p : ℕ} (hp0 : 0 < f p) (hp1 : f p < 1) (hmin : ∀ m : ℕ, 0 < f m ∧ f m < 1 → p ≤ m)
include hp0 hp1 hmin in
/-- The minimal positive integer with absolute value smaller than 1 is a prime number. -/
lemma is_prime_of_minimal_nat_zero_lt_and_lt_one : p.Prime := by
rw [← Nat.irreducible_iff_nat_prime]
constructor -- Two goals: p is not a unit and any product giving p must contain a unit.
· rw [Nat.isUnit_iff]
rintro rfl
simp only [Nat.cast_one, map_one, lt_self_iff_false] at hp1
· rintro a b rfl
rw [Nat.isUnit_iff, Nat.isUnit_iff]
by_contra! con
obtain ⟨ha₁, hb₁⟩ := con
obtain ⟨ha₀, hb₀⟩ : a ≠ 0 ∧ b ≠ 0 := by
refine mul_ne_zero_iff.mp fun h ↦ ?_
rwa [h, Nat.cast_zero, map_zero, lt_self_iff_false] at hp0
have hap : a < a * b := lt_mul_of_one_lt_right (by cutsat) (by cutsat)
have hbp : b < a * b := lt_mul_of_one_lt_left (by cutsat) (by cutsat)
have ha :=
le_of_not_gt <| not_and.mp ((hmin a).mt hap.not_ge) (map_pos_of_ne_zero f (mod_cast ha₀))
have hb :=
le_of_not_gt <| not_and.mp ((hmin b).mt hbp.not_ge) (map_pos_of_ne_zero f (mod_cast hb₀))
rw [Nat.cast_mul, map_mul] at hp1
exact ((one_le_mul_of_one_le_of_one_le ha hb).trans_lt hp1).false
-- ## Step 3: if p does not divide m, then f m = 1
open Real
include hp0 hp1 hmin bdd in
/-- A natural number not divisible by `p` has absolute value 1. -/
lemma eq_one_of_not_dvd {m : ℕ} (hpm : ¬ p ∣ m) : f m = 1 := by
apply le_antisymm (bdd m)
by_contra! hm
set M := f p ⊔ f m with hM
set k := Nat.ceil (M.logb (1 / 2)) + 1 with hk
obtain ⟨a, b, bezout⟩ : IsCoprime (p ^ k : ℤ) (m ^ k) :=
is_prime_of_minimal_nat_zero_lt_and_lt_one hp0 hp1 hmin
|>.coprime_iff_not_dvd |>.mpr hpm |>.isCoprime |>.pow
have le_half {x} (hx0 : 0 < x) (hx1 : x < 1) (hxM : x ≤ M) : x ^ k < 1 / 2 := by
calc
x ^ k = x ^ (k : ℝ) := (rpow_natCast x k).symm
_ < x ^ M.logb (1 / 2) := by
apply rpow_lt_rpow_of_exponent_gt hx0 hx1
rw [hk]
push_cast
exact lt_add_of_le_of_pos (Nat.le_ceil _) zero_lt_one
_ ≤ x ^ x.logb (1 / 2) := by
apply rpow_le_rpow_of_exponent_ge hx0 hx1.le
simp only [one_div, ← log_div_log, log_inv, neg_div, ← div_neg, hM]
gcongr
simp only [Left.neg_pos_iff]
exact log_neg (lt_sup_iff.mpr <| .inl hp0) (sup_lt_iff.mpr ⟨hp1, hm⟩)
_ = 1 / 2 := rpow_logb hx0 hx1.ne one_half_pos
apply lt_irrefl (1 : ℝ)
calc
1 = f 1 := (map_one f).symm
_ = f (a * p ^ k + b * m ^ k) := by rw_mod_cast [bezout]; norm_cast
_ ≤ f (a * p ^ k) + f (b * m ^ k) := f.add_le' ..
_ ≤ 1 * (f p) ^ k + 1 * (f m) ^ k := by
simp only [map_mul, map_pow]
gcongr
all_goals rw [← apply_natAbs_eq]; apply bdd
_ = (f p) ^ k + (f m) ^ k := by simp only [one_mul]
_ < 1 := by
have hm₀ : 0 < f m := f.pos <| Nat.cast_ne_zero.mpr fun H ↦ hpm <| H ▸ dvd_zero p
linarith only [le_half hp0 hp1 le_sup_left, le_half hm₀ hm le_sup_right]
-- ## Step 4: f p = p ^ (-t) for some positive real t
include hp0 hp1 hmin in
/-- The absolute value of `p` is `p ^ (-t)` for some positive real number `t`. -/
lemma exists_pos_eq_pow_neg : ∃ t : ℝ, 0 < t ∧ f p = p ^ (-t) := by
have pprime := is_prime_of_minimal_nat_zero_lt_and_lt_one hp0 hp1 hmin
refine ⟨- logb p (f p), Left.neg_pos_iff.mpr <| logb_neg (mod_cast pprime.one_lt) hp0 hp1, ?_⟩
rw [neg_neg]
exact (rpow_logb (mod_cast pprime.pos) (mod_cast pprime.ne_one) hp0).symm
-- ## Non-archimedean case: end goal
include hf_nontriv bdd in
/-- If `f` is bounded and not trivial, then it is equivalent to a p-adic absolute value. -/
theorem equiv_padic_of_bounded :
∃! p, ∃ (_ : Fact p.Prime), f.IsEquiv (padic p) := by
obtain ⟨p, hfp, hmin⟩ := exists_minimal_nat_zero_lt_and_lt_one hf_nontriv bdd
have hprime := is_prime_of_minimal_nat_zero_lt_and_lt_one hfp.1 hfp.2 hmin
have hprime_fact : Fact p.Prime := ⟨hprime⟩
obtain ⟨t, h⟩ := exists_pos_eq_pow_neg hfp.1 hfp.2 hmin
simp_rw [← exists_nat_rpow_iff_isEquiv]
refine ⟨p, ⟨hprime_fact, t⁻¹, inv_pos_of_pos h.1, fun n ↦ ?_⟩, fun q ⟨hq_prime, h_equiv⟩ ↦ ?_⟩
· have ht : t⁻¹ ≠ 0 := inv_ne_zero h.1.ne'
rcases eq_or_ne n 0 with rfl | hn -- Separate cases n = 0 and n ≠ 0
· simp [ht]
· /- Any natural number can be written as a power of p times a natural number not divisible
by p -/
rcases Nat.exists_eq_pow_mul_and_not_dvd hn p hprime.ne_one with ⟨e, m, hpm, rfl⟩
simp only [Nat.cast_mul, Nat.cast_pow, map_mul, map_pow, h.2,
eq_one_of_not_dvd bdd hfp.1 hfp.2 hmin hpm, padic_eq_padicNorm,
padicNorm.padicNorm_p_of_prime, cast_inv, cast_natCast, inv_pow]
rw [← padicNorm.nat_eq_one_iff] at hpm
simp only [← rpow_natCast, p.cast_nonneg, ← rpow_mul, neg_mul, mul_one, ← rpow_neg, hpm,
cast_one]
field_simp [h.1.ne']
· by_contra! hne
apply hq_prime.elim.ne_one
rw [ne_comm, ← Nat.coprime_primes hprime hq_prime.elim, hprime.coprime_iff_not_dvd] at hne
rcases h_equiv with ⟨c, _, h_eq⟩
simpa [eq_one_of_not_dvd bdd hfp.1 hfp.2 hmin hne] using h_eq q
end Non_archimedean
section Archimedean
/-!
### Archimedean case
Every unbounded absolute value on `ℚ` is equivalent to the standard absolute value.
-/
/-- The standard absolute value on `ℚ`. We name it `real` because it corresponds to the
unique real place of `ℚ`. -/
def real : AbsoluteValue ℚ ℝ where
toFun x := |x|
map_mul' x y := by simp
nonneg' x := by simp
eq_zero' x := by simp
add_le' x y := by simpa using abs_add_le (x : ℝ) (y : ℝ)
@[simp] lemma real_eq_abs (r : ℚ) : real r = |r| :=
(cast_abs r).symm
-- ## Preliminary result
/-- Given any two integers `n`, `m` with `m > 1`, the absolute value of `n` is bounded by
`m + m * f m + m * (f m) ^ 2 + ... + m * (f m) ^ d` where `d` is the number of digits of the
expansion of `n` in base `m`. -/
lemma apply_le_sum_digits (n : ℕ) {m : ℕ} (hm : 1 < m) :
f n ≤ ((Nat.digits m n).mapIdx fun i _ ↦ m * (f m) ^ i).sum := by
set L := Nat.digits m n
set L' : List ℚ := List.map Nat.cast (L.mapIdx fun i a ↦ (a * m ^ i)) with hL'
-- If `c` is a digit in the expansion of `n` in base `m`, then `f c` is less than `m`.
have hcoef {c : ℕ} (hc : c ∈ Nat.digits m n) : f c < m :=
lt_of_le_of_lt (f.apply_nat_le_self c) (mod_cast Nat.digits_lt_base hm hc)
calc
f n = f ((Nat.ofDigits m L : ℕ) : ℚ) := by rw [Nat.ofDigits_digits m n]
_ = f L'.sum := by rw [Nat.ofDigits_eq_sum_mapIdx]; norm_cast
_ ≤ (L'.map f).sum := listSum_le f L'
_ ≤ (L.mapIdx fun i _ ↦ m * (f m) ^ i).sum := ?_
simp only [hL', List.mapIdx_eq_zipIdx_map, List.map_map]
refine List.sum_le_sum fun ⟨a, i⟩ hia ↦ ?_
dsimp only [Function.comp_apply, Function.uncurry_apply_pair]
replace hia := List.mem_zipIdx hia
push_cast
rw [map_mul, map_pow]
refine mul_le_mul_of_nonneg_right ?_ <| pow_nonneg (f.nonneg _) i
simp only [zero_le, zero_add, tsub_zero, true_and] at hia
exact (hcoef (List.mem_iff_get.mpr ⟨⟨i, hia.1⟩, hia.2.symm⟩)).le
-- ## Step 1: if f is an AbsoluteValue and f n > 1 for some natural n, then f n > 1 for all n ≥ 2
/-- If `f n > 1` for some `n` then `f n > 1` for all `n ≥ 2` -/
lemma one_lt_of_not_bounded (notbdd : ¬ ∀ n : ℕ, f n ≤ 1) {n₀ : ℕ} (hn₀ : 1 < n₀) : 1 < f n₀ := by
contrapose! notbdd with h
intro n
have h_ineq1 {m : ℕ} (hm : 1 ≤ m) : f m ≤ n₀ * (logb n₀ m + 1) := by
/- L is the string of digits of `n` in the base `n₀` -/
set L := Nat.digits n₀ m
calc
f m ≤ (L.mapIdx fun i _ ↦ n₀ * f n₀ ^ i).sum := apply_le_sum_digits m hn₀
_ ≤ (L.mapIdx fun _ _ ↦ (n₀ : ℝ)).sum := by
simp only [List.mapIdx_eq_zipIdx_map]
refine List.sum_le_sum fun ⟨i, a⟩ _ ↦ ?_
simp only
exact (mul_le_mul_of_nonneg_right (mod_cast le_refl n₀) (by positivity)).trans <|
mul_le_of_le_one_right (by positivity) (pow_le_one₀ (by positivity) h)
_ = n₀ * (Nat.log n₀ m + 1) := by
rw [List.mapIdx_eq_zipIdx_map, List.eq_replicate_of_mem (a := (n₀ : ℝ)) (l := L.zipIdx.map _),
List.sum_replicate, List.length_map, List.length_zipIdx, nsmul_eq_mul, mul_comm,
Nat.digits_len n₀ m hn₀ (ne_zero_of_lt hm), Nat.cast_add_one]
simp +contextual
_ ≤ n₀ * (logb n₀ m + 1) := by gcongr; exact natLog_le_logb ..
-- For h_ineq2 we need to exclude the case n = 0.
rcases eq_or_ne n 0 with rfl | h₀
· simp
have h_ineq2 (k : ℕ) (hk : 0 < k) :
f n ≤ (n₀ * (logb n₀ n + 1)) ^ (k : ℝ)⁻¹ * k ^ (k : ℝ)⁻¹ := by
have : 0 ≤ logb n₀ n := logb_nonneg (one_lt_cast.mpr hn₀) (mod_cast Nat.one_le_of_lt h₀.bot_lt)
calc
f n = (f ↑(n ^ k)) ^ (k : ℝ)⁻¹ := by
rw [Nat.cast_pow, map_pow, ← rpow_natCast, rpow_rpow_inv (by positivity) (by positivity)]
_ ≤ (n₀ * (logb n₀ ↑(n ^ k) + 1)) ^ (k : ℝ)⁻¹ := by
gcongr
exact h_ineq1 <| one_le_pow₀ (one_le_iff_ne_zero.mpr h₀)
_ = (n₀ * (k * logb n₀ n + 1)) ^ (k : ℝ)⁻¹ := by
rw [Nat.cast_pow, logb_pow]
_ ≤ (n₀ * (k * logb n₀ n + k)) ^ (k : ℝ)⁻¹ := by
gcongr
exact one_le_cast.mpr hk
_ = (n₀ * (logb n₀ n + 1)) ^ (k : ℝ)⁻¹ * k ^ (k : ℝ)⁻¹ := by
rw [← mul_rpow (by positivity) (by positivity), mul_assoc, add_mul, one_mul,
mul_comm _ (k : ℝ)]
-- For 0 < logb n₀ n below we also need to exclude n = 1.
rcases eq_or_ne n 1 with rfl | h₁
· simp
refine le_of_tendsto_of_tendsto tendsto_const_nhds ?_ (eventually_atTop.mpr ⟨1, h_ineq2⟩)
nth_rw 2 [← mul_one 1]
have : 0 < logb n₀ n := logb_pos (mod_cast hn₀) (by norm_cast; cutsat)
exact (tendsto_const_rpow_inv (by positivity)).mul tendsto_nat_rpow_inv
-- ## Step 2: given m, n ≥ 2 and |m| = m^s, |n| = n^t for s, t > 0, we have t ≤ s
variable {m n : ℕ} (hm : 1 < m) (hn : 1 < n) (notbdd : ¬ ∀ n : ℕ, f n ≤ 1)
include hm notbdd in
private lemma expr_pos : 0 < m * f m / (f m - 1) := by
apply div_pos (mul_pos (mod_cast zero_lt_of_lt hm)
(map_pos_of_ne_zero f (mod_cast ne_zero_of_lt hm)))
linarith only [one_lt_of_not_bounded notbdd hm]
include hn hm notbdd in
private lemma param_upperbound {k : ℕ} (hk : k ≠ 0) :
f n ≤ (m * f m / (f m - 1)) ^ (k : ℝ)⁻¹ * f m ^ logb m n := by
have h_ineq1 {m n : ℕ} (hm : 1 < m) (hn : 1 < n) :
f n ≤ (m * f m / (f m - 1)) * f m ^ logb m n := by
let d := Nat.log m n
calc
f n ≤ ((Nat.digits m n).mapIdx fun i _ ↦ m * f m ^ i).sum := apply_le_sum_digits n hm
_ = m * ((Nat.digits m n).mapIdx fun i _ ↦ f m ^ i).sum := list_mul_sum (m.digits n) (f m) m
_ = m * ((f m ^ (d + 1) - 1) / (f m - 1)) := by
rw [list_geom _ (ne_of_gt (one_lt_of_not_bounded notbdd hm)),
← Nat.digits_len m n hm (ne_zero_of_lt hn)]
_ ≤ m * ((f m ^ (d + 1)) / (f m - 1)) := by
gcongr
· linarith only [one_lt_of_not_bounded notbdd hm]
· simp
_ = ↑m * f ↑m / (f ↑m - 1) * f ↑m ^ d := by ring
_ ≤ ↑m * f ↑m / (f ↑m - 1) * f ↑m ^ logb ↑m ↑n := by
gcongr
· exact (expr_pos hm notbdd).le
· rw [← rpow_natCast, rpow_le_rpow_left_iff (one_lt_of_not_bounded notbdd hm)]
exact natLog_le_logb n m
apply le_of_pow_le_pow_left₀ hk <| mul_nonneg (rpow_nonneg (expr_pos hm notbdd).le _)
(rpow_nonneg (apply_nonneg f ↑m) _)
nth_rewrite 2 [← rpow_natCast]
rw [mul_rpow (rpow_nonneg (expr_pos hm notbdd).le _) (rpow_nonneg (apply_nonneg f ↑m) _),
← rpow_mul (expr_pos hm notbdd).le, ← rpow_mul (apply_nonneg f ↑m),
inv_mul_cancel₀ (mod_cast hk), rpow_one, mul_comm (logb ..)]
calc
(f n) ^ k = f ↑(n ^ k) := by simp
_ ≤ (m * f m / (f m - 1)) * f m ^ logb m ↑(n ^ k) := h_ineq1 hm (Nat.one_lt_pow hk hn)
_ = (m * f m / (f m - 1)) * f m ^ (k * logb m n) := by rw [Nat.cast_pow, logb_pow]
include hm hn notbdd in
/-- Given two natural numbers `n, m` greater than 1 we have `f n ≤ f m ^ logb m n`. -/
lemma le_pow_log : f n ≤ f m ^ logb m n := by
have : Tendsto (fun k : ℕ ↦ (m * f m / (f m - 1)) ^ (k : ℝ)⁻¹ * f m ^ logb m n)
atTop (𝓝 (f m ^ logb m n)) := by
nth_rw 2 [← one_mul (f ↑m ^ logb ↑m ↑n)]
exact (tendsto_const_rpow_inv (expr_pos hm notbdd)).mul_const _
exact le_of_tendsto_of_tendsto (tendsto_const_nhds (x := f ↑n)) this <|
eventually_atTop.mpr ⟨2, fun b hb ↦ param_upperbound hm hn notbdd (ne_zero_of_lt hb)⟩
include hm hn notbdd in
/-- Given `m, n ≥ 2` and `f m = m ^ s`, `f n = n ^ t` for `s, t > 0`, we have `t ≤ s`. -/
private lemma le_of_eq_pow {s t : ℝ} (hfm : f m = m ^ s) (hfn : f n = n ^ t) : t ≤ s := by
rw [← rpow_le_rpow_left_iff (x := n) (mod_cast hn), ← hfn]
apply le_trans <| le_pow_log hm hn notbdd
rw [hfm, ← rpow_mul (Nat.cast_nonneg m), mul_comm, rpow_mul (Nat.cast_nonneg m),
rpow_logb (mod_cast zero_lt_of_lt hm) (mod_cast hm.ne') (mod_cast zero_lt_of_lt hn)]
include hm hn notbdd in
private lemma eq_of_eq_pow {s t : ℝ} (hfm : f m = m ^ s) (hfn : f n = n ^ t) : s = t :=
le_antisymm (le_of_eq_pow hn hm notbdd hfn hfm) (le_of_eq_pow hm hn notbdd hfm hfn)
-- ## Archimedean case: end goal
include notbdd in
/-- If `f` is not bounded and not trivial, then it is equivalent to the standard absolute value on
`ℚ`. -/
theorem equiv_real_of_unbounded : f.IsEquiv real := by
obtain ⟨m, hm⟩ := Classical.exists_not_of_not_forall notbdd
have oneltm : 1 < m := by
contrapose! hm
rcases le_one_iff_eq_zero_or_eq_one.mp hm with rfl | rfl <;> simp
rw [← exists_nat_rpow_iff_isEquiv]
set s := logb m (f m) with hs
refine ⟨s⁻¹,
inv_pos.mpr (logb_pos (Nat.one_lt_cast.mpr oneltm) (one_lt_of_not_bounded notbdd oneltm)),
fun n ↦ ?_⟩
rcases lt_trichotomy n 1 with h | rfl | h
· obtain rfl : n = 0 := by cutsat
have : (logb (↑m) (f ↑m))⁻¹ ≠ 0 := by
simp only [ne_eq, inv_eq_zero, logb_eq_zero, Nat.cast_eq_zero, Nat.cast_eq_one, map_eq_zero,
not_or]
exact ⟨ne_zero_of_lt oneltm, oneltm.ne', by norm_cast,
ne_zero_of_lt oneltm, ne_of_not_le hm, by linarith only [apply_nonneg f ↑m]⟩
simp [hs, this]
· simp
· simp only [real_eq_abs, abs_cast, Rat.cast_natCast]
rw [rpow_inv_eq (apply_nonneg f ↑n) (Nat.cast_nonneg n)
(logb_ne_zero_of_pos_of_ne_one (one_lt_cast.mpr oneltm) (by linarith only [hm])
(by linarith only [hm]))]
have hfm : f m = m ^ s := by
rw [rpow_logb (mod_cast zero_lt_of_lt oneltm) (mod_cast oneltm.ne') (by linarith only [hm])]
have hfn : f n = n ^ logb n (f n) := by
rw [rpow_logb (mod_cast zero_lt_of_lt h) (mod_cast h.ne')
(by apply map_pos_of_ne_zero; exact_mod_cast ne_zero_of_lt h)]
rwa [← hs, eq_of_eq_pow oneltm h notbdd hfm hfn]
end Archimedean
/-!
### The main result
-/
/-- **Ostrowski's Theorem**: every absolute value (with values in `ℝ`) on `ℚ` is equivalent
to either the standard absolute value or a `p`-adic absolute value for a prime `p`. -/
theorem equiv_real_or_padic (f : AbsoluteValue ℚ ℝ) (hf_nontriv : f.IsNontrivial) :
f ≈ real ∨ ∃! p, ∃ (_ : Fact p.Prime), f ≈ (padic p) := by
by_cases bdd : ∀ n : ℕ, f n ≤ 1
· exact .inr <| equiv_padic_of_bounded hf_nontriv bdd
· exact .inl <| equiv_real_of_unbounded bdd
/-- The standard absolute value on `ℚ` is not equivalent to any `p`-adic absolute value. -/
lemma not_real_isEquiv_padic (p : ℕ) [Fact p.Prime] : ¬ real.IsEquiv (padic p) := by
rw [isEquiv_iff_exists_rpow_eq]
rintro ⟨c, hc₀, hc⟩
apply_fun (· 2) at hc
simp only [real_eq_abs, abs_ofNat, cast_ofNat] at hc
exact ((padic_le_one p 2).trans_lt <| one_lt_rpow one_lt_two hc₀).ne' hc
@[deprecated (since := "2025-09-12")]
alias not_real_equiv_padic := not_real_isEquiv_padic
end Rat.AbsoluteValue |
.lake/packages/mathlib/Mathlib/NumberTheory/PythagoreanTriples.lean | import Mathlib.Data.Int.NatPrime
import Mathlib.Data.ZMod.Basic
import Mathlib.RingTheory.Int.Basic
import Mathlib.Tactic.Field
/-!
# Pythagorean Triples
The main result is the classification of Pythagorean triples. The final result is for general
Pythagorean triples. It follows from the more interesting relatively prime case. We use the
"rational parametrization of the circle" method for the proof. The parametrization maps the point
`(x / z, y / z)` to the slope of the line through `(-1, 0)` and `(x / z, y / z)`. This quickly
shows that `(x / z, y / z) = (2 * m * n / (m ^ 2 + n ^ 2), (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2))` where
`m / n` is the slope. In order to identify numerators and denominators we now need results showing
that these are coprime. This is easy except for the prime 2. In order to deal with that we have to
analyze the parity of `x`, `y`, `m` and `n` and eliminate all the impossible cases. This takes up
the bulk of the proof below.
-/
assert_not_exists TwoSidedIdeal
theorem sq_ne_two_fin_zmod_four (z : ZMod 4) : z * z ≠ 2 := by
change Fin 4 at z
fin_cases z <;> decide
theorem Int.sq_ne_two_mod_four (z : ℤ) : z * z % 4 ≠ 2 := by
suffices ¬z * z % (4 : ℕ) = 2 % (4 : ℕ) by exact this
rw [← ZMod.intCast_eq_intCast_iff']
simpa using sq_ne_two_fin_zmod_four _
noncomputable section
/-- Three integers `x`, `y`, and `z` form a Pythagorean triple if `x * x + y * y = z * z`. -/
def PythagoreanTriple (x y z : ℤ) : Prop :=
x * x + y * y = z * z
/-- Pythagorean triples are interchangeable, i.e `x * x + y * y = y * y + x * x = z * z`.
This comes from additive commutativity. -/
theorem pythagoreanTriple_comm {x y z : ℤ} : PythagoreanTriple x y z ↔ PythagoreanTriple y x z := by
delta PythagoreanTriple
rw [add_comm]
/-- The zeroth Pythagorean triple is all zeros. -/
theorem PythagoreanTriple.zero : PythagoreanTriple 0 0 0 := by
simp only [PythagoreanTriple, zero_mul, zero_add]
namespace PythagoreanTriple
variable {x y z : ℤ}
theorem eq (h : PythagoreanTriple x y z) : x * x + y * y = z * z :=
h
@[symm]
theorem symm (h : PythagoreanTriple x y z) : PythagoreanTriple y x z := by
rwa [pythagoreanTriple_comm]
/-- A triple is still a triple if you multiply `x`, `y` and `z`
by a constant `k`. -/
theorem mul (h : PythagoreanTriple x y z) (k : ℤ) : PythagoreanTriple (k * x) (k * y) (k * z) :=
calc
k * x * (k * x) + k * y * (k * y) = k ^ 2 * (x * x + y * y) := by ring
_ = k ^ 2 * (z * z) := by rw [h.eq]
_ = k * z * (k * z) := by ring
/-- `(k*x, k*y, k*z)` is a Pythagorean triple if and only if
`(x, y, z)` is also a triple. -/
theorem mul_iff (k : ℤ) (hk : k ≠ 0) :
PythagoreanTriple (k * x) (k * y) (k * z) ↔ PythagoreanTriple x y z := by
refine ⟨?_, fun h => h.mul k⟩
simp only [PythagoreanTriple]
intro h
rw [← mul_left_inj' (mul_ne_zero hk hk)]
convert h using 1 <;> ring
/-- A Pythagorean triple `x, y, z` is “classified” if there exist integers `k, m, n` such that
either
* `x = k * (m ^ 2 - n ^ 2)` and `y = k * (2 * m * n)`, or
* `x = k * (2 * m * n)` and `y = k * (m ^ 2 - n ^ 2)`. -/
@[nolint unusedArguments]
def IsClassified (_ : PythagoreanTriple x y z) :=
∃ k m n : ℤ,
(x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n) ∨
x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2)) ∧
Int.gcd m n = 1
/-- A primitive Pythagorean triple `x, y, z` is a Pythagorean triple with `x` and `y` coprime.
Such a triple is “primitively classified” if there exist coprime integers `m, n` such that either
* `x = m ^ 2 - n ^ 2` and `y = 2 * m * n`, or
* `x = 2 * m * n` and `y = m ^ 2 - n ^ 2`.
-/
@[nolint unusedArguments]
def IsPrimitiveClassified (_ : PythagoreanTriple x y z) :=
∃ m n : ℤ,
(x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n ∨ x = 2 * m * n ∧ y = m ^ 2 - n ^ 2) ∧
Int.gcd m n = 1 ∧ (m % 2 = 0 ∧ n % 2 = 1 ∨ m % 2 = 1 ∧ n % 2 = 0)
variable (h : PythagoreanTriple x y z)
include h
theorem mul_isClassified (k : ℤ) (hc : h.IsClassified) : (h.mul k).IsClassified := by
obtain ⟨l, m, n, ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co⟩⟩ := hc <;> use k * l, m, n <;> grind
theorem even_odd_of_coprime (hc : Int.gcd x y = 1) :
x % 2 = 0 ∧ y % 2 = 1 ∨ x % 2 = 1 ∧ y % 2 = 0 := by
rcases Int.emod_two_eq_zero_or_one x with hx | hx <;>
rcases Int.emod_two_eq_zero_or_one y with hy | hy
-- x even, y even
· exfalso
apply Nat.not_coprime_of_dvd_of_dvd (by decide : 1 < 2) _ _ hc
· apply Int.natCast_dvd.1
apply Int.dvd_of_emod_eq_zero hx
· apply Int.natCast_dvd.1
apply Int.dvd_of_emod_eq_zero hy
-- x even, y odd
· left
exact ⟨hx, hy⟩
-- x odd, y even
· right
exact ⟨hx, hy⟩
-- x odd, y odd
· exfalso
obtain ⟨x0, y0, rfl, rfl⟩ : ∃ x0 y0, x = x0 * 2 + 1 ∧ y = y0 * 2 + 1 := by
obtain ⟨x0, hx2⟩ := exists_eq_mul_left_of_dvd (Int.dvd_self_sub_of_emod_eq hx)
obtain ⟨y0, hy2⟩ := exists_eq_mul_left_of_dvd (Int.dvd_self_sub_of_emod_eq hy)
rw [sub_eq_iff_eq_add] at hx2 hy2
exact ⟨x0, y0, hx2, hy2⟩
apply Int.sq_ne_two_mod_four z
rw [show z * z = 4 * (x0 * x0 + x0 + y0 * y0 + y0) + 2 by
rw [← h.eq]
ring]
simp only [Int.add_emod, Int.mul_emod_right, zero_add]
decide
theorem gcd_dvd : (Int.gcd x y : ℤ) ∣ z := by
by_cases h0 : Int.gcd x y = 0
· have hx : x = 0 := by
apply Int.natAbs_eq_zero.mp
apply Nat.eq_zero_of_gcd_eq_zero_left h0
have hy : y = 0 := by
apply Int.natAbs_eq_zero.mp
apply Nat.eq_zero_of_gcd_eq_zero_right h0
have hz : z = 0 := by
simpa only [PythagoreanTriple, hx, hy, add_zero, zero_eq_mul, mul_zero,
or_self_iff] using h
simp only [hz, dvd_zero]
obtain ⟨k, x0, y0, _, h2, rfl, rfl⟩ :
∃ (k : ℕ) (x0 y0 : _), 0 < k ∧ Int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k :=
Int.exists_gcd_one' (Nat.pos_of_ne_zero h0)
rw [Int.gcd_mul_right, h2, Int.natAbs_natCast, one_mul]
rw [← Int.pow_dvd_pow_iff two_ne_zero, sq z, ← h.eq]
rw [(by ring : x0 * k * (x0 * k) + y0 * k * (y0 * k) = (k : ℤ) ^ 2 * (x0 * x0 + y0 * y0))]
exact dvd_mul_right _ _
theorem normalize : PythagoreanTriple (x / Int.gcd x y) (y / Int.gcd x y) (z / Int.gcd x y) := by
by_cases h0 : Int.gcd x y = 0
· have hx : x = 0 := by
apply Int.natAbs_eq_zero.mp
apply Nat.eq_zero_of_gcd_eq_zero_left h0
have hy : y = 0 := by
apply Int.natAbs_eq_zero.mp
apply Nat.eq_zero_of_gcd_eq_zero_right h0
have hz : z = 0 := by
simpa only [PythagoreanTriple, hx, hy, add_zero, zero_eq_mul, mul_zero,
or_self_iff] using h
simp only [hx, hy, hz]
exact zero
rcases h.gcd_dvd with ⟨z0, rfl⟩
obtain ⟨k, x0, y0, k0, h2, rfl, rfl⟩ :
∃ (k : ℕ) (x0 y0 : _), 0 < k ∧ Int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k :=
Int.exists_gcd_one' (Nat.pos_of_ne_zero h0)
have hk : (k : ℤ) ≠ 0 := by
norm_cast
rwa [pos_iff_ne_zero] at k0
rw [Int.gcd_mul_right, h2, Int.natAbs_natCast, one_mul] at h ⊢
rw [mul_comm x0, mul_comm y0, mul_iff k hk] at h
rwa [Int.mul_ediv_cancel _ hk, Int.mul_ediv_cancel _ hk, Int.mul_ediv_cancel_left _ hk]
theorem isClassified_of_isPrimitiveClassified (hp : h.IsPrimitiveClassified) : h.IsClassified := by
obtain ⟨m, n, H⟩ := hp
use 1, m, n
cutsat
theorem isClassified_of_normalize_isPrimitiveClassified (hc : h.normalize.IsPrimitiveClassified) :
h.IsClassified := by
convert h.normalize.mul_isClassified (Int.gcd x y)
(isClassified_of_isPrimitiveClassified h.normalize hc) <;>
rw [Int.mul_ediv_cancel']
· exact Int.gcd_dvd_left ..
· exact Int.gcd_dvd_right ..
· exact h.gcd_dvd
theorem ne_zero_of_coprime (hc : Int.gcd x y = 1) : z ≠ 0 := by
suffices 0 < z * z by
rintro rfl
norm_num at this
rw [← h.eq, ← sq, ← sq]
have hc' : Int.gcd x y ≠ 0 := by
rw [hc]
exact one_ne_zero
rcases Int.ne_zero_of_gcd hc' with hxz | hyz
· apply lt_add_of_pos_of_le (sq_pos_of_ne_zero hxz) (sq_nonneg y)
· apply lt_add_of_le_of_pos (sq_nonneg x) (sq_pos_of_ne_zero hyz)
theorem isPrimitiveClassified_of_coprime_of_zero_left (hc : Int.gcd x y = 1) (hx : x = 0) :
h.IsPrimitiveClassified := by
subst x
change Nat.gcd 0 (Int.natAbs y) = 1 at hc
rw [Nat.gcd_zero_left (Int.natAbs y)] at hc
rcases Int.natAbs_eq y with hy | hy
· use 1, 0
rw [hy, hc, Int.gcd_zero_right]
decide
· use 0, 1
rw [hy, hc, Int.gcd_zero_left]
decide
theorem coprime_of_coprime (hc : Int.gcd x y = 1) : Int.gcd y z = 1 := by
by_contra H
obtain ⟨p, hp, hpy, hpz⟩ := Nat.Prime.not_coprime_iff_dvd.mp H
apply hp.not_dvd_one
rw [← hc]
apply Nat.dvd_gcd (Int.Prime.dvd_natAbs_of_coe_dvd_sq hp _ _) hpy
rw [sq, eq_sub_of_add_eq h]
rw [← Int.natCast_dvd] at hpy hpz
exact dvd_sub (hpz.mul_right _) (hpy.mul_right _)
end PythagoreanTriple
section circleEquivGen
/-!
### A parametrization of the unit circle
For the classification of Pythagorean triples, we will use a parametrization of the unit circle.
-/
variable {K : Type*} [Field K]
-- see https://github.com/leanprover-community/mathlib4/issues/29041
set_option linter.unusedSimpArgs false in
/-- A parameterization of the unit circle that is useful for classifying Pythagorean triples.
(To be applied in the case where `K = ℚ`.) -/
def circleEquivGen (hk : ∀ x : K, 1 + x ^ 2 ≠ 0) :
K ≃ { p : K × K // p.1 ^ 2 + p.2 ^ 2 = 1 ∧ p.2 ≠ -1 } where
toFun x :=
⟨⟨2 * x / (1 + x ^ 2), (1 - x ^ 2) / (1 + x ^ 2)⟩, by field [hk x], by
simp only [Ne, div_eq_iff (hk x), neg_mul, one_mul, neg_add, sub_eq_add_neg, add_left_inj]
simpa only [eq_neg_iff_add_eq_zero, one_pow] using hk 1⟩
invFun p := (p : K × K).1 / ((p : K × K).2 + 1)
left_inv x := by
have h2 : (1 + 1 : K) = 2 := by norm_num
have h3 : (2 : K) ≠ 0 := by
convert hk 1
rw [one_pow 2, h2]
simp [field, hk x, h2, add_assoc, add_comm, add_sub_cancel, mul_comm]
right_inv := fun ⟨⟨x, y⟩, hxy, hy⟩ => by
change x ^ 2 + y ^ 2 = 1 at hxy
have h2 : y + 1 ≠ 0 := mt eq_neg_of_add_eq_zero_left hy
have h3 : (y + 1) ^ 2 + x ^ 2 = 2 * (y + 1) := by
rw [(add_neg_eq_iff_eq_add.mpr hxy.symm).symm]
ring
have h4 : (2 : K) ≠ 0 := by
convert hk 1
rw [one_pow 2]
ring
simp only [Prod.mk_inj, Subtype.mk_eq_mk]
constructor
· simp [field, h3]
· simp [field, h3]
rw [← add_neg_eq_iff_eq_add.mpr hxy.symm]
ring
@[simp]
theorem circleEquivGen_apply (hk : ∀ x : K, 1 + x ^ 2 ≠ 0) (x : K) :
(circleEquivGen hk x : K × K) = ⟨2 * x / (1 + x ^ 2), (1 - x ^ 2) / (1 + x ^ 2)⟩ :=
rfl
@[simp]
theorem circleEquivGen_symm_apply (hk : ∀ x : K, 1 + x ^ 2 ≠ 0)
(v : { p : K × K // p.1 ^ 2 + p.2 ^ 2 = 1 ∧ p.2 ≠ -1 }) :
(circleEquivGen hk).symm v = (v : K × K).1 / ((v : K × K).2 + 1) :=
rfl
end circleEquivGen
private theorem coprime_sq_sub_sq_add_of_even_odd {m n : ℤ} (h : Int.gcd m n = 1) (hm : m % 2 = 0)
(hn : n % 2 = 1) : Int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 := by
by_contra H
obtain ⟨p, hp, hp1, hp2⟩ := Nat.Prime.not_coprime_iff_dvd.mp H
rw [← Int.natCast_dvd] at hp1 hp2
have h2m : (p : ℤ) ∣ 2 * m ^ 2 := by
convert dvd_add hp2 hp1 using 1
ring
have h2n : (p : ℤ) ∣ 2 * n ^ 2 := by
convert dvd_sub hp2 hp1 using 1
ring
have hmc : p = 2 ∨ p ∣ Int.natAbs m := prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2m
have hnc : p = 2 ∨ p ∣ Int.natAbs n := prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2n
by_cases h2 : p = 2
· have h3 : (m ^ 2 + n ^ 2) % 2 = 1 := by
simp only [sq, Int.add_emod, Int.mul_emod, hm, hn, dvd_refl, Int.emod_emod_of_dvd]
decide
have h4 : (m ^ 2 + n ^ 2) % 2 = 0 := by
apply Int.emod_eq_zero_of_dvd
rwa [h2] at hp2
rw [h4] at h3
exact zero_ne_one h3
· apply hp.not_dvd_one
rw [← h]
exact Nat.dvd_gcd (Or.resolve_left hmc h2) (Or.resolve_left hnc h2)
private theorem coprime_sq_sub_sq_add_of_odd_even {m n : ℤ} (h : Int.gcd m n = 1) (hm : m % 2 = 1)
(hn : n % 2 = 0) : Int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 := by
rw [Int.gcd, ← Int.natAbs_neg (m ^ 2 - n ^ 2)]
rw [(by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2), add_comm]
apply coprime_sq_sub_sq_add_of_even_odd _ hn hm; rwa [Int.gcd_comm]
private theorem coprime_sq_sub_mul_of_even_odd {m n : ℤ} (h : Int.gcd m n = 1) (hm : m % 2 = 0)
(hn : n % 2 = 1) : Int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := by
by_contra H
obtain ⟨p, hp, hp1, hp2⟩ := Nat.Prime.not_coprime_iff_dvd.mp H
rw [← Int.natCast_dvd] at hp1 hp2
have hnp : ¬(p : ℤ) ∣ Int.gcd m n := by
rw [h]
norm_cast
exact mt Nat.dvd_one.mp (Nat.Prime.ne_one hp)
rcases Int.Prime.dvd_mul hp hp2 with hp2m | hpn
· rw [Int.natAbs_mul] at hp2m
rcases (Nat.Prime.dvd_mul hp).mp hp2m with hp2 | hpm
· have hp2' : p = 2 := (Nat.le_of_dvd zero_lt_two hp2).antisymm hp.two_le
revert hp1
rw [hp2']
apply mt Int.emod_eq_zero_of_dvd
simp only [sq, Nat.cast_ofNat, Int.sub_emod, Int.mul_emod, hm, hn,
mul_zero, EuclideanDomain.zero_mod, mul_one, zero_sub]
decide
apply mt (Int.dvd_coe_gcd (Int.natCast_dvd.mpr hpm)) hnp
apply or_self_iff.mp
apply Int.Prime.dvd_mul' hp
rw [(by ring : n * n = -(m ^ 2 - n ^ 2) + m * m)]
exact hp1.neg_right.add ((Int.natCast_dvd.2 hpm).mul_right _)
rw [Int.gcd_comm] at hnp
apply mt (Int.dvd_coe_gcd (Int.natCast_dvd.mpr hpn)) hnp
apply or_self_iff.mp
apply Int.Prime.dvd_mul' hp
rw [(by ring : m * m = m ^ 2 - n ^ 2 + n * n)]
apply dvd_add hp1
exact (Int.natCast_dvd.mpr hpn).mul_right n
private theorem coprime_sq_sub_mul_of_odd_even {m n : ℤ} (h : Int.gcd m n = 1) (hm : m % 2 = 1)
(hn : n % 2 = 0) : Int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := by
rw [Int.gcd, ← Int.natAbs_neg (m ^ 2 - n ^ 2)]
rw [(by ring : 2 * m * n = 2 * n * m), (by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2)]
apply coprime_sq_sub_mul_of_even_odd _ hn hm; rwa [Int.gcd_comm]
private theorem coprime_sq_sub_mul {m n : ℤ} (h : Int.gcd m n = 1)
(hmn : m % 2 = 0 ∧ n % 2 = 1 ∨ m % 2 = 1 ∧ n % 2 = 0) :
Int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := by
rcases hmn with h1 | h2
· exact coprime_sq_sub_mul_of_even_odd h h1.left h1.right
· exact coprime_sq_sub_mul_of_odd_even h h2.left h2.right
private theorem coprime_sq_sub_sq_sum_of_odd_odd {m n : ℤ} (h : Int.gcd m n = 1) (hm : m % 2 = 1)
(hn : n % 2 = 1) :
2 ∣ m ^ 2 + n ^ 2 ∧
2 ∣ m ^ 2 - n ^ 2 ∧
(m ^ 2 - n ^ 2) / 2 % 2 = 0 ∧ Int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1 := by
obtain ⟨m0, hm2⟩ := exists_eq_mul_left_of_dvd (Int.dvd_self_sub_of_emod_eq hm)
obtain ⟨n0, hn2⟩ := exists_eq_mul_left_of_dvd (Int.dvd_self_sub_of_emod_eq hn)
rw [sub_eq_iff_eq_add] at hm2 hn2
subst m
subst n
have h1 : (m0 * 2 + 1) ^ 2 + (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 + n0 ^ 2 + m0 + n0) + 1) := by
ring
have h2 : (m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 - n0 ^ 2 + m0 - n0)) := by ring
have h3 : ((m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2) / 2 % 2 = 0 := by
rw [h2, Int.mul_ediv_cancel_left, Int.mul_emod_right]
decide
refine ⟨⟨_, h1⟩, ⟨_, h2⟩, h3, ?_⟩
have h20 : (2 : ℤ) ≠ 0 := by decide
rw [h1, h2, Int.mul_ediv_cancel_left _ h20, Int.mul_ediv_cancel_left _ h20]
by_contra h4
obtain ⟨p, hp, hp1, hp2⟩ := Nat.Prime.not_coprime_iff_dvd.mp h4
apply hp.not_dvd_one
rw [← h]
rw [← Int.natCast_dvd] at hp1 hp2
apply Nat.dvd_gcd
· apply Int.Prime.dvd_natAbs_of_coe_dvd_sq hp
convert dvd_add hp1 hp2
ring
· apply Int.Prime.dvd_natAbs_of_coe_dvd_sq hp
convert dvd_sub hp2 hp1
ring
namespace PythagoreanTriple
variable {x y z : ℤ} (h : PythagoreanTriple x y z)
theorem isPrimitiveClassified_aux (hc : x.gcd y = 1) (hzpos : 0 < z) {m n : ℤ}
(hm2n2 : 0 < m ^ 2 + n ^ 2) (hv2 : (x : ℚ) / z = 2 * m * n / ((m : ℚ) ^ 2 + (n : ℚ) ^ 2))
(hw2 : (y : ℚ) / z = ((m : ℚ) ^ 2 - (n : ℚ) ^ 2) / ((m : ℚ) ^ 2 + (n : ℚ) ^ 2))
(H : Int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1) (co : Int.gcd m n = 1)
(pp : m % 2 = 0 ∧ n % 2 = 1 ∨ m % 2 = 1 ∧ n % 2 = 0) : h.IsPrimitiveClassified := by
have hz : z ≠ 0 := ne_of_gt hzpos
have h2 : y = m ^ 2 - n ^ 2 ∧ z = m ^ 2 + n ^ 2 := by
apply Rat.div_int_inj hzpos hm2n2 (h.coprime_of_coprime hc) H
rw [hw2]
norm_cast
use m, n
apply And.intro _ (And.intro co pp)
right
refine ⟨?_, h2.left⟩
rw [← Rat.coe_int_inj _ _, ← div_left_inj' ((mt (Rat.coe_int_inj z 0).mp) hz), hv2, h2.right]
norm_cast
theorem isPrimitiveClassified_of_coprime_of_odd_of_pos (hc : Int.gcd x y = 1) (hyo : y % 2 = 1)
(hzpos : 0 < z) : h.IsPrimitiveClassified := by
by_cases h0 : x = 0
· exact h.isPrimitiveClassified_of_coprime_of_zero_left hc h0
let v := (x : ℚ) / z
let w := (y : ℚ) / z
have hq : v ^ 2 + w ^ 2 = 1 := by
simp [field, v, w]
simp only [sq]
norm_cast
have hvz : v ≠ 0 := by simp [field, v, -mul_eq_zero, -div_eq_zero_iff, h0]
have hw1 : w ≠ -1 := by
contrapose! hvz with hw1
rw [hw1, neg_sq, one_pow, add_eq_right] at hq
exact eq_zero_of_pow_eq_zero hq
have hQ : ∀ x : ℚ, 1 + x ^ 2 ≠ 0 := by
intro q
apply ne_of_gt
exact lt_add_of_pos_of_le zero_lt_one (sq_nonneg q)
have hp : (⟨v, w⟩ : ℚ × ℚ) ∈ { p : ℚ × ℚ | p.1 ^ 2 + p.2 ^ 2 = 1 ∧ p.2 ≠ -1 } := ⟨hq, hw1⟩
let q := (circleEquivGen hQ).symm ⟨⟨v, w⟩, hp⟩
have ht4 : v = 2 * q / (1 + q ^ 2) ∧ w = (1 - q ^ 2) / (1 + q ^ 2) := by
apply Prod.mk.inj
exact congr_arg Subtype.val ((circleEquivGen hQ).apply_symm_apply ⟨⟨v, w⟩, hp⟩).symm
let m := (q.den : ℤ)
let n := q.num
have hm0 : m ≠ 0 := by
-- Added to adapt to https://github.com/leanprover/lean4/pull/2734.
-- Without `unfold`, `norm_cast` can't see the coercion.
-- One might try `zeta := true` in `Tactic.NormCast.derive`,
-- but that seems to break many other things.
unfold m
norm_cast
apply Rat.den_nz q
have hq2 : q = n / m := (Rat.num_div_den q).symm
have hm2n2 : 0 < m ^ 2 + n ^ 2 := by positivity
have hm2n20 : (m ^ 2 + n ^ 2 : ℚ) ≠ 0 := by positivity
have hw2 : w = ((m : ℚ) ^ 2 - (n : ℚ) ^ 2) / ((m : ℚ) ^ 2 + (n : ℚ) ^ 2) := by
calc
w = (1 - q ^ 2) / (1 + q ^ 2) := by apply ht4.2
_ = (1 - (↑n / ↑m) ^ 2) / (1 + (↑n / ↑m) ^ 2) := by rw [hq2]
_ = _ := by field
have hv2 : v = 2 * m * n / ((m : ℚ) ^ 2 + (n : ℚ) ^ 2) := by
calc
v = 2 * q / (1 + q ^ 2) := by apply ht4.1
_ = 2 * (n / m) / (1 + (↑n / ↑m) ^ 2) := by rw [hq2]
_ = _ := by field
have hnmcp : Int.gcd n m = 1 := q.reduced
have hmncp : Int.gcd m n = 1 := by
rw [Int.gcd_comm]
exact hnmcp
rcases Int.emod_two_eq_zero_or_one m with hm2 | hm2 <;>
rcases Int.emod_two_eq_zero_or_one n with hn2 | hn2
· -- m even, n even
exfalso
have h1 : 2 ∣ (Int.gcd n m : ℤ) :=
Int.dvd_coe_gcd (Int.dvd_of_emod_eq_zero hn2) (Int.dvd_of_emod_eq_zero hm2)
cutsat
· -- m even, n odd
apply h.isPrimitiveClassified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp
· apply Or.intro_left
exact And.intro hm2 hn2
· apply coprime_sq_sub_sq_add_of_even_odd hmncp hm2 hn2
· -- m odd, n even
apply h.isPrimitiveClassified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp
· apply Or.intro_right
exact And.intro hm2 hn2
apply coprime_sq_sub_sq_add_of_odd_even hmncp hm2 hn2
· -- m odd, n odd
exfalso
have h1 :
2 ∣ m ^ 2 + n ^ 2 ∧
2 ∣ m ^ 2 - n ^ 2 ∧
(m ^ 2 - n ^ 2) / 2 % 2 = 0 ∧ Int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1 :=
coprime_sq_sub_sq_sum_of_odd_odd hmncp hm2 hn2
have h2 : y = (m ^ 2 - n ^ 2) / 2 ∧ z = (m ^ 2 + n ^ 2) / 2 := by
apply Rat.div_int_inj hzpos _ (h.coprime_of_coprime hc) h1.2.2.2
· change w = _
rw [← Rat.divInt_eq_div, ← Rat.divInt_mul_right (by simp : (2 : ℤ) ≠ 0)]
rw [Int.ediv_mul_cancel h1.1, Int.ediv_mul_cancel h1.2.1, hw2, Rat.divInt_eq_div]
norm_cast
· cutsat
norm_num [h2.1, h1.2.2.1] at hyo
theorem isPrimitiveClassified_of_coprime_of_pos (hc : Int.gcd x y = 1) (hzpos : 0 < z) :
h.IsPrimitiveClassified := by
rcases h.even_odd_of_coprime hc with h1 | h2
· exact h.isPrimitiveClassified_of_coprime_of_odd_of_pos hc h1.right hzpos
rw [Int.gcd_comm] at hc
obtain ⟨m, n, H⟩ := h.symm.isPrimitiveClassified_of_coprime_of_odd_of_pos hc h2.left hzpos
use m, n; tauto
theorem isPrimitiveClassified_of_coprime (hc : Int.gcd x y = 1) : h.IsPrimitiveClassified := by
by_cases! hz : 0 < z
· exact h.isPrimitiveClassified_of_coprime_of_pos hc hz
have h' : PythagoreanTriple x y (-z) := by simpa [PythagoreanTriple, neg_mul_neg] using h.eq
apply h'.isPrimitiveClassified_of_coprime_of_pos hc
apply lt_of_le_of_ne _ (h'.ne_zero_of_coprime hc).symm
exact le_neg.mp hz
theorem classified : h.IsClassified := by
by_cases h0 : Int.gcd x y = 0
· have hx : x = 0 := by
apply Int.natAbs_eq_zero.mp
apply Nat.eq_zero_of_gcd_eq_zero_left h0
have hy : y = 0 := by
apply Int.natAbs_eq_zero.mp
apply Nat.eq_zero_of_gcd_eq_zero_right h0
use 0, 1, 0
simp [hx, hy]
apply h.isClassified_of_normalize_isPrimitiveClassified
apply h.normalize.isPrimitiveClassified_of_coprime
apply Int.gcd_div_gcd_div_gcd (Nat.pos_of_ne_zero h0)
theorem coprime_classification :
PythagoreanTriple x y z ∧ Int.gcd x y = 1 ↔
∃ m n,
(x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n ∨ x = 2 * m * n ∧ y = m ^ 2 - n ^ 2) ∧
(z = m ^ 2 + n ^ 2 ∨ z = -(m ^ 2 + n ^ 2)) ∧
Int.gcd m n = 1 ∧ (m % 2 = 0 ∧ n % 2 = 1 ∨ m % 2 = 1 ∧ n % 2 = 0) := by
constructor
· intro h
obtain ⟨m, n, H⟩ := h.left.isPrimitiveClassified_of_coprime h.right
use m, n
rcases H with ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co, pp⟩
· refine ⟨Or.inl ⟨rfl, rfl⟩, ?_, co, pp⟩
have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2 := by
rw [sq, ← h.left.eq]
ring
simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this
· refine ⟨Or.inr ⟨rfl, rfl⟩, ?_, co, pp⟩
have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2 := by
rw [sq, ← h.left.eq]
ring
simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this
· delta PythagoreanTriple
rintro ⟨m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl, co, pp⟩ <;>
first
| constructor; ring; exact coprime_sq_sub_mul co pp
| constructor; ring; rw [Int.gcd_comm]; exact coprime_sq_sub_mul co pp
/-- By assuming `x` is odd and `z` is positive we get a slightly more precise classification of
the Pythagorean triple `x ^ 2 + y ^ 2 = z ^ 2`. -/
theorem coprime_classification' {x y z : ℤ} (h : PythagoreanTriple x y z)
(h_coprime : Int.gcd x y = 1) (h_parity : x % 2 = 1) (h_pos : 0 < z) :
∃ m n,
x = m ^ 2 - n ^ 2 ∧
y = 2 * m * n ∧
z = m ^ 2 + n ^ 2 ∧
Int.gcd m n = 1 ∧ (m % 2 = 0 ∧ n % 2 = 1 ∨ m % 2 = 1 ∧ n % 2 = 0) ∧ 0 ≤ m := by
obtain ⟨m, n, ht1, ht2, ht3, ht4⟩ :=
PythagoreanTriple.coprime_classification.mp (And.intro h h_coprime)
rcases le_or_gt 0 m with hm | hm
· use m, n
rcases ht1 with h_odd | h_even
· apply And.intro h_odd.1
apply And.intro h_odd.2
rcases ht2 with h_pos | h_neg
· apply And.intro h_pos (And.intro ht3 (And.intro ht4 hm))
· exfalso
revert h_pos
rw [h_neg]
exact imp_false.mpr (not_lt.mpr (neg_nonpos.mpr (by positivity)))
exfalso
rcases h_even with ⟨rfl, -⟩
rw [mul_assoc, Int.mul_emod_right] at h_parity
exact zero_ne_one h_parity
· use -m, -n
rcases ht1 with h_odd | h_even
· rw [neg_sq m]
rw [neg_sq n]
apply And.intro h_odd.1
constructor
· rw [h_odd.2]
ring
rcases ht2 with h_pos | h_neg
· apply And.intro h_pos
constructor
· delta Int.gcd
rw [Int.natAbs_neg, Int.natAbs_neg]
exact ht3
· rw [Int.neg_emod_two, Int.neg_emod_two]
apply And.intro ht4
cutsat
· exfalso
revert h_pos
rw [h_neg]
exact imp_false.mpr (not_lt.mpr (neg_nonpos.mpr (by positivity)))
exfalso
rcases h_even with ⟨rfl, -⟩
rw [mul_assoc, Int.mul_emod_right] at h_parity
exact zero_ne_one h_parity
/-- **Formula for Pythagorean Triples** -/
theorem classification :
PythagoreanTriple x y z ↔
∃ k m n,
(x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n) ∨
x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2)) ∧
(z = k * (m ^ 2 + n ^ 2) ∨ z = -k * (m ^ 2 + n ^ 2)) := by
constructor
· intro h
obtain ⟨k, m, n, H⟩ := h.classified
use k, m, n
rcases H with (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩)
· refine ⟨Or.inl ⟨rfl, rfl⟩, ?_⟩
have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2 := by
rw [sq, ← h.eq]
ring
simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this
· refine ⟨Or.inr ⟨rfl, rfl⟩, ?_⟩
have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2 := by
rw [sq, ← h.eq]
ring
simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this
· rintro ⟨k, m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl⟩ <;> delta PythagoreanTriple <;> ring
end PythagoreanTriple |
.lake/packages/mathlib/Mathlib/NumberTheory/Harmonic/Int.lean | import Mathlib.NumberTheory.Harmonic.Defs
import Mathlib.NumberTheory.Padics.PadicNumbers
import Mathlib.Tactic.Positivity
/-!
The nth Harmonic number is not an integer. We formalize the proof using
2-adic valuations. This proof is due to Kürschák.
Reference:
https://kconrad.math.uconn.edu/blurbs/gradnumthy/padicharmonicsum.pdf
-/
lemma harmonic_pos {n : ℕ} (Hn : n ≠ 0) : 0 < harmonic n := by
unfold harmonic
rw [← Finset.nonempty_range_iff] at Hn
positivity
/-- The 2-adic valuation of the n-th harmonic number is the negative of the logarithm of n. -/
theorem padicValRat_two_harmonic (n : ℕ) : padicValRat 2 (harmonic n) = -Nat.log 2 n := by
induction n with
| zero => simp
| succ n ih =>
rcases eq_or_ne n 0 with rfl | hn
· simp
rw [harmonic_succ]
have key : padicValRat 2 (harmonic n) ≠ padicValRat 2 (↑(n + 1))⁻¹ := by
rw [ih, padicValRat.inv, padicValRat.of_nat, Ne, neg_inj, Nat.cast_inj]
exact Nat.log_ne_padicValNat_succ hn
rw [padicValRat.add_eq_min (harmonic_succ n ▸ (harmonic_pos n.succ_ne_zero).ne')
(harmonic_pos hn).ne' (inv_ne_zero (Nat.cast_ne_zero.mpr n.succ_ne_zero)) key, ih,
padicValRat.inv, padicValRat.of_nat, min_neg_neg, neg_inj, ← Nat.cast_max, Nat.cast_inj]
exact Nat.max_log_padicValNat_succ_eq_log_succ n
/-- The 2-adic norm of the n-th harmonic number is 2 raised to the logarithm of n in base 2. -/
lemma padicNorm_two_harmonic {n : ℕ} (hn : n ≠ 0) :
‖(harmonic n : ℚ_[2])‖ = 2 ^ (Nat.log 2 n) := by
rw [Padic.eq_padicNorm, padicNorm.eq_zpow_of_nonzero (harmonic_pos hn).ne',
padicValRat_two_harmonic, neg_neg, zpow_natCast, Rat.cast_pow, Rat.cast_natCast, Nat.cast_ofNat]
/-- The n-th harmonic number is not an integer for n ≥ 2. -/
theorem harmonic_not_int {n : ℕ} (h : 2 ≤ n) : ¬ (harmonic n).isInt := by
apply padicNorm.not_int_of_not_padic_int 2
rw [padicNorm.eq_zpow_of_nonzero (harmonic_pos (ne_zero_of_lt h)).ne',
padicValRat_two_harmonic, neg_neg, zpow_natCast]
exact one_lt_pow₀ one_lt_two (Nat.log_pos one_lt_two h).ne' |
.lake/packages/mathlib/Mathlib/NumberTheory/Harmonic/GammaDeriv.lean | import Mathlib.Analysis.Convex.Deriv
import Mathlib.Analysis.SpecialFunctions.Gamma.Deligne
import Mathlib.Data.Nat.Factorial.Basic
import Mathlib.NumberTheory.Harmonic.EulerMascheroni
/-!
# Derivative of Γ at positive integers
We prove the formula for the derivative of `Real.Gamma` at a positive integer:
`deriv Real.Gamma (n + 1) = Nat.factorial n * (-Real.eulerMascheroniConstant + harmonic n)`
-/
open Nat Set Filter Topology
local notation "γ" => Real.eulerMascheroniConstant
namespace Real
/-- Explicit formula for the derivative of the Gamma function at positive integers, in terms of
harmonic numbers and the Euler-Mascheroni constant `γ`. -/
lemma deriv_Gamma_nat (n : ℕ) :
deriv Gamma (n + 1) = n ! * (-γ + harmonic n) := by
/- This follows from two properties of the function `f n = log (Gamma n)`:
firstly, the elementary computation that `deriv f (n + 1) = deriv f n + 1 / n`, so that
`deriv f n = deriv f 1 + harmonic n`; secondly, the convexity of `f` (the Bohr-Mollerup theorem),
which shows that `deriv f n` is `log n + o(1)` as `n → ∞`. -/
let f := log ∘ Gamma
-- First reduce to computing derivative of `log ∘ Gamma`.
suffices deriv (log ∘ Gamma) (n + 1) = -γ + harmonic n by
rwa [Function.comp_def, deriv.log (differentiableAt_Gamma (fun m ↦ by linarith))
(by positivity), Gamma_nat_eq_factorial, div_eq_iff_mul_eq (by positivity),
mul_comm, Eq.comm] at this
have hc : ConvexOn ℝ (Ioi 0) f := convexOn_log_Gamma
have h_rec (x : ℝ) (hx : 0 < x) : f (x + 1) = f x + log x := by simp only [f, Function.comp_apply,
Gamma_add_one hx.ne', log_mul hx.ne' (Gamma_pos_of_pos hx).ne', add_comm]
have hder {x : ℝ} (hx : 0 < x) : DifferentiableAt ℝ f x := by
refine ((differentiableAt_Gamma ?_).log (Gamma_ne_zero ?_)) <;>
exact fun m ↦ ne_of_gt (by linarith)
-- Express derivative at general `n` in terms of value at `1` using recurrence relation
have hder_rec (x : ℝ) (hx : 0 < x) : deriv f (x + 1) = deriv f x + 1 / x := by
rw [← deriv_comp_add_const, one_div, ← deriv_log,
← deriv_add (hder <| by positivity) (differentiableAt_log hx.ne')]
apply EventuallyEq.deriv_eq
filter_upwards [eventually_gt_nhds hx] using h_rec
have hder_nat (n : ℕ) : deriv f (n + 1) = deriv f 1 + harmonic n := by
induction n with
| zero => simp
| succ n hn =>
rw [cast_succ, hder_rec (n + 1) (by positivity), hn, harmonic_succ]
push_cast
ring
suffices -deriv f 1 = γ by rw [hder_nat n, ← this, neg_neg]
-- Use convexity to show derivative of `f` at `n + 1` is between `log n` and `log (n + 1)`
have derivLB (n : ℕ) (hn : 0 < n) : log n ≤ deriv f (n + 1) := by
refine (le_of_eq ?_).trans <| hc.slope_le_deriv (mem_Ioi.mpr <| Nat.cast_pos.mpr hn)
(by positivity : _ < (_ : ℝ)) (by linarith) (hder <| by positivity)
rw [slope_def_field, show n + 1 - n = (1 : ℝ) by ring, div_one, h_rec n (by positivity),
add_sub_cancel_left]
have derivUB (n : ℕ) : deriv f (n + 1) ≤ log (n + 1) := by
refine (hc.deriv_le_slope (by positivity : (0 : ℝ) < n + 1) (by positivity : (0 : ℝ) < n + 2)
(by linarith) (hder <| by positivity)).trans (le_of_eq ?_)
rw [slope_def_field, show n + 2 - (n + 1) = (1 : ℝ) by ring, div_one,
show n + 2 = (n + 1) + (1 : ℝ) by ring, h_rec (n + 1) (by positivity), add_sub_cancel_left]
-- deduce `-deriv f 1` is bounded above + below by sequences which both tend to `γ`
apply le_antisymm
· apply ge_of_tendsto tendsto_harmonic_sub_log
filter_upwards [eventually_gt_atTop 0] with n hn
rw [le_sub_iff_add_le', ← sub_eq_add_neg, sub_le_iff_le_add', ← hder_nat]
exact derivLB n hn
· apply le_of_tendsto tendsto_harmonic_sub_log_add_one
filter_upwards with n
rw [sub_le_iff_le_add', ← sub_eq_add_neg, le_sub_iff_add_le', ← hder_nat]
exact derivUB n
lemma hasDerivAt_Gamma_nat (n : ℕ) :
HasDerivAt Gamma (n ! * (-γ + harmonic n)) (n + 1) :=
(deriv_Gamma_nat n).symm ▸
(differentiableAt_Gamma fun m ↦ (by linarith : (n : ℝ) + 1 ≠ -m)).hasDerivAt
lemma eulerMascheroniConstant_eq_neg_deriv : γ = -deriv Gamma 1 := by
rw [show (1 : ℝ) = ↑(0 : ℕ) + 1 by simp, deriv_Gamma_nat 0]
simp
lemma hasDerivAt_Gamma_one : HasDerivAt Gamma (-γ) 1 := by
simpa only [factorial_zero, cast_one, harmonic_zero, Rat.cast_zero, add_zero, mul_neg, one_mul,
cast_zero, zero_add] using hasDerivAt_Gamma_nat 0
lemma hasDerivAt_Gamma_one_half : HasDerivAt Gamma (-√π * (γ + 2 * log 2)) (1 / 2) := by
have h_diff {s : ℝ} (hs : 0 < s) : DifferentiableAt ℝ Gamma s :=
differentiableAt_Gamma fun m ↦ ((neg_nonpos.mpr m.cast_nonneg).trans_lt hs).ne'
have h_diff' {s : ℝ} (hs : 0 < s) : DifferentiableAt ℝ (fun s ↦ Gamma (2 * s)) s :=
.comp (g := Gamma) _ (h_diff <| mul_pos two_pos hs) (differentiableAt_id.const_mul _)
refine (h_diff one_half_pos).hasDerivAt.congr_deriv ?_
-- We calculate the deriv of Gamma at 1/2 using the doubling formula, since we already know
-- the derivative of Gamma at 1.
calc deriv Gamma (1 / 2)
_ = (deriv (fun s ↦ Gamma s * Gamma (s + 1 / 2)) (1 / 2)) + √π * γ := by
rw [deriv_fun_mul, Gamma_one_half_eq,
add_assoc, ← mul_add, deriv_comp_add_const,
(by norm_num : 1 / 2 + 1 / 2 = (1 : ℝ)), Gamma_one, mul_one,
eulerMascheroniConstant_eq_neg_deriv, add_neg_cancel, mul_zero, add_zero]
· apply h_diff; simp -- s = 1
· exact ((h_diff (by simp)).hasDerivAt.comp_add_const).differentiableAt -- s = 1
_ = (deriv (fun s ↦ Gamma (2 * s) * 2 ^ (1 - 2 * s) * √π) (1 / 2)) + √π * γ := by
rw [funext Gamma_mul_Gamma_add_half]
_ = √π * (deriv (fun s ↦ Gamma (2 * s) * 2 ^ (1 - 2 * s)) (1 / 2) + γ) := by
rw [mul_comm √π, mul_comm √π, deriv_mul_const, add_mul]
apply DifferentiableAt.mul
· exact .comp (g := Gamma) _ (by apply h_diff; simp) -- s = 1
(differentiableAt_id.const_mul _)
· exact (differentiableAt_const _).rpow (by fun_prop) two_ne_zero
_ = √π * (deriv (fun s ↦ Gamma (2 * s)) (1 / 2) +
deriv (fun s : ℝ ↦ 2 ^ (1 - 2 * s)) (1 / 2) + γ) := by
congr 2
rw [deriv_fun_mul]
· congr 1 <;> norm_num
· exact h_diff' one_half_pos
· exact DifferentiableAt.rpow (by fun_prop) (by fun_prop) two_ne_zero
_ = √π * (-2 * γ + deriv (fun s : ℝ ↦ 2 ^ (1 - 2 * s)) (1 / 2) + γ) := by
congr 3
change deriv (Gamma ∘ fun s ↦ 2 * s) _ = _
rw [deriv_comp, deriv_const_mul, mul_one_div, div_self two_ne_zero, deriv_id''] <;>
dsimp only
· rw [mul_one, mul_comm, hasDerivAt_Gamma_one.deriv, mul_neg, neg_mul]
· fun_prop
· apply h_diff; simp -- s = 1
· fun_prop
_ = √π * (-2 * γ + -(2 * log 2) + γ) := by
congr 3
apply HasDerivAt.deriv
have := HasDerivAt.rpow (hasDerivAt_const (1 / 2 : ℝ) (2 : ℝ))
(?_ : HasDerivAt (fun s : ℝ ↦ 1 - 2 * s) (-2) (1 / 2)) two_pos
· norm_num at this; exact this
simp_rw [mul_comm (2 : ℝ) _]
apply HasDerivAt.const_sub
exact hasDerivAt_mul_const (2 : ℝ)
_ = -√π * (γ + 2 * log 2) := by ring
end Real
namespace Complex
open scoped Real
private lemma HasDerivAt.complex_of_real {f : ℂ → ℂ} {g : ℝ → ℝ} {g' s : ℝ}
(hf : DifferentiableAt ℂ f s) (hg : HasDerivAt g g' s) (hfg : ∀ s : ℝ, f ↑s = ↑(g s)) :
HasDerivAt f ↑g' s := by
refine HasDerivAt.congr_deriv hf.hasDerivAt ?_
rw [← (funext hfg ▸ hf.hasDerivAt.comp_ofReal.deriv :)]
exact hg.ofReal_comp.deriv
lemma differentiableAt_Gamma_nat_add_one (n : ℕ) :
DifferentiableAt ℂ Gamma (n + 1) := by
refine differentiableAt_Gamma _ (fun m ↦ ?_)
simp only [Ne, ← ofReal_natCast, ← ofReal_one, ← ofReal_add, ← ofReal_neg, ofReal_inj,
eq_neg_iff_add_eq_zero]
positivity
@[deprecated (since := "2025-06-06")] alias differentiable_at_Gamma_nat_add_one :=
differentiableAt_Gamma_nat_add_one
lemma hasDerivAt_Gamma_nat (n : ℕ) :
HasDerivAt Gamma (n ! * (-γ + harmonic n)) (n + 1) := by
exact_mod_cast HasDerivAt.complex_of_real
(by exact_mod_cast differentiableAt_Gamma_nat_add_one n)
(Real.hasDerivAt_Gamma_nat n) Gamma_ofReal
/-- Explicit formula for the derivative of the complex Gamma function at positive integers, in
terms of harmonic numbers and the Euler-Mascheroni constant `γ`. -/
lemma deriv_Gamma_nat (n : ℕ) :
deriv Gamma (n + 1) = n ! * (-γ + harmonic n) :=
(hasDerivAt_Gamma_nat n).deriv
lemma hasDerivAt_Gamma_one : HasDerivAt Gamma (-γ) 1 := by
simpa only [factorial_zero, cast_one, harmonic_zero, Rat.cast_zero, add_zero, mul_neg, one_mul,
cast_zero, zero_add] using hasDerivAt_Gamma_nat 0
lemma hasDerivAt_Gamma_one_half : HasDerivAt Gamma (-√π * (γ + 2 * log 2)) (1 / 2) := by
have := HasDerivAt.complex_of_real
(differentiableAt_Gamma _ ?_) Real.hasDerivAt_Gamma_one_half Gamma_ofReal
· simpa only [neg_mul, one_div, ofReal_neg, ofReal_mul, ofReal_add, ofReal_ofNat, ofNat_log,
ofReal_inv] using this
· intro m
rw [← ofReal_natCast, ← ofReal_neg, ne_eq, ofReal_inj]
exact ((neg_nonpos.mpr m.cast_nonneg).trans_lt one_half_pos).ne'
lemma hasDerivAt_Gammaℂ_one : HasDerivAt Gammaℂ (-(γ + log (2 * π)) / π) 1 := by
let f (s : ℂ) : ℂ := 2 * (2 * π) ^ (-s)
have : HasDerivAt (fun s : ℂ ↦ 2 * (2 * π : ℂ) ^ (-s)) (-log (2 * π) / π) 1 := by
have := (hasDerivAt_neg' (1 : ℂ)).const_cpow (c := 2 * π)
(Or.inl (by exact_mod_cast Real.two_pi_pos.ne'))
refine (this.const_mul 2).congr_deriv ?_
rw [mul_neg_one, mul_neg, cpow_neg_one, ← div_eq_inv_mul, ← mul_div_assoc,
mul_div_mul_left _ _ two_ne_zero, neg_div]
have := this.mul hasDerivAt_Gamma_one
simp only at this
rwa [Gamma_one, mul_one, cpow_neg_one, ← div_eq_mul_inv, ← div_div, div_self two_ne_zero,
mul_comm (1 / _), mul_one_div, ← _root_.add_div, ← neg_add, add_comm] at this
lemma hasDerivAt_Gammaℝ_one : HasDerivAt Gammaℝ (-(γ + log (4 * π)) / 2) 1 := by
let f (s : ℂ) : ℂ := π ^ (-s / 2)
let g (s : ℂ) : ℂ := Gamma (s / 2)
have aux : (π : ℂ) ^ (1 / 2 : ℂ) = ↑√π := by
rw [Real.sqrt_eq_rpow, ofReal_cpow Real.pi_pos.le, ofReal_div, ofReal_one, ofReal_ofNat]
have aux2 : (√π : ℂ) ≠ 0 := by rw [ofReal_ne_zero]; positivity
have hf : HasDerivAt f (-log π / 2 / √π) 1 := by
have := ((hasDerivAt_neg (1 : ℂ)).div_const 2).const_cpow (c := π) (Or.inr (by simp))
refine this.congr_deriv ?_
rw [mul_assoc, ← mul_div_assoc, mul_neg_one, neg_div, cpow_neg, ← div_eq_inv_mul, aux]
have hg : HasDerivAt g (-√π * (γ + 2 * log 2) / 2) 1 := by
have := hasDerivAt_Gamma_one_half.comp 1 (?_ : HasDerivAt (fun s : ℂ ↦ s / 2) (1 / 2) 1)
· rwa [mul_one_div] at this
· exact (hasDerivAt_id _).div_const _
refine HasDerivAt.congr_deriv (hf.mul hg) ?_
simp only [f]
rw [Gamma_one_half_eq, aux, div_mul_cancel₀ _ aux2, neg_div _ (1 : ℂ), cpow_neg, aux,
mul_div_assoc, ← mul_assoc, mul_neg, inv_mul_cancel₀ aux2, neg_one_mul, ← neg_div,
← _root_.add_div, ← neg_add, add_comm, add_assoc, ← ofReal_log Real.pi_pos.le, ← ofReal_ofNat,
← ofReal_log zero_le_two,
← ofReal_mul, ← Nat.cast_ofNat (R := ℝ), ← Real.log_pow, ← ofReal_add,
← Real.log_mul (by positivity) (by positivity),
Nat.cast_ofNat, ofReal_ofNat, ofReal_log (by positivity)]
norm_num
end Complex |
.lake/packages/mathlib/Mathlib/NumberTheory/Harmonic/Defs.lean | import Mathlib.Data.Rat.Defs
import Mathlib.Algebra.BigOperators.Group.Finset.Basic
/-!
This file defines the harmonic numbers.
* `Mathlib/NumberTheory/Harmonic/Int.lean` proves that the `n`th harmonic number is not an integer.
* `Mathlib/NumberTheory/Harmonic/Bounds.lean` provides basic log bounds.
-/
/-- The nth-harmonic number defined as a finset sum of consecutive reciprocals. -/
def harmonic : ℕ → ℚ := fun n => ∑ i ∈ Finset.range n, (↑(i + 1))⁻¹
@[simp]
lemma harmonic_zero : harmonic 0 = 0 :=
rfl
@[simp]
lemma harmonic_succ (n : ℕ) : harmonic (n + 1) = harmonic n + (↑(n + 1))⁻¹ :=
Finset.sum_range_succ .. |
.lake/packages/mathlib/Mathlib/NumberTheory/Harmonic/ZetaAsymp.lean | import Mathlib.NumberTheory.LSeries.RiemannZeta
import Mathlib.NumberTheory.Harmonic.GammaDeriv
/-!
# Asymptotics of `ζ s` as `s → 1`
The goal of this file is to evaluate the limit of `ζ s - 1 / (s - 1)` as `s → 1`.
### Main results
* `tendsto_riemannZeta_sub_one_div`: the limit of `ζ s - 1 / (s - 1)`, at the filter of punctured
neighbourhoods of 1 in `ℂ`, exists and is equal to the Euler-Mascheroni constant `γ`.
* `riemannZeta_one_ne_zero`: with our definition of `ζ 1` (which is characterised as the limit of
`ζ s - 1 / (s - 1) / Gammaℝ s` as `s → 1`), we have `ζ 1 ≠ 0`.
### Outline of arguments
We consider the sum `F s = ∑' n : ℕ, f (n + 1) s`, where `s` is a real variable and
`f n s = ∫ x in n..(n + 1), (x - n) / x ^ (s + 1)`. We show that `F s` is continuous on `[1, ∞)`,
that `F 1 = 1 - γ`, and that `F s = 1 / (s - 1) - ζ s / s` for `1 < s`.
By combining these formulae, one deduces that the limit of `ζ s - 1 / (s - 1)` at `𝓝[>] (1 : ℝ)`
exists and is equal to `γ`. Finally, using this and the Riemann removable singularity criterion
we obtain the limit along punctured neighbourhoods of 1 in `ℂ`.
-/
open Real Set MeasureTheory Filter Topology
@[inherit_doc] local notation "γ" => eulerMascheroniConstant
namespace ZetaAsymptotics
-- since the intermediate lemmas are of little interest in themselves we put them in a namespace
/-!
## Definitions
-/
/-- Auxiliary function used in studying zeta-function asymptotics. -/
noncomputable def term (n : ℕ) (s : ℝ) : ℝ := ∫ x : ℝ in n..(n + 1), (x - n) / x ^ (s + 1)
/-- Sum of finitely many `term`s. -/
noncomputable def term_sum (s : ℝ) (N : ℕ) : ℝ := ∑ n ∈ Finset.range N, term (n + 1) s
/-- Topological sum of `term`s. -/
noncomputable def term_tsum (s : ℝ) : ℝ := ∑' n, term (n + 1) s
lemma term_nonneg (n : ℕ) (s : ℝ) : 0 ≤ term n s := by
rw [term, intervalIntegral.integral_of_le (by simp)]
refine setIntegral_nonneg measurableSet_Ioc (fun x hx ↦ ?_)
refine div_nonneg ?_ (rpow_nonneg ?_ _)
all_goals linarith [hx.1]
lemma term_welldef {n : ℕ} (hn : 0 < n) {s : ℝ} (hs : 0 < s) :
IntervalIntegrable (fun x : ℝ ↦ (x - n) / x ^ (s + 1)) volume n (n + 1) := by
rw [intervalIntegrable_iff_integrableOn_Icc_of_le (by linarith)]
refine (continuousOn_of_forall_continuousAt fun x hx ↦ ContinuousAt.div ?_ ?_ ?_).integrableOn_Icc
· fun_prop
· apply continuousAt_id.rpow_const (Or.inr <| by linarith)
· exact (rpow_pos_of_pos ((Nat.cast_pos.mpr hn).trans_le hx.1) _).ne'
section s_eq_one
/-!
## Evaluation of the sum for `s = 1`
-/
lemma term_one {n : ℕ} (hn : 0 < n) :
term n 1 = (log (n + 1) - log n) - 1 / (n + 1) := by
have hv : ∀ x ∈ uIcc (n : ℝ) (n + 1), 0 < x := by
intro x hx
rw [uIcc_of_le (by simp only [le_add_iff_nonneg_right, zero_le_one])] at hx
exact (Nat.cast_pos.mpr hn).trans_le hx.1
calc term n 1
_ = ∫ x : ℝ in n..(n + 1), (x - n) / x ^ 2 := by
simp_rw [term, one_add_one_eq_two, ← Nat.cast_two (R := ℝ), rpow_natCast]
_ = ∫ x : ℝ in n..(n + 1), (1 / x - n / x ^ 2) :=
intervalIntegral.integral_congr (fun x hx ↦ by field)
_ = (∫ x : ℝ in n..(n + 1), 1 / x) - n * ∫ x : ℝ in n..(n + 1), 1 / x ^ 2 := by
simp_rw [← mul_one_div (n : ℝ)]
rw [intervalIntegral.integral_sub]
· simp_rw [intervalIntegral.integral_const_mul]
· exact intervalIntegral.intervalIntegrable_one_div (fun x hx ↦ (hv x hx).ne') (by fun_prop)
· exact (intervalIntegral.intervalIntegrable_one_div
(fun x hx ↦ (sq_pos_of_pos (hv x hx)).ne') (by fun_prop)).const_mul _
_ = (log (↑n + 1) - log ↑n) - n * ∫ x : ℝ in n..(n + 1), 1 / x ^ 2 := by
congr 1
rw [integral_one_div_of_pos, log_div]
all_goals positivity
_ = (log (↑n + 1) - log ↑n) - n * ∫ x : ℝ in n..(n + 1), x ^ (-2 : ℝ) := by
congr 2
refine intervalIntegral.integral_congr (fun x hx ↦ ?_)
rw [rpow_neg, one_div, ← Nat.cast_two (R := ℝ), rpow_natCast]
exact (hv x hx).le
_ = log (↑n + 1) - log ↑n - n * (1 / n - 1 / (n + 1)) := by
rw [integral_rpow]
· simp_rw [sub_div, (by norm_num : (-2 : ℝ) + 1 = -1), div_neg, div_one, neg_sub_neg,
rpow_neg_one, ← one_div]
· refine Or.inr ⟨by simp, notMem_uIcc_of_lt ?_ ?_⟩
all_goals positivity
_ = log (↑n + 1) - log ↑n - 1 / (↑n + 1) := by
congr 1
simp [field]
lemma term_sum_one (N : ℕ) : term_sum 1 N = log (N + 1) - harmonic (N + 1) + 1 := by
induction N with
| zero =>
simp_rw [term_sum, Finset.sum_range_zero, harmonic_succ, harmonic_zero,
Nat.cast_zero, zero_add, Nat.cast_one, inv_one, Rat.cast_one, log_one, sub_add_cancel]
| succ N hN =>
unfold term_sum at hN ⊢
rw [Finset.sum_range_succ, hN, harmonic_succ (N + 1),
term_one (by positivity : 0 < N + 1)]
push_cast
ring_nf
/-- The topological sum of `ZetaAsymptotics.term (n + 1) 1` over all `n : ℕ` is `1 - γ`. This is
proved by directly evaluating the sum of the first `N` terms and using the limit definition of `γ`.
-/
lemma term_tsum_one : HasSum (fun n ↦ term (n + 1) 1) (1 - γ) := by
rw [hasSum_iff_tendsto_nat_of_nonneg (fun n ↦ term_nonneg (n + 1) 1)]
change Tendsto (fun N ↦ term_sum 1 N) atTop _
simp_rw [term_sum_one, sub_eq_neg_add]
refine Tendsto.add ?_ tendsto_const_nhds
have := (tendsto_eulerMascheroniSeq'.comp (tendsto_add_atTop_nat 1)).neg
refine this.congr' (Eventually.of_forall (fun n ↦ ?_))
simp_rw [Function.comp_apply, eulerMascheroniSeq', reduceCtorEq, if_false]
push_cast
abel
end s_eq_one
section s_gt_one
/-!
## Evaluation of the sum for `1 < s`
-/
lemma term_of_lt {n : ℕ} (hn : 0 < n) {s : ℝ} (hs : 1 < s) :
term n s = 1 / (s - 1) * (1 / n ^ (s - 1) - 1 / (n + 1) ^ (s - 1))
- n / s * (1 / n ^ s - 1 / (n + 1) ^ s) := by
have hv : ∀ x ∈ uIcc (n : ℝ) (n + 1), 0 < x := by
intro x hx
rw [uIcc_of_le (by simp only [le_add_iff_nonneg_right, zero_le_one])] at hx
exact (Nat.cast_pos.mpr hn).trans_le hx.1
calc term n s
_ = ∫ x : ℝ in n..(n + 1), (x - n) / x ^ (s + 1) := by rfl
_ = ∫ x : ℝ in n..(n + 1), (x ^ (-s) - n * x ^ (-(s + 1))) := by
refine intervalIntegral.integral_congr (fun x hx ↦ ?_)
rw [sub_div, rpow_add_one (hv x hx).ne', mul_comm, ← div_div, div_self (hv x hx).ne',
rpow_neg (hv x hx).le, rpow_neg (hv x hx).le, one_div, rpow_add_one (hv x hx).ne', mul_comm,
div_eq_mul_inv]
_ = (∫ x : ℝ in n..(n + 1), x ^ (-s)) - n * (∫ x : ℝ in n..(n + 1), x ^ (-(s + 1))) := by
rw [intervalIntegral.integral_sub, intervalIntegral.integral_const_mul] <;>
[skip; apply IntervalIntegrable.const_mul] <;>
· refine intervalIntegral.intervalIntegrable_rpow (Or.inr <| notMem_uIcc_of_lt ?_ ?_)
· exact_mod_cast hn
· linarith
_ = 1 / (s - 1) * (1 / n ^ (s - 1) - 1 / (n + 1) ^ (s - 1))
- n / s * (1 / n ^ s - 1 / (n + 1) ^ s) := by
have : 0 ∉ uIcc (n : ℝ) (n + 1) := (lt_irrefl _ <| hv _ ·)
rw [integral_rpow (Or.inr ⟨by linarith, this⟩), integral_rpow (Or.inr ⟨by linarith, this⟩)]
congr 1
· rw [show -s + 1 = -(s - 1) by ring, div_neg, ← neg_div, mul_comm, mul_one_div, neg_sub,
rpow_neg (Nat.cast_nonneg _), one_div, rpow_neg (by linarith), one_div]
· rw [show -(s + 1) + 1 = -s by ring, div_neg, ← neg_div, neg_sub, div_mul_eq_mul_div,
mul_div_assoc, rpow_neg (Nat.cast_nonneg _), one_div, rpow_neg (by linarith), one_div]
lemma term_sum_of_lt (N : ℕ) {s : ℝ} (hs : 1 < s) :
term_sum s N = 1 / (s - 1) * (1 - 1 / (N + 1) ^ (s - 1))
- 1 / s * ((∑ n ∈ Finset.range N, 1 / (n + 1 : ℝ) ^ s) - N / (N + 1) ^ s) := by
simp only [term_sum]
conv => enter [1, 2, n]; rw [term_of_lt (by simp) hs]
rw [Finset.sum_sub_distrib]
congr 1
· induction N with
| zero => simp
| succ N hN =>
rw [Finset.sum_range_succ, hN, Nat.cast_add_one]
ring_nf
· simp_rw [mul_comm (_ / _), ← mul_div_assoc, div_eq_mul_inv _ s, ← Finset.sum_mul, mul_one]
congr 1
induction N with
| zero => simp
| succ N hN =>
simp_rw [Finset.sum_range_succ, hN, Nat.cast_add_one, sub_eq_add_neg, add_assoc]
congr 1
ring_nf
/-- For `1 < s`, the topological sum of `ZetaAsymptotics.term (n + 1) s` over all `n : ℕ` is
`1 / (s - 1) - ζ s / s`.
-/
lemma term_tsum_of_lt {s : ℝ} (hs : 1 < s) :
term_tsum s = (1 / (s - 1) - 1 / s * ∑' n : ℕ, 1 / (n + 1 : ℝ) ^ s) := by
apply HasSum.tsum_eq
rw [hasSum_iff_tendsto_nat_of_nonneg (fun n ↦ term_nonneg (n + 1) s)]
change Tendsto (fun N ↦ term_sum s N) atTop _
simp_rw [term_sum_of_lt _ hs]
apply Tendsto.sub
· rw [show 𝓝 (1 / (s - 1)) = 𝓝 (1 / (s - 1) - 1 / (s - 1) * 0) by simp]
simp_rw [mul_sub, mul_one]
refine tendsto_const_nhds.sub (Tendsto.const_mul _ ?_)
refine tendsto_const_nhds.div_atTop <| (tendsto_rpow_atTop (by linarith)).comp ?_
exact tendsto_atTop_add_const_right _ _ tendsto_natCast_atTop_atTop
· rw [← sub_zero (tsum _)]
apply (((Summable.hasSum ?_).tendsto_sum_nat).sub ?_).const_mul
· exact_mod_cast (summable_nat_add_iff 1).mpr (summable_one_div_nat_rpow.mpr hs)
· apply tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds
· change Tendsto (fun n : ℕ ↦ (1 / ↑(n + 1) : ℝ) ^ (s - 1)) ..
rw [show 𝓝 (0 : ℝ) = 𝓝 (0 ^ (s - 1)) by rw [zero_rpow]; linarith]
refine Tendsto.rpow_const ?_ (Or.inr <| by linarith)
exact (tendsto_const_div_atTop_nhds_zero_nat _).comp (tendsto_add_atTop_nat _)
· intro n
positivity
· intro n
dsimp only
transitivity (n + 1) / (n + 1) ^ s
· gcongr
linarith
· apply le_of_eq
rw [rpow_sub_one, ← div_mul, div_one, mul_comm, one_div, inv_rpow, ← div_eq_mul_inv]
· norm_cast
all_goals positivity
/-- Reformulation of `ZetaAsymptotics.term_tsum_of_lt` which is useful for some computations
below. -/
lemma zeta_limit_aux1 {s : ℝ} (hs : 1 < s) :
(∑' n : ℕ, 1 / (n + 1 : ℝ) ^ s) - 1 / (s - 1) = 1 - s * term_tsum s := by
rw [term_tsum_of_lt hs]
generalize (∑' n : ℕ, 1 / (n + 1 : ℝ) ^ s) = Z
field [(show s - 1 ≠ 0 by linarith)]
end s_gt_one
section continuity
/-!
## Continuity of the sum
-/
lemma continuousOn_term (n : ℕ) :
ContinuousOn (fun x ↦ term (n + 1) x) (Ici 1) := by
-- TODO: can this be shortened using the lemma
-- `continuous_parametric_intervalIntegral_of_continuous'` from https://github.com/leanprover-community/mathlib4/pull/11185?
simp only [term, intervalIntegral.integral_of_le (by linarith : (↑(n + 1) : ℝ) ≤ ↑(n + 1) + 1)]
apply continuousOn_of_dominated (bound := fun x ↦ (x - ↑(n + 1)) / x ^ (2 : ℝ))
· exact fun s hs ↦ (term_welldef (by simp) (zero_lt_one.trans_le hs)).1.1
· intro s (hs : 1 ≤ s)
rw [ae_restrict_iff' measurableSet_Ioc]
filter_upwards with x hx
have : 1 < x := lt_of_le_of_lt (by simp) hx.1
rw [norm_of_nonneg (div_nonneg (sub_nonneg.mpr hx.1.le) (by positivity)), Nat.cast_add_one]
gcongr
· exact_mod_cast sub_nonneg.mpr hx.1.le
· exact this.le
· linarith
· rw [← IntegrableOn, ← intervalIntegrable_iff_integrableOn_Ioc_of_le (by linarith)]
exact_mod_cast term_welldef (by cutsat : 0 < (n + 1)) zero_lt_one
· rw [ae_restrict_iff' measurableSet_Ioc]
filter_upwards with x hx
refine continuousOn_of_forall_continuousAt (fun s (hs : 1 ≤ s) ↦ continuousAt_const.div ?_ ?_)
· exact continuousAt_const.rpow (continuousAt_id.add continuousAt_const) (Or.inr (by linarith))
· exact (rpow_pos_of_pos ((Nat.cast_pos.mpr (by simp)).trans hx.1) _).ne'
lemma continuousOn_term_tsum : ContinuousOn term_tsum (Ici 1) := by
-- We use dominated convergence, using `fun n ↦ term n 1` as our uniform bound (since `term` is
-- monotone decreasing in `s`.)
refine continuousOn_tsum (fun i ↦ continuousOn_term _) term_tsum_one.summable (fun n s hs ↦ ?_)
rw [term, term, norm_of_nonneg]
· simp_rw [intervalIntegral.integral_of_le (by linarith : (↑(n + 1) : ℝ) ≤ ↑(n + 1) + 1)]
refine setIntegral_mono_on ?_ ?_ measurableSet_Ioc (fun x hx ↦ ?_)
· exact (term_welldef n.succ_pos (zero_lt_one.trans_le hs)).1
· exact (term_welldef n.succ_pos zero_lt_one).1
· have : 1 ≤ x := le_trans (by simp) hx.1.le
gcongr
· exact sub_nonneg.mpr hx.1.le
· assumption
· exact hs
· rw [intervalIntegral.integral_of_le (by linarith)]
refine setIntegral_nonneg measurableSet_Ioc (fun x hx ↦ div_nonneg ?_ (rpow_nonneg ?_ _))
all_goals linarith [hx.1]
/-- First version of the limit formula, with a limit over real numbers tending to 1 from above. -/
lemma tendsto_riemannZeta_sub_one_div_nhds_right :
Tendsto (fun s : ℝ ↦ riemannZeta s - 1 / (s - 1)) (𝓝[>] 1) (𝓝 γ) := by
suffices Tendsto (fun s : ℝ ↦ (∑' n : ℕ, 1 / (n + 1 : ℝ) ^ s) - 1 / (s - 1))
(𝓝[>] 1) (𝓝 γ) by
apply ((Complex.continuous_ofReal.tendsto _).comp this).congr'
filter_upwards [self_mem_nhdsWithin] with s hs
simp only [Function.comp_apply, Complex.ofReal_sub, Complex.ofReal_div,
Complex.ofReal_one, sub_left_inj, Complex.ofReal_tsum]
rw [zeta_eq_tsum_one_div_nat_add_one_cpow (by simpa using hs)]
congr 1 with n
rw [Complex.ofReal_cpow (by positivity)]
norm_cast
suffices aux2 : Tendsto (fun s : ℝ ↦ (∑' n : ℕ, 1 / (n + 1 : ℝ) ^ s) - 1 / (s - 1))
(𝓝[>] 1) (𝓝 (1 - term_tsum 1)) by
have := term_tsum_one.tsum_eq
rw [← term_tsum, eq_sub_iff_add_eq, ← eq_sub_iff_add_eq'] at this
simpa only [this] using aux2
apply Tendsto.congr'
· filter_upwards [self_mem_nhdsWithin] with s hs using (zeta_limit_aux1 hs).symm
· apply tendsto_const_nhds.sub
rw [← one_mul (term_tsum 1)]
apply (tendsto_id.mono_left nhdsWithin_le_nhds).mul
have := continuousOn_term_tsum.continuousWithinAt left_mem_Ici
exact Tendsto.mono_left this (nhdsWithin_mono _ Ioi_subset_Ici_self)
/-- The function `ζ s - 1 / (s - 1)` tends to `γ` as `s → 1`. -/
theorem _root_.tendsto_riemannZeta_sub_one_div :
Tendsto (fun s : ℂ ↦ riemannZeta s - 1 / (s - 1)) (𝓝[≠] 1) (𝓝 γ) := by
-- We use the removable-singularity theorem to show that *some* limit over `𝓝[≠] (1 : ℂ)` exists,
-- and then use the previous result to deduce that this limit must be `γ`.
let f (s : ℂ) := riemannZeta s - 1 / (s - 1)
suffices ∃ C, Tendsto f (𝓝[≠] 1) (𝓝 C) by
obtain ⟨C, hC⟩ := this
suffices Tendsto (fun s : ℝ ↦ f s) _ _
from (tendsto_nhds_unique this tendsto_riemannZeta_sub_one_div_nhds_right) ▸ hC
refine hC.comp (tendsto_nhdsWithin_of_tendsto_nhds_of_eventually_within _ ?_ ?_)
· exact (Complex.continuous_ofReal.tendsto 1).mono_left (nhdsWithin_le_nhds ..)
· filter_upwards [self_mem_nhdsWithin] with a ha
rw [mem_compl_singleton_iff, ← Complex.ofReal_one, Ne, Complex.ofReal_inj]
exact ne_of_gt ha
refine ⟨_, Complex.tendsto_limUnder_of_differentiable_on_punctured_nhds_of_isLittleO ?_ ?_⟩
· filter_upwards [self_mem_nhdsWithin] with s hs
refine (differentiableAt_riemannZeta hs).sub ((differentiableAt_const _).div ?_ ?_)
· fun_prop
· rwa [mem_compl_singleton_iff, ← sub_ne_zero] at hs
· refine Asymptotics.isLittleO_of_tendsto' ?_ ?_
· filter_upwards [self_mem_nhdsWithin] with t ht ht'
rw [inv_eq_zero, sub_eq_zero] at ht'
tauto
· simp_rw [div_eq_mul_inv, inv_inv, sub_mul,
(by ring_nf : 𝓝 (0 : ℂ) = 𝓝 ((1 - 1) - f 1 * (1 - 1)))]
apply Tendsto.sub
· simp_rw [mul_comm (f _), f, mul_sub]
apply riemannZeta_residue_one.sub
refine Tendsto.congr' ?_ (tendsto_const_nhds.mono_left nhdsWithin_le_nhds)
filter_upwards [self_mem_nhdsWithin] with x hx
field [sub_ne_zero.mpr <| mem_compl_singleton_iff.mp hx]
· exact ((tendsto_id.sub tendsto_const_nhds).mono_left nhdsWithin_le_nhds).const_mul _
lemma _root_.isBigO_riemannZeta_sub_one_div {F : Type*} [Norm F] [One F] [NormOneClass F] :
(fun s : ℂ ↦ riemannZeta s - 1 / (s - 1)) =O[𝓝 1] (fun _ ↦ 1 : ℂ → F) := by
simpa only [Asymptotics.isBigO_one_nhds_ne_iff] using
tendsto_riemannZeta_sub_one_div.isBigO_one (F := F)
end continuity
section val_at_one
open Complex
lemma tendsto_Gamma_term_aux : Tendsto (fun s ↦ 1 / (s - 1) - 1 / Gammaℝ s / (s - 1)) (𝓝[≠] 1)
(𝓝 (-(γ + Complex.log (4 * ↑π)) / 2)) := by
have h := hasDerivAt_Gammaℝ_one
rw [hasDerivAt_iff_tendsto_slope, slope_fun_def_field, Gammaℝ_one] at h
have := h.div (hasDerivAt_Gammaℝ_one.continuousAt.tendsto.mono_left nhdsWithin_le_nhds)
(Gammaℝ_one.trans_ne one_ne_zero)
rw [Gammaℝ_one, div_one] at this
refine this.congr' ?_
have : {z | 0 < re z} ∈ 𝓝 (1 : ℂ) := by
apply (continuous_re.isOpen_preimage _ isOpen_Ioi).mem_nhds
simp only [mem_preimage, one_re, mem_Ioi, zero_lt_one]
rw [EventuallyEq, eventually_nhdsWithin_iff]
filter_upwards [this] with a ha _
rw [Pi.div_apply, ← sub_div, div_right_comm, sub_div' (Gammaℝ_ne_zero_of_re_pos ha), one_mul]
lemma tendsto_riemannZeta_sub_one_div_Gammaℝ :
Tendsto (fun s ↦ riemannZeta s - 1 / Gammaℝ s / (s - 1)) (𝓝[≠] 1)
(𝓝 ((γ - Complex.log (4 * ↑π)) / 2)) := by
have := tendsto_riemannZeta_sub_one_div.add tendsto_Gamma_term_aux
simp_rw [sub_add_sub_cancel] at this
convert this using 2
ring_nf
/-- Formula for `ζ 1`. Note that mathematically `ζ 1` is undefined, but our construction ascribes
this particular value to it. -/
lemma _root_.riemannZeta_one : riemannZeta 1 = (γ - Complex.log (4 * ↑π)) / 2 := by
have := (HurwitzZeta.tendsto_hurwitzZetaEven_sub_one_div_nhds_one 0).mono_left
<| nhdsWithin_le_nhds (s := {1}ᶜ)
simp only [HurwitzZeta.hurwitzZetaEven_zero, div_right_comm _ _ (Gammaℝ _)] at this
exact tendsto_nhds_unique this tendsto_riemannZeta_sub_one_div_Gammaℝ
/-- Formula for `Λ 1`. Note that mathematically `Λ 1` is undefined, but our construction ascribes
this particular value to it. -/
lemma _root_.completedRiemannZeta_one :
completedRiemannZeta 1 = (γ - Complex.log (4 * ↑π)) / 2 :=
(riemannZeta_one ▸ div_one (_ : ℂ) ▸ Gammaℝ_one ▸ riemannZeta_def_of_ne_zero one_ne_zero).symm
/-- Formula for `Λ₀ 1`, where `Λ₀` is the entire function satisfying
`Λ₀ s = π ^ (-s / 2) Γ(s / 2) ζ(s) + 1 / s + 1 / (1 - s)` away from `s = 0, 1`.
Note that `s = 1` is _not_ a pole of `Λ₀`, so this statement (unlike `riemannZeta_one`) is
a mathematically meaningful statement and is not dependent on Mathlib's particular conventions for
division by zero. -/
lemma _root_.completedRiemannZeta₀_one :
completedRiemannZeta₀ 1 = (γ - Complex.log (4 * ↑π)) / 2 + 1 := by
have := completedRiemannZeta_eq 1
rw [sub_self, div_zero, div_one, sub_zero, eq_sub_iff_add_eq] at this
rw [← this, completedRiemannZeta_one]
/-- With Mathlib's particular conventions, we have `ζ 1 ≠ 0`. -/
lemma _root_.riemannZeta_one_ne_zero : riemannZeta 1 ≠ 0 := by
-- This one's for you, Kevin.
suffices (γ - (4 * π).log) / 2 ≠ 0 by
simpa only [riemannZeta_one, ← ofReal_ne_zero, ofReal_log (by positivity : 0 ≤ 4 * π),
push_cast]
refine div_ne_zero (sub_lt_zero.mpr (lt_trans ?_ ?_ (b := 1))).ne two_ne_zero
· exact Real.eulerMascheroniConstant_lt_two_thirds.trans (by norm_num)
· rw [lt_log_iff_exp_lt (by positivity)]
exact (lt_trans Real.exp_one_lt_d9 (by norm_num)).trans_le
<| mul_le_mul_of_nonneg_left two_le_pi (by simp)
end val_at_one
end ZetaAsymptotics |
.lake/packages/mathlib/Mathlib/NumberTheory/Harmonic/EulerMascheroni.lean | import Mathlib.Analysis.Complex.ExponentialBounds
import Mathlib.Analysis.Normed.Order.Lattice
import Mathlib.Analysis.SpecialFunctions.Pow.Real
import Mathlib.NumberTheory.Harmonic.Defs
/-!
# The Euler-Mascheroni constant `γ`
We define the constant `γ`, and give upper and lower bounds for it.
## Main definitions and results
* `Real.eulerMascheroniConstant`: the constant `γ`
* `Real.tendsto_harmonic_sub_log`: the sequence `n ↦ harmonic n - log n` tends to `γ` as `n → ∞`
* `one_half_lt_eulerMascheroniConstant` and `eulerMascheroniConstant_lt_two_thirds`: upper and
lower bounds.
## Outline of proofs
We show that
* the sequence `eulerMascheroniSeq` given by `n ↦ harmonic n - log (n + 1)` is strictly increasing;
* the sequence `eulerMascheroniSeq'` given by `n ↦ harmonic n - log n`, modified with a junk value
for `n = 0`, is strictly decreasing;
* the difference `eulerMascheroniSeq' n - eulerMascheroniSeq n` is non-negative and tends to 0.
It follows that both sequences tend to a common limit `γ`, and we have the inequality
`eulerMascheroniSeq n < γ < eulerMascheroniSeq' n` for all `n`. Taking `n = 6` gives the bounds
`1 / 2 < γ < 2 / 3`.
-/
open Filter Topology
namespace Real
section LowerSequence
/-- The sequence with `n`-th term `harmonic n - log (n + 1)`. -/
noncomputable def eulerMascheroniSeq (n : ℕ) : ℝ := harmonic n - log (n + 1)
lemma eulerMascheroniSeq_zero : eulerMascheroniSeq 0 = 0 := by
simp [eulerMascheroniSeq, harmonic_zero]
lemma strictMono_eulerMascheroniSeq : StrictMono eulerMascheroniSeq := by
refine strictMono_nat_of_lt_succ (fun n ↦ ?_)
rw [eulerMascheroniSeq, eulerMascheroniSeq, ← sub_pos, sub_sub_sub_comm,
harmonic_succ, add_comm, Rat.cast_add, add_sub_cancel_right,
← log_div (by positivity) (by positivity), add_div, Nat.cast_add_one,
Nat.cast_add_one, div_self (by positivity), sub_pos, one_div, Rat.cast_inv, Rat.cast_add,
Rat.cast_one, Rat.cast_natCast]
refine (log_lt_sub_one_of_pos ?_ (ne_of_gt <| lt_add_of_pos_right _ ?_)).trans_le (le_of_eq ?_)
· positivity
· positivity
· simp only [add_sub_cancel_left]
lemma one_half_lt_eulerMascheroniSeq_six : 1 / 2 < eulerMascheroniSeq 6 := by
have : eulerMascheroniSeq 6 = 49 / 20 - log 7 := by
rw [eulerMascheroniSeq]
norm_num
rw [this, lt_sub_iff_add_lt, ← lt_sub_iff_add_lt', log_lt_iff_lt_exp (by positivity)]
refine lt_of_lt_of_le ?_ (Real.sum_le_exp_of_nonneg (by norm_num) 7)
simp_rw [Finset.sum_range_succ, Nat.factorial_succ]
norm_num
end LowerSequence
section UpperSequence
/-- The sequence with `n`-th term `harmonic n - log n`. We use a junk value for `n = 0`, in order
to have the sequence be strictly decreasing. -/
noncomputable def eulerMascheroniSeq' (n : ℕ) : ℝ :=
if n = 0 then 2 else ↑(harmonic n) - log n
lemma eulerMascheroniSeq'_one : eulerMascheroniSeq' 1 = 1 := by
simp [eulerMascheroniSeq']
lemma strictAnti_eulerMascheroniSeq' : StrictAnti eulerMascheroniSeq' := by
refine strictAnti_nat_of_succ_lt (fun n ↦ ?_)
rcases Nat.eq_zero_or_pos n with rfl | hn
· simp [eulerMascheroniSeq']
simp_rw [eulerMascheroniSeq', eq_false_intro hn.ne', reduceCtorEq, if_false]
rw [← sub_pos, sub_sub_sub_comm,
harmonic_succ, Rat.cast_add, ← sub_sub, sub_self, zero_sub, sub_eq_add_neg, neg_sub,
← sub_eq_neg_add, sub_pos, ← log_div (by positivity) (by positivity), ← neg_lt_neg_iff,
← log_inv]
refine (log_lt_sub_one_of_pos ?_ ?_).trans_le (le_of_eq ?_)
· positivity
· simp [field]
· simp [field]
lemma eulerMascheroniSeq'_six_lt_two_thirds : eulerMascheroniSeq' 6 < 2 / 3 := by
have h1 : eulerMascheroniSeq' 6 = 49 / 20 - log 6 := by
rw [eulerMascheroniSeq']
norm_num
rw [h1, sub_lt_iff_lt_add, ← sub_lt_iff_lt_add', lt_log_iff_exp_lt (by positivity)]
norm_num
have := rpow_lt_rpow (exp_pos _).le exp_one_lt_d9 (by simp : (0 : ℝ) < 107 / 60)
rw [exp_one_rpow] at this
refine lt_trans this ?_
rw [← rpow_lt_rpow_iff (z := 60), ← rpow_mul, div_mul_cancel₀, ← Nat.cast_ofNat,
← Nat.cast_ofNat, rpow_natCast, Nat.cast_ofNat, ← Nat.cast_ofNat (n := 60), rpow_natCast]
· norm_num
all_goals positivity
lemma eulerMascheroniSeq_lt_eulerMascheroniSeq' (m n : ℕ) :
eulerMascheroniSeq m < eulerMascheroniSeq' n := by
have (r : ℕ) : eulerMascheroniSeq r < eulerMascheroniSeq' r := by
rcases eq_zero_or_pos r with rfl | hr
· simp [eulerMascheroniSeq, eulerMascheroniSeq']
simp only [eulerMascheroniSeq, eulerMascheroniSeq', hr.ne', if_false]
gcongr
linarith
apply (strictMono_eulerMascheroniSeq.monotone (le_max_left m n)).trans_lt
exact (this _).trans_le (strictAnti_eulerMascheroniSeq'.antitone (le_max_right m n))
end UpperSequence
/-- The Euler-Mascheroni constant `γ`. -/
noncomputable def eulerMascheroniConstant : ℝ := limUnder atTop eulerMascheroniSeq
lemma tendsto_eulerMascheroniSeq :
Tendsto eulerMascheroniSeq atTop (𝓝 eulerMascheroniConstant) := by
have := tendsto_atTop_ciSup strictMono_eulerMascheroniSeq.monotone ?_
· rwa [eulerMascheroniConstant, this.limUnder_eq]
· exact ⟨_, fun _ ⟨_, hn⟩ ↦ hn ▸ (eulerMascheroniSeq_lt_eulerMascheroniSeq' _ 1).le⟩
lemma tendsto_harmonic_sub_log_add_one :
Tendsto (fun n : ℕ ↦ harmonic n - log (n + 1)) atTop (𝓝 eulerMascheroniConstant) :=
tendsto_eulerMascheroniSeq
lemma tendsto_eulerMascheroniSeq' :
Tendsto eulerMascheroniSeq' atTop (𝓝 eulerMascheroniConstant) := by
suffices Tendsto (fun n ↦ eulerMascheroniSeq' n - eulerMascheroniSeq n) atTop (𝓝 0) by
simpa using this.add tendsto_eulerMascheroniSeq
suffices Tendsto (fun x : ℝ ↦ log (x + 1) - log x) atTop (𝓝 0) by
apply (this.comp tendsto_natCast_atTop_atTop).congr'
filter_upwards [eventually_ne_atTop 0] with n hn
simp [eulerMascheroniSeq, eulerMascheroniSeq', eq_false_intro hn]
exact tendsto_log_comp_add_sub_log 1
lemma tendsto_harmonic_sub_log :
Tendsto (fun n : ℕ ↦ harmonic n - log n) atTop (𝓝 eulerMascheroniConstant) := by
apply tendsto_eulerMascheroniSeq'.congr'
filter_upwards [eventually_ne_atTop 0] with n hn
simp_rw [eulerMascheroniSeq', hn, if_false]
lemma eulerMascheroniSeq_lt_eulerMascheroniConstant (n : ℕ) :
eulerMascheroniSeq n < eulerMascheroniConstant := by
refine (strictMono_eulerMascheroniSeq (Nat.lt_succ_self n)).trans_le ?_
apply strictMono_eulerMascheroniSeq.monotone.ge_of_tendsto tendsto_eulerMascheroniSeq
lemma eulerMascheroniConstant_lt_eulerMascheroniSeq' (n : ℕ) :
eulerMascheroniConstant < eulerMascheroniSeq' n := by
refine lt_of_le_of_lt ?_ (strictAnti_eulerMascheroniSeq' (Nat.lt_succ_self n))
apply strictAnti_eulerMascheroniSeq'.antitone.le_of_tendsto tendsto_eulerMascheroniSeq'
/-- Lower bound for `γ`. (The true value is about 0.57.) -/
lemma one_half_lt_eulerMascheroniConstant : 1 / 2 < eulerMascheroniConstant :=
one_half_lt_eulerMascheroniSeq_six.trans (eulerMascheroniSeq_lt_eulerMascheroniConstant _)
/-- Upper bound for `γ`. (The true value is about 0.57.) -/
lemma eulerMascheroniConstant_lt_two_thirds : eulerMascheroniConstant < 2 / 3 :=
(eulerMascheroniConstant_lt_eulerMascheroniSeq' _).trans eulerMascheroniSeq'_six_lt_two_thirds
end Real |
.lake/packages/mathlib/Mathlib/NumberTheory/Harmonic/Bounds.lean | import Mathlib.Analysis.SpecialFunctions.Integrals.Basic
import Mathlib.Analysis.SumIntegralComparisons
import Mathlib.NumberTheory.Harmonic.Defs
/-!
This file proves $\log(n + 1) \le H_n \le 1 + \log(n)$ for all natural numbers $n$.
-/
lemma harmonic_eq_sum_Icc {n : ℕ} : harmonic n = ∑ i ∈ Finset.Icc 1 n, (↑i)⁻¹ := by
rw [harmonic, Finset.range_eq_Ico, Finset.sum_Ico_add' (fun (i : ℕ) ↦ (i : ℚ)⁻¹) 0 n (c := 1)]
simp only [Finset.Ico_add_one_right_eq_Icc]
theorem log_add_one_le_harmonic (n : ℕ) :
Real.log ↑(n + 1) ≤ harmonic n := by
calc _ = ∫ x in (1 : ℕ)..↑(n + 1), x⁻¹ := ?_
_ ≤ ∑ d ∈ Finset.Icc 1 n, (d : ℝ)⁻¹ := ?_
_ = harmonic n := ?_
· rw [Nat.cast_one, integral_inv (by simp [(show ¬ (1 : ℝ) ≤ 0 by simp)]), div_one]
· exact (inv_antitoneOn_Icc_right <| by simp).integral_le_sum_Ico (Nat.le_add_left 1 n)
· simp only [harmonic_eq_sum_Icc, Rat.cast_sum, Rat.cast_inv, Rat.cast_natCast]
theorem harmonic_le_one_add_log (n : ℕ) :
harmonic n ≤ 1 + Real.log n := by
by_cases hn0 : n = 0
· simp [hn0]
have hn : 1 ≤ n := Nat.one_le_iff_ne_zero.mpr hn0
simp_rw [harmonic_eq_sum_Icc, Rat.cast_sum, Rat.cast_inv, Rat.cast_natCast]
rw [← Finset.sum_erase_add (Finset.Icc 1 n) _ (Finset.left_mem_Icc.mpr hn), add_comm,
Nat.cast_one, inv_one]
gcongr
simp only [Finset.Icc_erase_left]
calc ∑ d ∈ .Ico 2 (n + 1), (d : ℝ)⁻¹
_ = ∑ d ∈ .Ico 2 (n + 1), (↑(d + 1) - 1)⁻¹ := ?_
_ ≤ ∫ x in 2..↑(n + 1), (x - 1)⁻¹ := ?_
_ = ∫ x in 1..n, x⁻¹ := ?_
_ = Real.log ↑n := ?_
· simp_rw [Nat.cast_add, Nat.cast_one, add_sub_cancel_right]
· exact @AntitoneOn.sum_le_integral_Ico 2 (n + 1) (fun x : ℝ ↦ (x - 1)⁻¹) (by linarith [hn]) <|
sub_inv_antitoneOn_Icc_right (by simp)
· convert intervalIntegral.integral_comp_sub_right _ 1
· norm_num
· simp only [Nat.cast_add, Nat.cast_one, add_sub_cancel_right]
· convert integral_inv _
· rw [div_one]
· simp only [Nat.one_le_cast, hn, Set.uIcc_of_le, Set.mem_Icc, Nat.cast_nonneg,
and_true, not_le, zero_lt_one]
theorem log_le_harmonic_floor (y : ℝ) (hy : 0 ≤ y) :
Real.log y ≤ harmonic ⌊y⌋₊ := by
by_cases h0 : y = 0
· simp [h0]
· calc
_ ≤ Real.log ↑(Nat.floor y + 1) := ?_
_ ≤ _ := log_add_one_le_harmonic _
gcongr
apply (Nat.le_ceil y).trans
norm_cast
exact Nat.ceil_le_floor_add_one y
theorem harmonic_floor_le_one_add_log (y : ℝ) (hy : 1 ≤ y) :
harmonic ⌊y⌋₊ ≤ 1 + Real.log y := by
refine (harmonic_le_one_add_log _).trans ?_
gcongr
· exact_mod_cast Nat.floor_pos.mpr hy
· exact Nat.floor_le <| zero_le_one.trans hy |
.lake/packages/mathlib/Mathlib/NumberTheory/Padics/ProperSpace.lean | import Mathlib.Analysis.Normed.Field.ProperSpace
import Mathlib.NumberTheory.Padics.RingHoms
/-!
# Properness of the p-adic numbers
In this file, we prove that `ℤ_[p]` is totally bounded and compact,
and that `ℚ_[p]` is proper.
## Main results
- `PadicInt.totallyBounded_univ` : The set of p-adic integers `ℤ_[p]` is totally bounded.
- `PadicInt.compactSpace` : The set of p-adic integers `ℤ_[p]` is a compact topological space.
- `Padic.instProperSpace` : The field of p-adic numbers `ℚ_[p]` is a proper metric space.
## Notation
- `p` : Is a natural prime.
## References
Gouvêa, F. Q. (2020) p-adic Numbers An Introduction. 3rd edition.
Cham, Springer International Publishing
-/
assert_not_exists FiniteDimensional
open Metric Topology
variable (p : ℕ) [Fact (Nat.Prime p)]
namespace PadicInt
/-- The set of p-adic integers `ℤ_[p]` is totally bounded. -/
theorem totallyBounded_univ : TotallyBounded (Set.univ : Set ℤ_[p]) := by
refine Metric.totallyBounded_iff.mpr (fun ε hε ↦ ?_)
obtain ⟨k, hk⟩ := exists_pow_neg_lt p hε
refine ⟨Nat.cast '' Finset.range (p ^ k), Set.toFinite _, fun z _ ↦ ?_⟩
simp only [PadicInt, Set.mem_iUnion, Metric.mem_ball, exists_prop, Set.exists_mem_image]
refine ⟨z.appr k, ?_, ?_⟩
· simpa only [Finset.mem_coe, Finset.mem_range] using z.appr_lt k
· exact (((z - z.appr k).norm_le_pow_iff_mem_span_pow k).mpr (z.appr_spec k)).trans_lt hk
/-- The set of p-adic integers `ℤ_[p]` is a compact topological space. -/
instance compactSpace : CompactSpace ℤ_[p] := by
rw [← isCompact_univ_iff, isCompact_iff_totallyBounded_isComplete]
exact ⟨totallyBounded_univ p, complete_univ⟩
end PadicInt
namespace Padic
/-- The field of p-adic numbers `ℚ_[p]` is a proper metric space. -/
instance : ProperSpace ℚ_[p] := by
suffices LocallyCompactSpace ℚ_[p] from .of_nontriviallyNormedField_of_weaklyLocallyCompactSpace _
have : closedBall 0 1 ∈ 𝓝 (0 : ℚ_[p]) := closedBall_mem_nhds _ zero_lt_one
simp only [closedBall, dist_eq_norm_sub, sub_zero] at this
refine IsCompact.locallyCompactSpace_of_mem_nhds_of_addGroup ?_ this
simpa only [isCompact_iff_compactSpace] using PadicInt.compactSpace p
end Padic |
.lake/packages/mathlib/Mathlib/NumberTheory/Padics/RingHoms.lean | import Mathlib.Algebra.Field.ZMod
import Mathlib.NumberTheory.Padics.PadicIntegers
import Mathlib.RingTheory.LocalRing.ResidueField.Defs
import Mathlib.RingTheory.ZMod
/-!
# Relating `ℤ_[p]` to `ZMod (p ^ n)`, aka `ℤ/p^nℤ`.
In this file we establish connections between the `p`-adic integers `ℤ_[p]`
and the integers modulo powers of `p`, `ℤ/p^nℤ`, implemented as `ZMod (p^n)`.
## Main declarations
We show that `ℤ_[p]` has a ring homomorphism to `ℤ/p^nℤ` for each `n`.
The case for `n = 1` is handled separately, since it is used in the general construction
and we may want to use it without the `^1` getting in the way.
* `PadicInt.toZMod`: ring homomorphism to `ℤ/pℤ`, implemented as `ZMod p`.
* `PadicInt.toZModPow`: ring homomorphism to `ℤ/p^nℤ`, implemented as `ZMod (p^n)`.
* `PadicInt.ker_toZMod` / `PadicInt.ker_toZModPow`: the kernels of these maps are the ideals
generated by `p^n`
* `PadicInt.residueField` shows that the residue field of `ℤ_[p]` is isomorphic to ``ℤ/pℤ`.
We also establish the universal property of `ℤ_[p]` as a projective limit.
Given a family of compatible ring homomorphisms `f_k : R → ℤ/p^nℤ`,
there is a unique limit `R → ℤ_[p]`
* `PadicInt.lift`: the limit function
* `PadicInt.lift_spec` / `PadicInt.lift_unique`: the universal property
## Implementation notes
The constructions of the ring homomorphisms go through an auxiliary constructor
`PadicInt.toZModHom`, which removes some boilerplate code.
-/
noncomputable section
open Nat IsLocalRing Padic
namespace PadicInt
variable {p : ℕ} [hp_prime : Fact p.Prime]
section RingHoms
/-! ### Ring homomorphisms to `ZMod p` and `ZMod (p ^ n)` -/
variable (p) (r : ℚ)
/-- `modPart p r` is an integer that satisfies
`‖(r - modPart p r : ℚ_[p])‖ < 1` when `‖(r : ℚ_[p])‖ ≤ 1`,
see `PadicInt.norm_sub_modPart`.
It is the unique non-negative integer that is `< p` with this property.
(Note that this definition assumes `r : ℚ`.
See `PadicInt.zmodRepr` for a version that takes values in `ℕ`
and works for arbitrary `x : ℤ_[p]`.) -/
def modPart : ℤ :=
r.num * gcdA r.den p % p
variable {p}
theorem modPart_lt_p : modPart p r < p := by
convert Int.emod_lt_abs _ _
· simp
· exact mod_cast hp_prime.1.ne_zero
theorem modPart_nonneg : 0 ≤ modPart p r :=
Int.emod_nonneg _ <| mod_cast hp_prime.1.ne_zero
theorem isUnit_den (r : ℚ) (h : ‖(r : ℚ_[p])‖ ≤ 1) : IsUnit (r.den : ℤ_[p]) := by
rw [isUnit_iff]
apply le_antisymm (r.den : ℤ_[p]).2
rw [← not_lt, coe_natCast]
intro norm_denom_lt
have hr : ‖(r * r.den : ℚ_[p])‖ = ‖(r.num : ℚ_[p])‖ := by
congr
rw_mod_cast [@Rat.mul_den_eq_num r]
rw [padicNormE.mul] at hr
have key : ‖(r.num : ℚ_[p])‖ < 1 := by
calc
_ = _ := hr.symm
_ < 1 * 1 := mul_lt_mul' h norm_denom_lt (norm_nonneg _) zero_lt_one
_ = 1 := mul_one 1
have : ↑p ∣ r.num ∧ (p : ℤ) ∣ r.den := by
simp only [← norm_int_lt_one_iff_dvd, ← padic_norm_e_of_padicInt]
exact ⟨key, norm_denom_lt⟩
apply hp_prime.1.not_dvd_one
rwa [← r.reduced.gcd_eq_one, Nat.dvd_gcd_iff, ← Int.natCast_dvd, ← Int.natCast_dvd_natCast]
theorem norm_sub_modPart_aux (r : ℚ) (h : ‖(r : ℚ_[p])‖ ≤ 1) :
↑p ∣ r.num - r.num * r.den.gcdA p % p * ↑r.den := by
rw [← ZMod.intCast_zmod_eq_zero_iff_dvd]
simp only [Int.cast_natCast, Int.cast_mul, Int.cast_sub]
have := congr_arg (fun x => x % p : ℤ → ZMod p) (gcd_eq_gcd_ab r.den p)
simp only [Int.cast_natCast, CharP.cast_eq_zero, EuclideanDomain.mod_zero, Int.cast_add,
Int.cast_mul, zero_mul, add_zero] at this
push_cast
rw [mul_right_comm, mul_assoc, ← this]
suffices rdcp : r.den.Coprime p by
rw [rdcp.gcd_eq_one]
simp only [mul_one, cast_one, sub_self]
apply Coprime.symm
apply (coprime_or_dvd_of_prime hp_prime.1 _).resolve_right
rw [← Int.natCast_dvd_natCast, ← norm_int_lt_one_iff_dvd, not_lt]
apply ge_of_eq
rw [← isUnit_iff]
exact isUnit_den r h
theorem norm_sub_modPart (h : ‖(r : ℚ_[p])‖ ≤ 1) : ‖(⟨r, h⟩ - modPart p r : ℤ_[p])‖ < 1 := by
let n := modPart p r
rw [norm_lt_one_iff_dvd, ← (isUnit_den r h).dvd_mul_right]
suffices ↑p ∣ r.num - n * r.den by
convert (map_dvd (Int.castRingHom ℤ_[p])) this
simp only [n, sub_mul, Int.cast_natCast, eq_intCast, Int.cast_mul, sub_left_inj,
Int.cast_sub]
apply Subtype.coe_injective
simp only [coe_mul, coe_natCast]
norm_cast
simp
exact norm_sub_modPart_aux r h
theorem exists_mem_range_of_norm_rat_le_one (h : ‖(r : ℚ_[p])‖ ≤ 1) :
∃ n : ℤ, 0 ≤ n ∧ n < p ∧ ‖(⟨r, h⟩ - n : ℤ_[p])‖ < 1 :=
⟨modPart p r, modPart_nonneg _, modPart_lt_p _, norm_sub_modPart _ h⟩
theorem zmod_congr_of_sub_mem_span_aux (n : ℕ) (x : ℤ_[p]) (a b : ℤ)
(ha : x - a ∈ (Ideal.span {(p : ℤ_[p]) ^ n}))
(hb : x - b ∈ (Ideal.span {(p : ℤ_[p]) ^ n})) : (a : ZMod (p ^ n)) = b := by
rw [Ideal.mem_span_singleton] at ha hb
rw [← sub_eq_zero, ← Int.cast_sub, ZMod.intCast_zmod_eq_zero_iff_dvd, Int.natCast_pow]
rw [← dvd_neg, neg_sub] at ha
have := dvd_add ha hb
rwa [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left, ← sub_eq_add_neg, ←
Int.cast_sub, pow_p_dvd_int_iff] at this
theorem zmod_congr_of_sub_mem_span (n : ℕ) (x : ℤ_[p]) (a b : ℕ)
(ha : x - a ∈ (Ideal.span {(p : ℤ_[p]) ^ n}))
(hb : x - b ∈ (Ideal.span {(p : ℤ_[p]) ^ n})) : (a : ZMod (p ^ n)) = b := by
simpa using zmod_congr_of_sub_mem_span_aux n x a b ha hb
theorem zmod_congr_of_sub_mem_max_ideal (x : ℤ_[p]) (m n : ℕ) (hm : x - m ∈ maximalIdeal ℤ_[p])
(hn : x - n ∈ maximalIdeal ℤ_[p]) : (m : ZMod p) = n := by
rw [maximalIdeal_eq_span_p] at hm hn
have := zmod_congr_of_sub_mem_span_aux 1 x m n
simp only [pow_one] at this
specialize this hm hn
apply_fun ZMod.castHom (show p ∣ p ^ 1 by rw [pow_one]) (ZMod p) at this
simp only [map_intCast] at this
simpa only [Int.cast_natCast] using this
variable (x : ℤ_[p])
theorem exists_mem_range : ∃ n : ℕ, n < p ∧ x - n ∈ maximalIdeal ℤ_[p] := by
simp only [maximalIdeal_eq_span_p, Ideal.mem_span_singleton, ← norm_lt_one_iff_dvd]
obtain ⟨r, hr⟩ := rat_dense p (x : ℚ_[p]) zero_lt_one
have H : ‖(r : ℚ_[p])‖ ≤ 1 := by
rw [norm_sub_rev] at hr
calc
_ = ‖(r : ℚ_[p]) - x + x‖ := by ring_nf
_ ≤ _ := Padic.nonarchimedean _ _
_ ≤ _ := max_le (le_of_lt hr) x.2
obtain ⟨n, hzn, hnp, hn⟩ := exists_mem_range_of_norm_rat_le_one r H
lift n to ℕ using hzn
use n
constructor
· exact mod_cast hnp
simp only [norm_def, coe_sub, coe_natCast] at hn ⊢
rw [show (x - n : ℚ_[p]) = x - r + (r - n) by ring]
apply lt_of_le_of_lt (Padic.nonarchimedean _ _)
apply max_lt hr
simpa using hn
theorem existsUnique_mem_range : ∃! n : ℕ, n < p ∧ x - n ∈ maximalIdeal ℤ_[p] := by
obtain ⟨n, hn₁, hn₂⟩ := exists_mem_range x
use n, ⟨hn₁, hn₂⟩, fun m ⟨hm₁, hm₂⟩ ↦ ?_
have := (zmod_congr_of_sub_mem_max_ideal x n m hn₂ hm₂).symm
rwa [ZMod.natCast_eq_natCast_iff, ModEq, mod_eq_of_lt hn₁, mod_eq_of_lt hm₁] at this
/-- `zmodRepr x` is the unique natural number smaller than `p`
satisfying `‖(x - zmodRepr x : ℤ_[p])‖ < 1`.
-/
def zmodRepr : ℕ :=
Classical.choose (existsUnique_mem_range x).exists
theorem zmodRepr_spec : zmodRepr x < p ∧ x - zmodRepr x ∈ maximalIdeal ℤ_[p] :=
Classical.choose_spec (existsUnique_mem_range x).exists
theorem zmodRepr_unique (y : ℕ) (hy₁ : y < p) (hy₂ : x - y ∈ maximalIdeal ℤ_[p]) : zmodRepr x = y :=
have h := (Classical.choose_spec (existsUnique_mem_range x)).right
(h (zmodRepr x) (zmodRepr_spec x)).trans (h y ⟨hy₁, hy₂⟩).symm
theorem zmodRepr_lt_p : zmodRepr x < p :=
(zmodRepr_spec _).1
theorem sub_zmodRepr_mem : x - zmodRepr x ∈ maximalIdeal ℤ_[p] :=
(zmodRepr_spec _).2
lemma zmodRepr_eq_zero_of_dvd {x : ℤ_[p]} (hx : (p : ℤ_[p]) ∣ x) : x.zmodRepr = 0 := by
apply zmodRepr_unique _ _ (Nat.Prime.pos Fact.out)
simp [maximalIdeal_eq_span_p, Ideal.mem_span_singleton, hx]
@[simp]
lemma zmodRepr_zero : (0 : ℤ_[p]).zmodRepr = 0 :=
zmodRepr_eq_zero_of_dvd (dvd_zero _)
lemma norm_sub_zmodRepr_lt_one (x : ℤ_[p]) :
‖x - x.zmodRepr‖ < 1 := by
rw [← mem_nonunits, ← IsLocalRing.mem_maximalIdeal]
exact sub_zmodRepr_mem _
lemma norm_natCast_zmodRepr_eq_one_iff {x : ℤ_[p]} :
‖(x.zmodRepr : ℤ_[p])‖ = 1 ↔ ‖x‖ = 1 := by
rcases eq_or_ne ‖(x.zmodRepr : ℤ_[p])‖ ‖x‖ with H | H
· rw [H]
· have := x.norm_sub_zmodRepr_lt_one
constructor <;> intro h <;> rw [← h] at this ⊢
· exact norm_eq_of_norm_sub_lt_right this
· exact (norm_eq_of_norm_sub_lt_left this).symm
lemma zmodRepr_eq_zero_iff_dvd {x : ℤ_[p]} :
x.zmodRepr = 0 ↔ (p : ℤ_[p]) ∣ x := by
refine ⟨fun H ↦ ?_, zmodRepr_eq_zero_of_dvd⟩
rw [← norm_lt_one_iff_dvd, ← sub_zero x, ← Nat.cast_zero, ← H]
exact norm_sub_zmodRepr_lt_one _
lemma norm_natCast_zmodRepr_eq_one_iff_ne (x : ℤ_[p]) :
‖(x.zmodRepr : ℤ_[p])‖ = 1 ↔ x.zmodRepr ≠ 0 := by
rw [norm_natCast_zmodRepr_eq_one_iff, ne_eq, zmodRepr_eq_zero_iff_dvd, ← norm_lt_one_iff_dvd]
simp
lemma norm_natCast_zmodRepr_eq (x : ℤ_[p]) :
‖(x.zmodRepr : ℤ_[p])‖ = 1 ∨ x.zmodRepr = 0 := by
grind [norm_natCast_zmodRepr_eq_one_iff_ne]
@[simp]
lemma zmodRepr_natCast_zmodRepr (x : ℤ_[p]) :
(x.zmodRepr : ℤ_[p]).zmodRepr = x.zmodRepr := by
apply zmodRepr_unique _ _ (zmodRepr_lt_p _)
simp
@[simp]
lemma norm_natCast_zmodRepr_eq_iff {x : ℤ_[p]} :
‖(x.zmodRepr : ℤ_[p])‖ = ‖x‖ ↔ ‖x‖ = 1 ∨ x = 0 := by
rcases norm_natCast_zmodRepr_eq x with h | h
· simp_all [eq_comm]
· rw [eq_comm, h]
simp [← norm_natCast_zmodRepr_eq_one_iff, h]
lemma zmodRepr_natCast (n : ℕ) :
zmodRepr (n : ℤ_[p]) = n % p := by
nth_rw 1 [← Nat.mod_add_div n p]
apply zmodRepr_unique
· exact Nat.mod_lt _ (Nat.Prime.pos Fact.out)
· simp [maximalIdeal_eq_span_p, Ideal.mem_span_singleton]
lemma zmodRepr_natCast_of_lt {n : ℕ} (hn : n < p) :
zmodRepr (n : ℤ_[p]) = n := by
rw [zmodRepr_natCast (p := p) n, Nat.mod_eq_of_lt hn]
lemma zmodRepr_natCast_ofNat {n : ℕ} (hn : ofNat(n) < p) :
zmodRepr (ofNat(n) : ℤ_[p]) = ofNat(n) := by
convert zmodRepr_natCast_of_lt hn
rcases n with _ | _ | n <;> simp
lemma zmodRepr_units_ne_zero (x : ℤ_[p]ˣ) : x.val.zmodRepr ≠ 0 := by
rw [ne_eq, zmodRepr_eq_zero_iff_dvd]
exact irreducible_p.not_dvd_isUnit x.isUnit
/-- `toZModHom` is an auxiliary constructor for creating ring homs from `ℤ_[p]` to `ZMod v`.
-/
def toZModHom (v : ℕ) (f : ℤ_[p] → ℕ) (f_spec : ∀ x, x - f x ∈ (Ideal.span {↑v} : Ideal ℤ_[p]))
(f_congr :
∀ (x : ℤ_[p]) (a b : ℕ),
x - a ∈ (Ideal.span {↑v} : Ideal ℤ_[p]) →
x - b ∈ (Ideal.span {↑v} : Ideal ℤ_[p]) → (a : ZMod v) = b) :
ℤ_[p] →+* ZMod v where
toFun x := f x
map_zero' := by
rw [f_congr (0 : ℤ_[p]) _ 0, cast_zero]
· exact f_spec _
· simp only [sub_zero, cast_zero, Submodule.zero_mem]
map_one' := by
rw [f_congr (1 : ℤ_[p]) _ 1, cast_one]
· exact f_spec _
· simp only [sub_self, cast_one, Submodule.zero_mem]
map_add' := by
intro x y
rw [f_congr (x + y) _ (f x + f y), cast_add]
· exact f_spec _
· convert Ideal.add_mem _ (f_spec x) (f_spec y) using 1
rw [cast_add]
ring
map_mul' := by
intro x y
rw [f_congr (x * y) _ (f x * f y), cast_mul]
· exact f_spec _
· let I : Ideal ℤ_[p] := Ideal.span {↑v}
convert I.add_mem (I.mul_mem_left x (f_spec y)) (I.mul_mem_right ↑(f y) (f_spec x)) using 1
rw [cast_mul]
ring
/-- `toZMod` is a ring hom from `ℤ_[p]` to `ZMod p`,
with the equality `toZMod x = (zmodRepr x : ZMod p)`.
-/
def toZMod : ℤ_[p] →+* ZMod p :=
toZModHom p zmodRepr
(by
rw [← maximalIdeal_eq_span_p]
exact sub_zmodRepr_mem)
(by
rw [← maximalIdeal_eq_span_p]
exact zmod_congr_of_sub_mem_max_ideal)
/-- `z - (toZMod z : ℤ_[p])` is contained in the maximal ideal of `ℤ_[p]`, for every `z : ℤ_[p]`.
The coercion from `ZMod p` to `ℤ_[p]` is `ZMod.cast`,
which coerces `ZMod p` into arbitrary rings.
This is unfortunate, but a consequence of the fact that we allow `ZMod p`
to coerce to rings of arbitrary characteristic, instead of only rings of characteristic `p`.
This coercion is only a ring homomorphism if it coerces into a ring whose characteristic divides
`p`. While this is not the case here we can still make use of the coercion.
-/
theorem toZMod_spec : x - (ZMod.cast (toZMod x) : ℤ_[p]) ∈ maximalIdeal ℤ_[p] := by
convert sub_zmodRepr_mem x using 2
dsimp [toZMod, toZModHom]
rcases Nat.exists_eq_add_of_lt hp_prime.1.pos with ⟨p', rfl⟩
change ↑((_ : ZMod (0 + p' + 1)).val) = (_ : ℤ_[0 + p' + 1])
rw [Nat.cast_inj]
apply mod_eq_of_lt
simpa only [zero_add] using zmodRepr_lt_p x
theorem ker_toZMod : RingHom.ker (toZMod : ℤ_[p] →+* ZMod p) = maximalIdeal ℤ_[p] := by
ext x
rw [RingHom.mem_ker]
constructor
· intro h
simpa only [h, ZMod.cast_zero, sub_zero] using toZMod_spec x
· intro h
rw [← sub_zero x] at h
dsimp [toZMod, toZModHom]
convert zmod_congr_of_sub_mem_max_ideal x _ 0 _ h
· norm_cast
· apply sub_zmodRepr_mem
@[simp]
lemma val_toZMod_eq_zmodRepr (x : ℤ_[p]) :
(toZMod x).val = x.zmodRepr :=
(zmodRepr_unique _ _ (ZMod.val_lt _) <| by simpa using toZMod_spec _).symm
lemma zmodRepr_mul (x y : ℤ_[p]) : (x * y).zmodRepr = x.zmodRepr * y.zmodRepr % p := by
simp [← val_toZMod_eq_zmodRepr, ZMod.val_mul]
/-- The equivalence between the residue field of the `p`-adic integers and `ℤ/pℤ` -/
def residueField : IsLocalRing.ResidueField ℤ_[p] ≃+* ZMod p :=
(Ideal.quotEquivOfEq PadicInt.ker_toZMod.symm).trans <|
RingHom.quotientKerEquivOfSurjective (ZMod.ringHom_surjective PadicInt.toZMod)
open scoped Classical in
/-- `appr n x` gives a value `v : ℕ` such that `x` and `↑v : ℤ_p` are congruent mod `p^n`.
See `appr_spec`. -/
noncomputable def appr : ℤ_[p] → ℕ → ℕ
| _x, 0 => 0
| x, n + 1 =>
let y := x - appr x n
if hy : y = 0 then appr x n
else
let u := (unitCoeff hy : ℤ_[p])
appr x n + p ^ n * (toZMod ((u * (p : ℤ_[p]) ^ (y.valuation - n : ℤ).natAbs) : ℤ_[p])).val
theorem appr_lt (x : ℤ_[p]) (n : ℕ) : x.appr n < p ^ n := by
induction n generalizing x with
| zero => simp only [appr, _root_.pow_zero, zero_lt_one]
| succ n ih =>
simp only [appr, map_natCast, ZMod.natCast_self, RingHom.map_pow, Int.natAbs, RingHom.map_mul]
have hp : p ^ n < p ^ (n + 1) := by apply Nat.pow_lt_pow_right hp_prime.1.one_lt n.lt_add_one
split_ifs with h
· apply lt_trans (ih _) hp
· calc
_ < p ^ n + p ^ n * (p - 1) := ?_
_ = p ^ (n + 1) := ?_
· apply add_lt_add_of_lt_of_le (ih _)
apply Nat.mul_le_mul_left
apply le_pred_of_lt
apply ZMod.val_lt
· rw [mul_tsub, mul_one, ← _root_.pow_succ]
apply add_tsub_cancel_of_le (le_of_lt hp)
theorem appr_mono (x : ℤ_[p]) : Monotone x.appr := by
apply monotone_nat_of_le_succ
intro n
dsimp [appr]
split_ifs; · rfl
apply Nat.le_add_right
theorem dvd_appr_sub_appr (x : ℤ_[p]) (m n : ℕ) (h : m ≤ n) : p ^ m ∣ x.appr n - x.appr m := by
obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_le h; clear h
induction k with
| zero =>
simp only [add_zero, le_refl, tsub_eq_zero_of_le, dvd_zero]
| succ k ih =>
rw [← add_assoc]
dsimp [appr]
split_ifs with h
· exact ih
rw [add_comm, add_tsub_assoc_of_le (appr_mono _ (Nat.le_add_right m k))]
apply dvd_add _ ih
apply dvd_mul_of_dvd_left
apply pow_dvd_pow _ (Nat.le_add_right m k)
theorem appr_spec (n : ℕ) : ∀ x : ℤ_[p], x - appr x n ∈ Ideal.span {(p : ℤ_[p]) ^ n} := by
simp only [Ideal.mem_span_singleton]
induction n with
| zero => simp only [_root_.pow_zero, isUnit_one, IsUnit.dvd, forall_const]
| succ n ih =>
intro x
dsimp only [appr]
split_ifs with h
· rw [h]
apply dvd_zero
push_cast
rw [sub_add_eq_sub_sub]
obtain ⟨c, hc⟩ := ih x
simp only [map_natCast, ZMod.natCast_self, RingHom.map_pow, RingHom.map_mul, ZMod.natCast_val]
have hc' : c ≠ 0 := by
rintro rfl
simp only [mul_zero] at hc
contradiction
conv_rhs =>
congr
simp only [hc]
rw [show (x - (appr x n : ℤ_[p])).valuation = ((p : ℤ_[p]) ^ n * c).valuation by rw [hc]]
rw [valuation_p_pow_mul _ _ hc', Nat.cast_add, add_sub_cancel_left, _root_.pow_succ, ← mul_sub]
apply mul_dvd_mul_left
obtain hc0 | hc0 := eq_or_ne c.valuation 0
· simp only [hc0, mul_one, _root_.pow_zero, Nat.cast_zero, Int.natAbs_zero]
rw [mul_comm, unitCoeff_spec h] at hc
suffices c = unitCoeff h by
rw [← this, ← Ideal.mem_span_singleton, ← maximalIdeal_eq_span_p]
apply toZMod_spec
lift c to ℤ_[p]ˣ using by simp [isUnit_iff, norm_eq_zpow_neg_valuation hc', hc0]
rw [IsDiscreteValuationRing.unit_mul_pow_congr_unit _ _ _ _ _ hc]
exact irreducible_p
· simp only [Int.natAbs_natCast, zero_pow hc0, sub_zero, ZMod.cast_zero, mul_zero]
rw [unitCoeff_spec hc']
exact (dvd_pow_self (p : ℤ_[p]) hc0).mul_left _
lemma toZMod_eq_residueField_comp_residue :
toZMod (p := p) = residueField.toRingHom.comp (IsLocalRing.residue _) :=
rfl
/-- A ring hom from `ℤ_[p]` to `ZMod (p^n)`, with underlying function `PadicInt.appr n`. -/
def toZModPow (n : ℕ) : ℤ_[p] →+* ZMod (p ^ n) :=
toZModHom (p ^ n) (fun x => appr x n)
(by
intros
rw [Nat.cast_pow]
exact appr_spec n _)
(by
intro x a b ha hb
apply zmod_congr_of_sub_mem_span n x a b
· simpa using ha
· simpa using hb)
theorem ker_toZModPow (n : ℕ) :
RingHom.ker (toZModPow n : ℤ_[p] →+* ZMod (p ^ n)) = Ideal.span {(p : ℤ_[p]) ^ n} := by
ext x
rw [RingHom.mem_ker]
constructor
· intro h
suffices x.appr n = 0 by
convert appr_spec n x
simp only [this, sub_zero, cast_zero]
dsimp [toZModPow, toZModHom] at h
rw [ZMod.natCast_eq_zero_iff] at h
apply eq_zero_of_dvd_of_lt h (appr_lt _ _)
· intro h
rw [← sub_zero x] at h
dsimp [toZModPow, toZModHom]
rw [zmod_congr_of_sub_mem_span n x _ 0 _ h, cast_zero]
apply appr_spec
-- This is not a simp lemma; simp can't match the LHS.
theorem zmod_cast_comp_toZModPow (m n : ℕ) (h : m ≤ n) :
(ZMod.castHom (pow_dvd_pow p h) (ZMod (p ^ m))).comp (@toZModPow p _ n) = @toZModPow p _ m := by
apply ZMod.ringHom_eq_of_ker_eq
ext x
rw [RingHom.mem_ker, RingHom.mem_ker]
simp only [Function.comp_apply, ZMod.castHom_apply, RingHom.coe_comp]
simp only [toZModPow, toZModHom, RingHom.coe_mk]
dsimp
rw [ZMod.cast_natCast (pow_dvd_pow p h),
zmod_congr_of_sub_mem_span m (x.appr n) (x.appr n) (x.appr m)]
· rw [sub_self]
apply Ideal.zero_mem _
· rw [Ideal.mem_span_singleton]
rcases dvd_appr_sub_appr x m n h with ⟨c, hc⟩
use c
rw [← Nat.cast_sub (appr_mono _ h), hc, Nat.cast_mul, Nat.cast_pow]
@[simp]
theorem cast_toZModPow (m n : ℕ) (h : m ≤ n) (x : ℤ_[p]) :
ZMod.cast (toZModPow n x) = toZModPow m x := by
rw [← zmod_cast_comp_toZModPow _ _ h]
simp
theorem denseRange_natCast : DenseRange (Nat.cast : ℕ → ℤ_[p]) := by
intro x
rw [Metric.mem_closure_range_iff]
intro ε hε
obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε
use x.appr n
rw [dist_eq_norm]
apply lt_of_le_of_lt _ hn
rw [norm_le_pow_iff_mem_span_pow]
apply appr_spec
theorem denseRange_intCast : DenseRange (Int.cast : ℤ → ℤ_[p]) := by
intro x
refine DenseRange.induction_on denseRange_natCast x ?_ ?_
· exact isClosed_closure
· intro a
apply subset_closure
exact Set.mem_range_self _
end RingHoms
section lift
/-! ### Universal property as projective limit -/
open CauSeq PadicSeq
variable {R : Type*} [NonAssocSemiring R] {p : Nat} (f : ∀ k : ℕ, R →+* ZMod (p ^ k))
/-- Given a family of ring homs `f : Π n : ℕ, R →+* ZMod (p ^ n)`,
`nthHom f r` is an integer-valued sequence
whose `n`th value is the unique integer `k` such that `0 ≤ k < p ^ n`
and `f n r = (k : ZMod (p ^ n))`.
-/
def nthHom (r : R) : ℕ → ℤ := fun n => (f n r : ZMod (p ^ n)).val
@[simp]
theorem nthHom_zero : nthHom f 0 = 0 := by
simp +unfoldPartialApp [nthHom, Pi.zero_def]
variable {f}
variable [hp_prime : Fact p.Prime]
section
variable
(f_compat : ∀ (k1 k2) (hk : k1 ≤ k2), (ZMod.castHom (pow_dvd_pow p hk) _).comp (f k2) = f k1)
include f_compat
theorem pow_dvd_nthHom_sub (r : R) (i j : ℕ) (h : i ≤ j) :
(p : ℤ) ^ i ∣ nthHom f r j - nthHom f r i := by
specialize f_compat i j h
rw [← Int.natCast_pow, ← ZMod.intCast_zmod_eq_zero_iff_dvd, Int.cast_sub]
dsimp [nthHom]
rw [← f_compat, RingHom.comp_apply]
simp only [ZMod.cast_id, ZMod.castHom_apply, sub_self, ZMod.natCast_val, ZMod.intCast_cast]
theorem isCauSeq_nthHom (r : R) : IsCauSeq (padicNorm p) fun n => nthHom f r n := by
intro ε hε
obtain ⟨k, hk⟩ : ∃ k : ℕ, (p : ℚ) ^ (-((k : ℕ) : ℤ)) < ε := exists_pow_neg_lt_rat p hε
use k
intro j hj
refine lt_of_le_of_lt ?_ hk
-- Need to do beta reduction first, as `norm_cast` doesn't.
-- Added to adapt to https://github.com/leanprover/lean4/pull/2734.
beta_reduce
norm_cast
rw [← padicNorm.dvd_iff_norm_le]
exact mod_cast pow_dvd_nthHom_sub f_compat r k j hj
/-- `nthHomSeq f_compat r` bundles `PadicInt.nthHom f r`
as a Cauchy sequence of rationals with respect to the `p`-adic norm.
The `n`th value of the sequence is `((f n r).val : ℚ)`.
-/
def nthHomSeq (r : R) : PadicSeq p :=
⟨fun n => nthHom f r n, isCauSeq_nthHom f_compat r⟩
-- this lemma ran into issues after changing to `NeZero` and I'm not sure why.
theorem nthHomSeq_one : nthHomSeq f_compat 1 ≈ 1 := by
intro ε hε
change _ < _ at hε
use 1
intro j hj
haveI : Fact (1 < p ^ j) := ⟨Nat.one_lt_pow (by cutsat) hp_prime.1.one_lt⟩
suffices (ZMod.cast (1 : ZMod (p ^ j)) : ℚ) = 1 by simp [nthHomSeq, nthHom, this, hε]
rw [ZMod.cast_eq_val, ZMod.val_one, Nat.cast_one]
theorem nthHomSeq_add (r s : R) :
nthHomSeq f_compat (r + s) ≈ nthHomSeq f_compat r + nthHomSeq f_compat s := by
intro ε hε
obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε
use n
intro j hj
dsimp [nthHomSeq]
apply lt_of_le_of_lt _ hn
rw [← Int.cast_add, ← Int.cast_sub, ← padicNorm.dvd_iff_norm_le, ←
ZMod.intCast_zmod_eq_zero_iff_dvd]
dsimp [nthHom]
simp only [ZMod.natCast_val, RingHom.map_add, Int.cast_sub, ZMod.intCast_cast, Int.cast_add]
rw [ZMod.cast_add (show p ^ n ∣ p ^ j from pow_dvd_pow _ hj)]
simp only [sub_self]
theorem nthHomSeq_mul (r s : R) :
nthHomSeq f_compat (r * s) ≈ nthHomSeq f_compat r * nthHomSeq f_compat s := by
intro ε hε
obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε
use n
intro j hj
dsimp [nthHomSeq]
apply lt_of_le_of_lt _ hn
rw [← Int.cast_mul, ← Int.cast_sub, ← padicNorm.dvd_iff_norm_le, ←
ZMod.intCast_zmod_eq_zero_iff_dvd]
dsimp [nthHom]
simp only [ZMod.natCast_val, RingHom.map_mul, Int.cast_sub, ZMod.intCast_cast, Int.cast_mul]
rw [ZMod.cast_mul (show p ^ n ∣ p ^ j from pow_dvd_pow _ hj), sub_self]
/--
`limNthHom f_compat r` is the limit of a sequence `f` of compatible ring homs `R →+* ZMod (p^k)`.
This is itself a ring hom: see `PadicInt.lift`.
-/
def limNthHom (r : R) : ℤ_[p] :=
ofIntSeq (nthHom f r) (isCauSeq_nthHom f_compat r)
theorem limNthHom_spec (r : R) :
∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ n ≥ N, ‖limNthHom f_compat r - nthHom f r n‖ < ε := by
intro ε hε
obtain ⟨ε', hε'0, hε'⟩ : ∃ v : ℚ, (0 : ℝ) < v ∧ ↑v < ε := exists_rat_btwn hε
norm_cast at hε'0
obtain ⟨N, hN⟩ := padicNormE.defn (nthHomSeq f_compat r) hε'0
use N
intro n hn
apply _root_.lt_trans _ hε'
change (padicNormE _ : ℝ) < _
norm_cast
exact hN _ hn
theorem limNthHom_zero : limNthHom f_compat 0 = 0 := by simp [limNthHom]; rfl
theorem limNthHom_one : limNthHom f_compat 1 = 1 :=
Subtype.ext <| Quot.sound <| nthHomSeq_one f_compat
theorem limNthHom_add (r s : R) :
limNthHom f_compat (r + s) = limNthHom f_compat r + limNthHom f_compat s :=
Subtype.ext <| Quot.sound <| nthHomSeq_add f_compat _ _
theorem limNthHom_mul (r s : R) :
limNthHom f_compat (r * s) = limNthHom f_compat r * limNthHom f_compat s :=
Subtype.ext <| Quot.sound <| nthHomSeq_mul f_compat _ _
-- TODO: generalize this to arbitrary complete discrete valuation rings
/-- `lift f_compat` is the limit of a sequence `f` of compatible ring homs `R →+* ZMod (p^k)`,
with the equality `lift f_compat r = PadicInt.limNthHom f_compat r`.
-/
def lift : R →+* ℤ_[p] where
toFun := limNthHom f_compat
map_one' := limNthHom_one f_compat
map_mul' := limNthHom_mul f_compat
map_zero' := limNthHom_zero f_compat
map_add' := limNthHom_add f_compat
theorem lift_sub_val_mem_span (r : R) (n : ℕ) :
lift f_compat r - (f n r).val ∈ (Ideal.span {(p : ℤ_[p]) ^ n}) := by
obtain ⟨k, hk⟩ :=
limNthHom_spec f_compat r _
(show (0 : ℝ) < (p : ℝ) ^ (-n : ℤ) from zpow_pos (mod_cast hp_prime.1.pos) _)
have := le_of_lt (hk (max n k) (le_max_right _ _))
rw [norm_le_pow_iff_mem_span_pow] at this
dsimp [lift]
rw [sub_eq_sub_add_sub (limNthHom f_compat r) _ ↑(nthHom f r (max n k))]
apply Ideal.add_mem _ _ this
rw [Ideal.mem_span_singleton]
convert
map_dvd (Int.castRingHom ℤ_[p]) (pow_dvd_nthHom_sub f_compat r n (max n k) (le_max_left _ _))
· simp
· simp [nthHom]
/-- One part of the universal property of `ℤ_[p]` as a projective limit.
See also `PadicInt.lift_unique`.
-/
theorem lift_spec (n : ℕ) : (toZModPow n).comp (lift f_compat) = f n := by
ext r
rw [RingHom.comp_apply, ← ZMod.natCast_zmod_val (f n r), ← map_natCast <| toZModPow n, ←
sub_eq_zero, ← RingHom.map_sub, ← RingHom.mem_ker, ker_toZModPow]
apply lift_sub_val_mem_span
/-- One part of the universal property of `ℤ_[p]` as a projective limit.
See also `PadicInt.lift_spec`.
-/
theorem lift_unique (g : R →+* ℤ_[p]) (hg : ∀ n, (toZModPow n).comp g = f n) :
lift f_compat = g := by
ext1 r
apply eq_of_forall_dist_le
intro ε hε
obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε
apply le_trans _ (le_of_lt hn)
rw [dist_eq_norm, norm_le_pow_iff_mem_span_pow, ← ker_toZModPow, RingHom.mem_ker,
RingHom.map_sub, ← RingHom.comp_apply, ← RingHom.comp_apply, lift_spec, hg, sub_self]
end
@[simp]
theorem lift_self (z : ℤ_[p]) : lift zmod_cast_comp_toZModPow z = z := by
change _ = RingHom.id _ z
rw [lift_unique zmod_cast_comp_toZModPow (RingHom.id ℤ_[p])]
intro; rw [RingHom.comp_id]
end lift
theorem ext_of_toZModPow {x y : ℤ_[p]} : (∀ n, toZModPow n x = toZModPow n y) ↔ x = y := by
constructor
· intro h
rw [← lift_self x, ← lift_self y]
simp +unfoldPartialApp [lift, limNthHom, nthHom, h]
· rintro rfl _
rfl
theorem toZModPow_eq_iff_ext {R : Type*} [NonAssocSemiring R] {g g' : R →+* ℤ_[p]} :
(∀ n, (toZModPow n).comp g = (toZModPow n).comp g') ↔ g = g' := by
constructor
· intro hg
ext x : 1
apply ext_of_toZModPow.mp
intro n
change (toZModPow n).comp g x = (toZModPow n).comp g' x
rw [hg n]
· rintro rfl _
rfl
lemma isCauSeq_padicNorm_of_pow_dvd_sub
(f : ℕ → ℤ) (p : ℕ) [Fact p.Prime] (hi : ∀ i, (p : ℤ) ^ i ∣ f (i + 1) - f i) :
IsCauSeq (padicNorm p) (f ·) := by
intro ε hε
obtain ⟨k, hk⟩ := PadicInt.exists_pow_neg_lt_rat p hε
simp only [← Int.cast_sub]
refine ⟨k, fun i hik ↦ (padicNorm.dvd_iff_norm_le.mp ?_).trans_lt hk⟩
obtain ⟨i, rfl⟩ := exists_add_of_le hik
clear hik
induction i with
| zero => simp
| succ n IH =>
have : (↑(p ^ k) : ℤ) ∣ ↑p ^ (k + n) := ⟨p ^ n, by simp [pow_add]⟩
simpa using (this.trans (hi _)).add IH
lemma toZModPow_ofIntSeq_of_pow_dvd_sub
(f : ℕ → ℤ) (p : ℕ) [Fact p.Prime] (hi : ∀ i, (p : ℤ) ^ i ∣ f (i + 1) - f i) (n : ℕ) :
(PadicInt.ofIntSeq _ (isCauSeq_padicNorm_of_pow_dvd_sub f p hi)).toZModPow n = f n := by
set x := PadicInt.ofIntSeq _ (isCauSeq_padicNorm_of_pow_dvd_sub f p hi)
let s : PadicSeq p := ⟨(f ·), isCauSeq_padicNorm_of_pow_dvd_sub f p hi⟩
have hs : x = Padic.mk s := rfl
obtain ⟨e, he⟩ := Ideal.mem_span_singleton.mp (PadicInt.appr_spec n x)
rw [sub_eq_iff_eq_add] at he
obtain ⟨N, hN⟩ := padicNormE.defn s (ε := p ^ (-n : ℤ))
(by simp only [zpow_neg, zpow_natCast, inv_pos]; exact_mod_cast Nat.pos_of_neZero _)
replace hN := hN (N + n) (Nat.le_add_right N n)
rw [← hs, he, ← Rat.cast_lt (K := ℝ)] at hN
push_cast at hN
simp only [← add_sub, s, Rat.cast_intCast, padicNormE.is_norm,
← Int.cast_natCast (R := ℚ_[p]) (x.appr n), ← Int.cast_sub] at hN
have : ‖(((x.appr n) - f (N + n) : ℤ) : ℚ_[p])‖ ≤ ↑p ^ (-n : ℤ) := by
by_contra! H
have H' : ‖(p ^ n * e : ℚ_[p])‖ < ‖(((x.appr n) - f (N + n) : ℤ) : ℚ_[p])‖ := by
refine LE.le.trans_lt ?_ H
simpa using mul_le_mul_of_nonneg le_rfl e.2 (show 0 ≤ (↑p ^ n)⁻¹ by simp) zero_le_one
rw [Padic.add_eq_max_of_ne H'.ne, sup_eq_right.mpr H'.le] at hN
exact lt_asymm hN H
rw [Padic.norm_int_le_pow_iff_dvd, ← Nat.cast_pow,
← ZMod.intCast_eq_intCast_iff_dvd_sub, Int.cast_natCast] at this
refine this.symm.trans ?_
clear * - hi
induction N with
| zero => simp
| succ N IH =>
rw [← IH, eq_comm, add_right_comm, ZMod.intCast_eq_intCast_iff_dvd_sub]
exact .trans ⟨p ^ N, by simp [pow_add, mul_comm]⟩ (hi _)
end PadicInt |
.lake/packages/mathlib/Mathlib/NumberTheory/Padics/PadicIntegers.lean | import Mathlib.NumberTheory.Padics.PadicNumbers
import Mathlib.RingTheory.DiscreteValuationRing.Basic
/-!
# p-adic integers
This file defines the `p`-adic integers `ℤ_[p]` as the subtype of `ℚ_[p]` with norm `≤ 1`.
We show that `ℤ_[p]`
* is complete,
* is nonarchimedean,
* is a normed ring,
* is a local ring, and
* is a discrete valuation ring.
The relation between `ℤ_[p]` and `ZMod p` is established in another file.
## Important definitions
* `PadicInt` : the type of `p`-adic integers
## Notation
We introduce the notation `ℤ_[p]` for the `p`-adic integers.
## Implementation notes
Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically
by taking `[Fact p.Prime]` as a type class argument.
Coercions into `ℤ_[p]` are set up to work with the `norm_cast` tactic.
## References
* [F. Q. Gouvêa, *p-adic numbers*][gouvea1997]
* [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019]
* <https://en.wikipedia.org/wiki/P-adic_number>
## Tags
p-adic, p adic, padic, p-adic integer
-/
open Padic Metric IsLocalRing
noncomputable section
variable (p : ℕ) [hp : Fact p.Prime]
/-- The `p`-adic integers `ℤ_[p]` are the `p`-adic numbers with norm `≤ 1`. -/
def PadicInt : Type := {x : ℚ_[p] // ‖x‖ ≤ 1}
/-- The ring of `p`-adic integers. -/
notation "ℤ_[" p "]" => PadicInt p
namespace PadicInt
variable {p} {x y : ℤ_[p]}
/-! ### Ring structure and coercion to `ℚ_[p]` -/
instance : Coe ℤ_[p] ℚ_[p] :=
⟨Subtype.val⟩
theorem ext {x y : ℤ_[p]} : (x : ℚ_[p]) = y → x = y :=
Subtype.ext
variable (p)
/-- The `p`-adic integers as a subring of `ℚ_[p]`. -/
def subring : Subring ℚ_[p] where
carrier := { x : ℚ_[p] | ‖x‖ ≤ 1 }
zero_mem' := by simp
one_mem' := by simp
add_mem' hx hy := (Padic.nonarchimedean _ _).trans <| max_le_iff.2 ⟨hx, hy⟩
mul_mem' hx hy := (padicNormE.mul _ _).trans_le <| mul_le_one₀ hx (norm_nonneg _) hy
neg_mem' hx := (norm_neg _).trans_le hx
@[simp]
theorem mem_subring_iff {x : ℚ_[p]} : x ∈ subring p ↔ ‖x‖ ≤ 1 := Iff.rfl
variable {p}
instance instCommRing : CommRing ℤ_[p] := inferInstanceAs <| CommRing (subring p)
instance : Inhabited ℤ_[p] := ⟨0⟩
@[simp]
theorem mk_zero {h} : (⟨0, h⟩ : ℤ_[p]) = (0 : ℤ_[p]) := rfl
@[simp, norm_cast]
theorem coe_add (z1 z2 : ℤ_[p]) : ((z1 + z2 : ℤ_[p]) : ℚ_[p]) = z1 + z2 := rfl
@[simp, norm_cast]
theorem coe_mul (z1 z2 : ℤ_[p]) : ((z1 * z2 : ℤ_[p]) : ℚ_[p]) = z1 * z2 := rfl
@[simp, norm_cast]
theorem coe_neg (z1 : ℤ_[p]) : ((-z1 : ℤ_[p]) : ℚ_[p]) = -z1 := rfl
@[simp, norm_cast]
theorem coe_sub (z1 z2 : ℤ_[p]) : ((z1 - z2 : ℤ_[p]) : ℚ_[p]) = z1 - z2 := rfl
@[simp, norm_cast]
theorem coe_one : ((1 : ℤ_[p]) : ℚ_[p]) = 1 := rfl
@[simp, norm_cast]
theorem coe_zero : ((0 : ℤ_[p]) : ℚ_[p]) = 0 := rfl
@[simp] lemma coe_eq_zero : (x : ℚ_[p]) = 0 ↔ x = 0 := by rw [← coe_zero, Subtype.coe_inj]
lemma coe_ne_zero : (x : ℚ_[p]) ≠ 0 ↔ x ≠ 0 := coe_eq_zero.not
@[simp, norm_cast]
theorem coe_natCast (n : ℕ) : ((n : ℤ_[p]) : ℚ_[p]) = n := rfl
@[simp, norm_cast]
theorem coe_intCast (z : ℤ) : ((z : ℤ_[p]) : ℚ_[p]) = z := rfl
/-- The coercion from `ℤ_[p]` to `ℚ_[p]` as a ring homomorphism. -/
@[simps!]
def Coe.ringHom : ℤ_[p] →+* ℚ_[p] := (subring p).subtype
@[simp, norm_cast]
theorem coe_pow (x : ℤ_[p]) (n : ℕ) : (↑(x ^ n) : ℚ_[p]) = (↑x : ℚ_[p]) ^ n := rfl
theorem mk_coe (k : ℤ_[p]) : (⟨k, k.2⟩ : ℤ_[p]) = k := by simp
@[simp]
lemma coe_sum {α : Type*} (s : Finset α) (f : α → ℤ_[p]) :
(((∑ z ∈ s, f z) : ℤ_[p]) : ℚ_[p]) = ∑ z ∈ s, (f z : ℚ_[p]) := by
simp [← Coe.ringHom_apply, map_sum PadicInt.Coe.ringHom f s]
/-- The inverse of a `p`-adic integer with norm equal to `1` is also a `p`-adic integer.
Otherwise, the inverse is defined to be `0`. -/
def inv : ℤ_[p] → ℤ_[p]
| ⟨k, _⟩ => if h : ‖k‖ = 1 then ⟨k⁻¹, by simp [h]⟩ else 0
instance : CharZero ℤ_[p] where
cast_injective m n h :=
Nat.cast_injective (R := ℚ_[p]) (by rw [Subtype.ext_iff] at h; norm_cast at h)
@[norm_cast]
theorem intCast_eq (z1 z2 : ℤ) : (z1 : ℤ_[p]) = z2 ↔ z1 = z2 := by simp
/-- A sequence of integers that is Cauchy with respect to the `p`-adic norm converges to a `p`-adic
integer. -/
def ofIntSeq (seq : ℕ → ℤ) (h : IsCauSeq (padicNorm p) fun n => seq n) : ℤ_[p] :=
⟨⟦⟨_, h⟩⟧,
show ↑(PadicSeq.norm _) ≤ (1 : ℝ) by
rw [PadicSeq.norm]
split_ifs with hne <;> norm_cast
apply padicNorm.of_int⟩
/-! ### Instances
We now show that `ℤ_[p]` is a
* complete metric space
* normed ring
* integral domain
-/
variable (p)
instance : MetricSpace ℤ_[p] := Subtype.metricSpace
instance : IsUltrametricDist ℤ_[p] := IsUltrametricDist.subtype _
instance completeSpace : CompleteSpace ℤ_[p] :=
have : IsClosed { x : ℚ_[p] | ‖x‖ ≤ 1 } := isClosed_le continuous_norm continuous_const
this.completeSpace_coe
instance : Norm ℤ_[p] := ⟨fun z => ‖(z : ℚ_[p])‖⟩
variable {p} in
theorem norm_def {z : ℤ_[p]} : ‖z‖ = ‖(z : ℚ_[p])‖ := rfl
instance : NormedCommRing ℤ_[p] where
__ := instCommRing
dist_eq := fun ⟨_, _⟩ ⟨_, _⟩ ↦ rfl
norm_mul_le := by simp [norm_def]
instance : NormOneClass ℤ_[p] :=
⟨norm_def.trans norm_one⟩
instance : NormMulClass ℤ_[p] := ⟨fun x y ↦ by simp [norm_def]⟩
instance : IsDomain ℤ_[p] := NoZeroDivisors.to_isDomain _
variable {p}
/-! ### Norm -/
theorem norm_le_one (z : ℤ_[p]) : ‖z‖ ≤ 1 := z.2
theorem nonarchimedean (q r : ℤ_[p]) : ‖q + r‖ ≤ max ‖q‖ ‖r‖ := Padic.nonarchimedean _ _
theorem norm_add_eq_max_of_ne {q r : ℤ_[p]} : ‖q‖ ≠ ‖r‖ → ‖q + r‖ = max ‖q‖ ‖r‖ :=
Padic.add_eq_max_of_ne
theorem norm_eq_of_norm_add_lt_right {z1 z2 : ℤ_[p]} (h : ‖z1 + z2‖ < ‖z2‖) : ‖z1‖ = ‖z2‖ :=
by_contra fun hne =>
not_lt_of_ge (by rw [norm_add_eq_max_of_ne hne]; apply le_max_right) h
theorem norm_eq_of_norm_add_lt_left {z1 z2 : ℤ_[p]} (h : ‖z1 + z2‖ < ‖z1‖) : ‖z1‖ = ‖z2‖ :=
by_contra fun hne =>
not_lt_of_ge (by rw [norm_add_eq_max_of_ne hne]; apply le_max_left) h
@[simp]
theorem padic_norm_e_of_padicInt (z : ℤ_[p]) : ‖(z : ℚ_[p])‖ = ‖z‖ := by simp [norm_def]
theorem norm_intCast_eq_padic_norm (z : ℤ) : ‖(z : ℤ_[p])‖ = ‖(z : ℚ_[p])‖ := by simp [norm_def]
@[simp]
theorem norm_eq_padic_norm {q : ℚ_[p]} (hq : ‖q‖ ≤ 1) : @norm ℤ_[p] _ ⟨q, hq⟩ = ‖q‖ := rfl
@[simp]
theorem norm_p : ‖(p : ℤ_[p])‖ = (p : ℝ)⁻¹ := Padic.norm_p
theorem norm_p_pow (n : ℕ) : ‖(p : ℤ_[p]) ^ n‖ = (p : ℝ) ^ (-n : ℤ) := by simp
@[simp]
lemma one_le_norm_iff {x : ℤ_[p]} :
1 ≤ ‖x‖ ↔ ‖x‖ = 1 := by
simp [le_antisymm_iff, ← padic_norm_e_of_padicInt, x.prop]
@[simp]
lemma norm_natCast_p_sub_one :
‖((p - 1 : ℕ) : ℤ_[p])‖ = 1 := by
simp [norm_def]
private def cauSeq_to_rat_cauSeq (f : CauSeq ℤ_[p] norm) : CauSeq ℚ_[p] fun a => ‖a‖ :=
⟨fun n => f n, fun _ hε => by simpa [norm, norm_def] using f.cauchy hε⟩
variable (p)
instance complete : CauSeq.IsComplete ℤ_[p] norm :=
⟨fun f =>
have hqn : ‖CauSeq.lim (cauSeq_to_rat_cauSeq f)‖ ≤ 1 :=
padicNormE_lim_le zero_lt_one fun _ => norm_le_one _
⟨⟨_, hqn⟩, fun ε => by
simpa [norm, norm_def] using CauSeq.equiv_lim (cauSeq_to_rat_cauSeq f) ε⟩⟩
theorem exists_pow_neg_lt {ε : ℝ} (hε : 0 < ε) : ∃ k : ℕ, (p : ℝ) ^ (-(k : ℤ)) < ε := by
obtain ⟨k, hk⟩ := exists_nat_gt ε⁻¹
use k
rw [← inv_lt_inv₀ hε (zpow_pos _ _)]
· rw [zpow_neg, inv_inv, zpow_natCast]
apply lt_of_lt_of_le hk
norm_cast
apply le_of_lt
convert Nat.lt_pow_self _ using 1
exact hp.1.one_lt
· exact mod_cast hp.1.pos
theorem exists_pow_neg_lt_rat {ε : ℚ} (hε : 0 < ε) : ∃ k : ℕ, (p : ℚ) ^ (-(k : ℤ)) < ε := by
obtain ⟨k, hk⟩ := @exists_pow_neg_lt p _ ε (mod_cast hε)
use k
rw [show (p : ℝ) = (p : ℚ) by simp] at hk
exact mod_cast hk
variable {p}
theorem norm_int_lt_one_iff_dvd (k : ℤ) : ‖(k : ℤ_[p])‖ < 1 ↔ (p : ℤ) ∣ k :=
suffices ‖(k : ℚ_[p])‖ < 1 ↔ ↑p ∣ k by rwa [norm_intCast_eq_padic_norm]
Padic.norm_intCast_lt_one_iff
theorem norm_int_le_pow_iff_dvd {k : ℤ} {n : ℕ} :
‖(k : ℤ_[p])‖ ≤ (p : ℝ) ^ (-n : ℤ) ↔ (p ^ n : ℤ) ∣ k :=
suffices ‖(k : ℚ_[p])‖ ≤ (p : ℝ) ^ (-n : ℤ) ↔ (p ^ n : ℤ) ∣ k by
simpa [norm_intCast_eq_padic_norm]
Padic.norm_int_le_pow_iff_dvd _ _
@[simp]
lemma norm_natCast_eq_one_iff {n : ℕ} :
‖(n : ℤ_[p])‖ = 1 ↔ p.Coprime n := by
rw [norm_def, coe_natCast, Padic.norm_natCast_eq_one_iff]
@[simp]
lemma norm_natCast_lt_one_iff {n : ℕ} :
‖(n : ℤ_[p])‖ < 1 ↔ p ∣ n := by
rw [norm_def, coe_natCast, Padic.norm_natCast_lt_one_iff]
@[simp]
lemma norm_intCast_eq_one_iff {z : ℤ} :
‖(z : ℤ_[p])‖ = 1 ↔ IsCoprime z p := by
rw [norm_def, coe_intCast, Padic.norm_intCast_eq_one_iff]
@[simp]
lemma norm_intCast_lt_one_iff {z : ℤ} :
‖(z : ℤ_[p])‖ < 1 ↔ (p : ℤ) ∣ z := by
rw [norm_def, coe_intCast, Padic.norm_intCast_lt_one_iff]
/-! ### Valuation on `ℤ_[p]` -/
lemma valuation_coe_nonneg : 0 ≤ (x : ℚ_[p]).valuation := by
obtain rfl | hx := eq_or_ne x 0
· simp
have := x.2
rwa [Padic.norm_eq_zpow_neg_valuation <| coe_ne_zero.2 hx, zpow_le_one_iff_right₀, neg_nonpos]
at this
exact mod_cast hp.out.one_lt
/-- `PadicInt.valuation` lifts the `p`-adic valuation on `ℚ` to `ℤ_[p]`. -/
def valuation (x : ℤ_[p]) : ℕ := (x : ℚ_[p]).valuation.toNat
@[simp, norm_cast] lemma valuation_coe (x : ℤ_[p]) : (x : ℚ_[p]).valuation = x.valuation := by
simp [valuation, valuation_coe_nonneg]
@[simp] lemma valuation_zero : valuation (0 : ℤ_[p]) = 0 := by simp [valuation]
@[simp] lemma valuation_one : valuation (1 : ℤ_[p]) = 0 := by simp [valuation]
@[simp] lemma valuation_p : valuation (p : ℤ_[p]) = 1 := by simp [valuation]
lemma le_valuation_add (hxy : x + y ≠ 0) : min x.valuation y.valuation ≤ (x + y).valuation := by
zify; simpa [← valuation_coe] using Padic.le_valuation_add <| coe_ne_zero.2 hxy
@[simp] lemma valuation_mul (hx : x ≠ 0) (hy : y ≠ 0) :
(x * y).valuation = x.valuation + y.valuation := by
zify; simp [← valuation_coe, Padic.valuation_mul (coe_ne_zero.2 hx) (coe_ne_zero.2 hy)]
@[simp]
lemma valuation_pow (x : ℤ_[p]) (n : ℕ) : (x ^ n).valuation = n * x.valuation := by
zify; simp [← valuation_coe]
lemma norm_eq_zpow_neg_valuation {x : ℤ_[p]} (hx : x ≠ 0) : ‖x‖ = p ^ (-x.valuation : ℤ) := by
simp [norm_def, Padic.norm_eq_zpow_neg_valuation <| coe_ne_zero.2 hx]
-- TODO: Do we really need this lemma?
@[simp]
theorem valuation_p_pow_mul (n : ℕ) (c : ℤ_[p]) (hc : c ≠ 0) :
((p : ℤ_[p]) ^ n * c).valuation = n + c.valuation := by
rw [valuation_mul (NeZero.ne _) hc, valuation_pow, valuation_p, mul_one]
section Units
/-! ### Units of `ℤ_[p]` -/
theorem mul_inv : ∀ {z : ℤ_[p]}, ‖z‖ = 1 → z * z.inv = 1
| ⟨k, _⟩, h => by
have hk : k ≠ 0 := fun h' => zero_ne_one' ℚ_[p] (by simp [h'] at h)
unfold PadicInt.inv
rw [norm_eq_padic_norm] at h
dsimp only
rw [dif_pos h]
apply Subtype.ext_iff.2
simp [mul_inv_cancel₀ hk]
theorem inv_mul {z : ℤ_[p]} (hz : ‖z‖ = 1) : z.inv * z = 1 := by rw [mul_comm, mul_inv hz]
theorem isUnit_iff {z : ℤ_[p]} : IsUnit z ↔ ‖z‖ = 1 :=
⟨fun h => by
rcases isUnit_iff_dvd_one.1 h with ⟨w, eq⟩
refine le_antisymm (norm_le_one _) ?_
have := mul_le_mul_of_nonneg_left (norm_le_one w) (norm_nonneg z)
rwa [mul_one, ← norm_mul, ← eq, norm_one] at this, fun h =>
⟨⟨z, z.inv, mul_inv h, inv_mul h⟩, rfl⟩⟩
theorem norm_lt_one_add {z1 z2 : ℤ_[p]} (hz1 : ‖z1‖ < 1) (hz2 : ‖z2‖ < 1) : ‖z1 + z2‖ < 1 :=
lt_of_le_of_lt (nonarchimedean _ _) (max_lt hz1 hz2)
theorem norm_lt_one_mul {z1 z2 : ℤ_[p]} (hz2 : ‖z2‖ < 1) : ‖z1 * z2‖ < 1 :=
calc
‖z1 * z2‖ = ‖z1‖ * ‖z2‖ := by simp
_ < 1 := mul_lt_one_of_nonneg_of_lt_one_right (norm_le_one _) (norm_nonneg _) hz2
theorem mem_nonunits {z : ℤ_[p]} : z ∈ nonunits ℤ_[p] ↔ ‖z‖ < 1 := by
simp [norm_le_one z, nonunits, isUnit_iff]
theorem not_isUnit_iff {z : ℤ_[p]} : ¬IsUnit z ↔ ‖z‖ < 1 := by
simpa using mem_nonunits
/-- A `p`-adic number `u` with `‖u‖ = 1` is a unit of `ℤ_[p]`. -/
def mkUnits {u : ℚ_[p]} (h : ‖u‖ = 1) : ℤ_[p]ˣ :=
let z : ℤ_[p] := ⟨u, le_of_eq h⟩
⟨z, z.inv, mul_inv h, inv_mul h⟩
@[simp]
lemma val_mkUnits {u : ℚ_[p]} (h : ‖u‖ = 1) : (mkUnits h).val = ⟨u, h.le⟩ := rfl
theorem mkUnits_eq {u : ℚ_[p]} (h : ‖u‖ = 1) : ((mkUnits h : ℤ_[p]) : ℚ_[p]) = u := rfl
@[simp]
theorem norm_units (u : ℤ_[p]ˣ) : ‖(u : ℤ_[p])‖ = 1 := isUnit_iff.mp <| by simp
/-- `unitCoeff hx` is the unit `u` in the unique representation `x = u * p ^ n`.
See `unitCoeff_spec`. -/
def unitCoeff {x : ℤ_[p]} (hx : x ≠ 0) : ℤ_[p]ˣ :=
let u : ℚ_[p] := x * (p : ℚ_[p]) ^ (-x.valuation : ℤ)
have hu : ‖u‖ = 1 := by
simp [u, hx, pow_ne_zero _ (NeZero.ne _), norm_eq_zpow_neg_valuation]
mkUnits hu
@[simp]
theorem unitCoeff_coe {x : ℤ_[p]} (hx : x ≠ 0) :
(unitCoeff hx : ℚ_[p]) = x * (p : ℚ_[p]) ^ (-x.valuation : ℤ) := rfl
theorem unitCoeff_spec {x : ℤ_[p]} (hx : x ≠ 0) :
x = (unitCoeff hx : ℤ_[p]) * (p : ℤ_[p]) ^ x.valuation := by
apply Subtype.coe_injective
push_cast
rw [unitCoeff_coe, mul_assoc, ← zpow_natCast, ← zpow_add₀]
· simp
· exact NeZero.ne _
end Units
section NormLeIff
/-! ### Various characterizations of open unit balls -/
theorem norm_le_pow_iff_le_valuation (x : ℤ_[p]) (hx : x ≠ 0) (n : ℕ) :
‖x‖ ≤ (p : ℝ) ^ (-n : ℤ) ↔ n ≤ x.valuation := by
rw [norm_eq_zpow_neg_valuation hx, zpow_le_zpow_iff_right₀, neg_le_neg_iff, Nat.cast_le]
exact mod_cast hp.out.one_lt
theorem mem_span_pow_iff_le_valuation (x : ℤ_[p]) (hx : x ≠ 0) (n : ℕ) :
x ∈ (Ideal.span {(p : ℤ_[p]) ^ n} : Ideal ℤ_[p]) ↔ n ≤ x.valuation := by
rw [Ideal.mem_span_singleton]
constructor
· rintro ⟨c, rfl⟩
suffices c ≠ 0 by
rw [valuation_p_pow_mul _ _ this]
exact le_self_add
contrapose! hx
rw [hx, mul_zero]
· nth_rewrite 2 [unitCoeff_spec hx]
simpa [Units.isUnit, IsUnit.dvd_mul_left] using pow_dvd_pow _
theorem norm_le_pow_iff_mem_span_pow (x : ℤ_[p]) (n : ℕ) :
‖x‖ ≤ (p : ℝ) ^ (-n : ℤ) ↔ x ∈ (Ideal.span {(p : ℤ_[p]) ^ n} : Ideal ℤ_[p]) := by
by_cases hx : x = 0
· subst hx
simp only [norm_zero, zpow_neg, zpow_natCast, inv_nonneg, iff_true, Submodule.zero_mem]
exact mod_cast Nat.zero_le _
rw [norm_le_pow_iff_le_valuation x hx, mem_span_pow_iff_le_valuation x hx]
theorem norm_le_pow_iff_norm_lt_pow_add_one (x : ℤ_[p]) (n : ℤ) :
‖x‖ ≤ (p : ℝ) ^ n ↔ ‖x‖ < (p : ℝ) ^ (n + 1) := by
rw [norm_def]; exact Padic.norm_le_pow_iff_norm_lt_pow_add_one _ _
theorem norm_lt_pow_iff_norm_le_pow_sub_one (x : ℤ_[p]) (n : ℤ) :
‖x‖ < (p : ℝ) ^ n ↔ ‖x‖ ≤ (p : ℝ) ^ (n - 1) := by
rw [norm_le_pow_iff_norm_lt_pow_add_one, sub_add_cancel]
theorem norm_lt_one_iff_dvd (x : ℤ_[p]) : ‖x‖ < 1 ↔ ↑p ∣ x := by
have := norm_le_pow_iff_mem_span_pow x 1
rw [Ideal.mem_span_singleton, pow_one] at this
rw [← this, norm_le_pow_iff_norm_lt_pow_add_one]
simp only [zpow_zero, Int.ofNat_zero, Int.natCast_succ, neg_add_cancel, zero_add]
@[simp]
theorem pow_p_dvd_int_iff (n : ℕ) (a : ℤ) : (p : ℤ_[p]) ^ n ∣ a ↔ (p ^ n : ℤ) ∣ a := by
rw [← Nat.cast_pow, ← norm_int_le_pow_iff_dvd, norm_le_pow_iff_mem_span_pow,
Ideal.mem_span_singleton, Nat.cast_pow]
end NormLeIff
section Dvr
/-! ### Discrete valuation ring -/
instance : IsLocalRing ℤ_[p] :=
IsLocalRing.of_nonunits_add <| by simp only [mem_nonunits]; exact fun x y => norm_lt_one_add
theorem p_nonunit : (p : ℤ_[p]) ∈ nonunits ℤ_[p] := by
have : (p : ℝ)⁻¹ < 1 := inv_lt_one_of_one_lt₀ <| mod_cast hp.out.one_lt
rwa [← norm_p, ← mem_nonunits] at this
@[deprecated (since := "2025-07-27")] alias p_nonnunit := p_nonunit
theorem maximalIdeal_eq_span_p : maximalIdeal ℤ_[p] = Ideal.span {(p : ℤ_[p])} := by
apply le_antisymm
· intro x hx
simp only [IsLocalRing.mem_maximalIdeal, mem_nonunits] at hx
rwa [Ideal.mem_span_singleton, ← norm_lt_one_iff_dvd]
· rw [Ideal.span_le, Set.singleton_subset_iff]
exact p_nonunit
theorem prime_p : Prime (p : ℤ_[p]) := by
rw [← Ideal.span_singleton_prime, ← maximalIdeal_eq_span_p]
· infer_instance
· exact NeZero.ne _
theorem irreducible_p : Irreducible (p : ℤ_[p]) := Prime.irreducible prime_p
instance : IsDiscreteValuationRing ℤ_[p] :=
IsDiscreteValuationRing.ofHasUnitMulPowIrreducibleFactorization
⟨p, irreducible_p, fun {x hx} =>
⟨x.valuation, unitCoeff hx, by rw [mul_comm, ← unitCoeff_spec hx]⟩⟩
theorem ideal_eq_span_pow_p {s : Ideal ℤ_[p]} (hs : s ≠ ⊥) :
∃ n : ℕ, s = Ideal.span {(p : ℤ_[p]) ^ n} :=
IsDiscreteValuationRing.ideal_eq_span_pow_irreducible hs irreducible_p
open CauSeq
instance : IsAdicComplete (maximalIdeal ℤ_[p]) ℤ_[p] where
prec' x hx := by
simp only [← Ideal.one_eq_top, smul_eq_mul, mul_one, SModEq.sub_mem, maximalIdeal_eq_span_p,
Ideal.span_singleton_pow, ← norm_le_pow_iff_mem_span_pow] at hx ⊢
let x' : CauSeq ℤ_[p] norm := ⟨x, ?_⟩; swap
· intro ε hε
obtain ⟨m, hm⟩ := exists_pow_neg_lt p hε
refine ⟨m, fun n hn => lt_of_le_of_lt ?_ hm⟩
rw [← neg_sub, norm_neg]
exact hx hn
· refine ⟨x'.lim, fun n => ?_⟩
have : (0 : ℝ) < (p : ℝ) ^ (-n : ℤ) := zpow_pos (mod_cast hp.out.pos) _
obtain ⟨i, hi⟩ := equiv_def₃ (equiv_lim x') this
by_cases! hin : i ≤ n
· exact (hi i le_rfl n hin).le
· specialize hi i le_rfl i le_rfl
specialize hx hin.le
have := nonarchimedean (x n - x i : ℤ_[p]) (x i - x'.lim)
rw [sub_add_sub_cancel] at this
exact this.trans (max_le_iff.mpr ⟨hx, hi.le⟩)
end Dvr
section FractionRing
instance algebra : Algebra ℤ_[p] ℚ_[p] :=
Algebra.ofSubring (subring p)
@[simp]
theorem algebraMap_apply (x : ℤ_[p]) : algebraMap ℤ_[p] ℚ_[p] x = x :=
rfl
instance isFractionRing : IsFractionRing ℤ_[p] ℚ_[p] where
map_units := fun ⟨x, hx⟩ => by
rwa [algebraMap_apply, isUnit_iff_ne_zero, PadicInt.coe_ne_zero, ←
mem_nonZeroDivisors_iff_ne_zero]
surj x := by
by_cases hx : ‖x‖ ≤ 1
· use (⟨x, hx⟩, 1)
rw [Submonoid.coe_one, map_one, mul_one, PadicInt.algebraMap_apply, Subtype.coe_mk]
· set n := Int.toNat (-x.valuation) with hn
have hn_coe : (n : ℤ) = -x.valuation := by
rw [hn, Int.toNat_of_nonneg]
rw [Right.nonneg_neg_iff]
rw [Padic.norm_le_one_iff_val_nonneg, not_le] at hx
exact hx.le
set a := x * (p : ℚ_[p]) ^ n with ha
have ha_norm : ‖a‖ = 1 := by
have hx : x ≠ 0 := by
intro h0
rw [h0, norm_zero] at hx
exact hx zero_le_one
rw [ha, padicNormE.mul, Padic.norm_p_pow, Padic.norm_eq_zpow_neg_valuation hx,
← zpow_add', hn_coe, neg_neg, neg_add_cancel, zpow_zero]
exact Or.inl (Nat.cast_ne_zero.mpr (NeZero.ne p))
use
(⟨a, le_of_eq ha_norm⟩,
⟨(p ^ n : ℤ_[p]), mem_nonZeroDivisors_iff_ne_zero.mpr (NeZero.ne _)⟩)
simp only [a, map_pow, map_natCast, algebraMap_apply]
exists_of_eq := by
simp_rw [algebraMap_apply, Subtype.coe_inj]
exact fun h => ⟨1, by rw [h]⟩
end FractionRing
end PadicInt |
.lake/packages/mathlib/Mathlib/NumberTheory/Padics/PadicNorm.lean | import Mathlib.Algebra.Order.AbsoluteValue.Basic
import Mathlib.NumberTheory.Padics.PadicVal.Basic
/-!
# p-adic norm
This file defines the `p`-adic norm on `ℚ`.
The `p`-adic valuation on `ℚ` is the difference of the multiplicities of `p` in the numerator and
denominator of `q`. This function obeys the standard properties of a valuation, with the appropriate
assumptions on `p`.
The valuation induces a norm on `ℚ`. This norm is a nonarchimedean absolute value.
It takes values in {0} ∪ {1/p^k | k ∈ ℤ}.
## Implementation notes
Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically
by taking `[Fact p.Prime]` as a type class argument.
## References
* [F. Q. Gouvêa, *p-adic numbers*][gouvea1997]
* [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019]
* <https://en.wikipedia.org/wiki/P-adic_number>
## Tags
p-adic, p adic, padic, norm, valuation
-/
/-- If `q ≠ 0`, the `p`-adic norm of a rational `q` is `p ^ (-padicValRat p q)`.
If `q = 0`, the `p`-adic norm of `q` is `0`. -/
def padicNorm (p : ℕ) (q : ℚ) : ℚ :=
if q = 0 then 0 else (p : ℚ) ^ (-padicValRat p q)
namespace padicNorm
open padicValRat
variable {p : ℕ}
/-- Unfolds the definition of the `p`-adic norm of `q` when `q ≠ 0`. -/
@[simp]
protected theorem eq_zpow_of_nonzero {q : ℚ} (hq : q ≠ 0) :
padicNorm p q = (p : ℚ) ^ (-padicValRat p q) := by simp [hq, padicNorm]
/-- The `p`-adic norm is nonnegative. -/
protected theorem nonneg (q : ℚ) : 0 ≤ padicNorm p q :=
if hq : q = 0 then by simp [hq, padicNorm]
else by
unfold padicNorm
split_ifs
apply zpow_nonneg
exact mod_cast Nat.zero_le _
/-- The `p`-adic norm of `0` is `0`. -/
@[simp]
protected theorem zero : padicNorm p 0 = 0 := by simp [padicNorm]
/-- The `p`-adic norm of `1` is `1`. -/
protected theorem one : padicNorm p 1 = 1 := by simp [padicNorm]
/-- The `p`-adic norm of `p` is `p⁻¹` if `p > 1`.
See also `padicNorm.padicNorm_p_of_prime` for a version assuming `p` is prime. -/
theorem padicNorm_p (hp : 1 < p) : padicNorm p p = (p : ℚ)⁻¹ := by
simp [padicNorm, (pos_of_gt hp).ne', padicValNat.self hp]
/-- The `p`-adic norm of `p` is `p⁻¹` if `p` is prime.
See also `padicNorm.padicNorm_p` for a version assuming `1 < p`. -/
@[simp]
theorem padicNorm_p_of_prime [Fact p.Prime] : padicNorm p p = (p : ℚ)⁻¹ :=
padicNorm_p <| Nat.Prime.one_lt Fact.out
/-- The `p`-adic norm of `q` is `1` if `q` is prime and not equal to `p`. -/
theorem padicNorm_of_prime_of_ne {q : ℕ} [p_prime : Fact p.Prime] [q_prime : Fact q.Prime]
(neq : p ≠ q) : padicNorm p q = 1 := by
have p : padicValRat p q = 0 := mod_cast padicValNat_primes neq
rw [padicNorm, p]
simp [q_prime.1.ne_zero]
/-- The `p`-adic norm of `p` is less than `1` if `1 < p`.
See also `padicNorm.padicNorm_p_lt_one_of_prime` for a version assuming `p` is prime. -/
theorem padicNorm_p_lt_one (hp : 1 < p) : padicNorm p p < 1 := by
rw [padicNorm_p hp, inv_lt_one_iff₀]
exact mod_cast Or.inr hp
/-- The `p`-adic norm of `p` is less than `1` if `p` is prime.
See also `padicNorm.padicNorm_p_lt_one` for a version assuming `1 < p`. -/
theorem padicNorm_p_lt_one_of_prime [Fact p.Prime] : padicNorm p p < 1 :=
padicNorm_p_lt_one <| Nat.Prime.one_lt Fact.out
/-- `padicNorm p q` takes discrete values `p ^ -z` for `z : ℤ`. -/
protected theorem values_discrete {q : ℚ} (hq : q ≠ 0) : ∃ z : ℤ, padicNorm p q = (p : ℚ) ^ (-z) :=
⟨padicValRat p q, by simp [padicNorm, hq]⟩
/-- `padicNorm p` is symmetric. -/
@[simp]
protected theorem neg (q : ℚ) : padicNorm p (-q) = padicNorm p q :=
if hq : q = 0 then by simp [hq] else by simp [padicNorm, hq]
variable [hp : Fact p.Prime]
/-- If `q ≠ 0`, then `padicNorm p q ≠ 0`. -/
protected theorem nonzero {q : ℚ} (hq : q ≠ 0) : padicNorm p q ≠ 0 := by
rw [padicNorm.eq_zpow_of_nonzero hq]
apply zpow_ne_zero
exact mod_cast ne_of_gt hp.1.pos
/-- If the `p`-adic norm of `q` is 0, then `q` is `0`. -/
theorem zero_of_padicNorm_eq_zero {q : ℚ} (h : padicNorm p q = 0) : q = 0 := by
apply by_contradiction; intro hq
unfold padicNorm at h; rw [if_neg hq] at h
apply absurd h
apply zpow_ne_zero
exact mod_cast hp.1.ne_zero
/-- The `p`-adic norm is multiplicative. -/
@[simp]
protected theorem mul (q r : ℚ) : padicNorm p (q * r) = padicNorm p q * padicNorm p r :=
if hq : q = 0 then by simp [hq]
else
if hr : r = 0 then by simp [hr]
else by
have : (p : ℚ) ≠ 0 := by simp [hp.1.ne_zero]
simp [padicNorm, *, padicValRat.mul, zpow_add₀ this, mul_comm]
/-- The `p`-adic norm respects division. -/
@[simp]
protected theorem div (q r : ℚ) : padicNorm p (q / r) = padicNorm p q / padicNorm p r :=
if hr : r = 0 then by simp [hr]
else eq_div_of_mul_eq (padicNorm.nonzero hr) (by rw [← padicNorm.mul, div_mul_cancel₀ _ hr])
/-- The `p`-adic norm of an integer is at most `1`. -/
protected theorem of_int (z : ℤ) : padicNorm p z ≤ 1 := by
obtain rfl | hz := eq_or_ne z 0
· simp
· rw [padicNorm, if_neg (mod_cast hz)]
exact zpow_le_one_of_nonpos₀ (mod_cast hp.1.one_le) (by simp)
private theorem nonarchimedean_aux {q r : ℚ} (h : padicValRat p q ≤ padicValRat p r) :
padicNorm p (q + r) ≤ max (padicNorm p q) (padicNorm p r) :=
have hnqp : padicNorm p q ≥ 0 := padicNorm.nonneg _
have hnrp : padicNorm p r ≥ 0 := padicNorm.nonneg _
if hq : q = 0 then by simp [hq, max_eq_right hnrp]
else
if hr : r = 0 then by simp [hr, max_eq_left hnqp]
else
if hqr : q + r = 0 then le_trans (by simpa [hqr] using hnqp) (le_max_left _ _)
else by
unfold padicNorm; split_ifs
apply le_max_iff.2
left
apply zpow_le_zpow_right₀
· exact mod_cast le_of_lt hp.1.one_lt
· apply neg_le_neg
have : padicValRat p q = min (padicValRat p q) (padicValRat p r) := (min_eq_left h).symm
rw [this]
exact min_le_padicValRat_add hqr
/-- The `p`-adic norm is nonarchimedean: the norm of `p + q` is at most the max of the norm of `p`
and the norm of `q`. -/
protected theorem nonarchimedean {q r : ℚ} :
padicNorm p (q + r) ≤ max (padicNorm p q) (padicNorm p r) := by
wlog hle : padicValRat p q ≤ padicValRat p r generalizing q r
· rw [add_comm, max_comm]
exact this (le_of_not_ge hle)
exact nonarchimedean_aux hle
/-- The `p`-adic norm respects the triangle inequality: the norm of `p + q` is at most the norm of
`p` plus the norm of `q`. -/
theorem triangle_ineq (q r : ℚ) : padicNorm p (q + r) ≤ padicNorm p q + padicNorm p r :=
calc
padicNorm p (q + r) ≤ max (padicNorm p q) (padicNorm p r) := padicNorm.nonarchimedean
_ ≤ padicNorm p q + padicNorm p r :=
max_le_add_of_nonneg (padicNorm.nonneg _) (padicNorm.nonneg _)
/-- The `p`-adic norm of a difference is at most the max of each component. Restates the archimedean
property of the `p`-adic norm. -/
protected theorem sub {q r : ℚ} : padicNorm p (q - r) ≤ max (padicNorm p q) (padicNorm p r) := by
rw [sub_eq_add_neg, ← padicNorm.neg r]
exact padicNorm.nonarchimedean
/-- If the `p`-adic norms of `q` and `r` are different, then the norm of `q + r` is equal to the max
of the norms of `q` and `r`. -/
theorem add_eq_max_of_ne {q r : ℚ} (hne : padicNorm p q ≠ padicNorm p r) :
padicNorm p (q + r) = max (padicNorm p q) (padicNorm p r) := by
wlog hlt : padicNorm p r < padicNorm p q
· rw [add_comm, max_comm]
exact this hne.symm (hne.lt_or_gt.resolve_right hlt)
have : padicNorm p q ≤ max (padicNorm p (q + r)) (padicNorm p r) :=
calc
padicNorm p q = padicNorm p (q + r + (-r)) := by ring_nf
_ ≤ max (padicNorm p (q + r)) (padicNorm p (-r)) := padicNorm.nonarchimedean
_ = max (padicNorm p (q + r)) (padicNorm p r) := by simp
have hnge : padicNorm p r ≤ padicNorm p (q + r) := by
apply le_of_not_gt
intro hgt
rw [max_eq_right_of_lt hgt] at this
exact not_lt_of_ge this hlt
have : padicNorm p q ≤ padicNorm p (q + r) := by rwa [max_eq_left hnge] at this
apply _root_.le_antisymm
· apply padicNorm.nonarchimedean
· rwa [max_eq_left_of_lt hlt]
/-- The `p`-adic norm is an absolute value: positive-definite and multiplicative, satisfying the
triangle inequality. -/
instance : IsAbsoluteValue (padicNorm p) where
abv_nonneg' := padicNorm.nonneg
abv_eq_zero' := ⟨zero_of_padicNorm_eq_zero, fun hx ↦ by simp [hx]⟩
abv_add' := padicNorm.triangle_ineq
abv_mul' := padicNorm.mul
theorem dvd_iff_norm_le {n : ℕ} {z : ℤ} : ↑(p ^ n) ∣ z ↔ padicNorm p z ≤ (p : ℚ) ^ (-n : ℤ) := by
unfold padicNorm; split_ifs with hz
· norm_cast at hz
simp [hz]
· rw [zpow_le_zpow_iff_right₀, neg_le_neg_iff, padicValRat.of_int,
padicValInt.of_ne_one_ne_zero hp.1.ne_one _]
· norm_cast
rw [← FiniteMultiplicity.pow_dvd_iff_le_multiplicity]
· norm_cast
· apply Int.finiteMultiplicity_iff.2 ⟨by simp [hp.out.ne_one], mod_cast hz⟩
· exact_mod_cast hz
· exact_mod_cast hp.out.one_lt
/-- The `p`-adic norm of an integer `m` is one iff `p` doesn't divide `m`. -/
theorem int_eq_one_iff (m : ℤ) : padicNorm p m = 1 ↔ ¬(p : ℤ) ∣ m := by
nth_rw 2 [← pow_one p]
simp only [dvd_iff_norm_le, Nat.cast_one, zpow_neg, zpow_one, not_le]
constructor
· intro h
rw [h, inv_lt_one₀] <;> norm_cast
· exact Nat.Prime.one_lt Fact.out
· exact Nat.Prime.pos Fact.out
· simp only [padicNorm]
split_ifs
· rw [inv_lt_zero, ← Nat.cast_zero, Nat.cast_lt]
intro h
exact (Nat.not_lt_zero p h).elim
· have : 1 < (p : ℚ) := by norm_cast; exact Nat.Prime.one_lt (Fact.out : Nat.Prime p)
rw [← zpow_neg_one, zpow_lt_zpow_iff_right₀ this]
have : 0 ≤ padicValRat p m := by simp only [of_int, Nat.cast_nonneg]
intro h
rw [← zpow_zero (p : ℚ), zpow_right_inj₀] <;> linarith
theorem int_lt_one_iff (m : ℤ) : padicNorm p m < 1 ↔ (p : ℤ) ∣ m := by
rw [← not_iff_not, ← int_eq_one_iff, eq_iff_le_not_lt]
simp only [padicNorm.of_int, true_and]
theorem of_nat (m : ℕ) : padicNorm p m ≤ 1 :=
padicNorm.of_int (m : ℤ)
/-- The `p`-adic norm of a natural `m` is one iff `p` doesn't divide `m`. -/
theorem nat_eq_one_iff (m : ℕ) : padicNorm p m = 1 ↔ ¬p ∣ m := by
rw [← Int.natCast_dvd_natCast, ← int_eq_one_iff, Int.cast_natCast]
theorem nat_lt_one_iff (m : ℕ) : padicNorm p m < 1 ↔ p ∣ m := by
rw [← Int.natCast_dvd_natCast, ← int_lt_one_iff, Int.cast_natCast]
/-- If a rational is not a p-adic integer, it is not an integer. -/
theorem not_int_of_not_padic_int (p : ℕ) {a : ℚ} [hp : Fact (Nat.Prime p)]
(H : 1 < padicNorm p a) : ¬ a.isInt := by
contrapose! H
rw [Rat.eq_num_of_isInt H]
apply padicNorm.of_int
theorem sum_lt {α : Type*} {F : α → ℚ} {t : ℚ} {s : Finset α} :
s.Nonempty → (∀ i ∈ s, padicNorm p (F i) < t) → padicNorm p (∑ i ∈ s, F i) < t := by
classical
refine s.induction_on (by rintro ⟨-, ⟨⟩⟩) ?_
rintro a S haS IH - ht
by_cases hs : S.Nonempty
· rw [Finset.sum_insert haS]
exact
lt_of_le_of_lt padicNorm.nonarchimedean
(max_lt (ht a (Finset.mem_insert_self a S))
(IH hs fun b hb ↦ ht b (Finset.mem_insert_of_mem hb)))
· simp_all
theorem sum_le {α : Type*} {F : α → ℚ} {t : ℚ} {s : Finset α} :
s.Nonempty → (∀ i ∈ s, padicNorm p (F i) ≤ t) → padicNorm p (∑ i ∈ s, F i) ≤ t := by
classical
refine s.induction_on (by rintro ⟨-, ⟨⟩⟩) ?_
rintro a S haS IH - ht
by_cases hs : S.Nonempty
· rw [Finset.sum_insert haS]
exact
padicNorm.nonarchimedean.trans
(max_le (ht a (Finset.mem_insert_self a S))
(IH hs fun b hb ↦ ht b (Finset.mem_insert_of_mem hb)))
· simp_all
theorem sum_lt' {α : Type*} {F : α → ℚ} {t : ℚ} {s : Finset α}
(hF : ∀ i ∈ s, padicNorm p (F i) < t) (ht : 0 < t) : padicNorm p (∑ i ∈ s, F i) < t := by
obtain rfl | hs := Finset.eq_empty_or_nonempty s
· simp [ht]
· exact sum_lt hs hF
theorem sum_le' {α : Type*} {F : α → ℚ} {t : ℚ} {s : Finset α}
(hF : ∀ i ∈ s, padicNorm p (F i) ≤ t) (ht : 0 ≤ t) : padicNorm p (∑ i ∈ s, F i) ≤ t := by
obtain rfl | hs := Finset.eq_empty_or_nonempty s
· simp [ht]
· exact sum_le hs hF
end padicNorm |
.lake/packages/mathlib/Mathlib/NumberTheory/Padics/MahlerBasis.lean | import Mathlib.Algebra.Group.ForwardDiff
import Mathlib.Analysis.Normed.Group.Ultra
import Mathlib.NumberTheory.Padics.ProperSpace
import Mathlib.RingTheory.Binomial
import Mathlib.Topology.Algebra.InfiniteSum.Nonarchimedean
import Mathlib.Topology.Algebra.Polynomial
import Mathlib.Topology.ContinuousMap.ZeroAtInfty
import Mathlib.Topology.MetricSpace.Ultra.ContinuousMaps
/-!
# The Mahler basis of continuous functions
In this file we introduce the Mahler basis function `mahler k`, for `k : ℕ`, which is the unique
continuous map `ℤ_[p] → ℤ_[p]` agreeing with `n ↦ n.choose k` for `n ∈ ℕ`.
Using this, we prove Mahler's theorem, showing that for any continuous function `f` on `ℤ_[p]`
(valued in a normed `ℤ_[p]`-module `E`), the Mahler series `x ↦ ∑' k, mahler k x • Δ^[n] f 0`
converges (uniformly) to `f`, and this construction defines a Banach-space isomorphism between
`C(ℤ_[p], E)` and the space of sequences `ℕ → E` tending to 0.
For this, we follow the argument of Bojanić [bojanic74].
The formalisation of Mahler's theorem presented here is based on code written by Giulio Caflisch
for his bachelor's thesis at ETH Zürich.
## References
* [R. Bojanić, *A simple proof of Mahler's theorem on approximation of continuous functions of a
p-adic variable by polynomials*][bojanic74]
* [P. Colmez, *Fonctions d'une variable p-adique*][colmez2010]
## Tags
Bojanic
-/
open Finset IsUltrametricDist NNReal Filter
open scoped fwdDiff ZeroAtInfty Topology
variable {p : ℕ} [hp : Fact p.Prime]
namespace PadicInt
/-- Bound for norms of ascending Pochhammer symbols. -/
lemma norm_ascPochhammer_le (k : ℕ) (x : ℤ_[p]) :
‖(ascPochhammer ℤ_[p] k).eval x‖ ≤ ‖(k.factorial : ℤ_[p])‖ := by
let f := (ascPochhammer ℤ_[p] k).eval
change ‖f x‖ ≤ ‖_‖
have hC : (k.factorial : ℤ_[p]) ≠ 0 := Nat.cast_ne_zero.mpr k.factorial_ne_zero
have hf : ContinuousAt f x := Polynomial.continuousAt _
-- find `n : ℕ` such that `‖f x - f n‖ ≤ ‖k!‖`
obtain ⟨n, hn⟩ : ∃ n : ℕ, ‖f x - f n‖ ≤ ‖(k.factorial : ℤ_[p])‖ := by
obtain ⟨δ, hδp, hδ⟩ := Metric.continuousAt_iff.mp hf _ (norm_pos_iff.mpr hC)
obtain ⟨n, hn'⟩ := PadicInt.denseRange_natCast.exists_dist_lt x hδp
simpa only [← dist_eq_norm_sub'] using ⟨n, (hδ (dist_comm x n ▸ hn')).le⟩
-- use ultrametric property to show that `‖f n‖ ≤ ‖k!‖` implies `‖f x‖ ≤ ‖k!‖`
refine sub_add_cancel (f x) _ ▸ (IsUltrametricDist.norm_add_le_max _ (f n)).trans (max_le hn ?_)
-- finish using the fact that `n.multichoose k ∈ ℤ`
simp_rw [f, ← ascPochhammer_eval_cast, Polynomial.eval_eq_smeval,
← Ring.factorial_nsmul_multichoose_eq_ascPochhammer, smul_eq_mul, Nat.cast_mul, norm_mul]
exact mul_le_of_le_one_right (norm_nonneg _) (norm_le_one _)
instance : IsAddTorsionFree ℤ_[p] where
nsmul_right_injective _ := smul_right_injective ℤ_[p]
/-- The p-adic integers are a binomial ring, i.e. a ring where binomial coefficients make sense. -/
noncomputable instance instBinomialRing : BinomialRing ℤ_[p] where
-- We define `multichoose` as a fraction in `ℚ_[p]` together with a proof that its norm is `≤ 1`.
multichoose x k := ⟨(ascPochhammer ℤ_[p] k).eval x / (k.factorial : ℚ_[p]), by
rw [norm_div, div_le_one (by simpa using k.factorial_ne_zero)]
exact x.norm_ascPochhammer_le k⟩
factorial_nsmul_multichoose x k := by rw [← Subtype.coe_inj, nsmul_eq_mul, PadicInt.coe_mul,
PadicInt.coe_natCast, mul_div_cancel₀ _ (mod_cast k.factorial_ne_zero), Subtype.coe_inj,
Polynomial.eval_eq_smeval, Polynomial.ascPochhammer_smeval_cast]
@[fun_prop]
lemma continuous_multichoose (k : ℕ) : Continuous (fun x : ℤ_[p] ↦ Ring.multichoose x k) := by
simp only [Ring.multichoose, BinomialRing.multichoose, continuous_induced_rng]
fun_prop
@[fun_prop]
lemma continuous_choose (k : ℕ) : Continuous (fun x : ℤ_[p] ↦ Ring.choose x k) := by
simp only [Ring.choose]
fun_prop
end PadicInt
/--
The `k`-th Mahler basis function, i.e. the unique continuous function `ℤ_[p] → ℤ_[p]`
agreeing with `n ↦ n.choose k` for `n ∈ ℕ`. See [colmez2010], §1.2.1.
-/
noncomputable def mahler (k : ℕ) : C(ℤ_[p], ℤ_[p]) where
toFun x := Ring.choose x k
continuous_toFun := PadicInt.continuous_choose k
lemma mahler_apply (k : ℕ) (x : ℤ_[p]) : mahler k x = Ring.choose x k := rfl
/-- The function `mahler k` extends `n ↦ n.choose k` on `ℕ`. -/
lemma mahler_natCast_eq (k n : ℕ) : mahler k (n : ℤ_[p]) = n.choose k := by
simp only [mahler_apply, Ring.choose_natCast]
section fwdDiff
variable {M G : Type*}
/-- Bound for iterated forward differences of a continuous function from a compact space to a
nonarchimedean seminormed group. -/
lemma IsUltrametricDist.norm_fwdDiff_iter_apply_le [TopologicalSpace M] [CompactSpace M]
[AddCommMonoid M] [SeminormedAddCommGroup G] [IsUltrametricDist G]
(h : M) (f : C(M, G)) (m : M) (n : ℕ) : ‖Δ_[h]^[n] f m‖ ≤ ‖f‖ := by
-- A proof by induction on `n` would be possible but would involve some messing around to
-- define `Δ_[h]` as an operator on continuous maps (not just on bare functions). So instead we
-- use the formula for `Δ_[h]^[n] f` as a sum.
rw [fwdDiff_iter_eq_sum_shift]
refine norm_sum_le_of_forall_le_of_nonneg (norm_nonneg f) fun i _ ↦ ?_
exact (norm_zsmul_le _ _).trans (f.norm_coe_le_norm _)
/-- First step in Bojanić's proof of Mahler's theorem (equation (10) of [bojanic74]): rewrite
`Δ^[n + R] f 0` in a shape that makes it easy to bound `p`-adically. -/
private lemma bojanic_mahler_step1 [AddCommMonoidWithOne M] [AddCommGroup G] (f : M → G)
(n : ℕ) {R : ℕ} (hR : 1 ≤ R) :
Δ_[1]^[n + R] f 0 = -∑ j ∈ range (R - 1), R.choose (j + 1) • Δ_[1]^[n + (j + 1)] f 0 +
∑ k ∈ range (n + 1), ((-1 : ℤ) ^ (n - k) * n.choose k) • (f (k + R) - f k) := by
have aux : Δ_[1]^[n + R] f 0 = R.choose (R - 1 + 1) • Δ_[1]^[n + R] f 0 := by
rw [Nat.sub_add_cancel hR, Nat.choose_self, one_smul]
rw [neg_add_eq_sub, eq_sub_iff_add_eq, add_comm, aux, (by cutsat : n + R = (n + ((R - 1) + 1))),
← sum_range_succ, Nat.sub_add_cancel hR,
← sub_eq_iff_eq_add.mpr (sum_range_succ' (fun x ↦ R.choose x • Δ_[1]^[n + x] f 0) R), add_zero,
Nat.choose_zero_right, one_smul]
have : ∑ k ∈ Finset.range (R + 1), R.choose k • Δ_[1]^[n + k] f 0 = Δ_[1]^[n] f R := by
simpa only [← Function.iterate_add_apply, add_comm, nsmul_one, add_zero] using
(shift_eq_sum_fwdDiff_iter 1 (Δ_[1]^[n] f) R 0).symm
simp only [this, fwdDiff_iter_eq_sum_shift (1 : M) f n, mul_comm, nsmul_one, mul_smul, add_comm,
add_zero, smul_sub, sum_sub_distrib]
end fwdDiff
namespace PadicInt
section norm_fwdDiff
variable {p : ℕ} [hp : Fact p.Prime] {E : Type*}
[NormedAddCommGroup E] [Module ℤ_[p] E] [IsBoundedSMul ℤ_[p] E] [IsUltrametricDist E]
/--
Second step in Bojanić's proof of Mahler's theorem (equation (11) of [bojanic74]): show that values
`Δ_[1]^[n + p ^ t] f 0` for large enough `n` are bounded by the max of `(‖f‖ / p ^ s)` and `1 / p`
times a sup over values for smaller `n`.
We use `nnnorm`s on the RHS since `Finset.sup` requires an order with a bottom element.
-/
private lemma bojanic_mahler_step2 {f : C(ℤ_[p], E)} {s t : ℕ}
(hst : ∀ x y : ℤ_[p], ‖x - y‖ ≤ p ^ (-t : ℤ) → ‖f x - f y‖ ≤ ‖f‖ / p ^ s) (n : ℕ) :
‖Δ_[1]^[n + p ^ t] f 0‖ ≤ max ↑((Finset.range (p ^ t - 1)).sup
fun j ↦ ‖Δ_[1]^[n + (j + 1)] f 0‖₊ / p) (‖f‖ / p ^ s) := by
-- Use previous lemma to rewrite in a convenient form.
rw [bojanic_mahler_step1 _ _ (one_le_pow₀ hp.out.one_le)]
-- Now use ultrametric property and bound each term separately.
refine (norm_add_le_max _ _).trans (max_le_max ?_ ?_)
· -- Bounding the sum over `range (p ^ t - 1)`: every term involves a value `Δ_[1]^[·] f 0` and
-- a binomial coefficient which is divisible by `p`
rw [norm_neg, ← coe_nnnorm, coe_le_coe]
refine nnnorm_sum_le_of_forall_le (fun i hi ↦ Finset.le_sup_of_le hi ?_)
rw [← Nat.cast_smul_eq_nsmul ℤ_[p], div_eq_inv_mul]
refine (nnnorm_smul_le _ _).trans <| mul_le_mul_of_nonneg_right ?_ (by simp only [zero_le])
-- remains to show norm of binomial coeff is `≤ p⁻¹`
rw [mem_range] at hi
have : 0 < (p ^ t).choose (i + 1) := Nat.choose_pos (by cutsat)
rw [← zpow_neg_one, ← coe_le_coe, coe_nnnorm, PadicInt.norm_eq_zpow_neg_valuation
(mod_cast this.ne'), coe_zpow, NNReal.coe_natCast,
zpow_le_zpow_iff_right₀ (mod_cast hp.out.one_lt), neg_le_neg_iff,
← PadicInt.valuation_coe, PadicInt.coe_natCast, Padic.valuation_natCast, Nat.one_le_cast]
exact one_le_padicValNat_of_dvd this.ne' <| hp.out.dvd_choose_pow (by cutsat) (by cutsat)
· -- Bounding the sum over `range (n + 1)`: every term is small by the choice of `t`
refine norm_sum_le_of_forall_le_of_nonempty nonempty_range_add_one (fun i _ ↦ ?_)
calc ‖((-1 : ℤ) ^ (n - i) * n.choose i) • (f (i + ↑(p ^ t)) - f i)‖
_ ≤ ‖((-1 : ℤ) ^ (n - i) * n.choose i : ℤ_[p])‖ * ‖(f (i + ↑(p ^ t)) - f i)‖ := by
rw [← Int.cast_smul_eq_zsmul ℤ_[p]]
exact (norm_smul_le ..).trans (by norm_cast)
_ ≤ ‖f (i + ↑(p ^ t)) - f i‖ := by
apply mul_le_of_le_one_left (norm_nonneg _)
simpa only [← coe_intCast] using norm_le_one _
_ ≤ ‖f‖ / p ^ s := by
apply hst
rw [Nat.cast_pow, add_sub_cancel_left, norm_pow, norm_p, inv_pow, zpow_neg, zpow_natCast]
/--
Explicit bound for the decay rate of the Mahler coefficients of a continuous function on `ℤ_[p]`.
This will be used to prove Mahler's theorem.
-/
lemma fwdDiff_iter_le_of_forall_le {f : C(ℤ_[p], E)} {s t : ℕ}
(hst : ∀ x y : ℤ_[p], ‖x - y‖ ≤ p ^ (-t : ℤ) → ‖f x - f y‖ ≤ ‖f‖ / p ^ s) (n : ℕ) :
‖Δ_[1]^[n + s * p ^ t] f 0‖ ≤ ‖f‖ / p ^ s := by
-- We show the following more general statement by induction on `k`:
suffices ∀ {k : ℕ}, k ≤ s → ‖Δ_[1]^[n + k * p ^ t] f 0‖ ≤ ‖f‖ / p ^ k from this le_rfl
intro k hk
induction k generalizing n with
| zero => -- base case just says that `‖Δ^[·] (⇑f) 0‖` is bounded by `‖f‖`
simpa only [zero_mul, pow_zero, add_zero, div_one] using norm_fwdDiff_iter_apply_le 1 f 0 n
| succ k IH => -- induction is the "step 2" lemma above
rw [add_mul, one_mul, ← add_assoc]
refine (bojanic_mahler_step2 hst (n + k * p ^ t)).trans (max_le ?_ ?_)
· rw [← coe_nnnorm, ← NNReal.coe_natCast, ← NNReal.coe_pow, ← NNReal.coe_div, NNReal.coe_le_coe]
refine Finset.sup_le fun j _ ↦ ?_
rw [pow_succ, ← div_div, div_le_div_iff_of_pos_right (mod_cast hp.out.pos), add_right_comm]
exact_mod_cast IH (n + (j + 1)) (by cutsat)
· exact div_le_div_of_nonneg_left (norm_nonneg _)
(mod_cast pow_pos hp.out.pos _) (mod_cast pow_le_pow_right₀ hp.out.one_le hk)
/-- Key lemma for Mahler's theorem: for `f` a continuous function on `ℤ_[p]`, the sequence
`n ↦ Δ^[n] f 0` tends to 0. See `PadicInt.fwdDiff_iter_le_of_forall_le` for an explicit
estimate of the decay rate. -/
lemma fwdDiff_tendsto_zero (f : C(ℤ_[p], E)) : Tendsto (Δ_[1]^[·] f 0) atTop (𝓝 0) := by
-- first extract an `s`
refine NormedAddCommGroup.tendsto_nhds_zero.mpr (fun ε hε ↦ ?_)
have : Tendsto (fun s ↦ ‖f‖ / p ^ s) _ _ := tendsto_const_nhds.div_atTop
(tendsto_pow_atTop_atTop_of_one_lt (mod_cast hp.out.one_lt))
obtain ⟨s, hs⟩ := (this.eventually_lt_const hε).exists
refine .mp ?_ (.of_forall fun x hx ↦ lt_of_le_of_lt hx hs)
-- use uniform continuity to find `t`
obtain ⟨t, ht⟩ : ∃ t : ℕ, ∀ x y, ‖x - y‖ ≤ p ^ (-t : ℤ) → ‖f x - f y‖ ≤ ‖f‖ / p ^ s := by
rcases eq_or_ne f 0 with rfl | hf
· -- silly case : f = 0
simp
have : 0 < ‖f‖ / p ^ s := div_pos (norm_pos_iff.mpr hf) (mod_cast pow_pos hp.out.pos _)
obtain ⟨δ, hδpos, hδf⟩ := f.uniform_continuity _ this
obtain ⟨t, ht⟩ := PadicInt.exists_pow_neg_lt p hδpos
exact ⟨t, fun x y hxy ↦ by simpa only [dist_eq_norm_sub] using (hδf (hxy.trans_lt ht)).le⟩
filter_upwards [eventually_ge_atTop (s * p ^ t)] with m hm
simpa only [Nat.sub_add_cancel hm] using fwdDiff_iter_le_of_forall_le ht (m - s * p ^ t)
end norm_fwdDiff
section mahler_coeff
variable {E : Type*} [NormedAddCommGroup E] [Module ℤ_[p] E] [IsBoundedSMul ℤ_[p] E]
(a : E) (n : ℕ) (x : ℤ_[p])
/--
A single term of a Mahler series, given by the product of the scalar-valued continuous map
`mahler n : ℤ_[p] → ℤ_[p]` with a constant vector in some normed `ℤ_[p]`-module.
-/
noncomputable def mahlerTerm : C(ℤ_[p], E) := (mahler n : C(_, ℤ_[p])) • .const _ a
lemma mahlerTerm_apply : mahlerTerm a n x = mahler n x • a := by
simp only [mahlerTerm, ContinuousMap.smul_apply', ContinuousMap.const_apply]
@[simp]
lemma norm_mahlerTerm : ‖(mahlerTerm a n : C(ℤ_[p], E))‖ = ‖a‖ := by
apply le_antisymm
· -- Show all values have norm ≤ 1
rw [ContinuousMap.norm_le_of_nonempty]
refine fun _ ↦ (norm_smul_le _ _).trans <| mul_le_of_le_one_left (norm_nonneg _) (norm_le_one _)
· -- Show norm 1 is attained at `x = k`
refine le_trans ?_ <| (mahlerTerm a n).norm_coe_le_norm n
simp [mahlerTerm_apply, mahler_natCast_eq]
@[simp]
lemma mahlerTerm_one : (mahlerTerm 1 n : C(ℤ_[p], ℤ_[p])) = mahler n := by
ext; simp [mahlerTerm_apply]
/--
The uniform norm of the `k`-th Mahler basis function is 1, for every `k`.
-/
@[simp] lemma norm_mahler_eq (k : ℕ) : ‖(mahler k : C(ℤ_[p], ℤ_[p]))‖ = 1 := by
simp [← mahlerTerm_one]
/-- A series of the form considered in Mahler's theorem. -/
noncomputable def mahlerSeries (a : ℕ → E) : C(ℤ_[p], E) := ∑' n, mahlerTerm (a n) n
variable [IsUltrametricDist E] [CompleteSpace E] {a : ℕ → E}
/-- A Mahler series whose coefficients tend to 0 is convergent. -/
lemma hasSum_mahlerSeries (ha : Tendsto a atTop (𝓝 0)) :
HasSum (fun n ↦ mahlerTerm (a n) n) (mahlerSeries a : C(ℤ_[p], E)) := by
refine (NonarchimedeanAddGroup.summable_of_tendsto_cofinite_zero ?_).hasSum
rw [tendsto_zero_iff_norm_tendsto_zero] at ha ⊢
simpa only [norm_mahlerTerm, Nat.cofinite_eq_atTop] using ha
/-- Evaluation of a Mahler series is just the pointwise sum. -/
lemma mahlerSeries_apply (ha : Tendsto a atTop (𝓝 0)) (x : ℤ_[p]) :
mahlerSeries a x = ∑' n, mahler n x • a n := by
simp only [mahlerSeries, ← ContinuousMap.tsum_apply (hasSum_mahlerSeries ha).summable,
mahlerTerm_apply]
/--
The value of a Mahler series at a natural number `n` is given by the finite sum of the first `m`
terms, for any `n ≤ m`.
-/
lemma mahlerSeries_apply_nat (ha : Tendsto a atTop (𝓝 0)) {m n : ℕ} (hmn : m ≤ n) :
mahlerSeries a (m : ℤ_[p]) = ∑ i ∈ range (n + 1), m.choose i • a i := by
have h_van (i) : m.choose (i + (n + 1)) = 0 := Nat.choose_eq_zero_of_lt (by cutsat)
have aux : Summable fun i ↦ m.choose (i + (n + 1)) • a (i + (n + 1)) := by
simpa only [h_van, zero_smul] using summable_zero
simp only [mahlerSeries_apply ha, mahler_natCast_eq, Nat.cast_smul_eq_nsmul, add_zero,
← aux.sum_add_tsum_nat_add' (f := fun i ↦ m.choose i • a i), h_van, zero_smul, tsum_zero]
/--
The coefficients of a Mahler series can be recovered from the sum by taking forward differences at
`0`.
-/
lemma fwdDiff_mahlerSeries (ha : Tendsto a atTop (𝓝 0)) (n) :
Δ_[1]^[n] (mahlerSeries a) (0 : ℤ_[p]) = a n :=
calc Δ_[1]^[n] (mahlerSeries a) 0
-- throw away terms after the nth
_ = Δ_[1]^[n] (fun k ↦ ∑ j ∈ range (n + 1), k.choose j • (a j)) 0 := by
simp only [fwdDiff_iter_eq_sum_shift, zero_add]
refine Finset.sum_congr rfl fun j hj ↦ ?_
rw [nsmul_one, nsmul_one,
mahlerSeries_apply_nat ha (Nat.lt_succ.mp <| Finset.mem_range.mp hj), Nat.cast_id]
-- bring `Δ_[1]` inside sum
_ = ∑ j ∈ range (n + 1), Δ_[1]^[n] (fun k ↦ k.choose j • (a j)) 0 := by
simp only [fwdDiff_iter_eq_sum_shift, smul_sum]
rw [sum_comm]
-- bring `Δ_[1]` inside scalar-mult
_ = ∑ j ∈ range (n + 1), (Δ_[1]^[n] (fun k ↦ k.choose j : ℕ → ℤ) 0) • (a j) := by
simp only [fwdDiff_iter_eq_sum_shift, zero_add, sum_smul, smul_assoc,
natCast_zsmul]
-- finish using `fwdDiff_iter_choose_zero`
_ = a n := by
simp only [fwdDiff_iter_choose_zero, ite_smul, one_smul, zero_smul, sum_ite_eq,
Finset.mem_range, lt_add_iff_pos_right, zero_lt_one, ↓reduceIte]
/--
**Mahler's theorem**: for any continuous function `f` from `ℤ_[p]` to a `p`-adic Banach space, the
Mahler series with coefficients `n ↦ Δ_[1]^[n] f 0` converges to the original function `f`.
-/
lemma hasSum_mahler (f : C(ℤ_[p], E)) : HasSum (fun n ↦ mahlerTerm (Δ_[1]^[n] f 0) n) f := by
-- First show `∑' n, mahlerTerm f n` converges to *something*.
have : HasSum (fun n ↦ mahlerTerm (Δ_[1]^[n] f 0) n)
(mahlerSeries (Δ_[1]^[·] f 0) : C(ℤ_[p], E)) :=
hasSum_mahlerSeries (fwdDiff_tendsto_zero f)
-- Now show that the sum of the Mahler terms must equal `f` on a dense set, so it is actually `f`.
convert this using 1
refine ContinuousMap.coe_injective (denseRange_natCast.equalizer
(map_continuous f) (map_continuous _) (funext fun n ↦ ?_))
simpa [mahlerSeries_apply_nat (fwdDiff_tendsto_zero f) le_rfl]
using shift_eq_sum_fwdDiff_iter 1 f n 0
variable (E) in
/--
The isometric equivalence from `C(ℤ_[p], E)` to the space of sequences in `E` tending to `0` given
by Mahler's theorem, for `E` a nonarchimedean `ℚ_[p]`-Banach space.
-/
noncomputable def mahlerEquiv : C(ℤ_[p], E) ≃ₗᵢ[ℤ_[p]] C₀(ℕ, E) where
toFun f := ⟨⟨(Δ_[1]^[·] f 0), continuous_of_discreteTopology⟩,
cocompact_eq_atTop (α := ℕ) ▸ fwdDiff_tendsto_zero f⟩
invFun a := mahlerSeries a
map_add' f g := by
ext x
simp only [ContinuousMap.coe_add, fwdDiff_iter_add, Pi.add_apply,
ZeroAtInftyContinuousMap.coe_mk, ZeroAtInftyContinuousMap.coe_add]
map_smul' r f := by
ext n
simp only [ContinuousMap.coe_smul, RingHom.id_apply, ZeroAtInftyContinuousMap.coe_mk,
ZeroAtInftyContinuousMap.coe_smul, Pi.smul_apply, fwdDiff_iter_const_smul]
left_inv f := (hasSum_mahler f).tsum_eq
right_inv a := ZeroAtInftyContinuousMap.ext <|
fwdDiff_mahlerSeries (cocompact_eq_atTop (α := ℕ) ▸ zero_at_infty a)
norm_map' f := by
simp only [LinearEquiv.coe_mk, ← ZeroAtInftyContinuousMap.norm_toBCF_eq_norm]
apply le_antisymm
· exact BoundedContinuousFunction.norm_le_of_nonempty.mpr
(fun n ↦ norm_fwdDiff_iter_apply_le 1 f 0 n)
· rw [← (hasSum_mahler f).tsum_eq]
refine (norm_tsum_le _).trans (ciSup_le fun n ↦ ?_)
refine le_trans (le_of_eq ?_) (BoundedContinuousFunction.norm_coe_le_norm _ n)
simp [(hasSum_mahler f).tsum_eq]
lemma mahlerEquiv_apply (f : C(ℤ_[p], E)) : mahlerEquiv E f = fun n ↦ Δ_[1]^[n] f 0 := rfl
lemma mahlerEquiv_symm_apply (a : C₀(ℕ, E)) : (mahlerEquiv E).symm a = (mahlerSeries (p := p) a) :=
rfl
end mahler_coeff
end PadicInt |
.lake/packages/mathlib/Mathlib/NumberTheory/Padics/WithVal.lean | import Mathlib.Analysis.RCLike.Basic
import Mathlib.NumberTheory.Padics.PadicNumbers
import Mathlib.Topology.Algebra.Valued.ValuedField
import Mathlib.Topology.Algebra.Valued.WithVal
import Mathlib.Topology.GDelta.MetrizableSpace
/-!
# Equivalence between `ℚ_[p]` and `(Rat.padicValuation p).Completion`
The `p`-adic numbers are isomorphic as a field to the completion of the rationals at the
`p`-adic valuation. This is implemented via `Valuation.Completion` using `Rat.padicValuation`,
which is shorthand for `UniformSpace.Completion (WithVal (Rat.padicValuation p))`.
## Main definitions
* `Padic.withValRingEquiv`: the field isomorphism between
`(Rat.padicValuation p).Completion` and `ℚ_[p]`
* `Padic.withValUniformEquiv`: the uniform space isomorphism between
`(Rat.padicValuation p).Completion` and `ℚ_[p]`
-/
namespace Padic
variable {p : ℕ} [Fact p.Prime]
open NNReal WithZero UniformSpace
lemma isUniformInducing_cast_withVal : IsUniformInducing ((Rat.castHom ℚ_[p]).comp
(WithVal.equiv (Rat.padicValuation p)).toRingHom) := by
have hp0' : 0 < (p : ℚ) := by simp [Nat.Prime.pos Fact.out]
have hp0 : 0 < (p : ℝ)⁻¹ := by simp [Nat.Prime.pos Fact.out]
have hp1' : 1 < (p : ℚ) := by simp [Nat.Prime.one_lt Fact.out]
have hp1 : (p : ℝ)⁻¹ < 1 := by simp [inv_lt_one_iff₀, Nat.Prime.one_lt Fact.out]
rw [Filter.HasBasis.isUniformInducing_iff (Valued.hasBasis_uniformity _ _)
(Metric.uniformity_basis_dist_le_pow hp0 hp1)]
simp only [Set.mem_setOf_eq, dist_eq_norm_sub, inv_pow, RingEquiv.toRingHom_eq_coe,
RingHom.coe_comp, Rat.coe_castHom, RingHom.coe_coe, Function.comp_apply, ← Rat.cast_sub,
← map_sub, Padic.eq_padicNorm, true_and, forall_const]
constructor
· intro n
use Units.mk0 (exp (-n : ℤ)) (by simp)
intro x y h
set x' : ℚ := (WithVal.equiv (Rat.padicValuation p)) x with hx
set y' : ℚ := (WithVal.equiv (Rat.padicValuation p)) y with hy
rw [Valuation.map_sub_swap, Units.val_mk0] at h
change Rat.padicValuation p (x' - y') < exp _ at h
rw [← Nat.cast_pow, ← Rat.cast_natCast, ← Rat.cast_inv_of_ne_zero, Rat.cast_le]
· rw [map_sub, ← hx, ← hy]
simp only [Rat.padicValuation, Valuation.coe_mk, MonoidWithZeroHom.coe_mk, ZeroHom.coe_mk,
padicNorm, zpow_neg, Nat.cast_pow] at h ⊢
split_ifs with H
· simp
· simp only [H, ↓reduceIte, exp_lt_exp, neg_lt_neg_iff] at h
simpa [hp0', zpow_pos, pow_pos, inv_le_inv₀] using
zpow_right_mono₀ (a := (p : ℚ)) (by exact_mod_cast (Nat.Prime.one_le Fact.out)) h.le
· simp [Nat.Prime.ne_zero Fact.out]
· intro γ
use (log (γ.val * exp (- 1))).natAbs
intro x y h
set x' : ℚ := (WithVal.equiv (Rat.padicValuation p)) x with hx
set y' : ℚ := (WithVal.equiv (Rat.padicValuation p)) y with hy
rw [Valuation.map_sub_swap]
change Rat.padicValuation p (x' - y') < γ
rw [← Nat.cast_pow, ← Rat.cast_natCast, ← Rat.cast_inv_of_ne_zero, Rat.cast_le] at h
· change padicNorm p (x' - y') ≤ _ at h
simp only [Rat.padicValuation, Valuation.coe_mk, MonoidWithZeroHom.coe_mk, ZeroHom.coe_mk,
padicNorm, zpow_neg, Nat.cast_pow] at h ⊢
split_ifs with H
· simp
· rw [← lt_log_iff_exp_lt (by simp)]
simp_all [← zpow_natCast, zpow_pos, inv_le_inv₀, zpow_le_zpow_iff_right₀ hp1', abs_le,
Int.lt_iff_add_one_le]
· simp [Nat.Prime.ne_zero Fact.out]
lemma isDenseInducing_cast_withVal : IsDenseInducing ((Rat.castHom ℚ_[p]).comp
(WithVal.equiv (Rat.padicValuation p)).toRingHom) := by
refine Padic.isUniformInducing_cast_withVal.isDenseInducing ?_
intro
-- nhds_discrete causes timeouts on TC search
simpa [-nhds_discrete] using Padic.denseRange_ratCast p _
open Completion in
open scoped Valued in
/-- The `p`-adic numbers are isomorphic as a field to the completion of the rationals at
the `p`-adic valuation. -/
noncomputable
def withValRingEquiv :
(Rat.padicValuation p).Completion ≃+* ℚ_[p] where
toFun := (extensionHom ((Rat.castHom ℚ_[p]).comp (WithVal.equiv (Rat.padicValuation p)).toRingHom)
Padic.isUniformInducing_cast_withVal.uniformContinuous.continuous)
invFun := Padic.isDenseInducing_cast_withVal.extend coe'
left_inv y := by
induction y using induction_on
· generalize_proofs _ _ _ H
refine isClosed_eq ?_ continuous_id
exact (uniformContinuous_uniformly_extend Padic.isUniformInducing_cast_withVal
(Padic.denseRange_ratCast p) (uniformContinuous_coe _)).continuous.comp
(continuous_extension)
· rw [extensionHom_coe]
apply IsDenseInducing.extend_eq
exact continuous_coe _
right_inv y := by
induction y using isClosed_property (Padic.denseRange_ratCast p)
· refine isClosed_eq ?_ continuous_id
refine continuous_extension.comp ?_
exact (uniformContinuous_uniformly_extend Padic.isUniformInducing_cast_withVal
(Padic.denseRange_ratCast p) (uniformContinuous_coe _)).continuous
· have : ∀ q : ℚ, Padic.isDenseInducing_cast_withVal.extend coe' q = coe'
((WithVal.equiv (Rat.padicValuation p)).symm q) := by
intro q
apply IsDenseInducing.extend_eq
exact continuous_coe _
rw [this, extensionHom_coe]
simp
map_mul' := map_mul _
map_add' := map_add _
@[simp]
lemma coe_withValRingEquiv :
⇑(Padic.withValRingEquiv (p := p)) = Completion.extension
((↑) ∘ (WithVal.equiv (Rat.padicValuation p))) :=
rfl
@[simp]
lemma coe_withValRingEquiv_symm :
⇑(Padic.withValRingEquiv (p := p)).symm =
Padic.isDenseInducing_cast_withVal.extend Completion.coe' := by
rfl
/-- The `p`-adic numbers are isomophic as uniform spaces to the completion of the rationals at
the `p`-adic valuation. -/
noncomputable
def withValUniformEquiv :
(Rat.padicValuation p).Completion ≃ᵤ ℚ_[p] :=
UniformEquiv.symm <| Padic.withValRingEquiv.symm.toUniformEquivOfIsUniformInducing <|
isDenseInducing_cast_withVal.isUniformInducing_extend isUniformInducing_cast_withVal
(Completion.isUniformInducing_coe _)
@[simp]
lemma toEquiv_withValUniformEquiv_eq_toEquiv_withValRingEquiv :
(withValUniformEquiv (p := p) : (Rat.padicValuation p).Completion ≃ ℚ_[p]) =
(withValRingEquiv (p := p) :) :=
rfl
end Padic |
.lake/packages/mathlib/Mathlib/NumberTheory/Padics/PadicNumbers.lean | import Mathlib.RingTheory.Valuation.Basic
import Mathlib.NumberTheory.Padics.PadicNorm
import Mathlib.Analysis.Normed.Field.Lemmas
import Mathlib.Tactic.Peel
import Mathlib.Topology.MetricSpace.Ultra.Basic
/-!
# p-adic numbers
This file defines the `p`-adic numbers (rationals) `ℚ_[p]` as
the completion of `ℚ` with respect to the `p`-adic norm.
We show that the `p`-adic norm on `ℚ` extends to `ℚ_[p]`, that `ℚ` is embedded in `ℚ_[p]`,
and that `ℚ_[p]` is Cauchy complete.
## Important definitions
* `Padic` : the type of `p`-adic numbers
* `padicNormE` : the rational-valued `p`-adic norm on `ℚ_[p]`
* `Padic.addValuation` : the additive `p`-adic valuation on `ℚ_[p]`, with values in `WithTop ℤ`
## Notation
We introduce the notation `ℚ_[p]` for the `p`-adic numbers.
## Implementation notes
Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically
by taking `[Fact p.Prime]` as a type class argument.
We use the same concrete Cauchy sequence construction that is used to construct `ℝ`.
`ℚ_[p]` inherits a field structure from this construction.
The extension of the norm on `ℚ` to `ℚ_[p]` is *not* analogous to extending the absolute value to
`ℝ` and hence the proof that `ℚ_[p]` is complete is different from the proof that ℝ is complete.
`padicNormE` is the rational-valued `p`-adic norm on `ℚ_[p]`.
To instantiate `ℚ_[p]` as a normed field, we must cast this into an `ℝ`-valued norm.
The `ℝ`-valued norm, using notation `‖ ‖` from normed spaces,
is the canonical representation of this norm.
`simp` prefers `padicNorm` to `padicNormE` when possible.
Since `padicNormE` and `‖ ‖` have different types, `simp` does not rewrite one to the other.
Coercions from `ℚ` to `ℚ_[p]` are set up to work with the `norm_cast` tactic.
## References
* [F. Q. Gouvêa, *p-adic numbers*][gouvea1997]
* [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019]
* <https://en.wikipedia.org/wiki/P-adic_number>
## Tags
p-adic, p adic, padic, norm, valuation, cauchy, completion, p-adic completion
-/
open WithZero
/-- The p-adic valuation on rationals, sending `p` to `(exp (-1) : ℤᵐ⁰)` -/
def Rat.padicValuation (p : ℕ) [Fact p.Prime] : Valuation ℚ ℤᵐ⁰ where
toFun x := if x = 0 then 0 else exp (-padicValRat p x)
map_zero' := by simp
map_one' := by simp
map_mul' := by
intros
split_ifs <;>
simp_all [padicValRat.mul, exp_add, mul_comm]
map_add_le_max' := by
intros
split_ifs
any_goals simp_all [- exp_neg]
rw [← min_le_iff]
exact padicValRat.min_le_padicValRat_add ‹_›
/-- The p-adic valuation on integers, sending `p` to `(exp (-1) : ℤᵐ⁰)` -/
def Int.padicValuation (p : ℕ) [Fact p.Prime] : Valuation ℤ ℤᵐ⁰ :=
(Rat.padicValuation p).comap (Int.castRingHom ℚ)
lemma Rat.padicValuation_cast (p : ℕ) [Fact p.Prime] (x : ℤ) :
Rat.padicValuation p (Int.cast x) = Int.padicValuation p x :=
rfl
lemma Rat.padicValuation_eq_zero_iff {p : ℕ} [Fact p.Prime] {x : ℚ} :
Rat.padicValuation p x = 0 ↔ x = 0 := by
simp
@[simp]
lemma Int.padicValuation_eq_zero_iff {p : ℕ} [Fact p.Prime] {x : ℤ} :
Int.padicValuation p x = 0 ↔ x = 0 := by
simp [← Rat.padicValuation_cast]
@[simp]
lemma Rat.padicValuation_self (p : ℕ) [Fact p.Prime] :
Rat.padicValuation p p = exp (-1) := by
simp [Rat.padicValuation, Nat.Prime.ne_zero Fact.out]
@[simp]
lemma Int.padicValuation_self (p : ℕ) [Fact p.Prime] :
Int.padicValuation p p = exp (-1) := by
simp [← Rat.padicValuation_cast]
lemma Int.padicValuation_le_one (p : ℕ) [Fact p.Prime] (x : ℤ) :
Int.padicValuation p x ≤ 1 := by
simp only [← Rat.padicValuation_cast, Rat.padicValuation, Valuation.coe_mk,
MonoidWithZeroHom.coe_mk, ZeroHom.coe_mk, Rat.intCast_eq_zero_iff, padicValRat.of_int]
split_ifs
· simp
· rw [← le_log_iff_exp_le] <;>
simp_all
lemma Int.padicValuation_eq_one_iff {p : ℕ} [Fact p.Prime] {x : ℤ} :
Int.padicValuation p x = 1 ↔ ¬ (p : ℤ) ∣ x := by
simp only [← Rat.padicValuation_cast, Rat.padicValuation, Valuation.coe_mk,
MonoidWithZeroHom.coe_mk, ZeroHom.coe_mk, Rat.intCast_eq_zero_iff, padicValRat.of_int]
split_ifs
· simp_all
· rw [← exp_zero, exp_injective.eq_iff]
simp_all [Nat.Prime.ne_one Fact.out]
lemma Int.padicValuation_lt_one_iff {p : ℕ} [Fact p.Prime] {x : ℤ} :
Int.padicValuation p x < 1 ↔ (p : ℤ) ∣ x := by
simp [lt_iff_le_and_ne, padicValuation_eq_one_iff, Int.padicValuation_le_one]
lemma Rat.padicValuation_le_one_iff {p : ℕ} [Fact p.Prime] {x : ℚ} :
Rat.padicValuation p x ≤ 1 ↔ ¬ p ∣ x.den := by
nth_rw 1 [← x.num_div_den, map_div₀, ← Int.natCast_dvd_natCast, ← Int.padicValuation_eq_one_iff,
Rat.padicValuation_cast, ← Int.cast_natCast, Rat.padicValuation_cast, div_le_one₀]
· rcases (Int.padicValuation_le_one p x.den).eq_or_lt with h | h
· simp [h, Int.padicValuation_le_one]
· simp only [h.ne, iff_false, not_le]
rcases (Int.padicValuation_le_one p x.num).eq_or_lt with h' | h'
· simp [h, h']
· rw [Int.padicValuation_lt_one_iff] at h h'
exfalso
rw [Int.natCast_dvd_natCast] at h
rw [Int.natCast_dvd] at h'
exact Nat.not_coprime_of_dvd_of_dvd (Nat.Prime.one_lt Fact.out) h h' x.reduced.symm
· simp [zero_lt_iff]
theorem Rat.surjective_padicValuation (p : ℕ) [hp : Fact (p.Prime)] :
Function.Surjective (Rat.padicValuation p) := by
intro x
induction x with
| zero => simp
| coe x =>
induction x with | ofAdd x
simp_rw [Rat.padicValuation, WithZero.exp, Valuation.coe_mk, MonoidWithZeroHom.coe_mk]
rcases le_or_gt 0 x with (hx | hx)
· exact ⟨(p ^ x.natAbs)⁻¹, by simp [hp.out.ne_zero, hx]⟩
· exact ⟨p ^ x.natAbs, by simp [hp.out.ne_zero, padicValRat.pow, abs_eq_neg_self.2 hx.le]⟩
noncomputable section
open Nat padicNorm CauSeq CauSeq.Completion Metric
/-- The type of Cauchy sequences of rationals with respect to the `p`-adic norm. -/
abbrev PadicSeq (p : ℕ) :=
CauSeq _ (padicNorm p)
namespace PadicSeq
section
variable {p : ℕ} [Fact p.Prime]
/-- The `p`-adic norm of the entries of a nonzero Cauchy sequence of rationals is eventually
constant. -/
theorem stationary {f : CauSeq ℚ (padicNorm p)} (hf : ¬f ≈ 0) :
∃ N, ∀ m n, N ≤ m → N ≤ n → padicNorm p (f n) = padicNorm p (f m) :=
have : ∃ ε > 0, ∃ N1, ∀ j ≥ N1, ε ≤ padicNorm p (f j) :=
CauSeq.abv_pos_of_not_limZero <| not_limZero_of_not_congr_zero hf
let ⟨ε, hε, N1, hN1⟩ := this
let ⟨N2, hN2⟩ := CauSeq.cauchy₂ f hε
⟨max N1 N2, fun n m hn hm ↦ by
have : padicNorm p (f n - f m) < ε := hN2 _ (max_le_iff.1 hn).2 _ (max_le_iff.1 hm).2
have : padicNorm p (f n - f m) < padicNorm p (f n) :=
lt_of_lt_of_le this <| hN1 _ (max_le_iff.1 hn).1
have : padicNorm p (f n - f m) < max (padicNorm p (f n)) (padicNorm p (f m)) :=
lt_max_iff.2 (Or.inl this)
by_contra hne
rw [← padicNorm.neg (f m)] at hne
have hnam := add_eq_max_of_ne hne
rw [padicNorm.neg, max_comm] at hnam
rw [← hnam, sub_eq_add_neg, add_comm] at this
apply _root_.lt_irrefl _ this⟩
/-- For all `n ≥ stationaryPoint f hf`, the `p`-adic norm of `f n` is the same. -/
def stationaryPoint {f : PadicSeq p} (hf : ¬f ≈ 0) : ℕ :=
Classical.choose <| stationary hf
theorem stationaryPoint_spec {f : PadicSeq p} (hf : ¬f ≈ 0) :
∀ {m n},
stationaryPoint hf ≤ m → stationaryPoint hf ≤ n → padicNorm p (f n) = padicNorm p (f m) :=
@(Classical.choose_spec <| stationary hf)
open Classical in
/-- Since the norm of the entries of a Cauchy sequence is eventually stationary,
we can lift the norm to sequences. -/
def norm (f : PadicSeq p) : ℚ :=
if hf : f ≈ 0 then 0 else padicNorm p (f (stationaryPoint hf))
theorem norm_zero_iff (f : PadicSeq p) : f.norm = 0 ↔ f ≈ 0 := by
constructor
· intro h
by_contra hf
unfold norm at h
split_ifs at h
apply hf
intro ε hε
exists stationaryPoint hf
intro j hj
have heq := stationaryPoint_spec hf le_rfl hj
simpa [h, heq]
· intro h
simp [norm, h]
end
section Embedding
open CauSeq
variable {p : ℕ} [Fact p.Prime]
theorem equiv_zero_of_val_eq_of_equiv_zero {f g : PadicSeq p}
(h : ∀ k, padicNorm p (f k) = padicNorm p (g k)) (hf : f ≈ 0) : g ≈ 0 := fun ε hε ↦
let ⟨i, hi⟩ := hf _ hε
⟨i, fun j hj ↦ by simpa [h] using hi _ hj⟩
theorem norm_nonzero_of_not_equiv_zero {f : PadicSeq p} (hf : ¬f ≈ 0) : f.norm ≠ 0 :=
hf ∘ f.norm_zero_iff.1
theorem norm_eq_norm_app_of_nonzero {f : PadicSeq p} (hf : ¬f ≈ 0) :
∃ k, f.norm = padicNorm p k ∧ k ≠ 0 :=
have heq : f.norm = padicNorm p (f <| stationaryPoint hf) := by simp [norm, hf]
⟨f <| stationaryPoint hf, heq, fun h ↦
norm_nonzero_of_not_equiv_zero hf (by simpa [h] using heq)⟩
theorem not_limZero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬LimZero (const (padicNorm p) q) :=
fun h' ↦ hq <| const_limZero.1 h'
theorem not_equiv_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬const (padicNorm p) q ≈ 0 :=
fun h : LimZero (const (padicNorm p) q - 0) ↦
not_limZero_const_of_nonzero (p := p) hq <| by simpa using h
theorem norm_nonneg (f : PadicSeq p) : 0 ≤ f.norm := by
classical exact if hf : f ≈ 0 then by simp [hf, norm] else by simp [norm, hf, padicNorm.nonneg]
/-- An auxiliary lemma for manipulating sequence indices. -/
theorem lift_index_left_left {f : PadicSeq p} (hf : ¬f ≈ 0) (v2 v3 : ℕ) :
padicNorm p (f (stationaryPoint hf)) =
padicNorm p (f (max (stationaryPoint hf) (max v2 v3))) := by
apply stationaryPoint_spec hf
· apply le_max_left
· exact le_rfl
/-- An auxiliary lemma for manipulating sequence indices. -/
theorem lift_index_left {f : PadicSeq p} (hf : ¬f ≈ 0) (v1 v3 : ℕ) :
padicNorm p (f (stationaryPoint hf)) =
padicNorm p (f (max v1 (max (stationaryPoint hf) v3))) := by
apply stationaryPoint_spec hf
· apply le_trans
· apply le_max_left _ v3
· apply le_max_right
· exact le_rfl
/-- An auxiliary lemma for manipulating sequence indices. -/
theorem lift_index_right {f : PadicSeq p} (hf : ¬f ≈ 0) (v1 v2 : ℕ) :
padicNorm p (f (stationaryPoint hf)) =
padicNorm p (f (max v1 (max v2 (stationaryPoint hf)))) := by
apply stationaryPoint_spec hf
· apply le_trans
· apply le_max_right v2
· apply le_max_right
· exact le_rfl
end Embedding
section Valuation
open CauSeq
variable {p : ℕ} [Fact p.Prime]
/-! ### Valuation on `PadicSeq` -/
open Classical in
/-- The `p`-adic valuation on `ℚ` lifts to `PadicSeq p`.
`Valuation f` is defined to be the valuation of the (`ℚ`-valued) stationary point of `f`. -/
def valuation (f : PadicSeq p) : ℤ :=
if hf : f ≈ 0 then 0 else padicValRat p (f (stationaryPoint hf))
theorem norm_eq_zpow_neg_valuation {f : PadicSeq p} (hf : ¬f ≈ 0) :
f.norm = (p : ℚ) ^ (-f.valuation : ℤ) := by
rw [norm, valuation, dif_neg hf, dif_neg hf, padicNorm, if_neg]
intro H
apply CauSeq.not_limZero_of_not_congr_zero hf
intro ε hε
use stationaryPoint hf
intro n hn
rw [stationaryPoint_spec hf le_rfl hn]
simpa [H] using hε
theorem val_eq_iff_norm_eq {f g : PadicSeq p} (hf : ¬f ≈ 0) (hg : ¬g ≈ 0) :
f.valuation = g.valuation ↔ f.norm = g.norm := by
rw [norm_eq_zpow_neg_valuation hf, norm_eq_zpow_neg_valuation hg, ← neg_inj, zpow_right_inj₀]
· exact mod_cast (Fact.out : p.Prime).pos
· exact mod_cast (Fact.out : p.Prime).ne_one
end Valuation
end PadicSeq
section
open PadicSeq
-- Porting note: Commented out `padic_index_simp` tactic
/-
private unsafe def index_simp_core (hh hf hg : expr)
(at_ : Interactive.Loc := Interactive.Loc.ns [none]) : tactic Unit := do
let [v1, v2, v3] ← [hh, hf, hg].mapM fun n => tactic.mk_app `` stationary_point [n] <|> return n
let e1 ← tactic.mk_app `` lift_index_left_left [hh, v2, v3] <|> return q(True)
let e2 ← tactic.mk_app `` lift_index_left [hf, v1, v3] <|> return q(True)
let e3 ← tactic.mk_app `` lift_index_right [hg, v1, v2] <|> return q(True)
let sl ← [e1, e2, e3].foldlM (fun s e => simp_lemmas.add s e) simp_lemmas.mk
when at_ (tactic.simp_target sl >> tactic.skip)
let hs ← at_.get_locals
hs (tactic.simp_hyp sl [])
/-- This is a special-purpose tactic that lifts `padicNorm (f (stationary_point f))` to
`padicNorm (f (max _ _ _))`. -/
unsafe def tactic.interactive.padic_index_simp (l : interactive.parse interactive.types.pexpr_list)
(at_ : interactive.parse interactive.types.location) : tactic Unit := do
let [h, f, g] ← l.mapM tactic.i_to_expr
index_simp_core h f g at_
-/
end
namespace PadicSeq
section Embedding
open CauSeq
variable {p : ℕ} [hp : Fact p.Prime]
theorem norm_mul (f g : PadicSeq p) : (f * g).norm = f.norm * g.norm := by
classical
exact if hf : f ≈ 0 then by
have hg : f * g ≈ 0 := mul_equiv_zero' _ hf
simp only [hf, hg, norm, dif_pos, zero_mul]
else
if hg : g ≈ 0 then by
have hf : f * g ≈ 0 := mul_equiv_zero _ hg
simp only [hf, hg, norm, dif_pos, mul_zero]
else by
unfold norm
have hfg := mul_not_equiv_zero hf hg
simp only [hfg, hf, hg, dite_false]
-- Porting note: originally `padic_index_simp [hfg, hf, hg]`
rw [lift_index_left_left hfg, lift_index_left hf, lift_index_right hg]
apply padicNorm.mul
theorem eq_zero_iff_equiv_zero (f : PadicSeq p) : mk f = 0 ↔ f ≈ 0 :=
mk_eq
theorem ne_zero_iff_nequiv_zero (f : PadicSeq p) : mk f ≠ 0 ↔ ¬f ≈ 0 :=
eq_zero_iff_equiv_zero _ |>.not
theorem norm_const (q : ℚ) : norm (const (padicNorm p) q) = padicNorm p q := by
obtain rfl | hq := eq_or_ne q 0
· simp [norm]
· simp [norm, not_equiv_zero_const_of_nonzero hq]
theorem norm_values_discrete (a : PadicSeq p) (ha : ¬a ≈ 0) : ∃ z : ℤ, a.norm = (p : ℚ) ^ (-z) := by
let ⟨k, hk, hk'⟩ := norm_eq_norm_app_of_nonzero ha
simpa [hk] using padicNorm.values_discrete hk'
theorem norm_one : norm (1 : PadicSeq p) = 1 := by
have h1 : ¬(1 : PadicSeq p) ≈ 0 := one_not_equiv_zero _
simp [h1, norm]
private theorem norm_eq_of_equiv_aux {f g : PadicSeq p} (hf : ¬f ≈ 0) (hg : ¬g ≈ 0) (hfg : f ≈ g)
(h : padicNorm p (f (stationaryPoint hf)) ≠ padicNorm p (g (stationaryPoint hg)))
(hlt : padicNorm p (g (stationaryPoint hg)) < padicNorm p (f (stationaryPoint hf))) :
False := by
have hpn : 0 < padicNorm p (f (stationaryPoint hf)) - padicNorm p (g (stationaryPoint hg)) :=
sub_pos_of_lt hlt
obtain ⟨N, hN⟩ := hfg _ hpn
let i := max N (max (stationaryPoint hf) (stationaryPoint hg))
have hi : N ≤ i := le_max_left _ _
have hN' := hN _ hi
-- Porting note: originally `padic_index_simp [N, hf, hg] at hN' h hlt`
rw [lift_index_left hf N (stationaryPoint hg), lift_index_right hg N (stationaryPoint hf)]
at hN' h hlt
have hpne : padicNorm p (f i) ≠ padicNorm p (-g i) := by rwa [← padicNorm.neg (g i)] at h
rw [CauSeq.sub_apply, sub_eq_add_neg, add_eq_max_of_ne hpne, padicNorm.neg, max_eq_left_of_lt hlt]
at hN'
have : padicNorm p (f i) < padicNorm p (f i) := by
apply lt_of_lt_of_le hN'
apply sub_le_self
apply padicNorm.nonneg
exact lt_irrefl _ this
private theorem norm_eq_of_equiv {f g : PadicSeq p} (hf : ¬f ≈ 0) (hg : ¬g ≈ 0) (hfg : f ≈ g) :
padicNorm p (f (stationaryPoint hf)) = padicNorm p (g (stationaryPoint hg)) := by
by_contra h
cases lt_or_ge (padicNorm p (g (stationaryPoint hg))) (padicNorm p (f (stationaryPoint hf))) with
| inl hlt =>
exact norm_eq_of_equiv_aux hf hg hfg h hlt
| inr hle =>
apply norm_eq_of_equiv_aux hg hf (Setoid.symm hfg) (Ne.symm h)
exact lt_of_le_of_ne hle h
theorem norm_equiv {f g : PadicSeq p} (hfg : f ≈ g) : f.norm = g.norm := by
classical
exact if hf : f ≈ 0 then by
have hg : g ≈ 0 := Setoid.trans (Setoid.symm hfg) hf
simp [norm, hf, hg]
else by
have hg : ¬g ≈ 0 := hf ∘ Setoid.trans hfg
unfold norm; split_ifs; exact norm_eq_of_equiv hf hg hfg
private theorem norm_nonarchimedean_aux {f g : PadicSeq p} (hfg : ¬f + g ≈ 0) (hf : ¬f ≈ 0)
(hg : ¬g ≈ 0) : (f + g).norm ≤ max f.norm g.norm := by
unfold norm; split_ifs
-- Porting note: originally `padic_index_simp [hfg, hf, hg]`
rw [lift_index_left_left hfg, lift_index_left hf, lift_index_right hg]
apply padicNorm.nonarchimedean
theorem norm_nonarchimedean (f g : PadicSeq p) : (f + g).norm ≤ max f.norm g.norm := by
classical
exact if hfg : f + g ≈ 0 then by
have : 0 ≤ max f.norm g.norm := le_max_of_le_left (norm_nonneg _)
simpa only [hfg, norm]
else
if hf : f ≈ 0 then by
have hfg' : f + g ≈ g := by
change LimZero (f - 0) at hf
change LimZero (f + g - g); · simpa only [sub_zero, add_sub_cancel_right] using hf
have hcfg : (f + g).norm = g.norm := norm_equiv hfg'
have hcl : f.norm = 0 := (norm_zero_iff f).2 hf
have : max f.norm g.norm = g.norm := by rw [hcl]; exact max_eq_right (norm_nonneg _)
rw [this, hcfg]
else
if hg : g ≈ 0 then by
have hfg' : f + g ≈ f := by
change LimZero (g - 0) at hg
change LimZero (f + g - f); · simpa only [add_sub_cancel_left, sub_zero] using hg
have hcfg : (f + g).norm = f.norm := norm_equiv hfg'
have hcl : g.norm = 0 := (norm_zero_iff g).2 hg
have : max f.norm g.norm = f.norm := by rw [hcl]; exact max_eq_left (norm_nonneg _)
rw [this, hcfg]
else norm_nonarchimedean_aux hfg hf hg
theorem norm_eq {f g : PadicSeq p} (h : ∀ k, padicNorm p (f k) = padicNorm p (g k)) :
f.norm = g.norm := by
classical
exact if hf : f ≈ 0 then by
have hg : g ≈ 0 := equiv_zero_of_val_eq_of_equiv_zero h hf
simp only [hf, hg, norm, dif_pos]
else by
have hg : ¬g ≈ 0 := fun hg ↦
hf <| equiv_zero_of_val_eq_of_equiv_zero (by simp only [h, forall_const]) hg
simp only [hg, hf, norm, dif_neg, not_false_iff]
let i := max (stationaryPoint hf) (stationaryPoint hg)
have hpf : padicNorm p (f (stationaryPoint hf)) = padicNorm p (f i) := by
apply stationaryPoint_spec
· apply le_max_left
· exact le_rfl
have hpg : padicNorm p (g (stationaryPoint hg)) = padicNorm p (g i) := by
apply stationaryPoint_spec
· apply le_max_right
· exact le_rfl
rw [hpf, hpg, h]
theorem norm_neg (a : PadicSeq p) : (-a).norm = a.norm :=
norm_eq <| by simp
theorem norm_eq_of_add_equiv_zero {f g : PadicSeq p} (h : f + g ≈ 0) : f.norm = g.norm := by
have : LimZero (f + g - 0) := h
have : f ≈ -g := show LimZero (f - -g) by simpa only [sub_zero, sub_neg_eq_add]
have : f.norm = (-g).norm := norm_equiv this
simpa only [norm_neg] using this
theorem add_eq_max_of_ne {f g : PadicSeq p} (hfgne : f.norm ≠ g.norm) :
(f + g).norm = max f.norm g.norm := by
classical
have hfg : ¬f + g ≈ 0 := mt norm_eq_of_add_equiv_zero hfgne
exact if hf : f ≈ 0 then by
have : LimZero (f - 0) := hf
have : f + g ≈ g := show LimZero (f + g - g) by simpa only [sub_zero, add_sub_cancel_right]
have h1 : (f + g).norm = g.norm := norm_equiv this
have h2 : f.norm = 0 := (norm_zero_iff _).2 hf
rw [h1, h2, max_eq_right (norm_nonneg _)]
else
if hg : g ≈ 0 then by
have : LimZero (g - 0) := hg
have : f + g ≈ f := show LimZero (f + g - f) by simpa only [add_sub_cancel_left, sub_zero]
have h1 : (f + g).norm = f.norm := norm_equiv this
have h2 : g.norm = 0 := (norm_zero_iff _).2 hg
rw [h1, h2, max_eq_left (norm_nonneg _)]
else by
unfold norm at hfgne ⊢; split_ifs at hfgne ⊢
-- Porting note: originally `padic_index_simp [hfg, hf, hg] at hfgne ⊢`
rw [lift_index_left hf, lift_index_right hg] at hfgne
· rw [lift_index_left_left hfg, lift_index_left hf, lift_index_right hg]
exact padicNorm.add_eq_max_of_ne hfgne
end Embedding
end PadicSeq
/-- The `p`-adic numbers `ℚ_[p]` are the Cauchy completion of `ℚ` with respect to the `p`-adic norm.
-/
def Padic (p : ℕ) [Fact p.Prime] :=
CauSeq.Completion.Cauchy (padicNorm p)
/-- notation for p-padic rationals -/
notation "ℚ_[" p "]" => Padic p
namespace Padic
section Completion
variable {p : ℕ} [Fact p.Prime]
instance field : Field ℚ_[p] :=
Cauchy.field
instance : Inhabited ℚ_[p] :=
⟨0⟩
-- short circuits
instance : CommRing ℚ_[p] :=
Cauchy.commRing
instance : Ring ℚ_[p] :=
Cauchy.ring
instance : Zero ℚ_[p] := by infer_instance
instance : One ℚ_[p] := by infer_instance
instance : Add ℚ_[p] := by infer_instance
instance : Mul ℚ_[p] := by infer_instance
instance : Sub ℚ_[p] := by infer_instance
instance : Neg ℚ_[p] := by infer_instance
instance : Div ℚ_[p] := by infer_instance
instance : AddCommGroup ℚ_[p] := by infer_instance
/-- Builds the equivalence class of a Cauchy sequence of rationals. -/
def mk : PadicSeq p → ℚ_[p] :=
Quotient.mk'
variable (p)
theorem zero_def : (0 : ℚ_[p]) = ⟦0⟧ := rfl
theorem mk_eq {f g : PadicSeq p} : mk f = mk g ↔ f ≈ g :=
Quotient.eq'
theorem const_equiv {q r : ℚ} : const (padicNorm p) q ≈ const (padicNorm p) r ↔ q = r :=
⟨fun heq ↦ eq_of_sub_eq_zero <| const_limZero.1 heq, fun heq ↦ by
rw [heq]⟩
@[norm_cast]
theorem coe_inj {q r : ℚ} : (↑q : ℚ_[p]) = ↑r ↔ q = r :=
⟨(const_equiv p).1 ∘ Quotient.eq'.1, fun h ↦ by rw [h]⟩
instance : CharZero ℚ_[p] :=
⟨fun m n ↦ by
rw [← Rat.cast_natCast]
norm_cast
exact id⟩
@[norm_cast]
theorem coe_add : ∀ {x y : ℚ}, (↑(x + y) : ℚ_[p]) = ↑x + ↑y :=
Rat.cast_add _ _
@[norm_cast]
theorem coe_neg : ∀ {x : ℚ}, (↑(-x) : ℚ_[p]) = -↑x :=
Rat.cast_neg _
@[norm_cast]
theorem coe_mul : ∀ {x y : ℚ}, (↑(x * y) : ℚ_[p]) = ↑x * ↑y :=
Rat.cast_mul _ _
@[norm_cast]
theorem coe_sub : ∀ {x y : ℚ}, (↑(x - y) : ℚ_[p]) = ↑x - ↑y :=
Rat.cast_sub _ _
@[norm_cast]
theorem coe_div : ∀ {x y : ℚ}, (↑(x / y) : ℚ_[p]) = ↑x / ↑y :=
Rat.cast_div _ _
@[norm_cast]
theorem coe_one : (↑(1 : ℚ) : ℚ_[p]) = 1 := rfl
@[norm_cast]
theorem coe_zero : (↑(0 : ℚ) : ℚ_[p]) = 0 := rfl
end Completion
end Padic
/-- The rational-valued `p`-adic norm on `ℚ_[p]` is lifted from the norm on Cauchy sequences. The
canonical form of this function is the normed space instance, with notation `‖ ‖`. -/
def padicNormE {p : ℕ} [hp : Fact p.Prime] : AbsoluteValue ℚ_[p] ℚ where
toFun := Quotient.lift PadicSeq.norm <| @PadicSeq.norm_equiv _ _
map_mul' q r := Quotient.inductionOn₂ q r <| PadicSeq.norm_mul
nonneg' q := Quotient.inductionOn q <| PadicSeq.norm_nonneg
eq_zero' q := Quotient.inductionOn q fun r ↦ by
rw [Padic.zero_def, Quotient.eq]
exact PadicSeq.norm_zero_iff r
add_le' q r := by
trans
max ((Quotient.lift PadicSeq.norm <| @PadicSeq.norm_equiv _ _) q)
((Quotient.lift PadicSeq.norm <| @PadicSeq.norm_equiv _ _) r)
· exact Quotient.inductionOn₂ q r <| PadicSeq.norm_nonarchimedean
refine max_le_add_of_nonneg (Quotient.inductionOn q <| PadicSeq.norm_nonneg) ?_
exact Quotient.inductionOn r <| PadicSeq.norm_nonneg
namespace padicNormE
section Embedding
open PadicSeq
variable {p : ℕ} [Fact p.Prime]
theorem defn (f : PadicSeq p) {ε : ℚ} (hε : 0 < ε) :
∃ N, ∀ i ≥ N, padicNormE (Padic.mk f - f i : ℚ_[p]) < ε := by
dsimp [padicNormE]
-- `change ∃ N, ∀ i ≥ N, (f - const _ (f i)).norm < ε` also works, but is very slow
suffices hyp : ∃ N, ∀ i ≥ N, (f - const _ (f i)).norm < ε by peel hyp with N; use N
by_contra! h
obtain ⟨N, hN⟩ := cauchy₂ f hε
rcases h N with ⟨i, hi, hge⟩
have hne : ¬f - const (padicNorm p) (f i) ≈ 0 := fun h ↦ by
rw [PadicSeq.norm, dif_pos h] at hge
exact not_lt_of_ge hge hε
unfold PadicSeq.norm at hge; split_ifs at hge
apply not_le_of_gt _ hge
cases _root_.le_total N (stationaryPoint hne) with
| inl hgen =>
exact hN _ hgen _ hi
| inr hngen =>
have := stationaryPoint_spec hne le_rfl hngen
rw [← this]
exact hN _ le_rfl _ hi
/-- Theorems about `padicNormE` are named with a `'` so the names do not conflict with the
equivalent theorems about `norm` (`‖ ‖`). -/
theorem nonarchimedean' (q r : ℚ_[p]) :
padicNormE (q + r : ℚ_[p]) ≤ max (padicNormE q) (padicNormE r) :=
Quotient.inductionOn₂ q r <| norm_nonarchimedean
/-- Theorems about `padicNormE` are named with a `'` so the names do not conflict with the
equivalent theorems about `norm` (`‖ ‖`). -/
theorem add_eq_max_of_ne' {q r : ℚ_[p]} :
padicNormE q ≠ padicNormE r → padicNormE (q + r : ℚ_[p]) = max (padicNormE q) (padicNormE r) :=
Quotient.inductionOn₂ q r fun _ _ ↦ PadicSeq.add_eq_max_of_ne
@[simp]
theorem eq_padic_norm' (q : ℚ) : padicNormE (q : ℚ_[p]) = padicNorm p q :=
norm_const _
protected theorem image' {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, padicNormE q = (p : ℚ) ^ (-n) :=
Quotient.inductionOn q fun f hf ↦
have : ¬f ≈ 0 := (ne_zero_iff_nequiv_zero f).1 hf
norm_values_discrete f this
end Embedding
end padicNormE
namespace Padic
section Complete
open PadicSeq Padic
variable {p : ℕ} [Fact p.Prime] (f : CauSeq _ (@padicNormE p _))
theorem rat_dense' (q : ℚ_[p]) {ε : ℚ} (hε : 0 < ε) : ∃ r : ℚ, padicNormE (q - r : ℚ_[p]) < ε :=
Quotient.inductionOn q fun q' ↦
have : ∃ N, ∀ m ≥ N, ∀ n ≥ N, padicNorm p (q' m - q' n) < ε := cauchy₂ _ hε
let ⟨N, hN⟩ := this
⟨q' N, by
classical
dsimp [padicNormE]
convert_to PadicSeq.norm (q' - const _ (q' N)) < ε -- `change` times out here.
rcases Decidable.em (q' - const (padicNorm p) (q' N) ≈ 0) with heq | hne'
· simpa only [heq, PadicSeq.norm, dif_pos]
· simp only [PadicSeq.norm, dif_neg hne']
change padicNorm p (q' _ - q' _) < ε
rcases Decidable.em (stationaryPoint hne' ≤ N) with hle | hle
· have := (stationaryPoint_spec hne' le_rfl hle).symm
simp only [const_apply, sub_apply, padicNorm.zero, sub_self] at this
simpa only [this]
· exact hN _ (lt_of_not_ge hle).le _ le_rfl⟩
private theorem div_nat_pos (n : ℕ) : 0 < 1 / (n + 1 : ℚ) :=
div_pos zero_lt_one (mod_cast succ_pos _)
/-- `limSeq f`, for `f` a Cauchy sequence of `p`-adic numbers, is a sequence of rationals with the
same limit point as `f`. -/
def limSeq : ℕ → ℚ :=
fun n ↦ Classical.choose (rat_dense' (f n) (div_nat_pos n))
theorem exi_rat_seq_conv {ε : ℚ} (hε : 0 < ε) :
∃ N, ∀ i ≥ N, padicNormE (f i - (limSeq f i : ℚ_[p]) : ℚ_[p]) < ε := by
refine (exists_nat_gt (1 / ε)).imp fun N hN i hi ↦ ?_
have h := Classical.choose_spec (rat_dense' (f i) (div_nat_pos i))
refine lt_of_lt_of_le h ((div_le_iff₀' <| mod_cast succ_pos _).mpr ?_)
rw [right_distrib]
apply le_add_of_le_of_nonneg
· exact (div_le_iff₀ hε).mp (le_trans (le_of_lt hN) (mod_cast hi))
· apply le_of_lt
simpa
theorem exi_rat_seq_conv_cauchy : IsCauSeq (padicNorm p) (limSeq f) := fun ε hε ↦ by
have hε3 : 0 < ε / 3 := div_pos hε (by simp)
let ⟨N, hN⟩ := exi_rat_seq_conv f hε3
let ⟨N2, hN2⟩ := f.cauchy₂ hε3
exists max N N2
intro j hj
suffices
padicNormE (limSeq f j - f (max N N2) + (f (max N N2) - limSeq f (max N N2)) : ℚ_[p]) < ε by
ring_nf at this
rw [← padicNormE.eq_padic_norm']
exact mod_cast this
apply lt_of_le_of_lt
· apply padicNormE.add_le
· rw [← add_thirds ε]
apply _root_.add_lt_add
· suffices padicNormE (limSeq f j - f j + (f j - f (max N N2)) : ℚ_[p]) < ε / 3 + ε / 3 by
simpa only [sub_add_sub_cancel]
apply lt_of_le_of_lt
· apply padicNormE.add_le
· apply _root_.add_lt_add
· rw [padicNormE.map_sub]
apply mod_cast hN j
exact le_of_max_le_left hj
· exact hN2 _ (le_of_max_le_right hj) _ (le_max_right _ _)
· apply mod_cast hN (max N N2)
apply le_max_left
private def lim' : PadicSeq p :=
⟨_, exi_rat_seq_conv_cauchy f⟩
private def lim : ℚ_[p] :=
⟦lim' f⟧
theorem complete' : ∃ q : ℚ_[p], ∀ ε > 0, ∃ N, ∀ i ≥ N, padicNormE (q - f i : ℚ_[p]) < ε :=
⟨lim f, fun ε hε ↦ by
obtain ⟨N, hN⟩ := exi_rat_seq_conv f (half_pos hε)
obtain ⟨N2, hN2⟩ := padicNormE.defn (lim' f) (half_pos hε)
refine ⟨max N N2, fun i hi ↦ ?_⟩
rw [← sub_add_sub_cancel _ (lim' f i : ℚ_[p]) _]
refine (padicNormE.add_le _ _).trans_lt ?_
rw [← add_halves ε]
apply _root_.add_lt_add
· apply hN2 _ (le_of_max_le_right hi)
· rw [padicNormE.map_sub]
exact hN _ (le_of_max_le_left hi)⟩
theorem complete'' : ∃ q : ℚ_[p], ∀ ε > 0, ∃ N, ∀ i ≥ N, padicNormE (f i - q : ℚ_[p]) < ε := by
obtain ⟨x, hx⟩ := complete' f
refine ⟨x, fun ε hε => ?_⟩
obtain ⟨N, hN⟩ := hx ε hε
refine ⟨N, fun i hi => ?_⟩
rw [padicNormE.map_sub]
exact hN i hi
end Complete
section NormedSpace
variable (p : ℕ) [Fact p.Prime]
instance : Dist ℚ_[p] :=
⟨fun x y ↦ padicNormE (x - y : ℚ_[p])⟩
instance : IsUltrametricDist ℚ_[p] :=
⟨fun x y z ↦ by simpa [dist] using padicNormE.nonarchimedean' (x - y) (y - z)⟩
instance metricSpace : MetricSpace ℚ_[p] where
dist_self := by simp [dist]
dist := dist
dist_comm x y := by simp [dist, ← padicNormE.map_neg (x - y : ℚ_[p])]
dist_triangle x y z := by
dsimp [dist]
exact mod_cast padicNormE.sub_le x y z
eq_of_dist_eq_zero := by
dsimp [dist]; intro _ _ h
apply eq_of_sub_eq_zero
apply padicNormE.eq_zero.1
exact mod_cast h
instance : Norm ℚ_[p] :=
⟨fun x ↦ padicNormE x⟩
instance normedField : NormedField ℚ_[p] :=
{ Padic.field,
Padic.metricSpace p with
dist_eq := fun _ _ ↦ rfl
norm_mul := by simp [Norm.norm, map_mul]
norm := norm }
instance isAbsoluteValue : IsAbsoluteValue fun a : ℚ_[p] ↦ ‖a‖ where
abv_nonneg' := norm_nonneg
abv_eq_zero' := norm_eq_zero
abv_add' := norm_add_le
abv_mul' := by simp [Norm.norm, map_mul]
theorem rat_dense (q : ℚ_[p]) {ε : ℝ} (hε : 0 < ε) : ∃ r : ℚ, ‖q - r‖ < ε :=
let ⟨ε', hε'l, hε'r⟩ := exists_rat_btwn hε
let ⟨r, hr⟩ := rat_dense' q (ε := ε') (by simpa using hε'l)
⟨r, lt_trans (by simpa [Norm.norm] using hr) hε'r⟩
lemma denseRange_ratCast : DenseRange ((↑) : ℚ → ℚ_[p]) := by
intro x
rw [Metric.mem_closure_range_iff]
exact fun _ ↦ Padic.rat_dense _ x
end NormedSpace
end Padic
namespace Padic
variable {p : ℕ} [hp : Fact p.Prime]
section NormedSpace
protected theorem padicNormE.mul (q r : ℚ_[p]) : ‖q * r‖ = ‖q‖ * ‖r‖ := by simp [Norm.norm, map_mul]
protected theorem padicNormE.is_norm (q : ℚ_[p]) : ↑(padicNormE q) = ‖q‖ := rfl
theorem nonarchimedean (q r : ℚ_[p]) : ‖q + r‖ ≤ max ‖q‖ ‖r‖ := by
dsimp [norm]
exact mod_cast padicNormE.nonarchimedean' _ _
theorem add_eq_max_of_ne {q r : ℚ_[p]} (h : ‖q‖ ≠ ‖r‖) : ‖q + r‖ = max ‖q‖ ‖r‖ := by
dsimp [norm] at h ⊢
have : padicNormE q ≠ padicNormE r := mod_cast h
exact mod_cast padicNormE.add_eq_max_of_ne' this
@[simp]
theorem eq_padicNorm (q : ℚ) : ‖(q : ℚ_[p])‖ = padicNorm p q := by
dsimp [norm]
rw [← padicNormE.eq_padic_norm']
@[simp]
theorem norm_p : ‖(p : ℚ_[p])‖ = (p : ℝ)⁻¹ := by
rw [← @Rat.cast_natCast ℝ _ p]
rw [← @Rat.cast_natCast ℚ_[p] _ p]
simp [hp.1.ne_zero, norm, padicNorm, padicValRat, padicValInt, zpow_neg,
-Rat.cast_natCast]
theorem norm_p_lt_one : ‖(p : ℚ_[p])‖ < 1 := by
rw [norm_p]
exact inv_lt_one_of_one_lt₀ <| mod_cast hp.1.one_lt
@[simp high] -- Shortcut lemma with higher priority.
theorem norm_p_zpow (n : ℤ) : ‖(p : ℚ_[p]) ^ n‖ = (p : ℝ) ^ (-n) := by
rw [norm_zpow, norm_p, zpow_neg, inv_zpow]
@[simp high] -- Shortcut lemma with higher priority.
theorem norm_p_pow (n : ℕ) : ‖(p : ℚ_[p]) ^ n‖ = (p : ℝ) ^ (-n : ℤ) := by
rw [← norm_p_zpow, zpow_natCast]
instance : NontriviallyNormedField ℚ_[p] :=
{ Padic.normedField p with
non_trivial :=
⟨p⁻¹, by
rw [norm_inv, norm_p, inv_inv]
exact mod_cast hp.1.one_lt⟩ }
protected theorem padicNormE.image {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, ‖q‖ = ↑((p : ℚ) ^ (-n)) :=
Quotient.inductionOn q fun f hf ↦
have : ¬f ≈ 0 := (PadicSeq.ne_zero_iff_nequiv_zero f).1 hf
let ⟨n, hn⟩ := PadicSeq.norm_values_discrete f this
⟨n, by rw [← hn]; rfl⟩
protected theorem padicNormE.is_rat (q : ℚ_[p]) : ∃ q' : ℚ, ‖q‖ = q' := by
classical
exact if h : q = 0 then ⟨0, by simp [h]⟩
else
let ⟨n, hn⟩ := padicNormE.image h
⟨_, hn⟩
/-- `ratNorm q`, for a `p`-adic number `q` is the `p`-adic norm of `q`, as rational number.
The lemma `padicNormE.eq_ratNorm` asserts `‖q‖ = ratNorm q`. -/
def ratNorm (q : ℚ_[p]) : ℚ :=
Classical.choose (padicNormE.is_rat q)
theorem eq_ratNorm (q : ℚ_[p]) : ‖q‖ = ratNorm q :=
Classical.choose_spec (padicNormE.is_rat q)
theorem norm_rat_le_one : ∀ {q : ℚ} (_ : ¬p ∣ q.den), ‖(q : ℚ_[p])‖ ≤ 1
| ⟨n, d, hn, hd⟩ => fun hq : ¬p ∣ d ↦
if hnz : n = 0 then by
have : (⟨n, d, hn, hd⟩ : ℚ) = 0 := Rat.zero_iff_num_zero.mpr hnz
norm_num [this]
else by
have hnz' : (⟨n, d, hn, hd⟩ : ℚ) ≠ 0 := mt Rat.zero_iff_num_zero.1 hnz
rw [eq_padicNorm]
norm_cast
-- Porting note: `Nat.cast_zero` instead of another `norm_cast` call
rw [padicNorm.eq_zpow_of_nonzero hnz', padicValRat, neg_sub,
padicValNat.eq_zero_of_not_dvd hq, Nat.cast_zero, zero_sub, zpow_neg, zpow_natCast]
apply inv_le_one_of_one_le₀
norm_cast
apply one_le_pow
exact hp.1.pos
theorem norm_int_le_one (z : ℤ) : ‖(z : ℚ_[p])‖ ≤ 1 :=
suffices ‖((z : ℚ) : ℚ_[p])‖ ≤ 1 by simpa
norm_rat_le_one <| by simp [hp.1.ne_one]
@[simp]
theorem norm_intCast_lt_one_iff {k : ℤ} : ‖(k : ℚ_[p])‖ < 1 ↔ ↑p ∣ k := by
constructor
· intro h
contrapose! h
apply le_of_eq
rw [eq_comm]
calc
‖(k : ℚ_[p])‖ = ‖((k : ℚ) : ℚ_[p])‖ := by norm_cast
_ = padicNorm p k := eq_padicNorm _
_ = 1 := mod_cast (int_eq_one_iff k).mpr h
· rintro ⟨x, rfl⟩
push_cast
rw [padicNormE.mul]
calc
_ ≤ ‖(p : ℚ_[p])‖ * 1 :=
mul_le_mul le_rfl (by simpa using norm_int_le_one _) (norm_nonneg _) (norm_nonneg _)
_ < 1 := by
rw [mul_one, norm_p]
exact inv_lt_one_of_one_lt₀ <| mod_cast hp.1.one_lt
@[deprecated (since := "2025-08-15")] alias norm_int_lt_one_iff_dvd := norm_intCast_lt_one_iff
@[simp]
lemma norm_natCast_lt_one_iff {n : ℕ} :
‖(n : ℚ_[p])‖ < 1 ↔ p ∣ n := by
simpa [Int.natCast_dvd_natCast] using norm_intCast_lt_one_iff (p := p) (k := n)
@[simp]
lemma norm_intCast_eq_one_iff {z : ℤ} :
‖(z : ℚ_[p])‖ = 1 ↔ IsCoprime z p := by
rw [← not_iff_not]
simp [Nat.coprime_comm, ← norm_natCast_lt_one_iff, - norm_intCast_lt_one_iff,
Int.isCoprime_iff_gcd_eq_one, Nat.coprime_iff_gcd_eq_one, Int.gcd,
← hp.out.dvd_iff_not_coprime, norm_natAbs, - cast_natAbs, norm_int_le_one]
@[simp]
lemma norm_natCast_eq_one_iff {n : ℕ} :
‖(n : ℚ_[p])‖ = 1 ↔ p.Coprime n := by
simpa [p.coprime_comm] using norm_intCast_eq_one_iff (p := p) (z := n)
theorem norm_int_le_pow_iff_dvd (k : ℤ) (n : ℕ) :
‖(k : ℚ_[p])‖ ≤ (p : ℝ) ^ (-n : ℤ) ↔ (p ^ n : ℤ) ∣ k := by
have : (p : ℝ) ^ (-n : ℤ) = (p : ℚ) ^ (-n : ℤ) := by simp
rw [show (k : ℚ_[p]) = ((k : ℚ) : ℚ_[p]) by norm_cast, eq_padicNorm, this]
norm_cast
rw [← padicNorm.dvd_iff_norm_le]
theorem norm_eq_of_norm_add_lt_right {z1 z2 : ℚ_[p]} (h : ‖z1 + z2‖ < ‖z2‖) : ‖z1‖ = ‖z2‖ :=
_root_.by_contradiction fun hne ↦
not_lt_of_ge (by rw [add_eq_max_of_ne hne]; apply le_max_right) h
@[deprecated (since := "2025-09-17")] alias eq_of_norm_add_lt_right := norm_eq_of_norm_add_lt_right
theorem norm_eq_of_norm_add_lt_left {z1 z2 : ℚ_[p]} (h : ‖z1 + z2‖ < ‖z1‖) : ‖z1‖ = ‖z2‖ :=
_root_.by_contradiction fun hne ↦
not_lt_of_ge (by rw [add_eq_max_of_ne hne]; apply le_max_left) h
@[deprecated (since := "2025-09-17")] alias eq_of_norm_add_lt_left := norm_eq_of_norm_add_lt_left
theorem norm_eq_of_norm_sub_lt_right {z1 z2 : ℚ_[p]} (h : ‖z1 - z2‖ < ‖z2‖) : ‖z1‖ = ‖z2‖ := by
rw [← norm_neg z2]
apply norm_eq_of_norm_add_lt_right
simp [← sub_eq_add_neg, h]
theorem norm_eq_of_norm_sub_lt_left {z1 z2 : ℚ_[p]} (h : ‖z1 - z2‖ < ‖z1‖) : ‖z1‖ = ‖z2‖ := by
rw [eq_comm]
apply norm_eq_of_norm_sub_lt_right
simpa [← norm_neg (z1 - _)] using h
@[simp]
lemma norm_natCast_p_sub_one :
‖((p - 1 : ℕ) : ℚ_[p])‖ = 1 := by
rw [norm_natCast_eq_one_iff]
exact (coprime_self_sub_right hp.out.one_le).mpr p.coprime_one_right
end NormedSpace
instance complete : CauSeq.IsComplete ℚ_[p] norm where
isComplete f := by
have cau_seq_norm_e : IsCauSeq padicNormE f := fun ε hε => by
have h := isCauSeq f ε (mod_cast hε)
dsimp [norm] at h
exact mod_cast h
-- Porting note: Padic.complete' works with `f i - q`, but the goal needs `q - f i`,
-- using `rewrite [padicNormE.map_sub]` causes time out, so a separate lemma is created
obtain ⟨q, hq⟩ := Padic.complete'' ⟨f, cau_seq_norm_e⟩
exists q
intro ε hε
obtain ⟨ε', hε'⟩ := exists_rat_btwn hε
norm_cast at hε'
obtain ⟨N, hN⟩ := hq ε' hε'.1
exists N
intro i hi
have h := hN i hi
change norm (f i - q) < ε
refine lt_trans ?_ hε'.2
dsimp [norm]
exact mod_cast h
theorem padicNormE_lim_le {f : CauSeq ℚ_[p] norm} {a : ℝ} (ha : 0 < a) (hf : ∀ i, ‖f i‖ ≤ a) :
‖f.lim‖ ≤ a := by
obtain ⟨N, hN⟩ := Setoid.symm (CauSeq.equiv_lim f) _ ha
calc
‖f.lim‖ = ‖f.lim - f N + f N‖ := by simp
_ ≤ max ‖f.lim - f N‖ ‖f N‖ := nonarchimedean _ _
_ ≤ a := max_le (le_of_lt (hN _ le_rfl)) (hf _)
open Filter Set
instance : CompleteSpace ℚ_[p] := by
apply complete_of_cauchySeq_tendsto
intro u hu
let c : CauSeq ℚ_[p] norm := ⟨u, Metric.cauchySeq_iff'.mp hu⟩
refine ⟨c.lim, fun s h ↦ ?_⟩
rcases Metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩
have := c.equiv_lim ε ε0
simp only [mem_map, mem_atTop_sets]
exact this.imp fun N hN n hn ↦ hε (hN n hn)
/-! ### Valuation on `ℚ_[p]` -/
/-- `Padic.valuation` lifts the `p`-adic valuation on rationals to `ℚ_[p]`. -/
def valuation : ℚ_[p] → ℤ :=
Quotient.lift (@PadicSeq.valuation p _) fun f g h ↦ by
by_cases hf : f ≈ 0
· have hg : g ≈ 0 := Setoid.trans (Setoid.symm h) hf
simp [hf, hg, PadicSeq.valuation]
· have hg : ¬g ≈ 0 := fun hg ↦ hf (Setoid.trans h hg)
rw [PadicSeq.val_eq_iff_norm_eq hf hg]
exact PadicSeq.norm_equiv h
@[simp]
theorem valuation_zero : valuation (0 : ℚ_[p]) = 0 :=
dif_pos ((const_equiv p).2 rfl)
theorem norm_eq_zpow_neg_valuation {x : ℚ_[p]} : x ≠ 0 → ‖x‖ = (p : ℝ) ^ (-x.valuation) := by
refine Quotient.inductionOn' x fun f hf => ?_
change (PadicSeq.norm _ : ℝ) = (p : ℝ) ^ (-PadicSeq.valuation _)
rw [PadicSeq.norm_eq_zpow_neg_valuation]
· rw [Rat.cast_zpow, Rat.cast_natCast]
· apply CauSeq.not_limZero_of_not_congr_zero
contrapose! hf
apply Quotient.sound
simpa using hf
@[simp]
lemma valuation_ratCast (q : ℚ) : valuation (q : ℚ_[p]) = padicValRat p q := by
rcases eq_or_ne q 0 with rfl | hq
· simp only [Rat.cast_zero, valuation_zero, padicValRat.zero]
refine neg_injective ((zpow_right_strictMono₀ (mod_cast hp.out.one_lt)).injective
<| (norm_eq_zpow_neg_valuation (mod_cast hq)).symm.trans ?_)
rw [eq_padicNorm, ← Rat.cast_natCast, ← Rat.cast_zpow, Rat.cast_inj]
exact padicNorm.eq_zpow_of_nonzero hq
@[simp]
lemma valuation_intCast (n : ℤ) : valuation (n : ℚ_[p]) = padicValInt p n := by
rw [← Rat.cast_intCast, valuation_ratCast, padicValRat.of_int]
@[simp]
lemma valuation_natCast (n : ℕ) : valuation (n : ℚ_[p]) = padicValNat p n := by
rw [← Rat.cast_natCast, valuation_ratCast, padicValRat.of_nat]
@[simp]
lemma valuation_ofNat (n : ℕ) [n.AtLeastTwo] :
valuation (ofNat(n) : ℚ_[p]) = padicValNat p n :=
valuation_natCast n
@[simp]
lemma valuation_one : valuation (1 : ℚ_[p]) = 0 := by
rw [← Nat.cast_one, valuation_natCast, padicValNat.one, cast_zero]
-- not @[simp], since simp can prove it
lemma valuation_p : valuation (p : ℚ_[p]) = 1 := by
rw [valuation_natCast, padicValNat_self, cast_one]
theorem le_valuation_add {x y : ℚ_[p]} (hxy : x + y ≠ 0) :
min x.valuation y.valuation ≤ (x + y).valuation := by
by_cases hx : x = 0
· simpa only [hx, zero_add] using min_le_right _ _
by_cases hy : y = 0
· simpa only [hy, add_zero] using min_le_left _ _
have : ‖x + y‖ ≤ max ‖x‖ ‖y‖ := nonarchimedean x y
simpa only [norm_eq_zpow_neg_valuation hxy, norm_eq_zpow_neg_valuation hx,
norm_eq_zpow_neg_valuation hy, le_max_iff,
zpow_le_zpow_iff_right₀ (mod_cast hp.out.one_lt : 1 < (p : ℝ)), neg_le_neg_iff, ← min_le_iff]
@[simp]
lemma valuation_mul {x y : ℚ_[p]} (hx : x ≠ 0) (hy : y ≠ 0) :
(x * y).valuation = x.valuation + y.valuation := by
have h_norm : ‖x * y‖ = ‖x‖ * ‖y‖ := norm_mul x y
have hp_ne_one : (p : ℝ) ≠ 1 := mod_cast (Fact.out : p.Prime).ne_one
have hp_pos : (0 : ℝ) < p := mod_cast NeZero.pos _
rwa [norm_eq_zpow_neg_valuation hx, norm_eq_zpow_neg_valuation hy,
norm_eq_zpow_neg_valuation (mul_ne_zero hx hy), ← zpow_add₀ hp_pos.ne',
zpow_right_inj₀ hp_pos hp_ne_one, ← neg_add, neg_inj] at h_norm
@[simp]
lemma valuation_inv (x : ℚ_[p]) : x⁻¹.valuation = -x.valuation := by
obtain rfl | hx := eq_or_ne x 0
· simp
have h_norm : ‖x⁻¹‖ = ‖x‖⁻¹ := norm_inv x
have hp_ne_one : (p : ℝ) ≠ 1 := mod_cast (Fact.out : p.Prime).ne_one
have hp_pos : (0 : ℝ) < p := mod_cast NeZero.pos _
rwa [norm_eq_zpow_neg_valuation hx, norm_eq_zpow_neg_valuation <| inv_ne_zero hx,
← zpow_neg, zpow_right_inj₀ hp_pos hp_ne_one, neg_inj] at h_norm
@[simp]
lemma valuation_pow (x : ℚ_[p]) : ∀ n : ℕ, (x ^ n).valuation = n * x.valuation
| 0 => by simp
| n + 1 => by
obtain rfl | hx := eq_or_ne x 0
· simp
· simp [pow_succ, hx, valuation_mul, valuation_pow, _root_.add_one_mul]
@[simp]
lemma valuation_zpow (x : ℚ_[p]) : ∀ n : ℤ, (x ^ n).valuation = n * x.valuation
| (n : ℕ) => by simp
| .negSucc n => by simp [← neg_mul]; simp [Int.negSucc_eq]
open Classical in
/-- The additive `p`-adic valuation on `ℚ_[p]`, with values in `WithTop ℤ`. -/
def addValuationDef : ℚ_[p] → WithTop ℤ :=
fun x ↦ if x = 0 then ⊤ else x.valuation
@[simp]
theorem AddValuation.map_zero : addValuationDef (0 : ℚ_[p]) = ⊤ := by
rw [addValuationDef, if_pos rfl]
@[simp]
theorem AddValuation.map_one : addValuationDef (1 : ℚ_[p]) = 0 := by
rw [addValuationDef, if_neg one_ne_zero, valuation_one, WithTop.coe_zero]
theorem AddValuation.map_mul (x y : ℚ_[p]) :
addValuationDef (x * y : ℚ_[p]) = addValuationDef x + addValuationDef y := by
simp only [addValuationDef]
by_cases hx : x = 0
· rw [hx, if_pos rfl, zero_mul, if_pos rfl, WithTop.top_add]
· by_cases hy : y = 0
· rw [hy, if_pos rfl, mul_zero, if_pos rfl, WithTop.add_top]
· rw [if_neg hx, if_neg hy, if_neg (mul_ne_zero hx hy), ← WithTop.coe_add, WithTop.coe_eq_coe,
valuation_mul hx hy]
theorem AddValuation.map_add (x y : ℚ_[p]) :
min (addValuationDef x) (addValuationDef y) ≤ addValuationDef (x + y : ℚ_[p]) := by
simp only [addValuationDef]
by_cases hxy : x + y = 0
· rw [hxy, if_pos rfl]
exact le_top
· by_cases hx : x = 0
· rw [hx, if_pos rfl, min_eq_right, zero_add]
exact le_top
· by_cases hy : y = 0
· rw [hy, if_pos rfl, min_eq_left, add_zero]
exact le_top
· rw [if_neg hx, if_neg hy, if_neg hxy, ← WithTop.coe_min, WithTop.coe_le_coe]
exact le_valuation_add hxy
open WithZero
open Classical in
/-- The `p`-adic valuation on `ℚ_[p]`, as a `Valuation`, bundled `Padic.valuation`. -/
@[simps]
noncomputable def mulValuation : Valuation ℚ_[p] ℤᵐ⁰ where
toFun x := if x = 0 then 0 else exp (-x.valuation)
map_zero' := by simp
map_one' := by simp
map_mul' _ _ := by split_ifs <;> simp_all [add_comm]
map_add_le_max' _ _ := by
split_ifs
any_goals simp_all [inv_le_inv₀]
simpa using le_valuation_add ‹_›
lemma comap_mulValuation_eq_padicValuation :
(mulValuation (p := p)).comap (Rat.castHom _) = Rat.padicValuation p := by
ext
simp [Rat.padicValuation]
lemma comap_mulValuation_eq_int_padicValuation :
(mulValuation (p := p)).comap (Int.castRingHom _) = Int.padicValuation p := by
ext
simp [← Rat.padicValuation_cast, ← comap_mulValuation_eq_padicValuation]
lemma norm_eq_zpow_log_mulValuation {x : ℚ_[p]} (hx : x ≠ 0) :
‖x‖ = (p : ℝ) ^ (log (mulValuation x)) := by
simp [norm_eq_zpow_neg_valuation, hx]
/-- The additive `p`-adic valuation on `ℚ_[p]`, as an `addValuation`. -/
def addValuation : AddValuation ℚ_[p] (WithTop ℤ) :=
AddValuation.of addValuationDef AddValuation.map_zero AddValuation.map_one AddValuation.map_add
AddValuation.map_mul
@[simp]
theorem addValuation.apply {x : ℚ_[p]} (hx : x ≠ 0) :
Padic.addValuation x = (x.valuation : WithTop ℤ) := by
simp only [Padic.addValuation, AddValuation.of_apply, addValuationDef, if_neg hx]
section NormLEIff
/-! ### Various characterizations of open unit balls -/
theorem norm_le_pow_iff_norm_lt_pow_add_one (x : ℚ_[p]) (n : ℤ) :
‖x‖ ≤ (p : ℝ) ^ n ↔ ‖x‖ < (p : ℝ) ^ (n + 1) := by
have aux (n : ℤ) : 0 < ((p : ℝ) ^ n) := zpow_pos (mod_cast hp.1.pos) _
by_cases hx0 : x = 0
· simp [hx0, norm_zero, aux, le_of_lt (aux _)]
rw [norm_eq_zpow_neg_valuation hx0]
have h1p : 1 < (p : ℝ) := mod_cast hp.1.one_lt
have H := zpow_right_strictMono₀ h1p
rw [H.le_iff_le, H.lt_iff_lt, Int.lt_add_one_iff]
theorem norm_lt_pow_iff_norm_le_pow_sub_one (x : ℚ_[p]) (n : ℤ) :
‖x‖ < (p : ℝ) ^ n ↔ ‖x‖ ≤ (p : ℝ) ^ (n - 1) := by
rw [norm_le_pow_iff_norm_lt_pow_add_one, sub_add_cancel]
theorem norm_le_one_iff_val_nonneg (x : ℚ_[p]) : ‖x‖ ≤ 1 ↔ 0 ≤ x.valuation := by
by_cases hx : x = 0
· simp only [hx, norm_zero, valuation_zero, zero_le_one, le_refl]
· rw [norm_eq_zpow_neg_valuation hx, ← zpow_zero (p : ℝ), zpow_le_zpow_iff_right₀, neg_nonpos]
exact Nat.one_lt_cast.2 (Nat.Prime.one_lt' p).1
end NormLEIff
end Padic |
.lake/packages/mathlib/Mathlib/NumberTheory/Padics/Complex.lean | import Mathlib.Analysis.Normed.Unbundled.SpectralNorm
import Mathlib.NumberTheory.Padics.PadicNumbers
import Mathlib.Topology.Algebra.Valued.NormedValued
import Mathlib.Topology.Algebra.Valued.ValuedField
/-!
# The field `ℂ_[p]` of `p`-adic complex numbers.
In this file we define the field `ℂ_[p]` of `p`-adic complex numbers as the `p`-adic completion of
an algebraic closure of `ℚ_[p]`. We endow `ℂ_[p]` with both a normed field and a valued field
structure, induced by the unique extension of the `p`-adic norm to `ℂ_[p]`.
## Main Definitions
* `PadicAlgCl p` : the algebraic closure of `ℚ_[p]`.
* `PadicComplex p` : the type of `p`-adic complex numbers, denoted by `ℂ_[p]`.
* `PadicComplexInt p` : the ring of integers of `ℂ_[p]`.
## Main Results
* `PadicComplex.norm_extends` : the norm on `ℂ_[p]` extends the norm on `PadicAlgCl p`, and hence
the norm on `ℚ_[p]`.
* `PadicComplex.isNonarchimedean` : The norm on `ℂ_[p]` is nonarchimedean.
## Notation
We introduce the notation `ℂ_[p]` for the `p`-adic complex numbers, and `𝓞_ℂ_[p]` for its ring of
integers.
## Tags
p-adic, p adic, padic, norm, valuation, Cauchy, completion, p-adic completion
-/
noncomputable section
open Valuation
open scoped NNReal
variable (p : ℕ) [hp : Fact (Nat.Prime p)]
/-- `PadicAlgCl p` is a fixed algebraic closure of `ℚ_[p]`. -/
abbrev PadicAlgCl := AlgebraicClosure ℚ_[p]
namespace PadicAlgCl
/-- `PadicAlgCl p` is an algebraic extension of `ℚ_[p]`. -/
theorem isAlgebraic : Algebra.IsAlgebraic ℚ_[p] (PadicAlgCl p) := AlgebraicClosure.isAlgebraic _
instance : Coe ℚ_[p] (PadicAlgCl p) := ⟨algebraMap ℚ_[p] (PadicAlgCl p)⟩
theorem coe_eq : (Coe.coe : ℚ_[p] → PadicAlgCl p) = algebraMap ℚ_[p] (PadicAlgCl p) := rfl
/-- `PadicAlgCl p` is a normed field, where the norm is the `p`-adic norm, that is, the
spectral norm induced by the `p`-adic norm on `ℚ_[p]`. -/
instance normedField : NormedField (PadicAlgCl p) := spectralNorm.normedField ℚ_[p] (PadicAlgCl p)
/-- The norm on `PadicAlgCl p` is nonarchimedean. -/
theorem isNonarchimedean : IsNonarchimedean (norm : PadicAlgCl p → ℝ) :=
isNonarchimedean_spectralNorm (K := ℚ_[p]) (L := PadicAlgCl p)
/-- The norm on `PadicAlgCl p` is the spectral norm induced by the `p`-adic norm on `ℚ_[p]`. -/
@[simp]
theorem spectralNorm_eq (x : PadicAlgCl p) : spectralNorm ℚ_[p] (PadicAlgCl p) x = ‖x‖ := rfl
/-- The norm on `PadicAlgCl p` extends the `p`-adic norm on `ℚ_[p]`. -/
@[simp] theorem norm_extends (x : ℚ_[p]) : ‖(x : PadicAlgCl p)‖ = ‖x‖ :=
spectralAlgNorm_extends (K := ℚ_[p]) (L := PadicAlgCl p) _
instance : IsUltrametricDist (PadicAlgCl p) :=
IsUltrametricDist.isUltrametricDist_of_forall_norm_add_le_max_norm (PadicAlgCl.isNonarchimedean p)
/-- `PadicAlgCl p` is a valued field, with the valuation corresponding to the `p`-adic norm. -/
instance valued : Valued (PadicAlgCl p) ℝ≥0 := NormedField.toValued
/-- The valuation of `x : PadicAlgCl p` agrees with its `ℝ≥0`-valued norm. -/
theorem valuation_def (x : PadicAlgCl p) : Valued.v x = ‖x‖₊ := rfl
/-- The coercion of the valuation of `x : PadicAlgCl p` to `ℝ` agrees with its norm. -/
@[simp] theorem valuation_coe (x : PadicAlgCl p) : ((Valued.v x : ℝ≥0) : ℝ) = ‖x‖ := rfl
/-- The valuation of `p : PadicAlgCl p` is `1/p`. -/
theorem valuation_p (p : ℕ) [Fact p.Prime] : Valued.v (p : PadicAlgCl p) = 1 / (p : ℝ≥0) := by
rw [← map_natCast (algebraMap ℚ_[p] (PadicAlgCl p))]
ext
rw [valuation_coe, norm_extends, Padic.norm_p, one_div, NNReal.coe_inv,
NNReal.coe_natCast]
/-- The valuation on `PadicAlgCl p` has rank one. -/
instance : RankOne (PadicAlgCl.valued p).v where
hom := MonoidWithZeroHom.id ℝ≥0
strictMono' := strictMono_id
exists_val_nontrivial := by
use p
have hp : Nat.Prime p := hp.1
simp only [valuation_p, one_div, ne_eq, inv_eq_zero, Nat.cast_eq_zero, inv_eq_one,
Nat.cast_eq_one]
exact ⟨hp.ne_zero, hp.ne_one⟩
instance : UniformContinuousConstSMul ℚ_[p] (PadicAlgCl p) :=
uniformContinuousConstSMul_of_continuousConstSMul ℚ_[p] (PadicAlgCl p)
end PadicAlgCl
/-- `ℂ_[p]` is the field of `p`-adic complex numbers, that is, the completion of `PadicAlgCl p` with
respect to the `p`-adic norm. -/
abbrev PadicComplex := UniformSpace.Completion (PadicAlgCl p)
/-- `ℂ_[p]` is the field of `p`-adic complex numbers. -/
notation "ℂ_[" p "]" => PadicComplex p
namespace PadicComplex
/-- `ℂ_[p]` is a valued field, where the valuation is the one extending that on `PadicAlgCl p`. -/
instance valued : Valued ℂ_[p] ℝ≥0 := inferInstance
/-- The valuation on `ℂ_[p]` extends the valuation on `PadicAlgCl p`. -/
theorem valuation_extends (x : PadicAlgCl p) : Valued.v (x : ℂ_[p]) = Valued.v x :=
Valued.extension_extends _
theorem coe_eq (x : PadicAlgCl p) : (x : ℂ_[p]) = algebraMap (PadicAlgCl p) ℂ_[p] x := rfl
@[simp] theorem coe_zero : ((0 : PadicAlgCl p) : ℂ_[p]) = 0 := rfl
/-- `ℂ_[p]` is an algebra over `ℚ_[p]`. -/
instance : Algebra ℚ_[p] ℂ_[p] where
smul := (UniformSpace.Completion.instSMul ℚ_[p] (PadicAlgCl p)).smul
algebraMap := (UniformSpace.Completion.coeRingHom).comp (algebraMap ℚ_[p] (PadicAlgCl p))
commutes' r x := by rw [mul_comm]
smul_def' r x := by
apply UniformSpace.Completion.ext' (continuous_const_smul r) (continuous_mul_left _)
intro a
rw [RingHom.coe_comp, Function.comp_apply, Algebra.smul_def]
rfl
instance : IsScalarTower ℚ_[p] (PadicAlgCl p) ℂ_[p] := IsScalarTower.of_algebraMap_eq (congrFun rfl)
@[simp, norm_cast]
lemma coe_natCast (n : ℕ) : ((n : PadicAlgCl p) : ℂ_[p]) = (n : ℂ_[p]) := by
rw [← map_natCast (algebraMap (PadicAlgCl p) ℂ_[p]) n, coe_eq]
/-- The valuation of `p : ℂ_[p]` is `1/p`. -/
theorem valuation_p : Valued.v (p : ℂ_[p]) = 1 / (p : ℝ≥0) := by
rw [← map_natCast (algebraMap (PadicAlgCl p) ℂ_[p]), ← coe_eq, valuation_extends,
PadicAlgCl.valuation_p]
/-- The valuation on `ℂ_[p]` has rank one. -/
instance : RankOne (PadicComplex.valued p).v where
hom := MonoidWithZeroHom.id ℝ≥0
strictMono' := strictMono_id
exists_val_nontrivial := by
use p
have hp : Nat.Prime p := hp.1
simp only [valuation_p, one_div, ne_eq, inv_eq_zero, Nat.cast_eq_zero, inv_eq_one,
Nat.cast_eq_one]
exact ⟨hp.ne_zero, hp.ne_one⟩
lemma rankOne_hom_eq :
RankOne.hom (PadicComplex.valued p).v = RankOne.hom (PadicAlgCl.valued p).v := rfl
/-- `ℂ_[p]` is a normed field, where the norm corresponds to the extension of the `p`-adic
valuation. -/
instance : NormedField ℂ_[p] := Valued.toNormedField _ _
theorem norm_def : (Norm.norm : ℂ_[p] → ℝ) = Valued.norm := rfl
/-- The norm on `ℂ_[p]` extends the norm on `PadicAlgCl p`. -/
theorem norm_extends (x : PadicAlgCl p) : ‖(x : ℂ_[p])‖ = ‖x‖ := by
rw [norm_def, Valued.norm, ← coe_nnnorm, valuation_extends p x, coe_nnnorm]
rfl
/-- The `ℝ≥0`-valued norm on `ℂ_[p]` extends that on `PadicAlgCl p`. -/
theorem nnnorm_extends (x : PadicAlgCl p) : ‖(x : ℂ_[p])‖₊ = ‖x‖₊ := by ext; exact norm_extends p x
/-- The norm on `ℂ_[p]` is nonarchimedean. -/
theorem isNonarchimedean : IsNonarchimedean (Norm.norm : ℂ_[p] → ℝ) := fun x y ↦ by
refine UniformSpace.Completion.induction_on₂ x y
(isClosed_le (continuous_norm.comp continuous_add) (by fun_prop)) (fun a b ↦ ?_)
rw [← UniformSpace.Completion.coe_add, norm_extends, norm_extends, norm_extends]
exact PadicAlgCl.isNonarchimedean p a b
end PadicComplex
/-- We define `𝓞_ℂ_[p]` as the valuation subring of `ℂ_[p]`, consisting of those elements with
valuation `≤ 1`. -/
def PadicComplexInt : ValuationSubring ℂ_[p] := (PadicComplex.valued p).v.valuationSubring
/-- We define `𝓞_ℂ_[p]` as the subring of elements of `ℂ_[p]` with valuation `≤ 1`. -/
notation "𝓞_ℂ_[" p "]" => PadicComplexInt p
/-- `𝓞_ℂ_[p]` is the ring of integers of `ℂ_[p]`. -/
theorem PadicComplexInt.integers : Valuation.Integers (PadicComplex.valued p).v 𝓞_ℂ_[p] :=
Valuation.integer.integers _ |
.lake/packages/mathlib/Mathlib/NumberTheory/Padics/ValuativeRel.lean | import Mathlib.NumberTheory.Padics.PadicNumbers
import Mathlib.RingTheory.Valuation.RankOne
/-!
# p-adic numbers with a valuative relation
## Tags
p-adic, p adic, padic, norm, valuation, cauchy, completion, p-adic completion
-/
variable {p : ℕ} [hp : Fact p.Prime] {Γ₀ : Type*} [LinearOrderedCommMonoidWithZero Γ₀]
(v : Valuation ℚ_[p] Γ₀)
open ValuativeRel WithZero
namespace Padic
-- TODO: should this be automatic from a nonarchimedean nontrivially normed field?
instance : ValuativeRel ℚ_[p] := .ofValuation mulValuation
instance : Valuation.Compatible (mulValuation (p := p)) := .ofValuation _
variable [v.Compatible]
lemma valuation_p_ne_zero : v p ≠ 0 := by
simp [(isEquiv v (Padic.mulValuation)).ne_zero, hp.out.ne_zero]
@[simp]
lemma valuation_p_lt_one : v p < 1 := by
simp [(isEquiv v (Padic.mulValuation)).lt_one_iff_lt_one, hp.out.ne_zero, inv_lt_one₀,
← log_lt_iff_lt_exp]
instance : IsNontrivial ℚ_[p] where
condition := ⟨ValuativeRel.valuation _ p, valuation_p_ne_zero _, (valuation_p_lt_one _).ne⟩
instance : IsRankLeOne ℚ_[p] := .of_compatible_mulArchimedean mulValuation
end Padic |
.lake/packages/mathlib/Mathlib/NumberTheory/Padics/AddChar.lean | import Mathlib.NumberTheory.Padics.MahlerBasis
import Mathlib.Topology.Algebra.Monoid.AddChar
import Mathlib.Analysis.SpecificLimits.Normed
/-!
# Additive characters of `ℤ_[p]`
We show that for any complete, ultrametric normed `ℤ_[p]`-algebra `R`, there is a bijection between
continuous additive characters `ℤ_[p] → R` and topologically nilpotent elements of `R`, given by
sending `κ` to the element `κ 1 - 1`. This is used to define the Mahler transform for `p`-adic
measures.
Note that if the norm on `R` is not strictly multiplicative, then the condition that `κ 1 - 1` be
topologically nilpotent is strictly weaker than assuming `‖κ 1 - 1‖ < 1`, although they are
equivalent if `NormMulClass R` holds.
## Main definitions and theorems:
* `addChar_of_value_at_one`: given a topologically nilpotent `r : R`, construct a continuous
additive character of `ℤ_[p]` mapping `1` to `1 + r`.
* `continuousAddCharEquiv`: for any complete, ultrametric normed `ℤ_[p]`-algebra `R`, the map
`addChar_of_value_at_one` defines a bijection between continuous additive characters `ℤ_[p] → R`
and topologically nilpotent elements of `R`.
* `continuousAddCharEquiv_of_norm_mul`: if the norm on `R` is strictly multiplicative (not just
sub-multiplicative), then `addChar_of_value_at_one` is a bijection between continuous additive
characters `ℤ_[p] → R` and elements of `R` with `‖r‖ < 1`.
## TODO:
* Show that the above equivalences are homeomorphisms, for appropriate choices of the topology.
-/
open scoped fwdDiff
open Filter Topology
variable {p : ℕ} [Fact p.Prime]
variable {R : Type*} [NormedRing R] [Algebra ℤ_[p] R] [IsBoundedSMul ℤ_[p] R]
[IsUltrametricDist R]
lemma AddChar.tendsto_eval_one_sub_pow {κ : AddChar ℤ_[p] R} (hκ : Continuous κ) :
Tendsto (fun n ↦ (κ 1 - 1) ^ n) atTop (𝓝 0) := by
refine (PadicInt.fwdDiff_tendsto_zero ⟨κ, hκ⟩).congr fun n ↦ ?_
simpa only [AddChar.map_zero_eq_one, mul_one] using fwdDiff_addChar_eq κ 0 1 n
namespace PadicInt
variable [CompleteSpace R]
/-- The unique continuous additive character of `ℤ_[p]` mapping `1` to `1 + r`. -/
noncomputable def addChar_of_value_at_one (r : R) (hr : Tendsto (r ^ ·) atTop (𝓝 0)) :
AddChar ℤ_[p] R where
toFun := mahlerSeries (r ^ ·)
map_zero_eq_one' := by
rw [← Nat.cast_zero, mahlerSeries_apply_nat hr le_rfl, zero_add, Finset.sum_range_one,
Nat.choose_self, pow_zero, one_smul]
map_add_eq_mul' a b := by
let F : C(ℤ_[p], R) := mahlerSeries (r ^ ·)
change F (a + b) = F a * F b
-- It is fiddly to show directly that `F (a + b) = F a * F b` for general `a, b`,
-- so we prove it for `a, b ∈ ℕ` directly, and then deduce it for all `a, b` by continuity.
have hF (n : ℕ) : F n = (r + 1) ^ n := by
rw [mahlerSeries_apply_nat hr le_rfl, (Commute.one_right _).add_pow]
refine Finset.sum_congr rfl fun i hi ↦ ?_
rw [one_pow, mul_one, nsmul_eq_mul, Nat.cast_comm]
refine congr_fun ((denseRange_natCast.prodMap denseRange_natCast).equalizer
((map_continuous F).comp continuous_add)
(continuous_mul.comp (map_continuous <| F.prodMap F)) (funext fun ⟨m, n⟩ ↦ ?_)) (a, b)
simp [← Nat.cast_add, hF, ContinuousMap.prodMap_apply, pow_add]
@[fun_prop]
lemma continuous_addChar_of_value_at_one {r : R} (hr : Tendsto (r ^ ·) atTop (𝓝 0)) :
Continuous (addChar_of_value_at_one r hr : ℤ_[p] → R) :=
map_continuous (mahlerSeries (r ^ ·))
lemma coe_addChar_of_value_at_one {r : R} (hr : Tendsto (r ^ ·) atTop (𝓝 0)) :
(addChar_of_value_at_one r hr : ℤ_[p] → R) = mahlerSeries (r ^ ·) :=
rfl
@[simp]
lemma addChar_of_value_at_one_def {r : R} (hr : Tendsto (r ^ ·) atTop (𝓝 0)) :
addChar_of_value_at_one r hr (1 : ℤ_[p]) = 1 + r := by
change mahlerSeries (r ^ ·) ↑(1 : ℕ) = _
rw [mahlerSeries_apply_nat hr le_rfl, Finset.sum_range_succ, Finset.sum_range_one,
Nat.choose_zero_right, Nat.choose_self, one_smul, one_smul, pow_zero, pow_one]
lemma eq_addChar_of_value_at_one {r : R} (hr : Tendsto (r ^ ·) atTop (𝓝 0))
{κ : AddChar ℤ_[p] R} (hκ : Continuous κ) (hκ' : κ 1 = 1 + r) :
κ = addChar_of_value_at_one r hr :=
denseRange_natCast.addChar_eq_of_eval_one_eq hκ (by fun_prop) (by simp [hκ'])
variable (p R) in
/-- Equivalence between continuous additive characters `ℤ_[p] → R`, and `r ∈ R` with `r ^ n → 0`. -/
noncomputable def continuousAddCharEquiv :
{κ : AddChar ℤ_[p] R // Continuous κ} ≃ {r : R // Tendsto (r ^ ·) atTop (𝓝 0)} where
toFun := fun ⟨κ, hκ⟩ ↦ ⟨κ 1 - 1, κ.tendsto_eval_one_sub_pow hκ⟩
invFun := fun ⟨r, hr⟩ ↦ ⟨_, continuous_addChar_of_value_at_one hr⟩
left_inv := fun ⟨κ, hκ⟩ ↦ by simpa using (eq_addChar_of_value_at_one _ hκ (by abel)).symm
right_inv := fun ⟨r, hr⟩ ↦ by simp [addChar_of_value_at_one_def hr]
@[simp] lemma continuousAddCharEquiv_apply {κ : AddChar ℤ_[p] R} (hκ : Continuous κ) :
continuousAddCharEquiv p R ⟨κ, hκ⟩ = κ 1 - 1 :=
rfl
@[simp] lemma continuousAddCharEquiv_symm_apply {r : R} (hr : Tendsto (r ^ ·) atTop (𝓝 0)) :
(continuousAddCharEquiv p R).symm ⟨r, hr⟩ =
(addChar_of_value_at_one r hr : AddChar ℤ_[p] R) :=
rfl
section NormMulClass
variable [NormMulClass R]
variable (p R) in
/-- Equivalence between continuous additive characters `ℤ_[p] → R`, and `r ∈ R` with `‖r‖ < 1`,
for rings with strictly multiplicative norm. -/
noncomputable def continuousAddCharEquiv_of_norm_mul :
{κ : AddChar ℤ_[p] R // Continuous κ} ≃ {r : R // ‖r‖ < 1} :=
(continuousAddCharEquiv p R).trans <|
.subtypeEquivProp (by simp only [tendsto_pow_atTop_nhds_zero_iff_norm_lt_one])
@[simp] lemma continuousAddCharEquiv_of_norm_mul_apply {κ : AddChar ℤ_[p] R} (hκ : Continuous κ) :
continuousAddCharEquiv_of_norm_mul p R ⟨κ, hκ⟩ = κ 1 - 1 :=
rfl
@[simp] lemma continuousAddCharEquiv_of_norm_mul_symm_apply {r : R} (hr : ‖r‖ < 1) :
(continuousAddCharEquiv_of_norm_mul p R).symm ⟨r, hr⟩ = (addChar_of_value_at_one r
(tendsto_pow_atTop_nhds_zero_iff_norm_lt_one.mpr hr) : AddChar ℤ_[p] R) :=
rfl
end NormMulClass
end PadicInt |
.lake/packages/mathlib/Mathlib/NumberTheory/Padics/Hensel.lean | import Mathlib.Algebra.Polynomial.Identities
import Mathlib.Analysis.SpecificLimits.Basic
import Mathlib.NumberTheory.Padics.PadicIntegers
import Mathlib.Topology.Algebra.Polynomial
import Mathlib.Topology.MetricSpace.CauSeqFilter
/-!
# Hensel's lemma on ℤ_p
This file proves Hensel's lemma on ℤ_p, roughly following Keith Conrad's writeup:
<http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf>
Hensel's lemma gives a simple condition for the existence of a root of a polynomial.
The proof and motivation are described in the paper
[R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019].
## References
* <http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf>
* [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019]
* <https://en.wikipedia.org/wiki/Hensel%27s_lemma>
## Tags
p-adic, p adic, padic, p-adic integer
-/
noncomputable section
open Topology
-- We begin with some general lemmas that are used below in the computation.
theorem padic_polynomial_dist {p : ℕ} [Fact p.Prime] {R : Type*} [CommSemiring R] [Algebra R ℤ_[p]]
(F : Polynomial R) (x y : ℤ_[p]) :
‖F.aeval x - F.aeval y‖ ≤ ‖x - y‖ := by
let ⟨z, hz⟩ := (F.map (algebraMap R ℤ_[p])).evalSubFactor x y
simp only [Polynomial.eval_map_algebraMap] at hz
calc
‖F.aeval x - F.aeval y‖ = ‖z‖ * ‖x - y‖ := by simp [hz]
_ ≤ 1 * ‖x - y‖ := by gcongr; apply PadicInt.norm_le_one
_ = ‖x - y‖ := by simp
open Filter Metric
private theorem comp_tendsto_lim {p : ℕ} [Fact p.Prime] {F : Polynomial ℤ_[p]}
(ncs : CauSeq ℤ_[p] norm) : Tendsto (fun i => F.eval (ncs i)) atTop (𝓝 (F.eval ncs.lim)) :=
Filter.Tendsto.comp (@Polynomial.continuousAt _ _ _ _ F _) ncs.tendsto_limit
section
variable {p : ℕ} [Fact p.Prime] {R : Type*} [CommSemiring R] [Algebra R ℤ_[p]]
{ncs : CauSeq ℤ_[p] norm} {F : Polynomial R}
{a : ℤ_[p]} (ncs_der_val : ∀ n, ‖F.derivative.aeval (ncs n)‖ = ‖F.derivative.aeval a‖)
private theorem ncs_tendsto_lim :
Tendsto (fun i => ‖F.derivative.aeval (ncs i)‖) atTop (𝓝 ‖F.derivative.aeval ncs.lim‖) := by
refine Tendsto.comp (continuous_iff_continuousAt.1 continuous_norm _) ?_
rw [← Polynomial.eval_map_algebraMap]
refine (comp_tendsto_lim ncs).congr ?_
simp
include ncs_der_val
private theorem ncs_tendsto_const :
Tendsto (fun i => ‖F.derivative.aeval (ncs i)‖) atTop (𝓝 ‖F.derivative.aeval a‖) := by
convert @tendsto_const_nhds ℝ _ ℕ _ _; rw [ncs_der_val]
private theorem norm_deriv_eq : ‖F.derivative.aeval ncs.lim‖ = ‖F.derivative.aeval a‖ :=
tendsto_nhds_unique ncs_tendsto_lim (ncs_tendsto_const ncs_der_val)
end
section
variable {p : ℕ} [Fact p.Prime] {R : Type*} [CommSemiring R] [Algebra R ℤ_[p]]
{ncs : CauSeq ℤ_[p] norm} {F : Polynomial R}
(hnorm : Tendsto (fun i => ‖F.aeval (ncs i)‖) atTop (𝓝 0))
include hnorm
private theorem tendsto_zero_of_norm_tendsto_zero :
Tendsto (fun i => F.aeval (ncs i)) atTop (𝓝 0) :=
tendsto_iff_norm_sub_tendsto_zero.2 (by simpa using hnorm)
theorem limit_zero_of_norm_tendsto_zero : F.aeval ncs.lim = 0 := by
refine tendsto_nhds_unique ?_ (tendsto_zero_of_norm_tendsto_zero hnorm)
rw [← Polynomial.eval_map_algebraMap]
refine (comp_tendsto_lim ncs).congr ?_
simp
end
section Hensel
open Nat
variable (p : ℕ) [Fact p.Prime] {R : Type*} [CommSemiring R] [Algebra R ℤ_[p]]
(F : Polynomial R) (a : ℤ_[p])
/-- `T` is an auxiliary value that is used to control the behavior of the polynomial `F`. -/
private def T_gen : ℝ := ‖F.aeval a / ((F.derivative.aeval a ^ 2 : ℤ_[p]) : ℚ_[p])‖
local notation "T" => @T_gen p _ _ _ _ F a
variable {p F a}
private theorem T_def : T = ‖F.aeval a‖ / ‖F.derivative.aeval a‖ ^ 2 := by
simp [T_gen]
private theorem T_nonneg : 0 ≤ T := norm_nonneg _
private theorem T_pow_nonneg (n : ℕ) : 0 ≤ T ^ n := pow_nonneg T_nonneg _
variable (hnorm : ‖F.aeval a‖ < ‖F.derivative.aeval a‖ ^ 2)
include hnorm
private theorem deriv_sq_norm_pos : 0 < ‖F.derivative.aeval a‖ ^ 2 :=
lt_of_le_of_lt (norm_nonneg _) hnorm
private theorem deriv_sq_norm_ne_zero : ‖F.derivative.aeval a‖ ^ 2 ≠ 0 :=
ne_of_gt (deriv_sq_norm_pos hnorm)
private theorem deriv_norm_ne_zero : ‖F.derivative.aeval a‖ ≠ 0 := fun h =>
deriv_sq_norm_ne_zero hnorm (by simp [*, sq])
private theorem deriv_norm_pos : 0 < ‖F.derivative.aeval a‖ :=
lt_of_le_of_ne (norm_nonneg _) (Ne.symm (deriv_norm_ne_zero hnorm))
private theorem deriv_ne_zero : F.derivative.aeval a ≠ 0 :=
mt norm_eq_zero.2 (deriv_norm_ne_zero hnorm)
private theorem T_lt_one : T < 1 := by
have h := (div_lt_one (deriv_sq_norm_pos hnorm)).2 hnorm
rw [T_def]; exact h
private theorem T_pow {n : ℕ} (hn : n ≠ 0) : T ^ n < 1 := pow_lt_one₀ T_nonneg (T_lt_one hnorm) hn
private theorem T_pow' (n : ℕ) : T ^ 2 ^ n < 1 := T_pow hnorm (pow_ne_zero _ two_ne_zero)
/-- We will construct a sequence of elements of ℤ_p satisfying successive values of `ih`. -/
private def ih_gen (n : ℕ) (z : ℤ_[p]) : Prop :=
‖F.derivative.aeval z‖ = ‖F.derivative.aeval a‖ ∧ ‖F.aeval z‖ ≤
‖F.derivative.aeval a‖ ^ 2 * T ^ 2 ^ n
local notation "ih" => @ih_gen p _ _ _ _ F a
private theorem ih_0 : ih 0 a :=
⟨rfl, by simp [T_def, mul_div_cancel₀ _ (ne_of_gt (deriv_sq_norm_pos hnorm))]⟩
private theorem calc_norm_le_one {n : ℕ} {z : ℤ_[p]} (hz : ih n z) :
‖(↑(F.aeval z) : ℚ_[p]) / ↑(F.derivative.aeval z)‖ ≤ 1 :=
calc
‖(↑(F.aeval z) : ℚ_[p]) / ↑(F.derivative.aeval z)‖ =
‖(↑(F.aeval z) : ℚ_[p])‖ / ‖(↑(F.derivative.aeval z) : ℚ_[p])‖ :=
norm_div _ _
_ = ‖F.aeval z‖ / ‖F.derivative.aeval a‖ := by simp [hz.1]
_ ≤ ‖F.derivative.aeval a‖ ^ 2 * T ^ 2 ^ n / ‖F.derivative.aeval a‖ := by
gcongr
apply hz.2
_ = ‖F.derivative.aeval a‖ * T ^ 2 ^ n := div_sq_cancel _ _
_ ≤ 1 := mul_le_one₀ (PadicInt.norm_le_one _) (T_pow_nonneg _) (le_of_lt (T_pow' hnorm _))
private theorem calc_deriv_dist {z z' z1 : ℤ_[p]} (hz' : z' = z - z1)
(hz1 : ‖z1‖ = ‖F.aeval z‖ / ‖F.derivative.aeval a‖) {n} (hz : ih n z) :
‖F.derivative.aeval z' - F.derivative.aeval z‖ < ‖F.derivative.aeval a‖ :=
calc
‖F.derivative.aeval z' - F.derivative.aeval z‖ ≤ ‖z' - z‖ := padic_polynomial_dist _ _ _
_ = ‖z1‖ := by simp only [sub_eq_add_neg, add_assoc, hz', add_add_neg_cancel'_right, norm_neg]
_ = ‖F.aeval z‖ / ‖F.derivative.aeval a‖ := hz1
_ ≤ ‖F.derivative.aeval a‖ ^ 2 * T ^ 2 ^ n / ‖F.derivative.aeval a‖ := by
gcongr
apply hz.2
_ = ‖F.derivative.aeval a‖ * T ^ 2 ^ n := div_sq_cancel _ _
_ < ‖F.derivative.aeval a‖ := (mul_lt_iff_lt_one_right (deriv_norm_pos hnorm)).2
(T_pow' hnorm _)
private def calc_eval_z' {z z' z1 : ℤ_[p]} (hz' : z' = z - z1) {n} (hz : ih n z)
(h1 : ‖(↑(F.aeval z) : ℚ_[p]) / ↑(F.derivative.aeval z)‖ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) :
{ q : ℤ_[p] // F.aeval z' = q * z1 ^ 2 } := by
have hdzne : F.derivative.aeval z ≠ 0 :=
mt norm_eq_zero.2 (by rw [hz.1]; apply deriv_norm_ne_zero; assumption)
have hdzne' : (↑(F.derivative.aeval z) : ℚ_[p]) ≠ 0 := fun h => hdzne (Subtype.ext_iff.2 h)
obtain ⟨q, hq⟩ := (F.map (algebraMap R ℤ_[p])).binomExpansion z (-z1)
have : ‖(↑(F.derivative.aeval z) * (↑(F.aeval z) / ↑(F.derivative.aeval z)) : ℚ_[p])‖ ≤ 1 := by
simpa using mul_le_one₀ (PadicInt.norm_le_one _) (norm_nonneg _) h1
have : F.derivative.aeval z * -z1 = -F.aeval z := by
calc
F.derivative.aeval z * -z1 =
F.derivative.aeval z * -⟨↑(F.aeval z) / ↑(F.derivative.aeval z), h1⟩ := by rw [hzeq]
_ = -(F.derivative.aeval z * ⟨↑(F.aeval z) / ↑(F.derivative.aeval z), h1⟩) := mul_neg _ _
_ = -⟨F.derivative.aeval z * (F.aeval z / (F.derivative.aeval z : ℤ_[p]) : ℚ_[p]), this⟩ :=
(Subtype.ext <| by simp only [PadicInt.coe_neg, PadicInt.coe_mul])
_ = -F.aeval z := by simp only [mul_div_cancel₀ _ hdzne', Subtype.coe_eta]
exact ⟨q, by simpa [sub_eq_add_neg, neg_mul_eq_mul_neg, this, hz'] using hq⟩
private def calc_eval_z'_norm {z z' z1 : ℤ_[p]} {n} (hz : ih n z) {q}
(heq : F.aeval z' = q * z1 ^ 2)
(h1 : ‖(↑(F.aeval z) : ℚ_[p]) / ↑(F.derivative.aeval z)‖ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) :
‖F.aeval z'‖ ≤ ‖F.derivative.aeval a‖ ^ 2 * T ^ 2 ^ (n + 1) := by
calc
‖F.aeval z'‖ = ‖q‖ * ‖z1‖ ^ 2 := by simp [heq]
_ ≤ 1 * ‖z1‖ ^ 2 := by gcongr; apply PadicInt.norm_le_one
_ = ‖F.aeval z‖ ^ 2 / ‖F.derivative.aeval a‖ ^ 2 := by simp [hzeq, hz.1, div_pow]
_ ≤ (‖F.derivative.aeval a‖ ^ 2 * T ^ 2 ^ n) ^ 2 / ‖F.derivative.aeval a‖ ^ 2 := by
gcongr
exact hz.2
_ = (‖F.derivative.aeval a‖ ^ 2) ^ 2 * (T ^ 2 ^ n) ^ 2 / ‖F.derivative.aeval a‖ ^ 2 := by
simp only [mul_pow]
_ = ‖F.derivative.aeval a‖ ^ 2 * (T ^ 2 ^ n) ^ 2 := div_sq_cancel _ _
_ = ‖F.derivative.aeval a‖ ^ 2 * T ^ 2 ^ (n + 1) := by rw [← pow_mul, pow_succ 2]
/-- Given `z : ℤ_[p]` satisfying `ih n z`, construct `z' : ℤ_[p]` satisfying `ih (n+1) z'`. We need
the hypothesis `ih n z`, since otherwise `z'` is not necessarily an integer. -/
private def ih_n {n : ℕ} {z : ℤ_[p]} (hz : ih n z) : { z' : ℤ_[p] // ih (n + 1) z' } :=
have h1 : ‖(↑(F.aeval z) : ℚ_[p]) / ↑(F.derivative.aeval z)‖ ≤ 1 := calc_norm_le_one hnorm hz
let z1 : ℤ_[p] := ⟨_, h1⟩
let z' : ℤ_[p] := z - z1
⟨z',
have hdist : ‖F.derivative.aeval z' - F.derivative.aeval z‖ < ‖F.derivative.aeval a‖ :=
calc_deriv_dist hnorm rfl (by simp [z1, hz.1]) hz
have hfeq : ‖F.derivative.aeval z'‖ = ‖F.derivative.aeval a‖ := by
rw [sub_eq_add_neg, ← hz.1, ← norm_neg (F.derivative.aeval z)] at hdist
have := PadicInt.norm_eq_of_norm_add_lt_right hdist
rwa [norm_neg, hz.1] at this
let ⟨_, heq⟩ := calc_eval_z' hnorm rfl hz h1 rfl
have hnle : ‖F.aeval z'‖ ≤ ‖F.derivative.aeval a‖ ^ 2 * T ^ 2 ^ (n + 1) :=
calc_eval_z'_norm hz heq h1 rfl
⟨hfeq, hnle⟩⟩
private def newton_seq_aux : ∀ n : ℕ, { z : ℤ_[p] // ih n z }
| 0 => ⟨a, ih_0 hnorm⟩
| k + 1 => ih_n hnorm (newton_seq_aux k).2
private def newton_seq_gen (n : ℕ) : ℤ_[p] :=
(newton_seq_aux hnorm n).1
local notation "newton_seq" => newton_seq_gen hnorm
private theorem newton_seq_deriv_norm (n : ℕ) :
‖F.derivative.aeval (newton_seq n)‖ = ‖F.derivative.aeval a‖ :=
(newton_seq_aux hnorm n).2.1
private theorem newton_seq_norm_le (n : ℕ) :
‖F.aeval (newton_seq n)‖ ≤ ‖F.derivative.aeval a‖ ^ 2 * T ^ 2 ^ n :=
(newton_seq_aux hnorm n).2.2
private theorem newton_seq_norm_eq (n : ℕ) :
‖newton_seq (n + 1) - newton_seq n‖ =
‖F.aeval (newton_seq n)‖ / ‖F.derivative.aeval (newton_seq n)‖ := by
rw [newton_seq_gen, newton_seq_gen, newton_seq_aux, ih_n]
simp [sub_eq_add_neg, add_comm]
private theorem newton_seq_succ_dist (n : ℕ) :
‖newton_seq (n + 1) - newton_seq n‖ ≤ ‖F.derivative.aeval a‖ * T ^ 2 ^ n :=
calc
‖newton_seq (n + 1) - newton_seq n‖ =
‖F.aeval (newton_seq n)‖ / ‖F.derivative.aeval (newton_seq n)‖ :=
newton_seq_norm_eq hnorm _
_ = ‖F.aeval (newton_seq n)‖ / ‖F.derivative.aeval a‖ := by rw [newton_seq_deriv_norm]
_ ≤ ‖F.derivative.aeval a‖ ^ 2 * T ^ 2 ^ n / ‖F.derivative.aeval a‖ := by
gcongr
apply newton_seq_norm_le
_ = ‖F.derivative.aeval a‖ * T ^ 2 ^ n := div_sq_cancel _ _
private theorem newton_seq_dist_aux (n : ℕ) :
∀ k : ℕ, ‖newton_seq (n + k) - newton_seq n‖ ≤ ‖F.derivative.aeval a‖ * T ^ 2 ^ n
| 0 => by simp [T_pow_nonneg, mul_nonneg]
| k + 1 =>
have : 2 ^ n ≤ 2 ^ (n + k) := by
apply pow_right_mono₀
· simp
· apply Nat.le_add_right
calc
‖newton_seq (n + (k + 1)) - newton_seq n‖ = ‖newton_seq (n + k + 1) - newton_seq n‖ := by
rw [add_assoc]
_ = ‖newton_seq (n + k + 1) - newton_seq (n + k) + (newton_seq (n + k) - newton_seq n)‖ := by
rw [← sub_add_sub_cancel]
_ ≤ max ‖newton_seq (n + k + 1) - newton_seq (n + k)‖ ‖newton_seq (n + k) - newton_seq n‖ :=
(PadicInt.nonarchimedean _ _)
_ ≤ max (‖F.derivative.aeval a‖ * T ^ 2 ^ (n + k)) (‖F.derivative.aeval a‖ * T ^ 2 ^ n) :=
(max_le_max (newton_seq_succ_dist _ _) (newton_seq_dist_aux _ _))
_ = ‖F.derivative.aeval a‖ * T ^ 2 ^ n :=
max_eq_right <|
mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _)
(le_of_lt (T_lt_one hnorm)) this) (norm_nonneg _)
private theorem newton_seq_dist {n k : ℕ} (hnk : n ≤ k) :
‖newton_seq k - newton_seq n‖ ≤ ‖F.derivative.aeval a‖ * T ^ 2 ^ n := by
have hex : ∃ m, k = n + m := Nat.exists_eq_add_of_le hnk
let ⟨_, hex'⟩ := hex
rw [hex']; apply newton_seq_dist_aux
private theorem bound' : Tendsto (fun n : ℕ => ‖F.derivative.aeval a‖ * T ^ 2 ^ n) atTop (𝓝 0) := by
rw [← mul_zero ‖F.derivative.aeval a‖]
exact
tendsto_const_nhds.mul
(Tendsto.comp (tendsto_pow_atTop_nhds_zero_of_lt_one (norm_nonneg _) (T_lt_one hnorm))
(tendsto_pow_atTop_atTop_of_one_lt (by simp)))
private theorem bound :
∀ {ε}, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → ‖F.derivative.aeval a‖ * T ^ 2 ^ n < ε := fun hε ↦
eventually_atTop.1 <| (bound' hnorm).eventually <| gt_mem_nhds hε
private theorem bound'_sq :
Tendsto (fun n : ℕ => ‖F.derivative.aeval a‖ ^ 2 * T ^ 2 ^ n) atTop (𝓝 0) := by
rw [← mul_zero ‖F.derivative.aeval a‖, sq]
simp only [mul_assoc]
apply Tendsto.mul
· apply tendsto_const_nhds
· apply bound'
assumption
private theorem newton_seq_is_cauchy : IsCauSeq norm newton_seq := fun _ε hε ↦
(bound hnorm hε).imp fun _N hN _j hj ↦ (newton_seq_dist hnorm hj).trans_lt <| hN le_rfl
private def newton_cau_seq : CauSeq ℤ_[p] norm := ⟨_, newton_seq_is_cauchy hnorm⟩
private def soln_gen : ℤ_[p] := (newton_cau_seq hnorm).lim
local notation "soln" => soln_gen hnorm
private theorem soln_spec {ε : ℝ} (hε : ε > 0) :
∃ N : ℕ, ∀ {i : ℕ}, i ≥ N → ‖soln - newton_cau_seq hnorm i‖ < ε :=
Setoid.symm (CauSeq.equiv_lim (newton_cau_seq hnorm)) _ hε
private theorem soln_deriv_norm : ‖F.derivative.aeval soln‖ = ‖F.derivative.aeval a‖ :=
norm_deriv_eq (newton_seq_deriv_norm hnorm)
private theorem newton_seq_norm_tendsto_zero :
Tendsto (fun i => ‖F.aeval (newton_cau_seq hnorm i)‖) atTop (𝓝 0) :=
squeeze_zero (fun _ => norm_nonneg _) (newton_seq_norm_le hnorm) (bound'_sq hnorm)
private theorem newton_seq_dist_tendsto' :
Tendsto (fun n => ‖newton_cau_seq hnorm n - a‖) atTop (𝓝 ‖soln - a‖) :=
(continuous_norm.tendsto _).comp ((newton_cau_seq hnorm).tendsto_limit.sub tendsto_const_nhds)
private theorem eval_soln : F.aeval soln = 0 :=
limit_zero_of_norm_tendsto_zero (newton_seq_norm_tendsto_zero hnorm)
variable (hnsol : F.aeval a ≠ 0)
include hnsol
private theorem T_pos : T > 0 := by
rw [T_def]
exact div_pos (norm_pos_iff.2 hnsol) (deriv_sq_norm_pos hnorm)
private theorem newton_seq_succ_dist_weak (n : ℕ) :
‖newton_seq (n + 2) - newton_seq (n + 1)‖ < ‖F.aeval a‖ / ‖F.derivative.aeval a‖ :=
have : 2 ≤ 2 ^ (n + 1) := by
have := pow_right_mono₀ (by simp : 1 ≤ 2) (Nat.le_add_left _ _ : 1 ≤ n + 1)
simpa using this
calc
‖newton_seq (n + 2) - newton_seq (n + 1)‖ ≤ ‖F.derivative.aeval a‖ * T ^ 2 ^ (n + 1) :=
newton_seq_succ_dist hnorm _
_ ≤ ‖F.derivative.aeval a‖ * T ^ 2 :=
(mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _)
(le_of_lt (T_lt_one hnorm)) this) (norm_nonneg _))
_ < ‖F.derivative.aeval a‖ * T ^ 1 :=
(mul_lt_mul_of_pos_left (pow_lt_pow_right_of_lt_one₀ (T_pos hnorm hnsol)
(T_lt_one hnorm) (by norm_num)) (deriv_norm_pos hnorm))
_ = ‖F.aeval a‖ / ‖F.derivative.aeval a‖ := by
rw [T_gen, sq, pow_one, norm_div, ← mul_div_assoc, PadicInt.padic_norm_e_of_padicInt,
PadicInt.coe_mul, norm_mul]
apply mul_div_mul_left
apply deriv_norm_ne_zero; assumption
private theorem newton_seq_dist_to_a :
∀ n : ℕ, 0 < n → ‖newton_seq n - a‖ = ‖F.aeval a‖ / ‖F.derivative.aeval a‖
| 1, _h => by simp [sub_eq_add_neg, add_assoc, newton_seq_gen, newton_seq_aux, ih_n]
| k + 2, _h =>
have hlt : ‖newton_seq (k + 2) - newton_seq (k + 1)‖ < ‖newton_seq (k + 1) - a‖ := by
rw [newton_seq_dist_to_a (k + 1) (succ_pos _)]; apply newton_seq_succ_dist_weak
assumption
have hne' : ‖newton_seq (k + 2) - newton_seq (k + 1)‖ ≠ ‖newton_seq (k + 1) - a‖ := ne_of_lt hlt
calc
‖newton_seq (k + 2) - a‖ =
‖newton_seq (k + 2) - newton_seq (k + 1) + (newton_seq (k + 1) - a)‖ := by
rw [← sub_add_sub_cancel]
_ = max ‖newton_seq (k + 2) - newton_seq (k + 1)‖ ‖newton_seq (k + 1) - a‖ :=
(PadicInt.norm_add_eq_max_of_ne hne')
_ = ‖newton_seq (k + 1) - a‖ := max_eq_right_of_lt hlt
_ = ‖Polynomial.aeval a F‖ / ‖Polynomial.aeval a (Polynomial.derivative F)‖ :=
newton_seq_dist_to_a (k + 1) (succ_pos _)
private theorem newton_seq_dist_tendsto :
Tendsto (fun n => ‖newton_cau_seq hnorm n - a‖)
atTop (𝓝 (‖F.aeval a‖ / ‖F.derivative.aeval a‖)) :=
tendsto_const_nhds.congr' (eventually_atTop.2
⟨1, fun _ hx => (newton_seq_dist_to_a hnorm hnsol _ hx).symm⟩)
private theorem soln_dist_to_a : ‖soln - a‖ = ‖F.aeval a‖ / ‖F.derivative.aeval a‖ :=
tendsto_nhds_unique (newton_seq_dist_tendsto' hnorm) (newton_seq_dist_tendsto hnorm hnsol)
private theorem soln_dist_to_a_lt_deriv : ‖soln - a‖ < ‖F.derivative.aeval a‖ := by
rw [soln_dist_to_a, div_lt_iff₀ (deriv_norm_pos _), ← sq] <;> assumption
private theorem soln_unique (z : ℤ_[p]) (hev : F.aeval z = 0)
(hnlt : ‖z - a‖ < ‖F.derivative.aeval a‖) : z = soln := by
have soln_dist : ‖z - soln‖ < ‖F.derivative.aeval a‖ :=
calc
‖z - soln‖ = ‖z - a + (a - soln)‖ := by rw [sub_add_sub_cancel]
_ ≤ max ‖z - a‖ ‖a - soln‖ := PadicInt.nonarchimedean _ _
_ < ‖F.derivative.aeval a‖ :=
max_lt hnlt ((norm_sub_rev soln a ▸ (soln_dist_to_a_lt_deriv hnorm)) hnsol)
let h := z - soln
let ⟨q, hq⟩ := (F.map (algebraMap R ℤ_[p])).binomExpansion soln h
simp only [Polynomial.eval_map_algebraMap, Polynomial.derivative_map] at hq
have : (F.derivative.aeval soln + q * h) * h = 0 :=
Eq.symm
(calc
0 = F.aeval (soln + h) := by simp [h, hev]
_ = F.derivative.aeval soln * h + q * h ^ 2 := by rw [hq, eval_soln, zero_add]
_ = (F.derivative.aeval soln + q * h) * h := by rw [sq, right_distrib, mul_assoc]
)
have : h = 0 :=
by_contra fun hne =>
have : F.derivative.aeval soln + q * h = 0 :=
(eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne
have : F.derivative.aeval soln = -q * h := by simpa using eq_neg_of_add_eq_zero_left this
lt_irrefl ‖F.derivative.aeval soln‖
(calc
‖F.derivative.aeval soln‖ = ‖-q * h‖ := by rw [this]
_ ≤ 1 * ‖h‖ := by
rw [norm_mul]
exact mul_le_mul_of_nonneg_right (PadicInt.norm_le_one _) (norm_nonneg _)
_ = ‖z - soln‖ := by simp [h]
_ < ‖F.derivative.aeval soln‖ := by rw [soln_deriv_norm]; apply soln_dist
)
exact eq_of_sub_eq_zero (by rw [← this])
end Hensel
variable {p : ℕ} [Fact p.Prime] {R : Type*} [CommSemiring R] [Algebra R ℤ_[p]]
{F : Polynomial R} {a : ℤ_[p]}
private theorem a_soln_is_unique (ha : F.aeval a = 0) (z' : ℤ_[p]) (hz' : F.aeval z' = 0)
(hnormz' : ‖z' - a‖ < ‖F.derivative.aeval a‖) : z' = a := by
let h := z' - a
let ⟨q, hq⟩ := (F.map (algebraMap R ℤ_[p])).binomExpansion a h
simp only [Polynomial.eval_map_algebraMap, Polynomial.derivative_map] at hq
have : (F.derivative.aeval a + q * h) * h = 0 :=
Eq.symm
(calc
0 = F.aeval (a + h) := show 0 = F.aeval (a + (z' - a)) by simp [hz']
_ = F.derivative.aeval a * h + q * h ^ 2 := by rw [hq, ha, zero_add]
_ = (F.derivative.aeval a + q * h) * h := by rw [sq, right_distrib, mul_assoc]
)
have : h = 0 :=
by_contra fun hne =>
have : F.derivative.aeval a + q * h = 0 :=
(eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne
have : F.derivative.aeval a = -q * h := by simpa using eq_neg_of_add_eq_zero_left this
lt_irrefl ‖F.derivative.aeval a‖
(calc
‖F.derivative.aeval a‖ = ‖q‖ * ‖h‖ := by simp [this]
_ ≤ 1 * ‖h‖ := by gcongr; apply PadicInt.norm_le_one
_ < ‖F.derivative.aeval a‖ := by simpa
)
exact eq_of_sub_eq_zero (by rw [← this])
variable (hnorm : ‖F.aeval a‖ < ‖F.derivative.aeval a‖ ^ 2)
include hnorm
private theorem a_is_soln (ha : F.aeval a = 0) :
F.aeval a = 0 ∧
‖a - a‖ < ‖F.derivative.aeval a‖ ∧
‖F.derivative.aeval a‖ = ‖F.derivative.aeval a‖ ∧
∀ z', F.aeval z' = 0 → ‖z' - a‖ < ‖F.derivative.aeval a‖ → z' = a :=
⟨ha, by simp [deriv_ne_zero hnorm], rfl, a_soln_is_unique ha⟩
theorem hensels_lemma :
∃ z : ℤ_[p],
F.aeval z = 0 ∧
‖z - a‖ < ‖F.derivative.aeval a‖ ∧
‖F.derivative.aeval z‖ = ‖F.derivative.aeval a‖ ∧
∀ z', F.aeval z' = 0 → ‖z' - a‖ < ‖F.derivative.aeval a‖ → z' = z := by
classical
exact if ha : F.aeval a = 0 then ⟨a, a_is_soln hnorm ha⟩
else by
exact ⟨soln_gen hnorm, eval_soln hnorm,
soln_dist_to_a_lt_deriv hnorm ha, soln_deriv_norm hnorm, fun z => soln_unique hnorm ha z⟩ |
.lake/packages/mathlib/Mathlib/NumberTheory/Padics/PadicVal/Basic.lean | import Mathlib.NumberTheory.Divisors
import Mathlib.NumberTheory.Padics.PadicVal.Defs
import Mathlib.Data.Nat.MaxPowDiv
import Mathlib.Data.Nat.Multiplicity
import Mathlib.Data.Nat.Prime.Int
/-!
# `p`-adic Valuation
This file defines the `p`-adic valuation on `ℕ`, `ℤ`, and `ℚ`.
The `p`-adic valuation on `ℚ` is the difference of the multiplicities of `p` in the numerator and
denominator of `q`. This function obeys the standard properties of a valuation, with the appropriate
assumptions on `p`. The `p`-adic valuations on `ℕ` and `ℤ` agree with that on `ℚ`.
The valuation induces a norm on `ℚ`. This norm is defined in padicNorm.lean.
## Notation
This file uses the local notation `/.` for `Rat.mk`.
## Implementation notes
Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically
by taking `[Fact p.Prime]` as a type class argument.
## Calculations with `p`-adic valuations
* `padicValNat_factorial`: Legendre's Theorem. The `p`-adic valuation of `n!` is the sum of the
quotients `n / p ^ i`. This sum is expressed over the finset `Ico 1 b` where `b` is any bound
greater than `log p n`. See `Nat.Prime.multiplicity_factorial` for the same result but stated in
the language of prime multiplicity.
* `sub_one_mul_padicValNat_factorial`: Legendre's Theorem. Taking (`p - 1`) times
the `p`-adic valuation of `n!` equals `n` minus the sum of base `p` digits of `n`.
* `padicValNat_choose`: Kummer's Theorem. The `p`-adic valuation of `n.choose k` is the number
of carries when `k` and `n - k` are added in base `p`. This sum is expressed over the finset
`Ico 1 b` where `b` is any bound greater than `log p n`. See `Nat.Prime.multiplicity_choose` for
the same result but stated in the language of prime multiplicity.
* `sub_one_mul_padicValNat_choose_eq_sub_sum_digits`: Kummer's Theorem. Taking (`p - 1`) times the
`p`-adic valuation of the binomial `n` over `k` equals the sum of the digits of `k` plus the sum
of the digits of `n - k` minus the sum of digits of `n`, all base `p`.
## References
* [F. Q. Gouvêa, *p-adic numbers*][gouvea1997]
* [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019]
* <https://en.wikipedia.org/wiki/P-adic_number>
## Tags
p-adic, p adic, padic, norm, valuation
-/
universe u
open Nat Rat
open scoped Finset
namespace padicValNat
variable {p : ℕ}
/-- If `p ≠ 0` and `p ≠ 1`, then `padicValNat p p` is `1`. -/
@[simp]
theorem self (hp : 1 < p) : padicValNat p p = 1 := by
simp [padicValNat_def', ne_zero_of_lt hp, hp.ne']
theorem eq_zero_of_not_dvd {n : ℕ} (h : ¬p ∣ n) : padicValNat p n = 0 :=
eq_zero_iff.2 <| Or.inr <| Or.inr h
open Nat.maxPowDiv
theorem maxPowDiv_eq_emultiplicity {p n : ℕ} (hp : 1 < p) (hn : n ≠ 0) :
p.maxPowDiv n = emultiplicity p n := by
apply (emultiplicity_eq_of_dvd_of_not_dvd (pow_dvd p n) _).symm
intro h
apply Nat.not_lt.mpr <| le_of_dvd hp hn h
simp
theorem maxPowDiv_eq_multiplicity {p n : ℕ} (hp : 1 < p) (hn : n ≠ 0) (h : FiniteMultiplicity p n) :
p.maxPowDiv n = multiplicity p n := by
exact_mod_cast h.emultiplicity_eq_multiplicity ▸ maxPowDiv_eq_emultiplicity hp hn
/-- Allows for more efficient code for `padicValNat` -/
@[csimp]
theorem padicValNat_eq_maxPowDiv : @padicValNat = @maxPowDiv := by
ext p n
set_option push_neg.use_distrib true in by_cases! h : 1 < p ∧ 0 < n
· rw [padicValNat_def' h.1.ne' h.2.ne', maxPowDiv_eq_multiplicity h.1 h.2.ne']
exact Nat.finiteMultiplicity_iff.2 ⟨h.1.ne', h.2⟩
· rcases h with (h | h)
· interval_cases p
· simp [Classical.em]
· dsimp [padicValNat, maxPowDiv]
rw [go, if_neg]; simp
· simp [Nat.le_zero.mp h]
end padicValNat
/-- For `p ≠ 1`, the `p`-adic valuation of an integer `z ≠ 0` is the largest natural number `k` such
that `p^k` divides `z`. If `x = 0` or `p = 1`, then `padicValInt p q` defaults to `0`. -/
def padicValInt (p : ℕ) (z : ℤ) : ℕ :=
padicValNat p z.natAbs
namespace padicValInt
variable {p : ℕ}
theorem of_ne_one_ne_zero {z : ℤ} (hp : p ≠ 1) (hz : z ≠ 0) :
padicValInt p z = multiplicity (p : ℤ) z := by
rw [padicValInt, padicValNat_def' hp (Int.natAbs_ne_zero.mpr hz)]
apply Int.multiplicity_natAbs
/-- `padicValInt p 0` is `0` for any `p`. -/
@[simp]
protected theorem zero : padicValInt p 0 = 0 := by simp [padicValInt]
/-- `padicValInt p 1` is `0` for any `p`. -/
@[simp]
protected theorem one : padicValInt p 1 = 0 := by simp [padicValInt]
/-- The `p`-adic value of a natural is its `p`-adic value as an integer. -/
@[simp]
theorem of_nat {n : ℕ} : padicValInt p n = padicValNat p n := by simp [padicValInt]
/-- If `p ≠ 0` and `p ≠ 1`, then `padicValInt p p` is `1`. -/
theorem self (hp : 1 < p) : padicValInt p p = 1 := by simp [padicValNat.self hp]
@[simp]
theorem eq_zero_iff {z : ℤ} : padicValInt p z = 0 ↔ p = 1 ∨ z = 0 ∨ ¬(p : ℤ) ∣ z := by
rw [padicValInt, padicValNat.eq_zero_iff, Int.natAbs_eq_zero, ← Int.ofNat_dvd_left]
theorem eq_zero_of_not_dvd {z : ℤ} (h : ¬(p : ℤ) ∣ z) : padicValInt p z = 0 := by
simp [h]
end padicValInt
/-- `padicValRat` defines the valuation of a rational `q` to be the valuation of `q.num` minus the
valuation of `q.den`. If `q = 0` or `p = 1`, then `padicValRat p q` defaults to `0`. -/
def padicValRat (p : ℕ) (q : ℚ) : ℤ :=
padicValInt p q.num - padicValNat p q.den
lemma padicValRat_def (p : ℕ) (q : ℚ) :
padicValRat p q = padicValInt p q.num - padicValNat p q.den :=
rfl
namespace padicValRat
variable {p : ℕ}
/-- `padicValRat p q` is symmetric in `q`. -/
@[simp]
protected theorem neg (q : ℚ) : padicValRat p (-q) = padicValRat p q := by
simp [padicValRat, padicValInt]
/-- `padicValRat p 0` is `0` for any `p`. -/
@[simp]
protected theorem zero : padicValRat p 0 = 0 := by simp [padicValRat]
/-- `padicValRat p 1` is `0` for any `p`. -/
@[simp]
protected theorem one : padicValRat p 1 = 0 := by simp [padicValRat]
/-- The `p`-adic value of an integer `z ≠ 0` is its `p`-adic_value as a rational. -/
@[simp]
theorem of_int {z : ℤ} : padicValRat p z = padicValInt p z := by simp [padicValRat]
/-- The `p`-adic value of an integer `z ≠ 0` is the multiplicity of `p` in `z`. -/
theorem of_int_multiplicity {z : ℤ} (hp : p ≠ 1) (hz : z ≠ 0) :
padicValRat p (z : ℚ) = multiplicity (p : ℤ) z := by
rw [of_int, padicValInt.of_ne_one_ne_zero hp hz]
theorem multiplicity_sub_multiplicity {q : ℚ} (hp : p ≠ 1) (hq : q ≠ 0) :
padicValRat p q = multiplicity (p : ℤ) q.num - multiplicity p q.den := by
rw [padicValRat, padicValInt.of_ne_one_ne_zero hp (Rat.num_ne_zero.2 hq),
padicValNat_def' hp q.den_ne_zero]
/-- The `p`-adic value of an integer `z ≠ 0` is its `p`-adic value as a rational. -/
@[simp]
theorem of_nat {n : ℕ} : padicValRat p n = padicValNat p n := by simp [padicValRat]
/-- If `p ≠ 0` and `p ≠ 1`, then `padicValRat p p` is `1`. -/
theorem self (hp : 1 < p) : padicValRat p p = 1 := by simp [hp]
end padicValRat
section padicValNat
variable {p : ℕ}
theorem zero_le_padicValRat_of_nat (n : ℕ) : 0 ≤ padicValRat p n := by simp
/-- `padicValRat` coincides with `padicValNat`. -/
@[norm_cast]
theorem padicValRat_of_nat (n : ℕ) : ↑(padicValNat p n) = padicValRat p n := by simp
@[simp]
theorem padicValNat_self [Fact p.Prime] : padicValNat p p = 1 := by
rw [padicValNat_def (@Fact.out p.Prime).ne_zero]
simp
theorem one_le_padicValNat_of_dvd {n : ℕ} [hp : Fact p.Prime] (hn : n ≠ 0) (div : p ∣ n) :
1 ≤ padicValNat p n := by
rwa [← WithTop.coe_le_coe, ENat.some_eq_coe, padicValNat_eq_emultiplicity hn,
← pow_dvd_iff_le_emultiplicity, pow_one]
theorem dvd_iff_padicValNat_ne_zero {p n : ℕ} [Fact p.Prime] (hn0 : n ≠ 0) :
p ∣ n ↔ padicValNat p n ≠ 0 :=
⟨fun h => one_le_iff_ne_zero.mp (one_le_padicValNat_of_dvd hn0 h), fun h =>
Classical.not_not.1 (mt padicValNat.eq_zero_of_not_dvd h)⟩
end padicValNat
namespace padicValRat
variable {p : ℕ} [hp : Fact p.Prime]
/-- The multiplicity of `p : ℕ` in `a : ℤ` is finite exactly when `a ≠ 0`. -/
theorem finite_int_prime_iff {a : ℤ} : FiniteMultiplicity (p : ℤ) a ↔ a ≠ 0 := by
simp [Int.finiteMultiplicity_iff, hp.1.ne_one]
/-- A rewrite lemma for `padicValRat p q` when `q` is expressed in terms of `Rat.mk`. -/
protected theorem defn (p : ℕ) [hp : Fact p.Prime] {q : ℚ} {n d : ℤ} (hqz : q ≠ 0)
(qdf : q = n /. d) :
padicValRat p q = multiplicity (p : ℤ) n - multiplicity (p : ℤ) d := by
have hd : d ≠ 0 := Rat.mk_denom_ne_zero_of_ne_zero hqz qdf
let ⟨c, hc1, hc2⟩ := Rat.num_den_mk hd qdf
rw [padicValRat.multiplicity_sub_multiplicity hp.1.ne_one hqz]
simp only [hc1, hc2]
rw [multiplicity_mul (Nat.prime_iff_prime_int.1 hp.1),
multiplicity_mul (Nat.prime_iff_prime_int.1 hp.1)]
· rw [Nat.cast_add, Nat.cast_add]
simp_rw [Int.natCast_multiplicity p q.den]
ring
· simpa [finite_int_prime_iff, hc2] using hd
· simpa [finite_int_prime_iff, hqz, hc2] using hd
/-- A rewrite lemma for `padicValRat p (q * r)` with conditions `q ≠ 0`, `r ≠ 0`. -/
protected theorem mul {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) :
padicValRat p (q * r) = padicValRat p q + padicValRat p r := by
have : q * r = (q.num * r.num) /. (q.den * r.den) := by
rw [Rat.mul_eq_mkRat, Rat.mkRat_eq_divInt, Nat.cast_mul]
have hq' : q.num /. q.den ≠ 0 := by rwa [Rat.num_divInt_den]
have hr' : r.num /. r.den ≠ 0 := by rwa [Rat.num_divInt_den]
have hp' : Prime (p : ℤ) := Nat.prime_iff_prime_int.1 hp.1
rw [padicValRat.defn p (mul_ne_zero hq hr) this]
conv_rhs =>
rw [← q.num_divInt_den, padicValRat.defn p hq', ← r.num_divInt_den, padicValRat.defn p hr']
rw [multiplicity_mul hp', multiplicity_mul hp', Nat.cast_add, Nat.cast_add]
· ring
· simp [finite_int_prime_iff]
· simp [finite_int_prime_iff, hq, hr]
/-- A rewrite lemma for `padicValRat p (q^k)` with condition `q ≠ 0`. -/
protected theorem pow {q : ℚ} (hq : q ≠ 0) {k : ℕ} :
padicValRat p (q ^ k) = k * padicValRat p q := by
induction k <;>
simp [*, padicValRat.mul hq (pow_ne_zero _ hq), _root_.pow_succ', add_mul, add_comm]
/-- A rewrite lemma for `padicValRat p (q⁻¹)` with condition `q ≠ 0`. -/
protected theorem inv (q : ℚ) : padicValRat p q⁻¹ = -padicValRat p q := by
by_cases hq : q = 0
· simp [hq]
· rw [eq_neg_iff_add_eq_zero, ← padicValRat.mul (inv_ne_zero hq) hq, inv_mul_cancel₀ hq,
padicValRat.one]
/-- A rewrite lemma for `padicValRat p (q / r)` with conditions `q ≠ 0`, `r ≠ 0`. -/
protected theorem div {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) :
padicValRat p (q / r) = padicValRat p q - padicValRat p r := by
rw [div_eq_mul_inv, padicValRat.mul hq (inv_ne_zero hr), padicValRat.inv r, sub_eq_add_neg]
/-- A condition for `padicValRat p (n₁ / d₁) ≤ padicValRat p (n₂ / d₂)`, in terms of
divisibility by `p^n`. -/
theorem padicValRat_le_padicValRat_iff {n₁ n₂ d₁ d₂ : ℤ} (hn₁ : n₁ ≠ 0) (hn₂ : n₂ ≠ 0)
(hd₁ : d₁ ≠ 0) (hd₂ : d₂ ≠ 0) :
padicValRat p (n₁ /. d₁) ≤ padicValRat p (n₂ /. d₂) ↔
∀ n : ℕ, (p : ℤ) ^ n ∣ n₁ * d₂ → (p : ℤ) ^ n ∣ n₂ * d₁ := by
have hf1 : FiniteMultiplicity (p : ℤ) (n₁ * d₂) := finite_int_prime_iff.2 (mul_ne_zero hn₁ hd₂)
have hf2 : FiniteMultiplicity (p : ℤ) (n₂ * d₁) := finite_int_prime_iff.2 (mul_ne_zero hn₂ hd₁)
conv =>
lhs
rw [padicValRat.defn p (Rat.divInt_ne_zero_of_ne_zero hn₁ hd₁) rfl,
padicValRat.defn p (Rat.divInt_ne_zero_of_ne_zero hn₂ hd₂) rfl, sub_le_iff_le_add', ←
add_sub_assoc, le_sub_iff_add_le]
norm_cast
rw [← multiplicity_mul (Nat.prime_iff_prime_int.1 hp.1) hf1, add_comm,
← multiplicity_mul (Nat.prime_iff_prime_int.1 hp.1) hf2,
hf1.multiplicity_le_multiplicity_iff hf2]
/-- Sufficient conditions to show that the `p`-adic valuation of `q` is less than or equal to the
`p`-adic valuation of `q + r`. -/
theorem le_padicValRat_add_of_le {q r : ℚ} (hqr : q + r ≠ 0)
(h : padicValRat p q ≤ padicValRat p r) : padicValRat p q ≤ padicValRat p (q + r) :=
if hq : q = 0 then by simpa [hq] using h
else
if hr : r = 0 then by simp [hr]
else by
have hqn : q.num ≠ 0 := Rat.num_ne_zero.2 hq
have hqd : (q.den : ℤ) ≠ 0 := mod_cast Rat.den_nz _
have hrn : r.num ≠ 0 := Rat.num_ne_zero.2 hr
have hrd : (r.den : ℤ) ≠ 0 := mod_cast Rat.den_nz _
have hqreq : q + r = (q.num * r.den + q.den * r.num) /. (q.den * r.den) := Rat.add_num_den _ _
have hqrd : q.num * r.den + q.den * r.num ≠ 0 := Rat.mk_num_ne_zero_of_ne_zero hqr hqreq
conv_lhs => rw [← q.num_divInt_den]
rw [hqreq, padicValRat_le_padicValRat_iff hqn hqrd hqd (mul_ne_zero hqd hrd), ←
emultiplicity_le_emultiplicity_iff, mul_left_comm,
emultiplicity_mul (Nat.prime_iff_prime_int.1 hp.1), add_mul]
rw [← q.num_divInt_den, ← r.num_divInt_den, padicValRat_le_padicValRat_iff hqn hrn hqd hrd, ←
emultiplicity_le_emultiplicity_iff] at h
calc
_ ≤ min (emultiplicity ↑p (q.num * r.den * q.den))
(emultiplicity ↑p (q.den * r.num * q.den)) :=
le_min
(by rw [emultiplicity_mul (a :=_ * _) (Nat.prime_iff_prime_int.1 hp.1), add_comm])
(by grw [mul_assoc, emultiplicity_mul (b := _ * _) (Nat.prime_iff_prime_int.1 hp.1), h])
_ ≤ _ := min_le_emultiplicity_add
/-- The minimum of the valuations of `q` and `r` is at most the valuation of `q + r`. -/
theorem min_le_padicValRat_add {q r : ℚ} (hqr : q + r ≠ 0) :
min (padicValRat p q) (padicValRat p r) ≤ padicValRat p (q + r) :=
(le_total (padicValRat p q) (padicValRat p r)).elim
(fun h => by rw [min_eq_left h]; exact le_padicValRat_add_of_le hqr h)
(fun h => by rw [min_eq_right h, add_comm]; exact le_padicValRat_add_of_le (by rwa [add_comm]) h)
/-- Ultrametric property of a p-adic valuation. -/
lemma add_eq_min {q r : ℚ} (hqr : q + r ≠ 0) (hq : q ≠ 0) (hr : r ≠ 0)
(hval : padicValRat p q ≠ padicValRat p r) :
padicValRat p (q + r) = min (padicValRat p q) (padicValRat p r) := by
have h1 := min_le_padicValRat_add (p := p) hqr
have h2 := min_le_padicValRat_add (p := p) (ne_of_eq_of_ne (add_neg_cancel_right q r) hq)
have h3 := min_le_padicValRat_add (p := p) (ne_of_eq_of_ne (add_neg_cancel_right r q) hr)
rw [add_neg_cancel_right, padicValRat.neg] at h2 h3
rw [add_comm] at h3
omega
lemma add_eq_of_lt {q r : ℚ} (hqr : q + r ≠ 0)
(hq : q ≠ 0) (hr : r ≠ 0) (hval : padicValRat p q < padicValRat p r) :
padicValRat p (q + r) = padicValRat p q := by
rw [add_eq_min hqr hq hr (ne_of_lt hval), min_eq_left (le_of_lt hval)]
lemma lt_add_of_lt {q r₁ r₂ : ℚ} (hqr : r₁ + r₂ ≠ 0)
(hval₁ : padicValRat p q < padicValRat p r₁) (hval₂ : padicValRat p q < padicValRat p r₂) :
padicValRat p q < padicValRat p (r₁ + r₂) :=
lt_of_lt_of_le (lt_min hval₁ hval₂) (padicValRat.min_le_padicValRat_add hqr)
@[simp]
lemma self_pow_inv (r : ℕ) : padicValRat p ((p : ℚ) ^ r)⁻¹ = -r := by
rw [padicValRat.inv, neg_inj, padicValRat.pow (Nat.cast_ne_zero.mpr hp.elim.ne_zero),
padicValRat.self hp.elim.one_lt, mul_one]
/-- A finite sum of rationals with positive `p`-adic valuation has positive `p`-adic valuation
(if the sum is non-zero). -/
theorem sum_pos_of_pos {n : ℕ} {F : ℕ → ℚ} (hF : ∀ i, i < n → 0 < padicValRat p (F i))
(hn0 : ∑ i ∈ Finset.range n, F i ≠ 0) : 0 < padicValRat p (∑ i ∈ Finset.range n, F i) := by
induction n with
| zero => exact False.elim (hn0 rfl)
| succ d hd =>
rw [Finset.sum_range_succ] at hn0 ⊢
by_cases h : ∑ x ∈ Finset.range d, F x = 0
· rw [h, zero_add]
exact hF d (lt_add_one _)
· refine lt_of_lt_of_le ?_ (min_le_padicValRat_add hn0)
refine lt_min (hd (fun i hi => ?_) h) (hF d (lt_add_one _))
exact hF _ (lt_trans hi (lt_add_one _))
/-- If the p-adic valuation of a finite set of positive rationals is greater than a given rational
number, then the p-adic valuation of their sum is also greater than the same rational number. -/
theorem lt_sum_of_lt {p j : ℕ} [hp : Fact (Nat.Prime p)] {F : ℕ → ℚ} {S : Finset ℕ}
(hS : S.Nonempty) (hF : ∀ i, i ∈ S → padicValRat p (F j) < padicValRat p (F i))
(hn1 : ∀ i : ℕ, 0 < F i) : padicValRat p (F j) < padicValRat p (∑ i ∈ S, F i) := by
induction hS using Finset.Nonempty.cons_induction with
| singleton k =>
rw [Finset.sum_singleton]
exact hF k (by simp)
| cons s S' Hnot Hne Hind =>
rw [Finset.cons_eq_insert, Finset.sum_insert Hnot]
exact padicValRat.lt_add_of_lt
(ne_of_gt (add_pos (hn1 s) (Finset.sum_pos (fun i _ => hn1 i) Hne)))
(hF _ (by simp [Finset.mem_insert, true_or]))
(Hind (fun i hi => hF _ (by rw [Finset.cons_eq_insert,Finset.mem_insert]; exact Or.inr hi)))
end padicValRat
namespace padicValNat
variable {p a b : ℕ} [hp : Fact p.Prime]
/-- A rewrite lemma for `padicValNat p (a * b)` with conditions `a ≠ 0`, `b ≠ 0`. -/
protected theorem mul : a ≠ 0 → b ≠ 0 → padicValNat p (a * b) = padicValNat p a + padicValNat p b :=
mod_cast padicValRat.mul (p := p) (q := a) (r := b)
protected theorem div_of_dvd (h : b ∣ a) :
padicValNat p (a / b) = padicValNat p a - padicValNat p b := by
rcases eq_or_ne a 0 with (rfl | ha)
· simp
obtain ⟨k, rfl⟩ := h
obtain ⟨hb, hk⟩ := mul_ne_zero_iff.mp ha
rw [mul_comm, k.mul_div_cancel hb.bot_lt, padicValNat.mul hk hb, Nat.add_sub_cancel]
/-- Dividing out by a prime factor reduces the `padicValNat` by `1`. -/
protected theorem div (dvd : p ∣ b) : padicValNat p (b / p) = padicValNat p b - 1 := by
rw [padicValNat.div_of_dvd dvd, padicValNat_self]
/-- A version of `padicValRat.pow` for `padicValNat`. -/
protected theorem pow (n : ℕ) (ha : a ≠ 0) : padicValNat p (a ^ n) = n * padicValNat p a := by
simpa only [← @Nat.cast_inj ℤ, push_cast] using padicValRat.pow (Nat.cast_ne_zero.mpr ha)
@[simp]
protected theorem prime_pow (n : ℕ) : padicValNat p (p ^ n) = n := by
rw [padicValNat.pow _ (@Fact.out p.Prime).ne_zero, padicValNat_self, mul_one]
protected theorem div_pow (dvd : p ^ a ∣ b) : padicValNat p (b / p ^ a) = padicValNat p b - a := by
rw [padicValNat.div_of_dvd dvd, padicValNat.prime_pow]
protected theorem div' {m : ℕ} (cpm : Coprime p m) {b : ℕ} (dvd : m ∣ b) :
padicValNat p (b / m) = padicValNat p b := by
rw [padicValNat.div_of_dvd dvd, eq_zero_of_not_dvd (hp.out.coprime_iff_not_dvd.mp cpm),
Nat.sub_zero]
end padicValNat
section padicValNat
variable {p : ℕ}
theorem dvd_of_one_le_padicValNat {n : ℕ} (hp : 1 ≤ padicValNat p n) : p ∣ n := by
by_contra h
rw [padicValNat.eq_zero_of_not_dvd h] at hp
exact lt_irrefl 0 (lt_of_lt_of_le zero_lt_one hp)
theorem pow_padicValNat_dvd {n : ℕ} : p ^ padicValNat p n ∣ n := by
rcases eq_or_ne n 0 with (rfl | hn); · simp
rcases eq_or_ne p 1 with (rfl | hp); · simp
apply pow_dvd_of_le_multiplicity
rw [padicValNat_def'] <;> assumption
theorem padicValNat_dvd_iff_le [hp : Fact p.Prime] {a n : ℕ} (ha : a ≠ 0) :
p ^ n ∣ a ↔ n ≤ padicValNat p a := by
rw [pow_dvd_iff_le_emultiplicity, ← padicValNat_eq_emultiplicity ha,
Nat.cast_le]
theorem padicValNat_dvd_iff (n : ℕ) [hp : Fact p.Prime] (a : ℕ) :
p ^ n ∣ a ↔ a = 0 ∨ n ≤ padicValNat p a := by
rcases eq_or_ne a 0 with (rfl | ha)
· exact iff_of_true (dvd_zero _) (Or.inl rfl)
· rw [padicValNat_dvd_iff_le ha, or_iff_right ha]
theorem pow_succ_padicValNat_not_dvd {n : ℕ} [hp : Fact p.Prime] (hn : n ≠ 0) :
¬p ^ (padicValNat p n + 1) ∣ n := by
rw [padicValNat_dvd_iff_le hn, not_le]
exact Nat.lt_succ_self _
theorem padicValNat_primes {q : ℕ} [hp : Fact p.Prime] [hq : Fact q.Prime] (neq : p ≠ q) :
padicValNat p q = 0 :=
@padicValNat.eq_zero_of_not_dvd p q <|
(not_congr (Iff.symm (prime_dvd_prime_iff_eq hp.1 hq.1))).mp neq
theorem padicValNat_prime_prime_pow {q : ℕ} [hp : Fact p.Prime] [hq : Fact q.Prime]
(n : ℕ) (neq : p ≠ q) : padicValNat p (q ^ n) = 0 := by
rw [padicValNat.pow _ <| Nat.Prime.ne_zero hq.elim, padicValNat_primes neq, mul_zero]
theorem padicValNat_mul_pow_left {q : ℕ} [hp : Fact p.Prime] [hq : Fact q.Prime]
(n m : ℕ) (neq : p ≠ q) : padicValNat p (p^n * q^m) = n := by
rw [padicValNat.mul (NeZero.ne' (p^n)).symm (NeZero.ne' (q^m)).symm,
padicValNat.prime_pow, padicValNat_prime_prime_pow m neq, add_zero]
theorem padicValNat_mul_pow_right {q : ℕ} [hp : Fact p.Prime] [hq : Fact q.Prime]
(n m : ℕ) (neq : q ≠ p) : padicValNat q (p^n * q^m) = m := by
rw [mul_comm (p^n) (q^m)]
exact padicValNat_mul_pow_left m n neq
/-- The p-adic valuation of `n` is less than or equal to its logarithm w.r.t. `p`. -/
lemma padicValNat_le_nat_log (n : ℕ) : padicValNat p n ≤ Nat.log p n := by
rcases n with _ | n
· simp
rcases p with _ | _ | p
· simp
· simp
exact Nat.le_log_of_pow_le p.one_lt_succ_succ (le_of_dvd n.succ_pos pow_padicValNat_dvd)
/-- The p-adic valuation of `n` is equal to the logarithm w.r.t. `p` iff
`n` is less than `p` raised to one plus the p-adic valuation of `n`. -/
lemma nat_log_eq_padicValNat_iff {n : ℕ} [hp : Fact (Nat.Prime p)] (hn : n ≠ 0) :
Nat.log p n = padicValNat p n ↔ n < p ^ (padicValNat p n + 1) := by
rw [Nat.log_eq_iff (Or.inr ⟨(Nat.Prime.one_lt' p).out, by cutsat⟩), and_iff_right_iff_imp]
exact fun _ => Nat.le_of_dvd (Nat.pos_iff_ne_zero.mpr hn) pow_padicValNat_dvd
/-- This is false for prime numbers other than 2:
for `p = 3`, `n = 1`, one has `log 3 1 = padicValNat 3 2 = 0`. -/
lemma Nat.log_ne_padicValNat_succ {n : ℕ} (hn : n ≠ 0) : log 2 n ≠ padicValNat 2 (n + 1) := by
rw [Ne, log_eq_iff (by simp [hn])]
rintro ⟨h1, h2⟩
rw [← Nat.lt_add_one_iff, ← mul_one (2 ^ _)] at h1
rw [← add_one_le_iff, Nat.pow_succ] at h2
refine not_dvd_of_lt_of_lt_mul_succ h1 (lt_of_le_of_ne' h2 ?_) pow_padicValNat_dvd
-- TODO(kmill): Why is this `p := 2` necessary?
exact pow_succ_padicValNat_not_dvd (p := 2) n.succ_ne_zero ∘ dvd_of_eq
lemma Nat.max_log_padicValNat_succ_eq_log_succ (n : ℕ) [hp : Fact p.Prime] :
max (log p n) (padicValNat p (n + 1)) = log p (n + 1) := by
apply le_antisymm (max_le (le_log_of_pow_le hp.out.one_lt (pow_log_le_add_one p n))
(padicValNat_le_nat_log (n + 1)))
rw [le_max_iff, or_iff_not_imp_left, not_le]
intro h
replace h := le_antisymm (add_one_le_iff.mpr (lt_pow_of_log_lt hp.out.one_lt h))
(pow_log_le_self p n.succ_ne_zero)
rw [h, padicValNat.prime_pow, ← h]
theorem range_pow_padicValNat_subset_divisors {n : ℕ} (hn : n ≠ 0) :
(Finset.range (padicValNat p n + 1)).image (p ^ ·) ⊆ n.divisors := by
intro t ht
simp only [Finset.mem_image, Finset.mem_range] at ht
obtain ⟨k, hk, rfl⟩ := ht
rw [Nat.mem_divisors]
exact ⟨(pow_dvd_pow p <| by cutsat).trans pow_padicValNat_dvd, hn⟩
theorem range_pow_padicValNat_subset_divisors' {n : ℕ} [hp : Fact p.Prime] :
((Finset.range (padicValNat p n)).image fun t => p ^ (t + 1)) ⊆ n.divisors.erase 1 := by
rcases eq_or_ne n 0 with (rfl | hn)
· simp
intro t ht
simp only [Finset.mem_image, Finset.mem_range] at ht
obtain ⟨k, hk, rfl⟩ := ht
rw [Finset.mem_erase, Nat.mem_divisors]
refine ⟨?_, (pow_dvd_pow p <| succ_le_iff.2 hk).trans pow_padicValNat_dvd, hn⟩
exact (Nat.one_lt_pow k.succ_ne_zero hp.out.one_lt).ne'
/-- The `p`-adic valuation of `(p * n)!` is `n` more than that of `n!`. -/
theorem padicValNat_factorial_mul (n : ℕ) [hp : Fact p.Prime] :
padicValNat p (p * n) ! = padicValNat p n ! + n := by
apply Nat.cast_injective (R := ℕ∞)
rw [padicValNat_eq_emultiplicity <| factorial_ne_zero (p * n), Nat.cast_add,
padicValNat_eq_emultiplicity <| factorial_ne_zero n]
exact Prime.emultiplicity_factorial_mul hp.out
/-- The `p`-adic valuation of `m` equals zero if it is between `p * k` and `p * (k + 1)` for
some `k`. -/
theorem padicValNat_eq_zero_of_mem_Ioo {m k : ℕ}
(hm : m ∈ Set.Ioo (p * k) (p * (k + 1))) : padicValNat p m = 0 :=
padicValNat.eq_zero_of_not_dvd <| not_dvd_of_lt_of_lt_mul_succ hm.1 hm.2
theorem padicValNat_factorial_mul_add {n : ℕ} (m : ℕ) [hp : Fact p.Prime] (h : n < p) :
padicValNat p (p * m + n) ! = padicValNat p (p * m) ! := by
induction n with
| zero => rw [add_zero]
| succ n hn =>
rw [add_succ, factorial_succ,
padicValNat.mul (succ_ne_zero (p * m + n)) <| factorial_ne_zero (p * m + _),
hn <| lt_of_succ_lt h, ← add_succ,
padicValNat_eq_zero_of_mem_Ioo ⟨(Nat.lt_add_of_pos_right <| succ_pos n),
(Nat.mul_add _ _ _▸ Nat.mul_one _ ▸ ((add_lt_add_iff_left (p * m)).mpr h))⟩,
zero_add]
/-- The `p`-adic valuation of `n!` is equal to the `p`-adic valuation of the factorial of the
largest multiple of `p` below `n`, i.e. `(p * ⌊n / p⌋)!`. -/
@[simp] theorem padicValNat_mul_div_factorial (n : ℕ) [hp : Fact p.Prime] :
padicValNat p (p * (n / p))! = padicValNat p n ! := by
nth_rw 2 [← div_add_mod n p]
exact (padicValNat_factorial_mul_add (n / p) <| mod_lt n hp.out.pos).symm
/-- **Legendre's Theorem**
The `p`-adic valuation of `n!` is the sum of the quotients `n / p ^ i`. This sum is expressed
over the finset `Ico 1 b` where `b` is any bound greater than `log p n`. -/
theorem padicValNat_factorial {n b : ℕ} [hp : Fact p.Prime] (hnb : log p n < b) :
padicValNat p (n !) = ∑ i ∈ Finset.Ico 1 b, n / p ^ i := by
exact_mod_cast ((padicValNat_eq_emultiplicity (p := p) <| factorial_ne_zero _) ▸
Prime.emultiplicity_factorial hp.out hnb)
/-- **Legendre's Theorem**
Taking (`p - 1`) times the `p`-adic valuation of `n!` equals `n` minus the sum of base `p` digits
of `n`. -/
theorem sub_one_mul_padicValNat_factorial [hp : Fact p.Prime] (n : ℕ) :
(p - 1) * padicValNat p (n !) = n - (p.digits n).sum := by
rw [padicValNat_factorial <| lt_succ_of_lt <| lt.base (log p n)]
nth_rw 2 [← zero_add 1]
rw [Nat.succ_eq_add_one, ← Finset.sum_Ico_add' _ 0 _ 1,
Ico_zero_eq_range, ← sub_one_mul_sum_log_div_pow_eq_sub_sum_digits, Nat.succ_eq_add_one]
variable (p)
theorem sub_one_mul_padicValNat_factorial_lt_of_ne_zero [hp : Fact p.Prime] {n : ℕ} (hn : n ≠ 0) :
(p - 1) * padicValNat p n.factorial < n := by
rw [sub_one_mul_padicValNat_factorial n]
refine Nat.sub_lt_self ?_ (digit_sum_le p n)
have hnil : p.digits n ≠ [] := Nat.digits_ne_nil_iff_ne_zero.mpr hn
exact Nat.sum_pos_iff_exists_pos.mpr
⟨_, List.getLast_mem hnil, Nat.pos_of_ne_zero (Nat.getLast_digit_ne_zero p hn)⟩
theorem padicValNat_factorial_lt_of_ne_zero [hp : Fact p.Prime] {n : ℕ} (hn : n ≠ 0) :
padicValNat p n.factorial < n := by
apply lt_of_le_of_lt _ (sub_one_mul_padicValNat_factorial_lt_of_ne_zero p hn)
conv_lhs => rw [← one_mul (padicValNat p n !)]
gcongr
exact le_sub_one_of_lt (Nat.Prime.one_lt hp.elim)
theorem padicValNat_factorial_le [hp : Fact p.Prime] (n : ℕ) : padicValNat p n.factorial ≤ n := by
by_cases hn : n = 0
· simp [hn]
· exact le_of_lt (padicValNat_factorial_lt_of_ne_zero p hn)
variable {p}
/-- **Kummer's Theorem**
The `p`-adic valuation of `n.choose k` is the number of carries when `k` and `n - k` are added
in base `p`. This sum is expressed over the finset `Ico 1 b` where `b` is any bound greater than
`log p n`. -/
theorem padicValNat_choose {n k b : ℕ} [hp : Fact p.Prime] (hkn : k ≤ n) (hnb : log p n < b) :
padicValNat p (choose n k) = #{i ∈ Finset.Ico 1 b | p ^ i ≤ k % p ^ i + (n - k) % p ^ i} := by
exact_mod_cast (padicValNat_eq_emultiplicity (p := p) <| (choose_ne_zero hkn)) ▸
Prime.emultiplicity_choose hp.out hkn hnb
/-- **Kummer's Theorem**
The `p`-adic valuation of `(n + k).choose k` is the number of carries when `k` and `n` are added
in base `p`. This sum is expressed over the finset `Ico 1 b` where `b` is any bound greater than
`log p (n + k)`. -/
theorem padicValNat_choose' {n k b : ℕ} [hp : Fact p.Prime] (hnb : log p (n + k) < b) :
padicValNat p (choose (n + k) k) = #{i ∈ Finset.Ico 1 b | p ^ i ≤ k % p ^ i + n % p ^ i} := by
exact_mod_cast (padicValNat_eq_emultiplicity (p := p) <| choose_ne_zero <|
Nat.le_add_left k n)▸ Prime.emultiplicity_choose' hp.out hnb
/-- **Kummer's Theorem**
Taking (`p - 1`) times the `p`-adic valuation of the binomial `n + k` over `k` equals the sum of the
digits of `k` plus the sum of the digits of `n` minus the sum of digits of `n + k`, all base `p`.
-/
theorem sub_one_mul_padicValNat_choose_eq_sub_sum_digits' {k n : ℕ} [hp : Fact p.Prime] :
(p - 1) * padicValNat p (choose (n + k) k) =
(p.digits k).sum + (p.digits n).sum - (p.digits (n + k)).sum := by
have h : k ≤ n + k := by exact Nat.le_add_left k n
simp only [Nat.choose_eq_factorial_div_factorial h]
rw [padicValNat.div_of_dvd <| factorial_mul_factorial_dvd_factorial h, Nat.mul_sub_left_distrib,
padicValNat.mul (factorial_ne_zero _) (factorial_ne_zero _), Nat.mul_add]
simp only [sub_one_mul_padicValNat_factorial]
rw [← Nat.sub_add_comm <| digit_sum_le p k, Nat.add_sub_cancel n k, ← Nat.add_sub_assoc <|
digit_sum_le p n, Nat.sub_sub (k + n), ← Nat.sub_right_comm, Nat.sub_sub, sub_add_eq,
add_comm, tsub_tsub_assoc (Nat.le_refl (k + n)) <| (add_comm k n) ▸ (Nat.add_le_add
(digit_sum_le p n) (digit_sum_le p k)), Nat.sub_self (k + n), zero_add, add_comm]
/-- **Kummer's Theorem**
Taking (`p - 1`) times the `p`-adic valuation of the binomial `n` over `k` equals the sum of the
digits of `k` plus the sum of the digits of `n - k` minus the sum of digits of `n`, all base `p`.
-/
theorem sub_one_mul_padicValNat_choose_eq_sub_sum_digits {k n : ℕ} [hp : Fact p.Prime]
(h : k ≤ n) : (p - 1) * padicValNat p (choose n k) =
(p.digits k).sum + (p.digits (n - k)).sum - (p.digits n).sum := by
convert @sub_one_mul_padicValNat_choose_eq_sub_sum_digits' _ _ _ ‹_›
all_goals cutsat
end padicValNat
section padicValInt
variable {p : ℕ} [hp : Fact p.Prime]
theorem padicValInt_dvd_iff (n : ℕ) (a : ℤ) : (p : ℤ) ^ n ∣ a ↔ a = 0 ∨ n ≤ padicValInt p a := by
rw [padicValInt, ← Int.natAbs_eq_zero, ← padicValNat_dvd_iff, ← Int.natCast_dvd, Int.natCast_pow]
theorem padicValInt_dvd (a : ℤ) : (p : ℤ) ^ padicValInt p a ∣ a := by
rw [padicValInt_dvd_iff]
exact Or.inr le_rfl
theorem padicValInt_self : padicValInt p p = 1 :=
padicValInt.self hp.out.one_lt
theorem padicValInt.mul {a b : ℤ} (ha : a ≠ 0) (hb : b ≠ 0) :
padicValInt p (a * b) = padicValInt p a + padicValInt p b := by
simp_rw [padicValInt]
rw [Int.natAbs_mul, padicValNat.mul] <;> rwa [Int.natAbs_ne_zero]
theorem padicValInt_mul_eq_succ (a : ℤ) (ha : a ≠ 0) :
padicValInt p (a * p) = padicValInt p a + 1 := by
rw [padicValInt.mul ha (Int.natCast_ne_zero.mpr hp.out.ne_zero)]
simp only [padicValInt.of_nat, padicValNat_self]
end padicValInt |
.lake/packages/mathlib/Mathlib/NumberTheory/Padics/PadicVal/Defs.lean | import Mathlib.RingTheory.Multiplicity
import Mathlib.Data.Nat.Factors
/-!
# `p`-adic Valuation
This file defines the `p`-adic valuation on `ℕ`, `ℤ`, and `ℚ`.
The `p`-adic valuation on `ℚ` is the difference of the multiplicities of `p` in the numerator and
denominator of `q`. This function obeys the standard properties of a valuation, with the appropriate
assumptions on `p`. The `p`-adic valuations on `ℕ` and `ℤ` agree with that on `ℚ`.
The valuation induces a norm on `ℚ`. This norm is defined in padicNorm.lean.
-/
assert_not_exists Field
universe u
open Nat
variable {p : ℕ}
/-- For `p ≠ 1`, the `p`-adic valuation of a natural `n ≠ 0` is the largest natural number `k` such
that `p^k` divides `n`. If `n = 0` or `p = 1`, then `padicValNat p q` defaults to `0`. -/
def padicValNat (p : ℕ) (n : ℕ) : ℕ :=
if h : p ≠ 1 ∧ 0 < n then Nat.find (finiteMultiplicity_iff.2 h) else 0
theorem padicValNat_def' {n : ℕ} (hp : p ≠ 1) (hn : n ≠ 0) :
padicValNat p n = multiplicity p n := by
simp only [padicValNat, ne_eq, hp, not_false_eq_true, Nat.pos_iff_ne_zero.mpr hn, and_self,
↓reduceDIte, multiplicity, emultiplicity,
finiteMultiplicity_iff.mpr ⟨hp, Nat.pos_iff_ne_zero.mpr hn⟩]
convert (WithTop.untopD_coe ..).symm
/-- A simplification of `padicValNat` when one input is prime, by analogy with
`padicValRat_def`. -/
theorem padicValNat_def [hp : Fact p.Prime] {n : ℕ} (hn : n ≠ 0) :
padicValNat p n = multiplicity p n :=
padicValNat_def' hp.out.ne_one hn
/-- A simplification of `padicValNat` when one input is prime, by analogy with
`padicValRat_def`. -/
theorem padicValNat_eq_emultiplicity [hp : Fact p.Prime] {n : ℕ} (hn : n ≠ 0) :
padicValNat p n = emultiplicity p n := by
rw [(finiteMultiplicity_iff.2
⟨hp.out.ne_one, Nat.pos_iff_ne_zero.mpr hn⟩).emultiplicity_eq_multiplicity]
exact_mod_cast padicValNat_def hn
namespace padicValNat
open List
/-- `padicValNat p 0` is `0` for any `p`. -/
@[simp]
protected theorem zero : padicValNat p 0 = 0 := by simp [padicValNat]
/-- `padicValNat p 1` is `0` for any `p`. -/
@[simp]
protected theorem one : padicValNat p 1 = 0 := by simp [padicValNat]
@[simp]
theorem eq_zero_iff {n : ℕ} : padicValNat p n = 0 ↔ p = 1 ∨ n = 0 ∨ ¬p ∣ n := by
simp only [padicValNat, ne_eq, pos_iff_ne_zero, dite_eq_right_iff, find_eq_zero, zero_add,
pow_one, and_imp, ← or_iff_not_imp_left]
end padicValNat
open List
theorem le_emultiplicity_iff_replicate_subperm_primeFactorsList {a b : ℕ} {n : ℕ} (ha : a.Prime)
(hb : b ≠ 0) :
↑n ≤ emultiplicity a b ↔ replicate n a <+~ b.primeFactorsList :=
(replicate_subperm_primeFactorsList_iff ha hb).trans
pow_dvd_iff_le_emultiplicity |>.symm
theorem le_padicValNat_iff_replicate_subperm_primeFactorsList {a b : ℕ} {n : ℕ} (ha : a.Prime)
(hb : b ≠ 0) :
n ≤ padicValNat a b ↔ replicate n a <+~ b.primeFactorsList := by
rw [← le_emultiplicity_iff_replicate_subperm_primeFactorsList ha hb,
Nat.finiteMultiplicity_iff.2 ⟨ha.ne_one, Nat.pos_of_ne_zero hb⟩
|>.emultiplicity_eq_multiplicity, ← padicValNat_def' ha.ne_one hb,
Nat.cast_le] |
.lake/packages/mathlib/Mathlib/NumberTheory/ModularForms/CongruenceSubgroups.lean | import Mathlib.LinearAlgebra.Matrix.Integer
import Mathlib.NumberTheory.ModularForms.ArithmeticSubgroups
/-!
# Congruence subgroups
This defines congruence subgroups of `SL(2, ℤ)` such as `Γ(N)`, `Γ₀(N)` and `Γ₁(N)` for `N` a
natural number.
It also contains basic results about congruence subgroups.
-/
open Matrix.SpecialLinearGroup Matrix
open scoped MatrixGroups ModularGroup Real
variable (N : ℕ)
local notation "SLMOD(" N ")" =>
@Matrix.SpecialLinearGroup.map (Fin 2) _ _ _ _ _ _ (Int.castRingHom (ZMod N))
@[simp]
theorem SL_reduction_mod_hom_val (γ : SL(2, ℤ)) (i j : Fin 2) :
SLMOD(N) γ i j = (γ i j : ZMod N) :=
rfl
namespace CongruenceSubgroup
/-- The full level `N` congruence subgroup of `SL(2, ℤ)` of matrices that reduce to the identity
modulo `N`. -/
def Gamma : Subgroup SL(2, ℤ) :=
SLMOD(N).ker
@[inherit_doc] scoped notation "Γ(" n ")" => Gamma n
theorem Gamma_mem' {N} {γ : SL(2, ℤ)} : γ ∈ Gamma N ↔ SLMOD(N) γ = 1 :=
Iff.rfl
@[simp]
theorem Gamma_mem {N} {γ : SL(2, ℤ)} : γ ∈ Gamma N ↔ (γ 0 0 : ZMod N) = 1 ∧
(γ 0 1 : ZMod N) = 0 ∧ (γ 1 0 : ZMod N) = 0 ∧ (γ 1 1 : ZMod N) = 1 := by
rw [Gamma_mem']
constructor
· intro h
simp [← SL_reduction_mod_hom_val N γ, h]
· intro h
ext i j
rw [SL_reduction_mod_hom_val N γ]
fin_cases i <;> fin_cases j <;> simp only
exacts [h.1, h.2.1, h.2.2.1, h.2.2.2]
theorem Gamma_normal : Subgroup.Normal (Gamma N) :=
SLMOD(N).normal_ker
theorem Gamma_one_top : Gamma 1 = ⊤ := by
ext
simp [eq_iff_true_of_subsingleton]
lemma mem_Gamma_one (γ : SL(2, ℤ)) : γ ∈ Γ(1) := by
simp only [Gamma_one_top, Subgroup.mem_top]
theorem Gamma_zero_bot : Gamma 0 = ⊥ := rfl
lemma ModularGroup_T_pow_mem_Gamma (N M : ℤ) (hNM : N ∣ M) :
(ModularGroup.T ^ M) ∈ Gamma (Int.natAbs N) := by
simp only [Gamma_mem, Fin.isValue, ModularGroup.coe_T_zpow, of_apply, cons_val', cons_val_zero,
empty_val', cons_val_fin_one, Int.cast_one, cons_val_one,
Int.cast_zero, and_self, and_true, true_and]
refine Iff.mpr (ZMod.intCast_zmod_eq_zero_iff_dvd M (Int.natAbs N)) ?_
simp only [Int.natCast_natAbs, abs_dvd, hNM]
instance instFiniteIndexGamma [NeZero N] : (Gamma N).FiniteIndex := Subgroup.finiteIndex_ker _
/-- The congruence subgroup of `SL(2, ℤ)` of matrices whose lower left-hand entry reduces to zero
modulo `N`. -/
def Gamma0 : Subgroup SL(2, ℤ) where
carrier := { g | (g 1 0 : ZMod N) = 0 }
one_mem' := by simp
mul_mem' := by
intro a b ha hb
simp only [Set.mem_setOf_eq]
have h := (Matrix.two_mul_expl a.1 b.1).2.2.1
simp only [coe_mul, Set.mem_setOf_eq] at *
rw [h]
simp [ha, hb]
inv_mem' := by
intro a ha
simp only [Set.mem_setOf_eq]
rw [SL2_inv_expl a]
simp only [cons_val_zero, cons_val_one,
Int.cast_neg, neg_eq_zero, Set.mem_setOf_eq] at *
exact ha
@[simp]
theorem Gamma0_mem {N} {A : SL(2, ℤ)} : A ∈ Gamma0 N ↔ (A 1 0 : ZMod N) = 0 :=
Iff.rfl
/-- The group homomorphism from `CongruenceSubgroup.Gamma0` to `ZMod N` given by
mapping a matrix to its lower right-hand entry. -/
def Gamma0Map (N : ℕ) : Gamma0 N →* ZMod N where
toFun g := g.1 1 1
map_one' := by simp
map_mul' := by
rintro ⟨A, hA⟩ ⟨B, _⟩
simp only [MulMemClass.mk_mul_mk, Fin.isValue, coe_mul, (two_mul_expl A.1 B).2.2.2,
Int.cast_add, Int.cast_mul, Gamma0_mem.mp hA, zero_mul, zero_add]
/-- The congruence subgroup `Gamma1` (as a subgroup of `Gamma0`) of matrices whose bottom
row is congruent to `(0, 1)` modulo `N`. -/
def Gamma1' (N : ℕ) : Subgroup (Gamma0 N) :=
(Gamma0Map N).ker
@[simp]
theorem Gamma1_mem' {N} {γ : Gamma0 N} : γ ∈ Gamma1' N ↔ Gamma0Map N γ = 1 :=
Iff.rfl
theorem Gamma1_to_Gamma0_mem {N} (A : Gamma0 N) :
A ∈ Gamma1' N ↔
((A.1 0 0 : ℤ) : ZMod N) = 1 ∧ ((A.1 1 1 : ℤ) : ZMod N) = 1
∧ ((A.1 1 0 : ℤ) : ZMod N) = 0 := by
constructor
· intro ha
have adet : (A.1.1.det : ZMod N) = 1 := by simp only [A.1.property, Int.cast_one]
rw [Matrix.det_fin_two] at adet
simp only [Gamma1_mem', Gamma0Map, MonoidHom.coe_mk, OneHom.coe_mk, Int.cast_sub,
Int.cast_mul] at *
simpa only [Gamma1_mem', Gamma0Map, MonoidHom.coe_mk, OneHom.coe_mk, Int.cast_sub,
Int.cast_mul, ha, Gamma0_mem.mp A.property, and_self_iff, and_true, mul_one, mul_zero,
sub_zero] using adet
· intro ha
simp only [Gamma1_mem', Gamma0Map, MonoidHom.coe_mk]
exact ha.2.1
/-- The congruence subgroup `Gamma1` of `SL(2, ℤ)` consisting of matrices
whose bottom row is congruent to `(0,1)` modulo `N`. -/
def Gamma1 (N : ℕ) : Subgroup SL(2, ℤ) :=
Subgroup.map ((Gamma0 N).subtype.comp (Gamma1' N).subtype) ⊤
@[simp]
theorem Gamma1_mem (N : ℕ) (A : SL(2, ℤ)) : A ∈ Gamma1 N ↔
(A 0 0 : ZMod N) = 1 ∧ (A 1 1 : ZMod N) = 1 ∧ (A 1 0 : ZMod N) = 0 := by
constructor
· intro ha
simp_rw [Gamma1, Subgroup.mem_map] at ha
obtain ⟨⟨x, hx⟩, hxx⟩ := ha
rw [Gamma1_to_Gamma0_mem] at hx
simp only [Subgroup.mem_top, true_and] at hxx
rw [← hxx]
convert hx
· intro ha
simp_rw [Gamma1, Subgroup.mem_map]
have hA : A ∈ Gamma0 N := by simp [ha.right.right, Gamma0_mem]
have HA : (⟨A, hA⟩ : Gamma0 N) ∈ Gamma1' N := by
simp only [Gamma1_to_Gamma0_mem]
exact ha
refine ⟨(⟨(⟨A, hA⟩ : Gamma0 N), HA⟩ : (Gamma1' N : Subgroup (Gamma0 N))), ?_⟩
simp
theorem Gamma1_in_Gamma0 (N : ℕ) : Gamma1 N ≤ Gamma0 N := by
intro x HA
simp only [Gamma0_mem, Gamma1_mem] at *
exact HA.2.2
section CongruenceSubgroups
/-- A congruence subgroup is a subgroup of `SL(2, ℤ)` which contains some `Gamma N` for some
`N ≠ 0`. -/
def IsCongruenceSubgroup (Γ : Subgroup SL(2, ℤ)) : Prop :=
∃ N ≠ 0, Gamma N ≤ Γ
theorem isCongruenceSubgroup_trans (H K : Subgroup SL(2, ℤ)) (h : H ≤ K)
(h2 : IsCongruenceSubgroup H) : IsCongruenceSubgroup K := by
obtain ⟨N, hN⟩ := h2
exact ⟨N, hN.1, hN.2.trans h⟩
theorem Gamma_is_cong_sub (N : ℕ) [NeZero N] : IsCongruenceSubgroup (Gamma N) :=
⟨N, NeZero.ne _, le_rfl⟩
theorem Gamma1_is_congruence (N : ℕ) [NeZero N] : IsCongruenceSubgroup (Gamma1 N) := by
refine ⟨N, NeZero.ne _, fun A hA ↦ ?_⟩
simp_all [Gamma1_mem, Gamma_mem]
theorem Gamma0_is_congruence (N : ℕ) [NeZero N] : IsCongruenceSubgroup (Gamma0 N) :=
isCongruenceSubgroup_trans _ _ (Gamma1_in_Gamma0 N) (Gamma1_is_congruence N)
lemma IsCongruenceSubgroup.finiteIndex {Γ : Subgroup SL(2, ℤ)}
(h : IsCongruenceSubgroup Γ) : Γ.FiniteIndex := by
obtain ⟨N, hN⟩ := h
have : NeZero N := ⟨hN.1⟩
exact Subgroup.finiteIndex_of_le hN.2
instance instFiniteIndexGamma0 [NeZero N] : (Gamma0 N).FiniteIndex :=
(Gamma0_is_congruence N).finiteIndex
instance instFiniteIndexGamma1 [NeZero N] : (Gamma1 N).FiniteIndex :=
(Gamma1_is_congruence N).finiteIndex
end CongruenceSubgroups
section Conjugation
open Pointwise ConjAct
/-- The subgroup `SL(2, ℤ) ∩ g⁻¹ Γ g`, for `Γ` a subgroup of `SL(2, ℤ)` and `g ∈ GL(2, ℝ)`. -/
def conjGL (Γ : Subgroup SL(2, ℤ)) (g : GL (Fin 2) ℝ) : Subgroup SL(2, ℤ) :=
((toConjAct g⁻¹) • (Γ.map <| mapGL ℝ)).comap (mapGL ℝ)
@[simp] lemma mem_conjGL {Γ : Subgroup SL(2, ℤ)} {g : GL (Fin 2) ℝ} {x : SL(2, ℤ)} :
x ∈ conjGL Γ g ↔ ∃ y ∈ Γ, y = g * x * g⁻¹ := by
simp [conjGL, mapGL, Subgroup.mem_inv_pointwise_smul_iff, toConjAct_smul]
@[deprecated "use mem_conjGL" (since := "2025-08-16")]
lemma mem_conjGL' {Γ : Subgroup SL(2, ℤ)} {g : GL (Fin 2) ℝ} {x : SL(2, ℤ)} :
x ∈ conjGL Γ g ↔ ∃ y ∈ Γ, g⁻¹ * y * g = x := by
rw [mem_conjGL]
refine exists_congr fun y ↦ and_congr_right fun hy ↦ ?_
rw [eq_mul_inv_iff_mul_eq, mul_assoc, inv_mul_eq_iff_eq_mul]
@[simp]
lemma conjGL_coe (Γ : Subgroup SL(2, ℤ)) (g : SL(2, ℤ)) :
conjGL Γ g = (toConjAct g⁻¹) • Γ := by
ext x
simp_rw [mem_conjGL, ← map_inv, ← map_mul, toGL_injective.eq_iff, map_intCast_injective.eq_iff,
exists_eq_right, toConjAct_inv, Subgroup.mem_inv_pointwise_smul_iff, toConjAct_smul]
@[deprecated (since := "2025-05-15")] alias conjGLPos := conjGL
@[deprecated (since := "2025-05-15")] alias conjGLPos_coe := conjGL_coe
@[deprecated (since := "2025-05-15")] alias mem_conjGLPos := mem_conjGL
@[deprecated (since := "2025-05-15")] alias mem_conjGLPos' := mem_conjGL'
theorem Gamma_cong_eq_self (N : ℕ) (g : ConjAct SL(2, ℤ)) : g • Gamma N = Gamma N := by
apply Subgroup.Normal.conjAct (Gamma_normal N)
theorem conj_cong_is_cong (g : ConjAct SL(2, ℤ)) (Γ : Subgroup SL(2, ℤ))
(h : IsCongruenceSubgroup Γ) : IsCongruenceSubgroup (g • Γ) := by
obtain ⟨N, HN⟩ := h
refine ⟨N, ?_⟩
rw [← Gamma_cong_eq_self N g, Subgroup.pointwise_smul_le_pointwise_smul_iff]
exact HN
/-- For any `g ∈ GL(2, ℚ)` and `M ≠ 0`, there exists `N` such that `g x g⁻¹ ∈ Γ(M)` for all
`x ∈ Γ(N)`. -/
theorem exists_Gamma_le_conj (g : GL (Fin 2) ℚ) (M : ℕ) [NeZero M] :
∃ N ≠ 0, ∀ x ∈ Gamma N, g * (mapGL ℚ x) * g⁻¹ ∈ (Gamma M).map (mapGL ℚ) := by
-- Give names to the numerators and denominators of `g` and `g⁻¹`
let A₁ := g.1
let A₂ := (g⁻¹).1
have hA₁₂ : A₁ * A₂ = 1 := by simp only [← Matrix.GeneralLinearGroup.coe_mul,
mul_inv_cancel, Matrix.GeneralLinearGroup.coe_one, A₁, A₂]
let a₁ := A₁.den
let a₂ := A₂.den
-- we take `N = a₁ * a₂`
refine ⟨a₁ * a₂ * M, mul_ne_zero (mul_ne_zero A₁.den_ne_zero A₂.den_ne_zero) (NeZero.ne _),
fun ⟨y, hy⟩ hy' ↦ ?_⟩
-- Show that `y` is of the form `1 + (a₁ * a₂) • k` for some integer matrix `k`.
obtain ⟨k, hk⟩ : ∃ k, y = 1 + (a₁ * a₂ * M) • k := by
replace hy' : y.map (Int.cast : ℤ → ZMod (a₁ * a₂ * M)) = 1 := by
rw [CongruenceSubgroup.Gamma_mem', Subtype.ext_iff] at hy'
simpa using hy'
use Matrix.of fun i j ↦ (y - 1) i j / (a₁ * a₂ * M)
rw [← sub_eq_iff_eq_add']
ext i j
simp_rw [Matrix.smul_apply, Matrix.of_apply, nsmul_eq_mul, Nat.cast_mul]
refine (Int.mul_ediv_cancel_of_dvd ?_).symm
rw [← Matrix.map_one Int.cast (by simp) (by simp), ← sub_eq_zero,
← Matrix.map_sub _ (by simp)] at hy'
simpa only [Matrix.zero_apply, Matrix.map_apply, ZMod.intCast_zmod_eq_zero_iff_dvd,
Nat.cast_mul] using congr_fun₂ hy' i j
-- use this `k` to cook up a new integer matrix, which we will show comes from `SL(2, ℤ)`
let z := 1 + M • (A₁.num * k * A₂.num)
have hz_coe : z.map Int.cast = A₁ * (y.map Int.cast) * A₂ := by
simp only [Matrix.map_add _ Int.cast_add, Matrix.map_one _ Int.cast_zero Int.cast_one, hk,
mul_add, mul_one, add_mul, hA₁₂, add_right_inj, z]
conv_rhs => rw [← A₁.inv_denom_smul_num, ← A₂.inv_denom_smul_num, Matrix.map_smul _ _ (by simp)]
simp only [Matrix.smul_mul, Matrix.mul_smul, Matrix.map_smul (Int.cast : ℤ → ℚ) M (by simp),
Matrix.map_mul_intCast]
rw [← Nat.cast_smul_eq_nsmul ℚ (_ * M), ← MulAction.mul_smul, ← MulAction.mul_smul,
mul_comm a₁ a₂, Nat.cast_mul, Nat.cast_mul, mul_assoc _ _ (M : ℚ), mul_comm _ (M : ℚ),
inv_mul_cancel_left₀ (mod_cast A₂.den_ne_zero),
mul_inv_cancel_right₀ (mod_cast A₁.den_ne_zero), Nat.cast_smul_eq_nsmul]
have hz_det : z.det = 1 := by
have := congr_arg Matrix.det hz_coe
simp_rw [Matrix.det_mul, ← Int.cast_det] at this
rwa [mul_right_comm, ← Matrix.det_mul, hA₁₂, Matrix.det_one, one_mul, hy, Int.cast_inj] at this
refine ⟨⟨z, hz_det⟩, ?_, by simpa only [Subtype.ext_iff, Subgroup.coe_mul, Units.ext_iff,
Units.val_mul] using hz_coe⟩
rw [SetLike.mem_coe, CongruenceSubgroup.Gamma_mem', Subtype.ext_iff]
ext i j
simp_rw [map_apply_coe, z, map_add, map_one, RingHom.mapMatrix_apply, Int.coe_castRingHom,
add_apply, map_apply, coe_one, add_eq_left, Matrix.smul_apply, nsmul_eq_mul, Int.cast_mul,
Int.cast_natCast, ZMod.natCast_self M, zero_mul]
/-- For any `g ∈ GL(2, ℚ)` and `M ≠ 0`, there exists `N` such that `g Γ(N) g⁻¹ ≤ Γ(M)`. -/
theorem exists_Gamma_le_conj' (g : GL (Fin 2) ℚ) (M : ℕ) [NeZero M] :
∃ N ≠ 0, (toConjAct <| g.map (Rat.castHom ℝ)) • (Gamma N).map (mapGL ℝ)
≤ (Gamma M).map (mapGL ℝ) := by
obtain ⟨N, hN, h⟩ := exists_Gamma_le_conj g M
refine ⟨N, hN, fun y hy ↦ ?_⟩
simp_rw [Subgroup.mem_pointwise_smul_iff_inv_smul_mem, Subgroup.mem_map,
eq_inv_smul_iff] at hy
obtain ⟨x, hx, rfl⟩ := hy
obtain ⟨z, hz, hz'⟩ := h x hx
use z, hz
simpa only [Subtype.ext_iff, Units.ext_iff, map_mul] using
congr_arg (GeneralLinearGroup.map (Rat.castHom ℝ)) hz'
open Subgroup in
/-- If `Γ` has finite index in `SL(2, ℤ)`, then so does `g⁻¹ Γ g ∩ SL(2, ℤ)` for any
`g ∈ GL(2, ℚ)`. -/
lemma finiteIndex_conjGL (g : GL (Fin 2) ℚ) : (conjGL ⊤ (g.map <| Rat.castHom ℝ)).FiniteIndex := by
constructor
let t := (toConjAct <| g.map <| Rat.castHom ℝ)⁻¹
suffices (t • 𝒮ℒ ⊓ 𝒮ℒ).relIndex 𝒮ℒ ≠ 0 by
rwa [conjGL, index_comap, ← inf_relIndex_right, ← MonoidHom.range_eq_map]
obtain ⟨N, hN, hN'⟩ := exists_Gamma_le_conj' g 1
rw [Gamma_one_top, ← MonoidHom.range_eq_map] at hN'
suffices Γ(N) ≤ (t • 𝒮ℒ ⊓ 𝒮ℒ).comap (mapGL ℝ) by
haveI _ : NeZero N := ⟨hN⟩
simpa only [index_comap] using (finiteIndex_of_le this).index_ne_zero
intro k hk
simpa [mem_pointwise_smul_iff_inv_smul_mem] using
hN' <| smul_mem_pointwise_smul _ _ _ ⟨k, hk, rfl⟩
/-- Conjugates of `SL(2, ℤ)` by `GL(2, ℚ)` are arithmetic subgroups. -/
lemma isArithmetic_conj_SL2Z (g : GL (Fin 2) ℚ) :
(toConjAct (g.map (Rat.castHom ℝ)) • 𝒮ℒ).IsArithmetic := by
constructor
rw [MonoidHom.range_eq_map]
constructor
· rw [← Subgroup.relIndex_comap, Subgroup.relIndex_top_right]
exact (finiteIndex_conjGL g⁻¹).index_ne_zero
· rw [← Subgroup.relIndex_pointwise_smul (toConjAct (g.map (Rat.castHom ℝ)))⁻¹,
inv_smul_smul, ← Subgroup.relIndex_comap, Subgroup.relIndex_top_right]
exact (finiteIndex_conjGL g).index_ne_zero
/-- Conjugation by `GL(2, ℚ)` preserves arithmetic subgroups. -/
lemma _root_.Subgroup.IsArithmetic.conj (𝒢 : Subgroup (GL (Fin 2) ℝ)) [𝒢.IsArithmetic]
(g : GL (Fin 2) ℚ) :
(toConjAct (g.map (Rat.castHom ℝ)) • 𝒢).IsArithmetic :=
⟨(Subgroup.IsArithmetic.is_commensurable.conj _).trans
(isArithmetic_conj_SL2Z g).is_commensurable⟩
@[deprecated (since := "2025-09-17")] alias IsArithmetic.conj := _root_.Subgroup.IsArithmetic.conj
/-- If `Γ` is a congruence subgroup, then so is `g⁻¹ Γ g ∩ SL(2, ℤ)` for any `g ∈ GL(2, ℚ)`. -/
lemma IsCongruenceSubgroup.conjGL {Γ : Subgroup SL(2, ℤ)} (hΓ : IsCongruenceSubgroup Γ)
(g : GL (Fin 2) ℚ) :
IsCongruenceSubgroup (conjGL Γ (g.map <| Rat.castHom ℝ)) := by
obtain ⟨M, hN, hΓM⟩ := hΓ
haveI _ : NeZero M := ⟨hN⟩
obtain ⟨N, hN, hN'⟩ := exists_Gamma_le_conj' g M
rw [Subgroup.pointwise_smul_subset_iff] at hN'
refine ⟨N, ‹_›, fun x hx ↦ ?_⟩
obtain ⟨y, hy, hy'⟩ := Subgroup.mem_inv_pointwise_smul_iff.mp <| hN' ⟨x, hx, rfl⟩
exact mem_conjGL.mpr ⟨y, hΓM hy, hy'⟩
end Conjugation
end CongruenceSubgroup |
.lake/packages/mathlib/Mathlib/NumberTheory/ModularForms/SlashInvariantForms.lean | import Mathlib.NumberTheory.ModularForms.ArithmeticSubgroups
import Mathlib.NumberTheory.ModularForms.SlashActions
/-!
# Slash invariant forms
This file defines functions that are invariant under a `SlashAction` which forms the basis for
defining `ModularForm` and `CuspForm`. We prove several instances for such spaces, in particular
that they form a module over `ℝ`, and over `ℂ` if the group is contained in `SL(2, ℝ)`.
-/
open Complex UpperHalfPlane ModularForm
open scoped MatrixGroups
noncomputable section
section SlashInvariantForms
open ModularForm
variable (F : Type*) (Γ : outParam <| Subgroup (GL (Fin 2) ℝ)) (k : outParam ℤ)
/-- Functions `ℍ → ℂ` that are invariant under the `SlashAction`. -/
structure SlashInvariantForm where
/-- The underlying function `ℍ → ℂ`.
Do NOT use directly. Use the coercion instead. -/
toFun : ℍ → ℂ
slash_action_eq' : ∀ γ ∈ Γ, toFun ∣[k] γ = toFun
/-- `SlashInvariantFormClass F Γ k` asserts `F` is a type of bundled functions that are invariant
under the `SlashAction`. -/
class SlashInvariantFormClass [FunLike F ℍ ℂ] : Prop where
slash_action_eq : ∀ (f : F), ∀ γ ∈ Γ, (f : ℍ → ℂ) ∣[k] γ = f
instance (priority := 100) SlashInvariantForm.funLike :
FunLike (SlashInvariantForm Γ k) ℍ ℂ where
coe := SlashInvariantForm.toFun
coe_injective' f g h := by cases f; cases g; congr
instance (priority := 100) SlashInvariantFormClass.slashInvariantForm :
SlashInvariantFormClass (SlashInvariantForm Γ k) Γ k where
slash_action_eq := SlashInvariantForm.slash_action_eq'
variable {F Γ k}
@[simp]
theorem SlashInvariantForm.toFun_eq_coe {f : SlashInvariantForm Γ k} : f.toFun = (f : ℍ → ℂ) :=
rfl
@[simp]
theorem SlashInvariantForm.coe_mk (f : ℍ → ℂ) (hf : ∀ γ ∈ Γ, f ∣[k] γ = f) : ⇑(mk f hf) = f := rfl
@[ext]
theorem SlashInvariantForm.ext {f g : SlashInvariantForm Γ k} (h : ∀ x, f x = g x) : f = g :=
DFunLike.ext f g h
/-- Copy of a `SlashInvariantForm` with a new `toFun` equal to the old one.
Useful to fix definitional equalities. -/
protected def SlashInvariantForm.copy (f : SlashInvariantForm Γ k) (f' : ℍ → ℂ) (h : f' = ⇑f) :
SlashInvariantForm Γ k where
toFun := f'
slash_action_eq' := h.symm ▸ f.slash_action_eq'
end SlashInvariantForms
namespace SlashInvariantForm
variable {F : Type*} {Γ : Subgroup <| GL (Fin 2) ℝ} {k : ℤ} [FunLike F ℍ ℂ]
theorem slash_action_eqn [SlashInvariantFormClass F Γ k] (f : F) (γ) (hγ : γ ∈ Γ) :
↑f ∣[k] γ = ⇑f :=
SlashInvariantFormClass.slash_action_eq f γ hγ
theorem slash_action_eqn' {k : ℤ} [Γ.HasDetOne] [SlashInvariantFormClass F Γ k]
(f : F) {γ} (hγ : γ ∈ Γ) (z : ℍ) :
f (γ • z) = (γ 1 0 * z + γ 1 1) ^ k * f z := by
have : f (γ • z) = f z * denom γ z ^ k := by
simpa [slash_def, σ, mul_inv_eq_iff_eq_mul₀ (zpow_ne_zero _ (denom_ne_zero _ _)),
Subgroup.HasDetOne.det_eq hγ] using congr_fun (slash_action_eqn f γ hγ) z
rw [this, denom, mul_comm]
/-- Every `SlashInvariantForm` `f` satisfies ` f (γ • z) = (denom γ z) ^ k * f z`. -/
theorem slash_action_eqn'' {k : ℤ} [Γ.HasDetOne] [SlashInvariantFormClass F Γ k]
(f : F) {γ} (hγ : γ ∈ Γ) (z : ℍ) :
f (γ • z) = (denom γ z) ^ k * f z :=
SlashInvariantForm.slash_action_eqn' f hγ z
/-- Every `SlashInvariantForm` `f` satisfies ` f (γ • z) = (denom γ z) ^ k * f z`. -/
theorem slash_action_eqn_SL'' {k : ℤ} {Γ : Subgroup SL(2, ℤ)} [SlashInvariantFormClass F Γ k]
(f : F) {γ} (hγ : γ ∈ Γ) (z : ℍ) :
f (γ • z) = (denom γ z) ^ k * f z :=
SlashInvariantForm.slash_action_eqn' f (by simpa using hγ) z
instance [SlashInvariantFormClass F Γ k] : CoeTC F (SlashInvariantForm Γ k) :=
⟨fun f ↦ { slash_action_eq' := slash_action_eqn f, .. }⟩
instance instAdd : Add (SlashInvariantForm Γ k) :=
⟨fun f g ↦
{ toFun := f + g
slash_action_eq' := fun γ hγ ↦ by
rw [SlashAction.add_slash, slash_action_eqn f γ hγ, slash_action_eqn g γ hγ] }⟩
@[simp]
theorem coe_add (f g : SlashInvariantForm Γ k) : ⇑(f + g) = f + g :=
rfl
@[simp]
theorem add_apply (f g : SlashInvariantForm Γ k) (z : ℍ) : (f + g) z = f z + g z :=
rfl
instance instZero : Zero (SlashInvariantForm Γ k) :=
⟨{toFun := 0
slash_action_eq' := fun _ _ ↦ SlashAction.zero_slash _ _}⟩
@[simp]
theorem coe_zero : ⇑(0 : SlashInvariantForm Γ k) = (0 : ℍ → ℂ) :=
rfl
section smul
variable [Γ.HasDetOne] {α : Type*} [SMul α ℂ] [IsScalarTower α ℂ ℂ]
/-- Scalar multiplication by `ℂ`, assuming that `Γ ⊆ SL(2, ℝ)`. -/
instance instSMul : SMul α (SlashInvariantForm Γ k) where
smul c f :=
{ toFun := c • ↑f
slash_action_eq' γ hγ := by
rw [← smul_one_smul ℂ]
simp [-smul_assoc, smul_slash, slash_action_eqn _ _ hγ, σ, Subgroup.HasDetOne.det_eq hγ] }
@[simp]
theorem coe_smul (f : SlashInvariantForm Γ k) (n : α) : ⇑(n • f) = n • ⇑f :=
rfl
@[simp]
theorem smul_apply (f : SlashInvariantForm Γ k) (n : α) (z : ℍ) : (n • f) z = n • f z :=
rfl
end smul
section smulℝ
variable {α : Type*} [SMul α ℂ] [SMul α ℝ] [IsScalarTower α ℝ ℂ]
/-- Scalar multiplication by `ℝ`, valid without restrictions on the determinant. -/
instance instSMulℝ : SMul α (SlashInvariantForm Γ k) where
smul c f :=
{ toFun := c • ↑f
slash_action_eq' γ hγ := by
rw [← smul_one_smul ℝ, ← smul_one_smul ℂ, smul_slash,
Complex.real_smul, mul_one, σ_ofReal, slash_action_eqn _ _ hγ] }
@[simp]
theorem coe_smulℝ (f : SlashInvariantForm Γ k) (n : α) : ⇑(n • f) = n • ⇑f :=
rfl
@[simp]
theorem smul_applyℝ (f : SlashInvariantForm Γ k) (n : α) (z : ℍ) :
(n • f) z = n • f z :=
rfl
end smulℝ
instance instNeg : Neg (SlashInvariantForm Γ k) :=
⟨fun f =>
{ toFun := -f
slash_action_eq' := fun γ hγ => by rw [SlashAction.neg_slash, slash_action_eqn f γ hγ] }⟩
@[simp]
theorem coe_neg (f : SlashInvariantForm Γ k) : ⇑(-f) = -f :=
rfl
@[simp]
theorem neg_apply (f : SlashInvariantForm Γ k) (z : ℍ) : (-f) z = -f z :=
rfl
instance instSub : Sub (SlashInvariantForm Γ k) :=
⟨fun f g => f + -g⟩
@[simp]
theorem coe_sub (f g : SlashInvariantForm Γ k) : ⇑(f - g) = f - g :=
rfl
@[simp]
theorem sub_apply (f g : SlashInvariantForm Γ k) (z : ℍ) : (f - g) z = f z - g z :=
rfl
instance : AddCommGroup (SlashInvariantForm Γ k) :=
DFunLike.coe_injective.addCommGroup _ rfl coe_add coe_neg coe_sub coe_smulℝ coe_smulℝ
/-- Additive coercion from `SlashInvariantForm` to `ℍ → ℂ`. -/
def coeHom : SlashInvariantForm Γ k →+ ℍ → ℂ where
toFun f := f
map_zero' := rfl
map_add' _ _ := rfl
theorem coeHom_injective : Function.Injective (@coeHom Γ k) :=
DFunLike.coe_injective
instance instModuleComplex [Γ.HasDetOne] {α : Type*} [Semiring α] [Module α ℂ]
[IsScalarTower α ℂ ℂ] : Module α (SlashInvariantForm Γ k) :=
coeHom_injective.module α _ (fun _ _ ↦ rfl)
instance instModuleReal {α : Type*} [Semiring α] [Module α ℝ] [Module α ℂ] [IsScalarTower α ℝ ℂ] :
Module α (SlashInvariantForm Γ k) :=
coeHom_injective.module α _ (fun _ _ ↦ rfl)
/-- The `SlashInvariantForm` corresponding to `Function.const _ x`. -/
@[simps -fullyApplied]
def const [Γ.HasDetOne] (x : ℂ) : SlashInvariantForm Γ 0 where
toFun := Function.const _ x
slash_action_eq' g hg := by ext; simp [slash_def, σ, Subgroup.HasDetOne.det_eq hg]
/-- The `SlashInvariantForm` corresponding to `Function.const _ x`. -/
@[simps -fullyApplied]
def constℝ [Γ.HasDetPlusMinusOne] (x : ℝ) : SlashInvariantForm Γ 0 where
toFun := Function.const _ x
slash_action_eq' g hg := funext fun τ ↦ by simp [slash_apply,
Subgroup.HasDetPlusMinusOne.abs_det hg, -Matrix.GeneralLinearGroup.val_det_apply]
instance [Γ.HasDetPlusMinusOne] : One (SlashInvariantForm Γ 0) where
one := { constℝ 1 with toFun := 1 }
@[simp]
theorem one_coe_eq_one [Γ.HasDetPlusMinusOne] : ((1 : SlashInvariantForm Γ 0) : ℍ → ℂ) = 1 :=
rfl
instance : Inhabited (SlashInvariantForm Γ k) :=
⟨0⟩
/-- The slash invariant form of weight `k₁ + k₂` given by the product of two slash-invariant forms
of weights `k₁` and `k₂`. -/
def mul [Γ.HasDetPlusMinusOne] {k₁ k₂ : ℤ} (f : SlashInvariantForm Γ k₁)
(g : SlashInvariantForm Γ k₂) : SlashInvariantForm Γ (k₁ + k₂) where
toFun := f * g
slash_action_eq' A hA := by simp [mul_slash, Subgroup.HasDetPlusMinusOne.abs_det hA,
-Matrix.GeneralLinearGroup.val_det_apply, slash_action_eqn f A hA, slash_action_eqn g A hA]
@[simp]
theorem coe_mul [Γ.HasDetPlusMinusOne] {k₁ k₂ : ℤ} (f : SlashInvariantForm Γ k₁)
(g : SlashInvariantForm Γ k₂) : ⇑(f.mul g) = ⇑f * ⇑g :=
rfl
instance [Γ.HasDetPlusMinusOne] : NatCast (SlashInvariantForm Γ 0) where
natCast n := constℝ n
@[simp, norm_cast]
theorem coe_natCast [Γ.HasDetPlusMinusOne] (n : ℕ) : ⇑(n : SlashInvariantForm Γ 0) = n := rfl
instance [Γ.HasDetPlusMinusOne] : IntCast (SlashInvariantForm Γ 0) where
intCast z := constℝ z
@[simp, norm_cast]
theorem coe_intCast [Γ.HasDetPlusMinusOne] (z : ℤ) : ⇑(z : SlashInvariantForm Γ 0) = z := rfl
open ConjAct Pointwise in
/-- Translating a `SlashInvariantForm` by `g : GL (Fin 2) ℝ`, to obtain a new
`SlashInvariantForm` of level `g⁻¹ Γ g`. -/
noncomputable def translate [SlashInvariantFormClass F Γ k] (f : F) (g : GL (Fin 2) ℝ) :
SlashInvariantForm (toConjAct g⁻¹ • Γ) k where
toFun := f ∣[k] g
slash_action_eq' j hj := by
rw [map_inv, Γ.mem_inv_pointwise_smul_iff, toConjAct_smul] at hj
simpa [← SlashAction.slash_mul] using congr_arg (· ∣[k] g) (slash_action_eqn f _ hj)
@[simp]
lemma coe_translate [SlashInvariantFormClass F Γ k] (f : F) (g : GL (Fin 2) ℝ) :
translate f g = ⇑f ∣[k] g :=
rfl
@[deprecated (since := "2025-08-15")] alias translateGL := translate
@[deprecated (since := "2025-08-15")] alias coe_translateGL := coe_translate
@[deprecated (since := "2025-05-15")] alias translateGLPos := translate
@[deprecated (since := "2025-05-15")] alias coe_translateGLPos := coe_translate
end SlashInvariantForm |
.lake/packages/mathlib/Mathlib/NumberTheory/ModularForms/ArithmeticSubgroups.lean | import Mathlib.Topology.Algebra.IsUniformGroup.DiscreteSubgroup
import Mathlib.Topology.Algebra.Ring.Real
import Mathlib.Topology.Instances.Matrix
import Mathlib.Topology.MetricSpace.Isometry
/-!
# Arithmetic subgroups of `GL(2, ℝ)`
We define a subgroup of `GL (Fin 2) ℝ` to be *arithmetic* if it is commensurable with the image
of `SL(2, ℤ)`.
-/
open Matrix Matrix.SpecialLinearGroup
open scoped MatrixGroups
local notation "SL" => SpecialLinearGroup
variable {n : Type*} [Fintype n] [DecidableEq n]
namespace Subgroup
section det_typeclasses
variable {R : Type*} [CommRing R] (Γ : Subgroup (GL n R))
/-- Typeclass saying that a subgroup of `GL(2, ℝ)` has determinant contained in `{±1}`. Necessary
so that the typeclass system can detect when the slash action is multiplicative. -/
class HasDetPlusMinusOne : Prop where
det_eq {g} (hg : g ∈ Γ) : g.det = 1 ∨ g.det = -1
variable {Γ} in
lemma HasDetPlusMinusOne.abs_det [LinearOrder R] [IsOrderedRing R] [HasDetPlusMinusOne Γ]
{g} (hg : g ∈ Γ) : |g.det.val| = 1 := by
rcases HasDetPlusMinusOne.det_eq hg with h | h <;> simp [h]
/-- Typeclass saying that a subgroup of `GL(n, R)` is contained in `SL(n, R)`. Necessary so that
the typeclass system can detect when the slash action is `ℂ`-linear. -/
class HasDetOne : Prop where
det_eq {g} (hg : g ∈ Γ) : g.det = 1
instance (Γ : Subgroup (SL n R)) : HasDetOne (Γ.map toGL) where
det_eq {g} hg := by rcases hg with ⟨g, hg, rfl⟩; simp
instance {S : Type*} [CommRing S] [Algebra S R] (Γ : Subgroup (SL n S)) :
HasDetOne (Γ.map <| mapGL R) where
det_eq {g} hg := by rcases hg with ⟨g, hg, rfl⟩; simp
instance [HasDetOne Γ] : HasDetPlusMinusOne Γ := ⟨fun {g} hg ↦ by simp [HasDetOne.det_eq hg]⟩
end det_typeclasses
section SL2Z_in_GL2R
/-- The image of the modular group `SL(2, ℤ)`, as a subgroup of `GL(2, ℝ)`. -/
scoped[MatrixGroups] notation "𝒮ℒ" => MonoidHom.range (mapGL ℝ : SL(2, ℤ) →* GL (Fin 2) ℝ)
/-- Coercion from subgroups of `SL(2, ℤ)` to subgroups of `GL(2, ℝ)` by mapping along the obvious
inclusion homomorphism. -/
instance : Coe (Subgroup SL(2, ℤ)) (Subgroup (GL (Fin 2) ℝ)) where
coe := map (mapGL ℝ)
/-- A subgroup of `GL(2, ℝ)` is arithmetic if it is commensurable with the image of `SL(2, ℤ)`. -/
class IsArithmetic (𝒢 : Subgroup (GL (Fin 2) ℝ)) : Prop where
is_commensurable : Commensurable 𝒢 𝒮ℒ
/-- The image of `SL(2, ℤ)` in `GL(2, ℝ)` is arithmetic. -/
instance : IsArithmetic 𝒮ℒ where is_commensurable := .refl 𝒮ℒ
lemma isArithmetic_iff_finiteIndex {Γ : Subgroup SL(2, ℤ)} : IsArithmetic Γ ↔ Γ.FiniteIndex := by
constructor <;>
· refine fun ⟨h⟩ ↦ ⟨?_⟩
simpa [Commensurable, MonoidHom.range_eq_map, ← relIndex_comap,
comap_map_eq_self_of_injective mapGL_injective] using h
/-- Images in `GL(2, ℝ)` of finite-index subgroups of `SL(2, ℤ)` are arithmetic. -/
instance (Γ : Subgroup SL(2, ℤ)) [Γ.FiniteIndex] : IsArithmetic Γ :=
isArithmetic_iff_finiteIndex.mpr ‹_›
/-- If `Γ` is arithmetic, its preimage in `SL(2, ℤ)` has finite index. -/
instance IsArithmetic.finiteIndex_comap (𝒢 : Subgroup (GL (Fin 2) ℝ)) [IsArithmetic 𝒢] :
(𝒢.comap (mapGL (R := ℤ) ℝ)).FiniteIndex :=
⟨𝒢.index_comap (mapGL (R := ℤ) ℝ) ▸ IsArithmetic.is_commensurable.1⟩
instance {Γ : Subgroup (GL (Fin 2) ℝ)} [h : Γ.IsArithmetic] : HasDetPlusMinusOne Γ := by
refine ⟨fun {g} hg ↦ ?_⟩
suffices |g.det.val| = 1 by rcases abs_cases g.det.val <;> aesop
obtain ⟨n, hn, _, hgn⟩ := Subgroup.exists_pow_mem_of_relIndex_ne_zero
Subgroup.IsArithmetic.is_commensurable.2 hg
suffices |(g.det ^ n).val| = 1 by simpa [← abs_pow, abs_pow_eq_one _ (Nat.ne_zero_of_lt hn)]
obtain ⟨t, ht⟩ := hgn.1
have := congr_arg Matrix.GeneralLinearGroup.det ht.symm
rw [Matrix.SpecialLinearGroup.det_mapGL, map_pow] at this
simp [this]
end SL2Z_in_GL2R
end Subgroup
namespace Matrix.SpecialLinearGroup
instance discreteSpecialLinearGroupIntRange : DiscreteTopology (mapGL (n := n) (R := ℤ) ℝ).range :=
(isEmbedding_mapGL (Isometry.isEmbedding fun _ _ ↦ rfl)).toHomeomorph.discreteTopology
lemma isClosedEmbedding_mapGLInt : Topology.IsClosedEmbedding (mapGL ℝ : SL n ℤ → GL n ℝ) :=
⟨isEmbedding_mapGL (Isometry.isEmbedding fun _ _ ↦ rfl), (mapGL ℝ).range.isClosed_of_discrete⟩
end Matrix.SpecialLinearGroup
/-- Arithmetic subgroups of `GL(2, ℝ)` are discrete. -/
instance Subgroup.IsArithmetic.discreteTopology {𝒢 : Subgroup (GL (Fin 2) ℝ)} [IsArithmetic 𝒢] :
DiscreteTopology 𝒢 := by
rw [is_commensurable.discreteTopology_iff]
infer_instance |
.lake/packages/mathlib/Mathlib/NumberTheory/ModularForms/Basic.lean | import Mathlib.Algebra.DirectSum.Algebra
import Mathlib.Analysis.Calculus.FDeriv.Star
import Mathlib.Analysis.Complex.UpperHalfPlane.Manifold
import Mathlib.Geometry.Manifold.MFDeriv.SpecificFunctions
import Mathlib.NumberTheory.ModularForms.BoundedAtCusp
import Mathlib.NumberTheory.ModularForms.SlashInvariantForms
/-!
# Modular forms
This file defines modular forms and proves some basic properties about them. Including constructing
the graded ring of modular forms.
We begin by defining modular forms and cusp forms as extension of `SlashInvariantForm`s then we
define the space of modular forms, cusp forms and prove that the product of two modular forms is a
modular form.
-/
open Complex UpperHalfPlane Matrix.SpecialLinearGroup
open scoped Topology Manifold MatrixGroups ComplexConjugate
noncomputable section
namespace UpperHalfPlane
/-- The matrix `[-1, 0; 0, 1]`, which defines an anti-holomorphic involution of `ℍ` via
`τ ↦ -conj τ`. -/
def J : GL (Fin 2) ℝ := .mkOfDetNeZero !![-1, 0; 0, 1] (by simp)
lemma coe_J_smul (τ : ℍ) : (↑(J • τ) : ℂ) = -conj ↑τ := by
simp [UpperHalfPlane.coe_smul, σ, J, show ¬(1 : ℝ) < 0 by simp, num, denom]
lemma J_smul (τ : ℍ) : J • τ = ofComplex (-(conj ↑τ)) := by
ext
rw [coe_J_smul, ofComplex_apply_of_im_pos (by simpa using τ.im_pos), coe_mk_subtype]
@[simp] lemma val_J : J.val = !![-1, 0; 0, 1] := rfl
@[simp] lemma J_sq : J ^ 2 = 1 := by ext; simp [J, sq, Matrix.one_fin_two]
@[simp] lemma det_J : J.det = -1 := by ext; simp [J]
@[simp] lemma sigma_J : σ J = starRingEnd ℂ := by simp [σ, J]
@[simp] lemma denom_J (τ : ℍ) : denom J τ = 1 := by simp [J, denom]
end UpperHalfPlane
section ModularForm
open ModularForm
/-- The weight `k` slash action of `GL(2, ℝ)⁺` preserves holomorphic functions. This is private,
since it is a step towards the proof of `MDifferentiable.slash` which is more general. -/
private lemma MDifferentiable.slash_of_pos {f : ℍ → ℂ} (hf : MDifferentiable 𝓘(ℂ) 𝓘(ℂ) f)
(k : ℤ) {g : GL (Fin 2) ℝ} (hg : 0 < g.det.val) :
MDifferentiable 𝓘(ℂ) 𝓘(ℂ) (f ∣[k] g) := by
refine .mul (.mul ?_ mdifferentiable_const) (mdifferentiable_denom_zpow g _)
simpa only [σ, hg, ↓reduceIte] using hf.comp (mdifferentiable_smul hg)
private lemma slash_J (f : ℍ → ℂ) (k : ℤ) :
f ∣[k] J = fun τ : ℍ ↦ conj (f <| ofComplex <| -(conj ↑τ)) := by
simp [slash_def, J_smul]
/-- The weight `k` slash action of the negative-determinant matrix `J` preserves holomorphic
functions. -/
private lemma MDifferentiable.slashJ {f : ℍ → ℂ} (hf : MDifferentiable 𝓘(ℂ) 𝓘(ℂ) f) (k : ℤ) :
MDifferentiable 𝓘(ℂ) 𝓘(ℂ) (f ∣[k] J) := by
simp only [mdifferentiable_iff, slash_J, Function.comp_def] at hf ⊢
have : {z | 0 < z.im}.EqOn (fun x ↦ conj (f <| ofComplex <| -conj ↑(ofComplex x)))
(fun x ↦ conj (f <| ofComplex <| -conj x)) := fun z h ↦ by simp [ofComplex_apply_of_im_pos h]
refine .congr (fun z hz ↦ DifferentiableAt.differentiableWithinAt ?_) this
have : 0 < (-conj z).im := by simpa using hz
have := hf.differentiableAt (isOpen_upperHalfPlaneSet.mem_nhds this)
simpa using (this.comp _ differentiable_neg.differentiableAt).star_star.neg
/-- The weight `k` slash action of `GL(2, ℝ)` preserves holomorphic functions. -/
lemma MDifferentiable.slash {f : ℍ → ℂ} (hf : MDifferentiable 𝓘(ℂ) 𝓘(ℂ) f)
(k : ℤ) (g : GL (Fin 2) ℝ) : MDifferentiable 𝓘(ℂ) 𝓘(ℂ) (f ∣[k] g) := by
refine g.det_ne_zero.lt_or_gt.elim (fun hg ↦ ?_) (hf.slash_of_pos k)
rw [show g = J * (J * g) by simp [← mul_assoc, ← sq], SlashAction.slash_mul]
exact (hf.slashJ k).slash_of_pos _ (by simpa using hg)
variable (F : Type*) (Γ : Subgroup (GL (Fin 2) ℝ)) (k : ℤ)
open scoped ModularForm
/-- These are `SlashInvariantForm`'s that are holomorphic and bounded at infinity. -/
structure ModularForm extends SlashInvariantForm Γ k where
holo' : MDifferentiable 𝓘(ℂ) 𝓘(ℂ) (toSlashInvariantForm : ℍ → ℂ)
bdd_at_cusps' {c : OnePoint ℝ} (hc : IsCusp c Γ) : c.IsBoundedAt toFun k
/-- The `SlashInvariantForm` associated to a `ModularForm`. -/
add_decl_doc ModularForm.toSlashInvariantForm
/-- These are `SlashInvariantForm`s that are holomorphic and zero at infinity. -/
structure CuspForm extends SlashInvariantForm Γ k where
holo' : MDifferentiable 𝓘(ℂ) 𝓘(ℂ) (toSlashInvariantForm : ℍ → ℂ)
zero_at_cusps' {c : OnePoint ℝ} (hc : IsCusp c Γ) : c.IsZeroAt toFun k
/-- The `SlashInvariantForm` associated to a `CuspForm`. -/
add_decl_doc CuspForm.toSlashInvariantForm
/-- `ModularFormClass F Γ k` says that `F` is a type of bundled functions that extend
`SlashInvariantFormClass` by requiring that the functions be holomorphic and bounded
at all cusps. -/
class ModularFormClass (F : Type*) (Γ : outParam <| Subgroup (GL (Fin 2) ℝ)) (k : outParam ℤ)
[FunLike F ℍ ℂ] : Prop extends SlashInvariantFormClass F Γ k where
holo : ∀ f : F, MDifferentiable 𝓘(ℂ) 𝓘(ℂ) (f : ℍ → ℂ)
bdd_at_cusps (f : F) {c : OnePoint ℝ} (hc : IsCusp c Γ) : c.IsBoundedAt f k
/-- `CuspFormClass F Γ k` says that `F` is a type of bundled functions that extend
`SlashInvariantFormClass` by requiring that the functions be holomorphic and zero
at all cusps. -/
class CuspFormClass (F : Type*) (Γ : outParam <| Subgroup (GL (Fin 2) ℝ)) (k : outParam ℤ)
[FunLike F ℍ ℂ] : Prop extends SlashInvariantFormClass F Γ k where
holo : ∀ f : F, MDifferentiable 𝓘(ℂ) 𝓘(ℂ) (f : ℍ → ℂ)
zero_at_cusps (f : F) {c : OnePoint ℝ} (hc : IsCusp c Γ) : c.IsZeroAt f k
instance (priority := 100) ModularForm.funLike :
FunLike (ModularForm Γ k) ℍ ℂ where
coe f := f.toFun
coe_injective' f g h := by cases f; cases g; congr; exact DFunLike.ext' h
instance (priority := 100) ModularFormClass.modularForm :
ModularFormClass (ModularForm Γ k) Γ k where
slash_action_eq f := f.slash_action_eq'
holo := ModularForm.holo'
bdd_at_cusps := ModularForm.bdd_at_cusps'
@[fun_prop]
lemma ModularFormClass.continuous {k : ℤ} {Γ : Subgroup SL(2, ℤ)}
{F : Type*} [FunLike F ℍ ℂ] [ModularFormClass F Γ k] (f : F) :
Continuous f :=
(ModularFormClass.holo f).continuous
instance (priority := 100) CuspForm.funLike : FunLike (CuspForm Γ k) ℍ ℂ where
coe f := f.toFun
coe_injective' f g h := by cases f; cases g; congr; exact DFunLike.ext' h
instance (priority := 100) CuspFormClass.cuspForm : CuspFormClass (CuspForm Γ k) Γ k where
slash_action_eq f := f.slash_action_eq'
holo := CuspForm.holo'
zero_at_cusps := CuspForm.zero_at_cusps'
variable {F Γ k}
theorem ModularForm.toFun_eq_coe (f : ModularForm Γ k) : f.toFun = (f : ℍ → ℂ) :=
rfl
@[simp]
theorem ModularForm.toSlashInvariantForm_coe (f : ModularForm Γ k) : ⇑f.1 = f :=
rfl
theorem CuspForm.toFun_eq_coe {f : CuspForm Γ k} : f.toFun = (f : ℍ → ℂ) :=
rfl
@[simp]
theorem CuspForm.toSlashInvariantForm_coe (f : CuspForm Γ k) : ⇑f.1 = f := rfl
@[ext]
theorem ModularForm.ext {f g : ModularForm Γ k} (h : ∀ x, f x = g x) : f = g :=
DFunLike.ext f g h
@[ext]
theorem CuspForm.ext {f g : CuspForm Γ k} (h : ∀ x, f x = g x) : f = g :=
DFunLike.ext f g h
/-- Copy of a `ModularForm` with a new `toFun` equal to the old one. Useful to fix
definitional equalities. -/
protected def ModularForm.copy (f : ModularForm Γ k) (f' : ℍ → ℂ) (h : f' = ⇑f) :
ModularForm Γ k where
toSlashInvariantForm := f.1.copy f' h
holo' := h.symm ▸ f.holo'
bdd_at_cusps' A := h.symm ▸ f.bdd_at_cusps' A
/-- Copy of a `CuspForm` with a new `toFun` equal to the old one. Useful to fix
definitional equalities. -/
protected def CuspForm.copy (f : CuspForm Γ k) (f' : ℍ → ℂ) (h : f' = ⇑f) : CuspForm Γ k where
toSlashInvariantForm := f.1.copy f' h
holo' := h.symm ▸ f.holo'
zero_at_cusps' A := h.symm ▸ f.zero_at_cusps' A
end ModularForm
namespace ModularForm
open SlashInvariantForm
variable {Γ : Subgroup (GL (Fin 2) ℝ)} {k : ℤ}
instance add : Add (ModularForm Γ k) where add f g :=
{ toSlashInvariantForm := f + g
holo' := f.holo'.add g.holo'
bdd_at_cusps' hc := by simpa using (f.bdd_at_cusps' hc).add (g.bdd_at_cusps' hc) }
@[simp]
theorem coe_add (f g : ModularForm Γ k) : ⇑(f + g) = f + g :=
rfl
@[simp]
theorem add_apply (f g : ModularForm Γ k) (z : ℍ) : (f + g) z = f z + g z :=
rfl
instance instZero : Zero (ModularForm Γ k) :=
⟨ { toSlashInvariantForm := 0
holo' := fun _ => mdifferentiableAt_const
bdd_at_cusps' hc g hg := by
simp only [SlashInvariantForm.toFun_eq_coe, coe_zero, SlashAction.zero_slash]
exact zero_form_isBoundedAtImInfty } ⟩
@[simp]
theorem coe_zero : ⇑(0 : ModularForm Γ k) = (0 : ℍ → ℂ) :=
rfl
@[simp]
theorem zero_apply (z : ℍ) : (0 : ModularForm Γ k) z = 0 :=
rfl
section
-- scalar multiplication by real types (no assumption on `Γ`)
variable {α : Type*} [SMul α ℝ] [SMul α ℂ] [IsScalarTower α ℝ ℂ]
local instance : IsScalarTower α ℂ ℂ where
smul_assoc a y z := by simpa using smul_assoc (a • (1 : ℝ)) y z
instance instSMulℝ : SMul α (ModularForm Γ k) where
smul c f :=
{ toSlashInvariantForm := c • f.1
holo' := by simpa using f.holo'.const_smul (c • (1 : ℂ))
bdd_at_cusps' := fun hc g hg ↦ by
simpa only [IsBoundedAtImInfty, Filter.BoundedAtFilter, SlashInvariantForm.toFun_eq_coe,
SlashInvariantForm.coe_smulℝ, toSlashInvariantForm_coe, ← smul_one_smul ℂ c ⇑f, smul_slash]
using (f.bdd_at_cusps' hc g hg).const_smul_left _ }
@[simp]
theorem coe_smul (f : ModularForm Γ k) (n : α) : ⇑(n • f) = n • ⇑f :=
rfl
@[simp]
theorem smul_apply (f : ModularForm Γ k) (n : α) (z : ℍ) : (n • f) z = n • f z :=
rfl
end
section
variable {α : Type*} [SMul α ℂ] [IsScalarTower α ℂ ℂ] [Γ.HasDetOne]
instance instSMulℂ : SMul α (ModularForm Γ k) where
smul c f :=
{ toSlashInvariantForm := c • f.1
holo' := by simpa using f.holo'.const_smul (c • (1 : ℂ))
bdd_at_cusps' := fun hc g hg ↦ by
simp_rw [IsBoundedAtImInfty, Filter.BoundedAtFilter, SlashInvariantForm.toFun_eq_coe,
SlashInvariantForm.coe_smul, toSlashInvariantForm_coe, ← smul_one_smul ℂ c ⇑f, smul_slash]
exact (f.bdd_at_cusps' hc g hg).const_smul_left (σ g (c • (1 : ℂ))) }
@[simp]
theorem IsGLPos.coe_smul (f : ModularForm Γ k) (n : α) : ⇑(n • f) = n • ⇑f :=
rfl
@[simp]
theorem IsGLPos.smul_apply (f : ModularForm Γ k) (n : α) (z : ℍ) : (n • f) z = n • f z :=
rfl
end
instance instNeg : Neg (ModularForm Γ k) :=
⟨fun f =>
{ toSlashInvariantForm := -f.1
holo' := f.holo'.neg
bdd_at_cusps' := fun hc g hg => by simpa using (f.bdd_at_cusps' hc g hg).neg }⟩
@[simp]
theorem coe_neg (f : ModularForm Γ k) : ⇑(-f) = -f :=
rfl
@[simp]
theorem neg_apply (f : ModularForm Γ k) (z : ℍ) : (-f) z = -f z :=
rfl
instance instSub : Sub (ModularForm Γ k) :=
⟨fun f g => f + -g⟩
@[simp]
theorem coe_sub (f g : ModularForm Γ k) : ⇑(f - g) = f - g :=
rfl
@[simp]
theorem sub_apply (f g : ModularForm Γ k) (z : ℍ) : (f - g) z = f z - g z :=
rfl
instance : AddCommGroup (ModularForm Γ k) :=
DFunLike.coe_injective.addCommGroup _ rfl coe_add coe_neg coe_sub coe_smul coe_smul
/-- Additive coercion from `ModularForm` to `ℍ → ℂ`. -/
@[simps]
def coeHom : ModularForm Γ k →+ ℍ → ℂ where
toFun f := f
map_zero' := coe_zero
map_add' _ _ := rfl
instance : Module ℝ (ModularForm Γ k) :=
Function.Injective.module ℝ coeHom DFunLike.coe_injective fun _ _ => rfl
instance [Γ.HasDetOne] : Module ℂ (ModularForm Γ k) :=
Function.Injective.module ℂ coeHom DFunLike.coe_injective fun _ _ => rfl
instance : Inhabited (ModularForm Γ k) :=
⟨0⟩
/-- The modular form of weight `k_1 + k_2` given by the product of two modular forms of weights
`k_1` and `k_2`. -/
def mul {k_1 k_2 : ℤ} [Γ.HasDetPlusMinusOne] (f : ModularForm Γ k_1) (g : ModularForm Γ k_2) :
ModularForm Γ (k_1 + k_2) where
toSlashInvariantForm := f.1.mul g.1
holo' := f.holo'.mul g.holo'
bdd_at_cusps' hc γ hγ := by
simpa [mul_slash] using ((f.bdd_at_cusps' hc γ hγ).mul (g.bdd_at_cusps' hc γ hγ)).smul _
@[simp]
theorem mul_coe [Γ.HasDetPlusMinusOne] {k_1 k_2 : ℤ} (f : ModularForm Γ k_1)
(g : ModularForm Γ k_2) : (f.mul g : ℍ → ℂ) = f * g :=
rfl
/-- The constant function with value `x : ℂ` as a modular form of weight 0 and any level. -/
def const (x : ℂ) [Γ.HasDetOne] : ModularForm Γ 0 where
toSlashInvariantForm := .const x
holo' _ := mdifferentiableAt_const
bdd_at_cusps' hc g hg := by simpa only [const_toFun, slash_def, SlashInvariantForm.toFun_eq_coe,
Function.const_apply, neg_zero, zpow_zero] using atImInfty.const_boundedAtFilter _
@[simp]
lemma const_apply [Γ.HasDetOne] (x : ℂ) (τ : ℍ) : (const x : ModularForm Γ 0) τ = x := rfl
/-- The constant function with value `x : ℂ` as a modular form of weight 0 and any level. -/
def constℝ (x : ℝ) [Γ.HasDetPlusMinusOne] : ModularForm Γ 0 where
toSlashInvariantForm := .constℝ x
holo' _ := mdifferentiableAt_const
bdd_at_cusps' hc g hg := by simpa only [constℝ_toFun, slash_def, SlashInvariantForm.toFun_eq_coe,
Function.const_apply, neg_zero, zpow_zero] using atImInfty.const_boundedAtFilter _
@[simp]
lemma constℝ_apply [Γ.HasDetPlusMinusOne] (x : ℝ) (τ : ℍ) :
(constℝ x : ModularForm Γ 0) τ = x :=
rfl
instance [Γ.HasDetPlusMinusOne] : One (ModularForm Γ 0) where
one := { constℝ 1 with toSlashInvariantForm := 1 }
@[simp]
theorem one_coe_eq_one [Γ.HasDetPlusMinusOne] : ⇑(1 : ModularForm Γ 0) = 1 :=
rfl
instance [Γ.HasDetPlusMinusOne] : NatCast (ModularForm Γ 0) where
natCast n := constℝ n
@[simp, norm_cast]
lemma coe_natCast [Γ.HasDetPlusMinusOne] (n : ℕ) :
⇑(n : ModularForm Γ 0) = n := rfl
lemma toSlashInvariantForm_natCast [Γ.HasDetPlusMinusOne] (n : ℕ) :
(n : ModularForm Γ 0).toSlashInvariantForm = n := rfl
instance [Γ.HasDetPlusMinusOne] : IntCast (ModularForm Γ 0) where
intCast z := constℝ z
@[simp, norm_cast]
lemma coe_intCast [Γ.HasDetPlusMinusOne] (z : ℤ) :
⇑(z : ModularForm Γ 0) = z := rfl
lemma toSlashInvariantForm_intCast [Γ.HasDetPlusMinusOne] (z : ℤ) :
(z : ModularForm Γ 0).toSlashInvariantForm = z := rfl
end ModularForm
namespace CuspForm
open ModularForm
variable {F : Type*} {Γ : Subgroup (GL (Fin 2) ℝ)} {k : ℤ}
instance hasAdd : Add (CuspForm Γ k) :=
⟨fun f g =>
{ toSlashInvariantForm := f + g
holo' := f.holo'.add g.holo'
zero_at_cusps' := fun A => by simpa using (f.zero_at_cusps' A).add (g.zero_at_cusps' A) }⟩
@[simp]
theorem coe_add (f g : CuspForm Γ k) : ⇑(f + g) = f + g :=
rfl
@[simp]
theorem add_apply (f g : CuspForm Γ k) (z : ℍ) : (f + g) z = f z + g z :=
rfl
instance instZero : Zero (CuspForm Γ k) :=
⟨ { toSlashInvariantForm := 0
holo' := fun _ => mdifferentiableAt_const
zero_at_cusps' hc g hg := by simpa using Filter.zero_zeroAtFilter _ } ⟩
@[simp]
theorem coe_zero : ⇑(0 : CuspForm Γ k) = (0 : ℍ → ℂ) :=
rfl
@[simp]
theorem zero_apply (z : ℍ) : (0 : CuspForm Γ k) z = 0 :=
rfl
section
-- scalar multiplication by real types (no assumption on `Γ`)
variable {α : Type*} [SMul α ℝ] [SMul α ℂ] [IsScalarTower α ℝ ℂ]
local instance : IsScalarTower α ℂ ℂ where
smul_assoc a y z := by simpa using smul_assoc (a • (1 : ℝ)) y z
instance instSMul : SMul α (CuspForm Γ k) where smul c f :=
{ toSlashInvariantForm := c • f.1
holo' := by simpa using f.holo'.const_smul (c • (1 : ℂ))
zero_at_cusps' hc g hg := by
simp_rw [IsZeroAtImInfty, Filter.ZeroAtFilter, SlashInvariantForm.toFun_eq_coe,
SlashInvariantForm.coe_smulℝ, toSlashInvariantForm_coe, ← smul_one_smul ℂ c ⇑f, smul_slash]
exact (f.zero_at_cusps' hc g hg).smul _ }
@[simp]
theorem coe_smul (f : CuspForm Γ k) (n : α) : ⇑(n • f) = n • ⇑f :=
rfl
@[simp]
theorem smul_apply (f : CuspForm Γ k) (n : α) {z : ℍ} : (n • f) z = n • f z :=
rfl
end
section
-- scalar multiplication by complex types (assuming `IsGLPos Γ`)
variable {α : Type*} [SMul α ℂ] [IsScalarTower α ℂ ℂ] [Γ.HasDetOne]
instance IsGLPos.instSMul : SMul α (CuspForm Γ k) where smul c f :=
{ toSlashInvariantForm := c • f.1
holo' := by simpa using f.holo'.const_smul (c • (1 : ℂ))
zero_at_cusps' hc g hg := by
simp_rw [IsZeroAtImInfty, Filter.ZeroAtFilter, SlashInvariantForm.toFun_eq_coe,
SlashInvariantForm.coe_smul, toSlashInvariantForm_coe, ← smul_one_smul ℂ c ⇑f,
smul_slash]
exact (f.zero_at_cusps' hc g hg).smul _ }
@[simp]
theorem IsGLPos.coe_smul (f : CuspForm Γ k) (n : α) : ⇑(n • f) = n • ⇑f :=
rfl
@[simp]
theorem IsGLPos.smul_apply (f : CuspForm Γ k) (n : α) {z : ℍ} : (n • f) z = n • f z :=
rfl
end
instance instNeg : Neg (CuspForm Γ k) :=
⟨fun f =>
{ toSlashInvariantForm := -f.1
holo' := f.holo'.neg
zero_at_cusps' hc g hg := by simpa using (f.zero_at_cusps' hc g hg).neg }⟩
@[simp]
theorem coe_neg (f : CuspForm Γ k) : ⇑(-f) = -f :=
rfl
@[simp]
theorem neg_apply (f : CuspForm Γ k) (z : ℍ) : (-f) z = -f z :=
rfl
instance instSub : Sub (CuspForm Γ k) :=
⟨fun f g => f + -g⟩
@[simp]
theorem coe_sub (f g : CuspForm Γ k) : ⇑(f - g) = f - g :=
rfl
@[simp]
theorem sub_apply (f g : CuspForm Γ k) (z : ℍ) : (f - g) z = f z - g z :=
rfl
instance : AddCommGroup (CuspForm Γ k) :=
DFunLike.coe_injective.addCommGroup _ rfl coe_add coe_neg coe_sub coe_smul coe_smul
/-- Additive coercion from `CuspForm` to `ℍ → ℂ`. -/
@[simps]
def coeHom : CuspForm Γ k →+ ℍ → ℂ where
toFun f := f
map_zero' := CuspForm.coe_zero
map_add' _ _ := rfl
instance : Module ℝ (CuspForm Γ k) :=
Function.Injective.module ℝ coeHom DFunLike.coe_injective fun _ _ => rfl
instance [Γ.HasDetOne] : Module ℂ (CuspForm Γ k) :=
Function.Injective.module ℂ coeHom DFunLike.coe_injective fun _ _ => rfl
instance : Inhabited (CuspForm Γ k) :=
⟨0⟩
instance (priority := 99) [FunLike F ℍ ℂ] [CuspFormClass F Γ k] : ModularFormClass F Γ k where
slash_action_eq := SlashInvariantFormClass.slash_action_eq
holo := CuspFormClass.holo
bdd_at_cusps f _ hc g hg := (CuspFormClass.zero_at_cusps f hc g hg).boundedAtFilter
end CuspForm
namespace ModularForm
section GradedRing
/-- Cast for modular forms, which is useful for avoiding `Heq`s. -/
def mcast {a b : ℤ} {Γ : Subgroup (GL (Fin 2) ℝ)} (h : a = b) (f : ModularForm Γ a) :
ModularForm Γ b where
toFun := (f : ℍ → ℂ)
slash_action_eq' A := h ▸ f.slash_action_eq' A
holo' := f.holo'
bdd_at_cusps' A := h ▸ f.bdd_at_cusps' A
@[ext (iff := false)]
theorem gradedMonoid_eq_of_cast {Γ : Subgroup (GL (Fin 2) ℝ)} {a b : GradedMonoid (ModularForm Γ)}
(h : a.fst = b.fst) (h2 : mcast h a.snd = b.snd) : a = b := by
obtain ⟨i, a⟩ := a
obtain ⟨j, b⟩ := b
cases h
exact congr_arg _ h2
instance (Γ : Subgroup (GL (Fin 2) ℝ)) [Γ.HasDetPlusMinusOne] :
GradedMonoid.GOne (ModularForm Γ) where
one := 1
instance (Γ : Subgroup (GL (Fin 2) ℝ)) [Γ.HasDetPlusMinusOne] :
GradedMonoid.GMul (ModularForm Γ) where
mul f g := f.mul g
instance instGCommRing (Γ : Subgroup (GL (Fin 2) ℝ)) [Γ.HasDetPlusMinusOne] :
DirectSum.GCommRing (ModularForm Γ) where
one_mul _ := gradedMonoid_eq_of_cast (zero_add _) (ext fun _ => one_mul _)
mul_one _ := gradedMonoid_eq_of_cast (add_zero _) (ext fun _ => mul_one _)
mul_assoc _ _ _ := gradedMonoid_eq_of_cast (add_assoc _ _ _) (ext fun _ => mul_assoc _ _ _)
mul_zero {_ _} _ := ext fun _ => mul_zero _
zero_mul {_ _} _ := ext fun _ => zero_mul _
mul_add {_ _} _ _ _ := ext fun _ => mul_add _ _ _
add_mul {_ _} _ _ _ := ext fun _ => add_mul _ _ _
mul_comm _ _ := gradedMonoid_eq_of_cast (add_comm _ _) (ext fun _ => mul_comm _ _)
natCast := Nat.cast
natCast_zero := ext fun _ => Nat.cast_zero
natCast_succ _ := ext fun _ => Nat.cast_succ _
intCast := Int.cast
intCast_ofNat _ := ext fun _ => AddGroupWithOne.intCast_ofNat _
intCast_negSucc_ofNat _ := ext fun _ => AddGroupWithOne.intCast_negSucc _
instance instGAlgebra (Γ : Subgroup (GL (Fin 2) ℝ)) [Γ.HasDetOne] :
DirectSum.GAlgebra ℂ (ModularForm Γ) where
toFun := { toFun z := const z, map_zero' := rfl, map_add' := fun _ _ => rfl }
map_one := rfl
map_mul _x _y := rfl
commutes _c _x := gradedMonoid_eq_of_cast (add_comm _ _) (ext fun _ => mul_comm _ _)
smul_def _x _x := gradedMonoid_eq_of_cast (zero_add _).symm (ext fun _ => rfl)
open scoped DirectSum in
example (Γ : Subgroup (GL (Fin 2) ℝ)) [Γ.HasDetOne] : Algebra ℂ (⨁ i, ModularForm Γ i) :=
inferInstance
end GradedRing
end ModularForm
section translate
open ModularForm OnePoint
variable {k : ℤ} {Γ : Subgroup (GL (Fin 2) ℝ)} {F : Type*} [FunLike F ℍ ℂ] (f : F)
open ConjAct Pointwise in
/-- Translating a `ModularForm` by `GL(2, ℝ)`, to obtain a new `ModularForm`. -/
noncomputable def ModularForm.translate [ModularFormClass F Γ k] (g : GL (Fin 2) ℝ) :
ModularForm (toConjAct g⁻¹ • Γ) k where
__ := SlashInvariantForm.translate f g
bdd_at_cusps' {c} hc γ hγ := by
rw [SlashInvariantForm.toFun_eq_coe, SlashInvariantForm.coe_translate,
← SlashAction.slash_mul, ← isBoundedAt_infty_iff, ← OnePoint.IsBoundedAt.smul_iff]
apply ModularFormClass.bdd_at_cusps f
simpa [mul_smul, hγ] using hc.smul g
holo' := (ModularFormClass.holo f).slash k g
@[simp]
lemma ModularForm.coe_translate [ModularFormClass F Γ k] (g : GL (Fin 2) ℝ) :
translate f g = ⇑f ∣[k] g :=
rfl
open ConjAct Pointwise in
/-- Translating a `CuspForm` by `SL(2, ℤ)`, to obtain a new `CuspForm`. -/
noncomputable def CuspForm.translate [CuspFormClass F Γ k] (g : GL (Fin 2) ℝ) :
CuspForm (toConjAct g⁻¹ • Γ) k where
__ := ModularForm.translate f g
zero_at_cusps' {c} hc γ hγ := by
rw [SlashInvariantForm.toFun_eq_coe, ModularForm.toSlashInvariantForm_coe,
ModularForm.coe_translate, ← SlashAction.slash_mul, ← isZeroAt_infty_iff,
← OnePoint.IsZeroAt.smul_iff]
apply CuspFormClass.zero_at_cusps f
simpa [mul_smul, hγ] using hc.smul g
@[simp]
lemma CuspForm.coe_translate [CuspFormClass F Γ k] (g : SL(2, ℤ)) :
translate f g = ⇑f ∣[k] g :=
rfl
end translate
section SL2Z
open ModularForm CuspForm
variable {k F} {Γ : Subgroup (GL (Fin 2) ℝ)} [Γ.IsArithmetic] [FunLike F ℍ ℂ]
lemma ModularFormClass.bdd_at_infty_slash [ModularFormClass F Γ k]
(f : F) (g : SL(2, ℤ)) : IsBoundedAtImInfty (f ∣[k] g) := by
rw [← OnePoint.isBoundedAt_infty_iff, SL_slash, ← OnePoint.IsBoundedAt.smul_iff]
apply bdd_at_cusps f
rw [Subgroup.IsArithmetic.isCusp_iff_isCusp_SL2Z, isCusp_SL2Z_iff']
exact ⟨g, by simp [mapGL]⟩
lemma ModularFormClass.bdd_at_infty [ModularFormClass F Γ k]
(f : F) : IsBoundedAtImInfty f := by
simpa using ModularFormClass.bdd_at_infty_slash f 1
lemma CuspFormClass.zero_at_infty_slash [CuspFormClass F Γ k]
(f : F) (g : SL(2, ℤ)) : IsZeroAtImInfty (f ∣[k] g) := by
rw [← OnePoint.isZeroAt_infty_iff, SL_slash, ← OnePoint.IsZeroAt.smul_iff]
apply zero_at_cusps f
rw [Subgroup.IsArithmetic.isCusp_iff_isCusp_SL2Z, isCusp_SL2Z_iff']
exact ⟨g, by simp [mapGL]⟩
lemma CuspFormClass.zero_at_infty [CuspFormClass F Γ k]
(f : F) : IsZeroAtImInfty f := by
simpa using CuspFormClass.zero_at_infty_slash f 1
end SL2Z |
.lake/packages/mathlib/Mathlib/NumberTheory/ModularForms/Petersson.lean | import Mathlib.Analysis.Complex.UpperHalfPlane.Topology
import Mathlib.NumberTheory.ModularForms.SlashInvariantForms
/-!
# The Petersson scalar product
For `f, f'` functions `ℍ → ℂ`, we define `petersson k f f'` to be the function
`τ ↦ conj (f τ) * f' τ * τ.im ^ k`.
We show this function is (weight 0) invariant under `Γ` if `f, f'` are (weight `k`) invariant under
`Γ`.
-/
open UpperHalfPlane
open scoped MatrixGroups ComplexConjugate ModularForm
namespace UpperHalfPlane
/-- The integrand in the Petersson scalar product of two modular forms. -/
noncomputable def petersson (k : ℤ) (f f' : ℍ → ℂ) (τ : ℍ) :=
conj (f τ) * f' τ * τ.im ^ k
@[fun_prop]
lemma petersson_continuous (k : ℤ) {f f' : ℍ → ℂ} (hf : Continuous f) (hf' : Continuous f') :
Continuous (petersson k f f') := by
unfold petersson
fun_prop (disch := simp [im_ne_zero _])
lemma petersson_slash (k : ℤ) (f f' : ℍ → ℂ) (g : GL (Fin 2) ℝ) (τ : ℍ) :
petersson k (f ∣[k] g) (f' ∣[k] g) τ =
|g.det.val| ^ (k - 2) * σ g (petersson k f f' (g • τ)) := by
set D := |g.det.val|
have hD : (D : ℂ) ≠ 0 := mod_cast abs_ne_zero.mpr g.det_ne_zero
set j := denom g τ
calc petersson k (f ∣[k] g) (f' ∣[k] g) τ
_ = D ^ (k - 2 + k) * conj (σ g (f (g • τ))) * σ g (f' (g • τ))
* (τ.im ^ k * j.normSq ^ (-k)) := by
simp [Complex.normSq_eq_conj_mul_self, (by abel : k - 2 + k = (k - 1) + (k - 1)), petersson,
zpow_add₀ hD, mul_zpow, ModularForm.slash_def, -Matrix.GeneralLinearGroup.val_det_apply]
ring
_ = D ^ (k - 2) * (conj (σ g (f (g • τ))) * σ g (f' (g • τ)) * (D * τ.im / j.normSq) ^ k) := by
rw [div_zpow, mul_zpow, zpow_neg, div_eq_mul_inv, zpow_add₀ hD]
ring
_ = D ^ (k - 2) * (conj (σ g (f (g • τ))) * σ g (f' (g • τ)) * (im (g • τ)) ^ k) := by
rw [im_smul_eq_div_normSq, Complex.ofReal_div, Complex.ofReal_mul]
_ = D ^ (k - 2) * σ g (petersson k f f' (g • τ)) := by simp [petersson, σ_conj]
lemma petersson_slash_SL (k : ℤ) (f f' : ℍ → ℂ) (g : SL(2, ℤ)) (τ : ℍ) :
petersson k (f ∣[k] g) (f' ∣[k] g) τ = petersson k f f' (g • τ) := by
-- need to disable two simp lemmas as they work against `Matrix.SpecialLinearGroup.det_coe`
simp [σ, ModularForm.SL_slash, petersson_slash,
-Matrix.SpecialLinearGroup.map_apply_coe, -Matrix.SpecialLinearGroup.coe_matrix_coe]
end UpperHalfPlane
section
variable {F F' : Type*} [FunLike F ℍ ℂ] [FunLike F' ℍ ℂ]
lemma SlashInvariantFormClass.petersson_smul {k g τ} {Γ : Subgroup (GL (Fin 2) ℝ)} [Γ.HasDetOne]
[SlashInvariantFormClass F Γ k] {f : F} [SlashInvariantFormClass F' Γ k] {f' : F'}
(hg : g ∈ Γ) : petersson k f f' (g • τ) = petersson k f f' τ := by
simpa [SlashInvariantFormClass.slash_action_eq _ _ hg, Subgroup.HasDetOne.det_eq hg, σ]
using (petersson_slash k f f' g τ).symm
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.