source
stringlengths
17
118
lean4
stringlengths
0
335k
.lake/packages/mathlib/Mathlib/Data/Fintype/Shrink.lean
import Mathlib.Data.Countable.Small import Mathlib.Data.Fintype.EquivFin /-! # Fintype instance for `Shrink` -/ universe u v variable {Ξ± : Type u} [Fintype Ξ±] noncomputable instance Shrink.instFintype : Fintype (Shrink.{v} Ξ±) := .ofEquiv _ (equivShrink _) instance Shrink.instFinite {Ξ± : Type u} [Finite Ξ±] : Finite (Shrink.{v} Ξ±) := .of_equiv _ (equivShrink _) @[simp] lemma Fintype.card_shrink [Fintype (Shrink.{v} Ξ±)] : card (Shrink.{v} Ξ±) = card Ξ± := card_congr (equivShrink _).symm
.lake/packages/mathlib/Mathlib/Data/Fintype/BigOperators.lean
import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise import Mathlib.Algebra.BigOperators.Group.Finset.Sigma import Mathlib.Algebra.BigOperators.Option import Mathlib.Data.Fintype.Option import Mathlib.Data.Fintype.Prod import Mathlib.Data.Fintype.Sigma import Mathlib.Data.Fintype.Sum import Mathlib.Data.Fintype.Vector /-! Results about "big operations" over a `Fintype`, and consequent results about cardinalities of certain types. ## Implementation note This content had previously been in `Data.Fintype.Basic`, but was moved here to avoid requiring `Algebra.BigOperators` (and hence many other imports) as a dependency of `Fintype`. However many of the results here really belong in `Algebra.BigOperators.Group.Finset` and should be moved at some point. -/ assert_not_exists MulAction open Mathlib universe u v variable {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} namespace Fintype @[to_additive] theorem prod_bool [CommMonoid Ξ±] (f : Bool β†’ Ξ±) : ∏ b, f b = f true * f false := by simp theorem card_eq_sum_ones {Ξ±} [Fintype Ξ±] : Fintype.card Ξ± = βˆ‘ _a : Ξ±, 1 := Finset.card_eq_sum_ones _ section open Finset variable {ΞΉ : Type*} [DecidableEq ΞΉ] [Fintype ΞΉ] @[to_additive] theorem prod_extend_by_one [CommMonoid Ξ±] (s : Finset ΞΉ) (f : ΞΉ β†’ Ξ±) : ∏ i, (if i ∈ s then f i else 1) = ∏ i ∈ s, f i := by rw [← prod_filter, filter_mem_eq_inter, univ_inter] end section variable {M : Type*} [Fintype Ξ±] [CommMonoid M] @[to_additive] theorem prod_eq_one (f : Ξ± β†’ M) (h : βˆ€ a, f a = 1) : ∏ a, f a = 1 := Finset.prod_eq_one fun a _ha => h a @[to_additive] theorem prod_congr (f g : Ξ± β†’ M) (h : βˆ€ a, f a = g a) : ∏ a, f a = ∏ a, g a := Finset.prod_congr rfl fun a _ha => h a @[to_additive] theorem prod_eq_single {f : Ξ± β†’ M} (a : Ξ±) (h : βˆ€ x β‰  a, f x = 1) : ∏ x, f x = f a := Finset.prod_eq_single a (fun x _ hx => h x hx) fun ha => (ha (Finset.mem_univ a)).elim @[to_additive] theorem prod_eq_mul {f : Ξ± β†’ M} (a b : Ξ±) (h₁ : a β‰  b) (hβ‚‚ : βˆ€ x, x β‰  a ∧ x β‰  b β†’ f x = 1) : ∏ x, f x = f a * f b := by apply Finset.prod_eq_mul a b h₁ fun x _ hx => hβ‚‚ x hx <;> exact fun hc => (hc (Finset.mem_univ _)).elim /-- If a product of a `Finset` of a subsingleton type has a given value, so do the terms in that product. -/ @[to_additive /-- If a sum of a `Finset` of a subsingleton type has a given value, so do the terms in that sum. -/] theorem eq_of_subsingleton_of_prod_eq {ΞΉ : Type*} [Subsingleton ΞΉ] {s : Finset ΞΉ} {f : ΞΉ β†’ M} {b : M} (h : ∏ i ∈ s, f i = b) : βˆ€ i ∈ s, f i = b := Finset.eq_of_card_le_one_of_prod_eq (Finset.card_le_one_of_subsingleton s) h end end Fintype open Finset section variable {M : Type*} [Fintype Ξ±] [CommMonoid M] @[to_additive (attr := simp)] theorem Fintype.prod_option (f : Option Ξ± β†’ M) : ∏ i, f i = f none * ∏ i, f (some i) := Finset.prod_insertNone f univ @[to_additive] theorem Fintype.prod_eq_mul_prod_subtype_ne [DecidableEq Ξ±] (f : Ξ± β†’ M) (a : Ξ±) : ∏ i, f i = f a * ∏ i : {i // i β‰  a}, f i.1 := by simp_rw [← (Equiv.optionSubtypeNe a).prod_comp, prod_option, Equiv.optionSubtypeNe_none, Equiv.optionSubtypeNe_some] end section Pi variable {ΞΉ ΞΊ : Type*} {Ξ± : ΞΉ β†’ Type*} [DecidableEq ΞΉ] [DecidableEq ΞΊ] @[simp] lemma Finset.card_pi (s : Finset ΞΉ) (t : βˆ€ i, Finset (Ξ± i)) : #(s.pi t) = ∏ i ∈ s, #(t i) := Multiset.card_pi _ _ namespace Fintype variable [Fintype ΞΉ] @[simp] lemma card_piFinset (s : βˆ€ i, Finset (Ξ± i)) : #(piFinset s) = ∏ i, #(s i) := by simp [piFinset, card_map] /-- This lemma is specifically designed to be used backwards, whence the specialisation to `Fin n` as the indexing type doesn't matter in practice. The more general forward direction lemma here is `Fintype.card_piFinset`. -/ lemma card_piFinset_const {Ξ± : Type*} (s : Finset Ξ±) (n : β„•) : #(piFinset fun _ : Fin n ↦ s) = #s ^ n := by simp @[simp] lemma card_pi [βˆ€ i, Fintype (Ξ± i)] : card (βˆ€ i, Ξ± i) = ∏ i, card (Ξ± i) := card_piFinset _ /-- This lemma is specifically designed to be used backwards, whence the specialisation to `Fin n` as the indexing type doesn't matter in practice. The more general forward direction lemma here is `Fintype.card_pi`. -/ lemma card_pi_const (Ξ± : Type*) [Fintype Ξ±] (n : β„•) : card (Fin n β†’ Ξ±) = card Ξ± ^ n := card_piFinset_const _ _ /-- Product over a sigma type equals the repeated product. This is a version of `Finset.prod_sigma` specialized to the case of multiplication over `Finset.univ`. -/ @[to_additive /-- Sum over a sigma type equals the repeated sum. This is a version of `Finset.sum_sigma` specialized to the case of summation over `Finset.univ`. -/] theorem prod_sigma {ΞΉ} {Ξ± : ΞΉ β†’ Type*} {M : Type*} [Fintype ΞΉ] [βˆ€ i, Fintype (Ξ± i)] [CommMonoid M] (f : Sigma Ξ± β†’ M) : ∏ x, f x = ∏ x, ∏ y, f ⟨x, y⟩ := Finset.prod_sigma .. /-- Product over a sigma type equals the repeated product, curried version. This version is useful to rewrite from right to left. -/ @[to_additive /-- Sum over a sigma type equals the repeated sum, curried version. This version is useful to rewrite from right to left. -/] theorem prod_sigma' {ΞΉ} {Ξ± : ΞΉ β†’ Type*} {M : Type*} [Fintype ΞΉ] [βˆ€ i, Fintype (Ξ± i)] [CommMonoid M] (f : (i : ΞΉ) β†’ Ξ± i β†’ M) : ∏ x : Sigma Ξ±, f x.1 x.2 = ∏ x, ∏ y, f x y := prod_sigma .. @[simp] nonrec lemma card_sigma {ΞΉ} {Ξ± : ΞΉ β†’ Type*} [Fintype ΞΉ] [βˆ€ i, Fintype (Ξ± i)] : card (Sigma Ξ±) = βˆ‘ i, card (Ξ± i) := card_sigma _ _ /-- The number of dependent maps `f : Ξ  j, s j` for which the `i` component is `a` is the product over all `j β‰  i` of `#(s j)`. Note that this is just a composition of easier lemmas, but there's some glue missing to make that smooth enough not to need this lemma. -/ lemma card_filter_piFinset_eq_of_mem [βˆ€ i, DecidableEq (Ξ± i)] (s : βˆ€ i, Finset (Ξ± i)) (i : ΞΉ) {a : Ξ± i} (ha : a ∈ s i) : #{f ∈ piFinset s | f i = a} = ∏ j ∈ univ.erase i, #(s j) := by calc _ = ∏ j, #(Function.update s i {a} j) := by rw [← piFinset_update_singleton_eq_filter_piFinset_eq _ _ ha, Fintype.card_piFinset] _ = ∏ j, Function.update (fun j ↦ #(s j)) i 1 j := Fintype.prod_congr _ _ fun j ↦ by obtain rfl | hji := eq_or_ne j i <;> simp [*] _ = _ := by simp [prod_update_of_mem, erase_eq] lemma card_filter_piFinset_const_eq_of_mem (s : Finset ΞΊ) (i : ΞΉ) {x : ΞΊ} (hx : x ∈ s) : #{f ∈ piFinset fun _ ↦ s | f i = x} = #s ^ (card ΞΉ - 1) := (card_filter_piFinset_eq_of_mem _ _ hx).trans <| by rw [prod_const #s, card_erase_of_mem (mem_univ _), card_univ] lemma card_filter_piFinset_eq [βˆ€ i, DecidableEq (Ξ± i)] (s : βˆ€ i, Finset (Ξ± i)) (i : ΞΉ) (a : Ξ± i) : #{f ∈ piFinset s | f i = a} = if a ∈ s i then ∏ b ∈ univ.erase i, #(s b) else 0 := by split_ifs with h Β· rw [card_filter_piFinset_eq_of_mem _ _ h] Β· rw [filter_piFinset_of_notMem _ _ _ h, Finset.card_empty] lemma card_filter_piFinset_const (s : Finset ΞΊ) (i : ΞΉ) (j : ΞΊ) : #{f ∈ piFinset fun _ ↦ s | f i = j} = if j ∈ s then #s ^ (card ΞΉ - 1) else 0 := (card_filter_piFinset_eq _ _ _).trans <| by rw [prod_const #s, card_erase_of_mem (mem_univ _), card_univ] end Fintype end Pi -- TODO: this is a basic theorem about `Fintype.card`, -- and ideally could be moved to `Mathlib/Data/Fintype/Card.lean`. theorem Fintype.card_fun [DecidableEq Ξ±] [Fintype Ξ±] [Fintype Ξ²] : Fintype.card (Ξ± β†’ Ξ²) = Fintype.card Ξ² ^ Fintype.card Ξ± := by simp @[simp] theorem card_vector [Fintype Ξ±] (n : β„•) : Fintype.card (List.Vector Ξ± n) = Fintype.card Ξ± ^ n := by rw [Fintype.ofEquiv_card]; simp /-- It is equivalent to compute the product of a function over `Fin n` or `Finset.range n`. -/ @[to_additive /-- It is equivalent to sum a function over `fin n` or `finset.range n`. -/] theorem Fin.prod_univ_eq_prod_range [CommMonoid Ξ±] (f : β„• β†’ Ξ±) (n : β„•) : ∏ i : Fin n, f i = ∏ i ∈ range n, f i := calc ∏ i : Fin n, f i = ∏ i : { x // x ∈ range n }, f i := Fintype.prod_equiv (Fin.equivSubtype.trans (Equiv.subtypeEquivRight (by simp))) _ _ (by simp) _ = ∏ i ∈ range n, f i := by rw [← attach_eq_univ, prod_attach] @[to_additive] theorem Finset.prod_fin_eq_prod_range [CommMonoid Ξ²] {n : β„•} (c : Fin n β†’ Ξ²) : ∏ i, c i = ∏ i ∈ Finset.range n, if h : i < n then c ⟨i, h⟩ else 1 := by rw [← Fin.prod_univ_eq_prod_range, Finset.prod_congr rfl] rintro ⟨i, hi⟩ _ simp only [hi, dif_pos] @[to_additive] theorem Finset.prod_toFinset_eq_subtype {M : Type*} [CommMonoid M] [Fintype Ξ±] (p : Ξ± β†’ Prop) [DecidablePred p] (f : Ξ± β†’ M) : ∏ a ∈ { x | p x }.toFinset, f a = ∏ a : Subtype p, f a := by rw [← Finset.prod_subtype] simp_rw [Set.mem_toFinset]; intro; rfl nonrec theorem Fintype.prod_dite [Fintype Ξ±] {p : Ξ± β†’ Prop} [DecidablePred p] [CommMonoid Ξ²] (f : βˆ€ a, p a β†’ Ξ²) (g : βˆ€ a, Β¬p a β†’ Ξ²) : (∏ a, dite (p a) (f a) (g a)) = (∏ a : { a // p a }, f a a.2) * ∏ a : { a // Β¬p a }, g a a.2 := by simp only [prod_dite] congr 1 Β· exact (Equiv.subtypeEquivRight <| by simp).prod_comp fun x : { x // p x } => f x x.2 Β· exact (Equiv.subtypeEquivRight <| by simp).prod_comp fun x : { x // Β¬p x } => g x x.2 section variable {α₁ : Type*} {Ξ±β‚‚ : Type*} {M : Type*} [Fintype α₁] [Fintype Ξ±β‚‚] [CommMonoid M] @[to_additive] theorem Fintype.prod_sumElim (f : α₁ β†’ M) (g : Ξ±β‚‚ β†’ M) : ∏ x, Sum.elim f g x = (∏ a₁, f a₁) * ∏ aβ‚‚, g aβ‚‚ := prod_disjSum _ _ _ @[to_additive (attr := simp)] theorem Fintype.prod_sum_type (f : α₁ βŠ• Ξ±β‚‚ β†’ M) : ∏ x, f x = (∏ a₁, f (Sum.inl a₁)) * ∏ aβ‚‚, f (Sum.inr aβ‚‚) := prod_disjSum _ _ _ /-- The product over a product type equals the product of the fiberwise products. For rewriting in the reverse direction, use `Fintype.prod_prod_type'`. -/ @[to_additive Fintype.sum_prod_type /-- The sum over a product type equals the sum of fiberwise sums. For rewriting in the reverse direction, use `Fintype.sum_prod_type'`. -/] theorem Fintype.prod_prod_type [CommMonoid Ξ³] (f : α₁ Γ— Ξ±β‚‚ β†’ Ξ³) : ∏ x, f x = ∏ x, ∏ y, f (x, y) := Finset.prod_product .. /-- The product over a product type equals the product of the fiberwise products. For rewriting in the reverse direction, use `Fintype.prod_prod_type`. -/ @[to_additive Fintype.sum_prod_type' /-- The sum over a product type equals the sum of fiberwise sums. For rewriting in the reverse direction, use `Fintype.sum_prod_type`. -/] theorem Fintype.prod_prod_type' [CommMonoid Ξ³] (f : α₁ β†’ Ξ±β‚‚ β†’ Ξ³) : ∏ x : α₁ Γ— Ξ±β‚‚, f x.1 x.2 = ∏ x, ∏ y, f x y := Finset.prod_product' .. @[to_additive Fintype.sum_prod_type_right] theorem Fintype.prod_prod_type_right [CommMonoid Ξ³] (f : α₁ Γ— Ξ±β‚‚ β†’ Ξ³) : ∏ x, f x = ∏ y, ∏ x, f (x, y) := Finset.prod_product_right .. /-- An uncurried version of `Finset.prod_prod_type_right`. -/ @[to_additive Fintype.sum_prod_type_right' /-- An uncurried version of `Finset.sum_prod_type_right` -/] theorem Fintype.prod_prod_type_right' [CommMonoid Ξ³] (f : α₁ β†’ Ξ±β‚‚ β†’ Ξ³) : ∏ x : α₁ Γ— Ξ±β‚‚, f x.1 x.2 = ∏ y, ∏ x, f x y := Finset.prod_product_right' .. end
.lake/packages/mathlib/Mathlib/Data/Fintype/WithTopBot.lean
import Mathlib.Data.Fintype.Option import Mathlib.Order.TypeTags /-! # Fintype instances for `WithTop Ξ±` and `WithBot Ξ±` -/ variable {Ξ± : Type*} instance [Fintype Ξ±] : Fintype (WithTop Ξ±) := instFintypeOption instance [Finite Ξ±] : Finite (WithTop Ξ±) := have := Fintype.ofFinite Ξ± Finite.of_fintype _ instance [Fintype Ξ±] : Fintype (WithBot Ξ±) := instFintypeOption instance [Finite Ξ±] : Finite (WithBot Ξ±) := have := Fintype.ofFinite Ξ± Finite.of_fintype _
.lake/packages/mathlib/Mathlib/Data/Fintype/Parity.lean
import Mathlib.Data.Fintype.Card import Mathlib.Algebra.Group.Even /-! # The cardinality of `Fin 2` is even. -/ variable {Ξ± : Type*} namespace Fintype instance IsSquare.decidablePred [Mul Ξ±] [Fintype Ξ±] [DecidableEq Ξ±] : DecidablePred (IsSquare : Ξ± β†’ Prop) := fun _ => Fintype.decidableExistsFintype /-- The cardinality of `Fin 2` is even, `Fact` version. This `Fact` is needed as an instance by `Matrix.SpecialLinearGroup.instNeg`. -/ instance card_fin_two : Fact (Even (Fintype.card (Fin 2))) := ⟨⟨1, rfl⟩⟩ end Fintype
.lake/packages/mathlib/Mathlib/Data/Fintype/Lattice.lean
import Mathlib.Data.Finset.Max import Mathlib.Data.Fintype.Basic /-! # Lemmas relating fintypes and order/lattice structure. -/ open Function open Nat universe u v variable {ΞΉ Ξ± Ξ² : Type*} namespace Finset variable [Fintype Ξ±] {s : Finset Ξ±} /-- A special case of `Finset.sup_eq_iSup` that omits the useless `x ∈ univ` binder. -/ theorem sup_univ_eq_iSup [CompleteLattice Ξ²] (f : Ξ± β†’ Ξ²) : Finset.univ.sup f = iSup f := (sup_eq_iSup _ f).trans <| congr_arg _ <| funext fun _ => iSup_pos (mem_univ _) /-- A special case of `Finset.inf_eq_iInf` that omits the useless `x ∈ univ` binder. -/ theorem inf_univ_eq_iInf [CompleteLattice Ξ²] (f : Ξ± β†’ Ξ²) : Finset.univ.inf f = iInf f := @sup_univ_eq_iSup _ Ξ²α΅’α΅ˆ _ _ (f : Ξ± β†’ Ξ²α΅’α΅ˆ) @[simp] theorem fold_inf_univ [SemilatticeInf Ξ±] [OrderBot Ξ±] (a : Ξ±) : (Finset.univ.fold min a fun x => x) = βŠ₯ := eq_bot_iff.2 <| ((Finset.fold_op_rel_iff_and <| @le_inf_iff Ξ± _).1 le_rfl).2 βŠ₯ <| Finset.mem_univ _ @[simp] theorem fold_sup_univ [SemilatticeSup Ξ±] [OrderTop Ξ±] (a : Ξ±) : (Finset.univ.fold max a fun x => x) = ⊀ := @fold_inf_univ Ξ±α΅’α΅ˆ _ _ _ _ lemma mem_inf [DecidableEq Ξ±] {s : Finset ΞΉ} {f : ΞΉ β†’ Finset Ξ±} {a : Ξ±} : a ∈ s.inf f ↔ βˆ€ i ∈ s, a ∈ f i := by induction s using Finset.cons_induction <;> simp [*] end Finset open Finset theorem Finite.exists_max [Finite Ξ±] [Nonempty Ξ±] [LinearOrder Ξ²] (f : Ξ± β†’ Ξ²) : βˆƒ xβ‚€ : Ξ±, βˆ€ x, f x ≀ f xβ‚€ := by cases nonempty_fintype Ξ± simpa using exists_max_image univ f univ_nonempty theorem Finite.exists_min [Finite Ξ±] [Nonempty Ξ±] [LinearOrder Ξ²] (f : Ξ± β†’ Ξ²) : βˆƒ xβ‚€ : Ξ±, βˆ€ x, f xβ‚€ ≀ f x := by cases nonempty_fintype Ξ± simpa using exists_min_image univ f univ_nonempty
.lake/packages/mathlib/Mathlib/Data/Fintype/Units.lean
import Mathlib.Algebra.Ring.Int.Units import Mathlib.Data.Fintype.Prod import Mathlib.Data.Fintype.Sum import Mathlib.SetTheory.Cardinal.Finite import Mathlib.Algebra.GroupWithZero.Units.Equiv /-! # fintype instances relating to units -/ assert_not_exists Field variable {Ξ± : Type*} instance UnitsInt.fintype : Fintype β„€Λ£ := ⟨{1, -1}, fun x ↦ by cases Int.units_eq_one_or x <;> simp [*]⟩ @[simp] theorem UnitsInt.univ : (Finset.univ : Finset β„€Λ£) = {1, -1} := rfl @[simp] theorem Fintype.card_units_int : Fintype.card β„€Λ£ = 2 := rfl instance [Monoid Ξ±] [Fintype Ξ±] [DecidableEq Ξ±] : Fintype Ξ±Λ£ := Fintype.ofEquiv _ (unitsEquivProdSubtype Ξ±).symm instance [Monoid Ξ±] [Finite Ξ±] : Finite Ξ±Λ£ := .of_injective _ Units.val_injective variable (Ξ±) theorem Nat.card_units [GroupWithZero Ξ±] : Nat.card Ξ±Λ£ = Nat.card Ξ± - 1 := by classical rw [Nat.card_congr unitsEquivNeZero, eq_comm, ← Nat.card_congr (Equiv.sumCompl (Β· = (0 : Ξ±)))] rcases finite_or_infinite {a : Ξ± // a β‰  0} Β· rw [Nat.card_sum, Nat.card_unique, add_tsub_cancel_left] Β· rw [Nat.card_eq_zero_of_infinite, Nat.card_eq_zero_of_infinite, zero_tsub] theorem Nat.card_eq_card_units_add_one [GroupWithZero Ξ±] [Finite Ξ±] : Nat.card Ξ± = Nat.card Ξ±Λ£ + 1 := by rw [Nat.card_units, tsub_add_cancel_of_le Nat.card_pos] theorem Fintype.card_units [GroupWithZero Ξ±] [Fintype Ξ±] [DecidableEq Ξ±] : Fintype.card Ξ±Λ£ = Fintype.card Ξ± - 1 := by rw [← Nat.card_eq_fintype_card, Nat.card_units, Nat.card_eq_fintype_card] theorem Fintype.card_eq_card_units_add_one [GroupWithZero Ξ±] [Fintype Ξ±] [DecidableEq Ξ±] : Fintype.card Ξ± = Fintype.card Ξ±Λ£ + 1 := by rw [Fintype.card_units, tsub_add_cancel_of_le Fintype.card_pos]
.lake/packages/mathlib/Mathlib/Data/Fintype/Inv.lean
import Mathlib.Data.Finset.Basic import Mathlib.Data.Fintype.Defs /-! # Computable inverses for injective/surjective functions on finite types ## Main results * `Function.Injective.invOfMemRange`, `Embedding.invOfMemRange`, `Fintype.bijInv`: computable versions of `Function.invFun`. * `Fintype.choose`: computably obtain a witness for `ExistsUnique`. -/ assert_not_exists Monoid open Function open Nat universe u v variable {Ξ± Ξ² Ξ³ : Type*} section Inv namespace Function variable [Fintype Ξ±] [DecidableEq Ξ²] namespace Injective variable {f : Ξ± β†’ Ξ²} (hf : Function.Injective f) /-- The inverse of an `hf : injective` function `f : Ξ± β†’ Ξ²`, of the type `β†₯(Set.range f) β†’ Ξ±`. This is the computable version of `Function.invFun` that requires `Fintype Ξ±` and `DecidableEq Ξ²`, or the function version of applying `(Equiv.ofInjective f hf).symm`. This function should not usually be used for actual computation because for most cases, an explicit inverse can be stated that has better computational properties. This function computes by checking all terms `a : Ξ±` to find the `f a = b`, so it is O(N) where `N = Fintype.card Ξ±`. -/ def invOfMemRange : Set.range f β†’ Ξ± := fun b => Finset.choose (fun a => f a = b) Finset.univ ((existsUnique_congr (by simp)).mp (hf.existsUnique_of_mem_range b.property)) theorem left_inv_of_invOfMemRange (b : Set.range f) : f (hf.invOfMemRange b) = b := (Finset.choose_spec (fun a => f a = b) _ _).right @[simp] theorem right_inv_of_invOfMemRange (a : Ξ±) : hf.invOfMemRange ⟨f a, Set.mem_range_self a⟩ = a := hf (Finset.choose_spec (fun a' => f a' = f a) _ _).right theorem invFun_restrict [Nonempty Ξ±] : (Set.range f).restrict (invFun f) = hf.invOfMemRange := by ext ⟨b, h⟩ apply hf simp [hf.left_inv_of_invOfMemRange, @invFun_eq _ _ _ f b (Set.mem_range.mp h)] theorem invOfMemRange_surjective : Function.Surjective hf.invOfMemRange := fun a => ⟨⟨f a, Set.mem_range_self a⟩, by simp⟩ end Injective namespace Embedding variable (f : Ξ± β†ͺ Ξ²) (b : Set.range f) /-- The inverse of an embedding `f : Ξ± β†ͺ Ξ²`, of the type `β†₯(Set.range f) β†’ Ξ±`. This is the computable version of `Function.invFun` that requires `Fintype Ξ±` and `DecidableEq Ξ²`, or the function version of applying `(Equiv.ofInjective f f.injective).symm`. This function should not usually be used for actual computation because for most cases, an explicit inverse can be stated that has better computational properties. This function computes by checking all terms `a : Ξ±` to find the `f a = b`, so it is O(N) where `N = Fintype.card Ξ±`. -/ def invOfMemRange : Ξ± := f.injective.invOfMemRange b @[simp] theorem left_inv_of_invOfMemRange : f (f.invOfMemRange b) = b := f.injective.left_inv_of_invOfMemRange b @[simp] theorem right_inv_of_invOfMemRange (a : Ξ±) : f.invOfMemRange ⟨f a, Set.mem_range_self a⟩ = a := f.injective.right_inv_of_invOfMemRange a theorem invFun_restrict [Nonempty Ξ±] : (Set.range f).restrict (invFun f) = f.invOfMemRange := by ext ⟨b, h⟩ apply f.injective simp [f.left_inv_of_invOfMemRange, @invFun_eq _ _ _ f b (Set.mem_range.mp h)] theorem invOfMemRange_surjective : Function.Surjective f.invOfMemRange := fun a => ⟨⟨f a, Set.mem_range_self a⟩, by simp⟩ end Embedding end Function end Inv open Finset namespace Fintype section Choose open Fintype Equiv variable [Fintype Ξ±] (p : Ξ± β†’ Prop) [DecidablePred p] /-- Given a fintype `Ξ±` and a predicate `p`, associate to a proof that there is a unique element of `Ξ±` satisfying `p` this unique element, as an element of the corresponding subtype. -/ def chooseX (hp : βˆƒ! a : Ξ±, p a) : { a // p a } := ⟨Finset.choose p univ (by simpa), Finset.choose_property _ _ _⟩ /-- Given a fintype `Ξ±` and a predicate `p`, associate to a proof that there is a unique element of `Ξ±` satisfying `p` this unique element, as an element of `Ξ±`. -/ def choose (hp : βˆƒ! a, p a) : Ξ± := chooseX p hp theorem choose_spec (hp : βˆƒ! a, p a) : p (choose p hp) := (chooseX p hp).property theorem choose_subtype_eq {Ξ± : Type*} (p : Ξ± β†’ Prop) [Fintype { a : Ξ± // p a }] [DecidableEq Ξ±] (x : { a : Ξ± // p a }) (h : βˆƒ! a : { a // p a }, (a : Ξ±) = x := ⟨x, rfl, fun y hy => by simpa [Subtype.ext_iff] using hy⟩) : Fintype.choose (fun y : { a : Ξ± // p a } => (y : Ξ±) = x) h = x := by rw [Subtype.ext_iff, Fintype.choose_spec (fun y : { a : Ξ± // p a } => (y : Ξ±) = x) _] end Choose section BijectionInverse variable [Fintype Ξ±] [DecidableEq Ξ²] {f : Ξ± β†’ Ξ²} /-- `bijInv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `Function.invFun`. -/ def bijInv (f_bij : Bijective f) (b : Ξ²) : Ξ± := Fintype.choose (fun a => f a = b) (f_bij.existsUnique b) theorem leftInverse_bijInv (f_bij : Bijective f) : LeftInverse (bijInv f_bij) f := fun a => f_bij.left (choose_spec (fun a' => f a' = f a) _) theorem rightInverse_bijInv (f_bij : Bijective f) : RightInverse (bijInv f_bij) f := fun b => choose_spec (fun a' => f a' = b) _ theorem bijective_bijInv (f_bij : Bijective f) : Bijective (bijInv f_bij) := ⟨(rightInverse_bijInv _).injective, (leftInverse_bijInv _).surjective⟩ end BijectionInverse end Fintype
.lake/packages/mathlib/Mathlib/Data/Complex/ExponentialBounds.lean
import Mathlib.Analysis.Complex.ExponentialBounds deprecated_module (since := "2025-08-26")
.lake/packages/mathlib/Mathlib/Data/Complex/Norm.lean
import Mathlib.Analysis.Complex.Norm deprecated_module (since := "2025-08-26")
.lake/packages/mathlib/Mathlib/Data/Complex/Exponential.lean
import Mathlib.Analysis.Complex.Exponential deprecated_module (since := "2025-08-26")
.lake/packages/mathlib/Mathlib/Data/Complex/Order.lean
import Mathlib.Analysis.Complex.Order deprecated_module (since := "2025-08-26")
.lake/packages/mathlib/Mathlib/Data/Complex/Basic.lean
import Mathlib.Algebra.Ring.CharZero import Mathlib.Algebra.Ring.Torsion import Mathlib.Algebra.Star.Basic import Mathlib.Data.Real.Basic import Mathlib.Order.Interval.Set.UnorderedInterval import Mathlib.Tactic.Ring /-! # The complex numbers The complex numbers are modelled as ℝ^2 in the obvious way and it is shown that they form a field of characteristic zero. For the result that the complex numbers are algebraically closed, see `Complex.isAlgClosed` in `Mathlib.Analysis.Complex.Polynomial.Basic`. -/ assert_not_exists Multiset Algebra open Set Function /-! ### Definition and basic arithmetic -/ /-- Complex numbers consist of two `Real`s: a real part `re` and an imaginary part `im`. -/ structure Complex : Type where /-- The real part of a complex number. -/ re : ℝ /-- The imaginary part of a complex number. -/ im : ℝ @[inherit_doc] notation "β„‚" => Complex namespace Complex open ComplexConjugate noncomputable instance : DecidableEq β„‚ := Classical.decEq _ /-- The equivalence between the complex numbers and `ℝ Γ— ℝ`. -/ @[simps apply] def equivRealProd : β„‚ ≃ ℝ Γ— ℝ where toFun z := ⟨z.re, z.im⟩ invFun p := ⟨p.1, p.2⟩ @[simp] theorem eta : βˆ€ z : β„‚, Complex.mk z.re z.im = z | ⟨_, _⟩ => rfl -- We only mark this lemma with `ext` *locally* to avoid it applying whenever terms of `β„‚` appear. theorem ext : βˆ€ {z w : β„‚}, z.re = w.re β†’ z.im = w.im β†’ z = w | ⟨_, _⟩, ⟨_, _⟩, rfl, rfl => rfl attribute [local ext] Complex.ext lemma Β«forallΒ» {p : β„‚ β†’ Prop} : (βˆ€ x, p x) ↔ βˆ€ a b, p ⟨a, b⟩ := by aesop lemma Β«existsΒ» {p : β„‚ β†’ Prop} : (βˆƒ x, p x) ↔ βˆƒ a b, p ⟨a, b⟩ := by aesop theorem re_surjective : Surjective re := fun x => ⟨⟨x, 0⟩, rfl⟩ theorem im_surjective : Surjective im := fun y => ⟨⟨0, y⟩, rfl⟩ @[simp] theorem range_re : range re = univ := re_surjective.range_eq @[simp] theorem range_im : range im = univ := im_surjective.range_eq /-- The natural inclusion of the real numbers into the complex numbers. -/ @[coe] def ofReal (r : ℝ) : β„‚ := ⟨r, 0⟩ instance : Coe ℝ β„‚ := ⟨ofReal⟩ @[simp, norm_cast] theorem ofReal_re (r : ℝ) : Complex.re (r : β„‚) = r := rfl @[simp, norm_cast] theorem ofReal_im (r : ℝ) : (r : β„‚).im = 0 := rfl theorem ofReal_def (r : ℝ) : (r : β„‚) = ⟨r, 0⟩ := rfl @[simp, norm_cast] theorem ofReal_inj {z w : ℝ} : (z : β„‚) = w ↔ z = w := ⟨congrArg re, by apply congrArg⟩ theorem ofReal_injective : Function.Injective ((↑) : ℝ β†’ β„‚) := fun _ _ => congrArg re instance canLift : CanLift β„‚ ℝ (↑) fun z => z.im = 0 where prf z hz := ⟨z.re, ext rfl hz.symm⟩ /-- The product of a set on the real axis and a set on the imaginary axis of the complex plane, denoted by `s Γ—β„‚ t`. -/ def reProdIm (s t : Set ℝ) : Set β„‚ := re ⁻¹' s ∩ im ⁻¹' t @[inherit_doc] infixl:72 " Γ—β„‚ " => reProdIm theorem mem_reProdIm {z : β„‚} {s t : Set ℝ} : z ∈ s Γ—β„‚ t ↔ z.re ∈ s ∧ z.im ∈ t := Iff.rfl instance : Zero β„‚ := ⟨(0 : ℝ)⟩ instance : Inhabited β„‚ := ⟨0⟩ @[simp] theorem zero_re : (0 : β„‚).re = 0 := rfl @[simp] theorem zero_im : (0 : β„‚).im = 0 := rfl @[simp, norm_cast] theorem ofReal_zero : ((0 : ℝ) : β„‚) = 0 := rfl @[simp] theorem ofReal_eq_zero {z : ℝ} : (z : β„‚) = 0 ↔ z = 0 := ofReal_inj theorem ofReal_ne_zero {z : ℝ} : (z : β„‚) β‰  0 ↔ z β‰  0 := not_congr ofReal_eq_zero instance : One β„‚ := ⟨(1 : ℝ)⟩ @[simp] theorem one_re : (1 : β„‚).re = 1 := rfl @[simp] theorem one_im : (1 : β„‚).im = 0 := rfl @[simp, norm_cast] theorem ofReal_one : ((1 : ℝ) : β„‚) = 1 := rfl @[simp] theorem ofReal_eq_one {z : ℝ} : (z : β„‚) = 1 ↔ z = 1 := ofReal_inj theorem ofReal_ne_one {z : ℝ} : (z : β„‚) β‰  1 ↔ z β‰  1 := not_congr ofReal_eq_one instance : Add β„‚ := ⟨fun z w => ⟨z.re + w.re, z.im + w.im⟩⟩ @[simp] theorem add_re (z w : β„‚) : (z + w).re = z.re + w.re := rfl @[simp] theorem add_im (z w : β„‚) : (z + w).im = z.im + w.im := rfl -- replaced by `re_ofNat` -- replaced by `im_ofNat` @[simp, norm_cast] theorem ofReal_add (r s : ℝ) : ((r + s : ℝ) : β„‚) = r + s := Complex.ext_iff.2 <| by simp [ofReal] -- replaced by `Complex.ofReal_ofNat` instance : Neg β„‚ := ⟨fun z => ⟨-z.re, -z.im⟩⟩ @[simp] theorem neg_re (z : β„‚) : (-z).re = -z.re := rfl @[simp] theorem neg_im (z : β„‚) : (-z).im = -z.im := rfl @[simp, norm_cast] theorem ofReal_neg (r : ℝ) : ((-r : ℝ) : β„‚) = -r := Complex.ext_iff.2 <| by simp [ofReal] instance : Sub β„‚ := ⟨fun z w => ⟨z.re - w.re, z.im - w.im⟩⟩ instance : Mul β„‚ := ⟨fun z w => ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩⟩ @[simp] theorem mul_re (z w : β„‚) : (z * w).re = z.re * w.re - z.im * w.im := rfl @[simp] theorem mul_im (z w : β„‚) : (z * w).im = z.re * w.im + z.im * w.re := rfl @[simp, norm_cast] theorem ofReal_mul (r s : ℝ) : ((r * s : ℝ) : β„‚) = r * s := Complex.ext_iff.2 <| by simp [ofReal] theorem re_ofReal_mul (r : ℝ) (z : β„‚) : (r * z).re = r * z.re := by simp [ofReal] theorem im_ofReal_mul (r : ℝ) (z : β„‚) : (r * z).im = r * z.im := by simp [ofReal] lemma re_mul_ofReal (z : β„‚) (r : ℝ) : (z * r).re = z.re * r := by simp [ofReal] lemma im_mul_ofReal (z : β„‚) (r : ℝ) : (z * r).im = z.im * r := by simp [ofReal] theorem ofReal_mul' (r : ℝ) (z : β„‚) : ↑r * z = ⟨r * z.re, r * z.im⟩ := ext (re_ofReal_mul _ _) (im_ofReal_mul _ _) /-! ### The imaginary unit, `I` -/ /-- The imaginary unit. -/ def I : β„‚ := ⟨0, 1⟩ @[simp] theorem I_re : I.re = 0 := rfl @[simp] theorem I_im : I.im = 1 := rfl @[simp] theorem I_mul_I : I * I = -1 := Complex.ext_iff.2 <| by simp theorem I_mul (z : β„‚) : I * z = ⟨-z.im, z.re⟩ := Complex.ext_iff.2 <| by simp @[simp] lemma I_ne_zero : (I : β„‚) β‰  0 := mt (congr_arg im) zero_ne_one.symm theorem mk_eq_add_mul_I (a b : ℝ) : Complex.mk a b = a + b * I := Complex.ext_iff.2 <| by simp [ofReal] @[simp] theorem re_add_im (z : β„‚) : (z.re : β„‚) + z.im * I = z := Complex.ext_iff.2 <| by simp [ofReal] theorem mul_I_re (z : β„‚) : (z * I).re = -z.im := by simp theorem mul_I_im (z : β„‚) : (z * I).im = z.re := by simp theorem I_mul_re (z : β„‚) : (I * z).re = -z.im := by simp theorem I_mul_im (z : β„‚) : (I * z).im = z.re := by simp @[simp] theorem equivRealProd_symm_apply (p : ℝ Γ— ℝ) : equivRealProd.symm p = p.1 + p.2 * I := by ext <;> simp [Complex.equivRealProd, ofReal] /-- The natural `AddEquiv` from `β„‚` to `ℝ Γ— ℝ`. -/ @[simps! +simpRhs apply symm_apply_re symm_apply_im] def equivRealProdAddHom : β„‚ ≃+ ℝ Γ— ℝ := { equivRealProd with map_add' := by simp } theorem equivRealProdAddHom_symm_apply (p : ℝ Γ— ℝ) : equivRealProdAddHom.symm p = p.1 + p.2 * I := equivRealProd_symm_apply p /-! ### Commutative ring instance and lemmas -/ /- We use a nonstandard formula for the `β„•` and `β„€` actions to make sure there is no diamond from the other actions they inherit through the `ℝ`-action on `β„‚` and action transitivity defined in `Data.Complex.Module`. -/ instance : Nontrivial β„‚ := domain_nontrivial re rfl rfl namespace SMul -- The useless `0` multiplication in `smul` is to make sure that -- `RestrictScalars.module ℝ β„‚ β„‚ = Complex.module` definitionally. -- instance made scoped to avoid situations like instance synthesis -- of `SMul β„‚ β„‚` trying to proceed via `SMul β„‚ ℝ`. /-- Scalar multiplication by `R` on `ℝ` extends to `β„‚`. This is used here and in `Mathlib/Data/Complex/Module.lean` to transfer instances from `ℝ` to `β„‚`, but is not needed outside, so we make it scoped. -/ scoped instance instSMulRealComplex {R : Type*} [SMul R ℝ] : SMul R β„‚ where smul r x := ⟨r β€’ x.re - 0 * x.im, r β€’ x.im + 0 * x.re⟩ end SMul open scoped SMul section SMul variable {R : Type*} [SMul R ℝ] theorem smul_re (r : R) (z : β„‚) : (r β€’ z).re = r β€’ z.re := by simp [(Β· β€’ Β·), SMul.smul] theorem smul_im (r : R) (z : β„‚) : (r β€’ z).im = r β€’ z.im := by simp [(Β· β€’ Β·), SMul.smul] @[simp] theorem real_smul {x : ℝ} {z : β„‚} : x β€’ z = x * z := rfl end SMul instance addCommGroup : AddCommGroup β„‚ where nsmul := (Β· β€’ Β·) zsmul := (Β· β€’ Β·) zsmul_zero' := by intros; ext <;> simp [smul_re, smul_im] nsmul_zero := by intros; ext <;> simp [smul_re, smul_im] nsmul_succ := by intros; ext <;> simp [smul_re, smul_im] <;> ring zsmul_succ' := by intros; ext <;> simp [smul_re, smul_im] <;> ring zsmul_neg' := by intros; ext <;> simp [smul_re, smul_im] <;> ring add_assoc := by intros; ext <;> simp <;> ring zero_add := by intros; ext <;> simp add_zero := by intros; ext <;> simp add_comm := by intros; ext <;> simp <;> ring neg_add_cancel := by intros; ext <;> simp /-! ### Casts -/ instance instNatCast : NatCast β„‚ where natCast n := ofReal n instance instIntCast : IntCast β„‚ where intCast n := ofReal n instance instNNRatCast : NNRatCast β„‚ where nnratCast q := ofReal q instance instRatCast : RatCast β„‚ where ratCast q := ofReal q @[simp, norm_cast] lemma ofReal_ofNat (n : β„•) [n.AtLeastTwo] : ofReal ofNat(n) = ofNat(n) := rfl @[simp, norm_cast] lemma ofReal_natCast (n : β„•) : ofReal n = n := rfl @[simp, norm_cast] lemma ofReal_intCast (n : β„€) : ofReal n = n := rfl @[simp, norm_cast] lemma ofReal_nnratCast (q : β„šβ‰₯0) : ofReal q = q := rfl @[simp, norm_cast] lemma ofReal_ratCast (q : β„š) : ofReal q = q := rfl @[simp] lemma re_ofNat (n : β„•) [n.AtLeastTwo] : (ofNat(n) : β„‚).re = ofNat(n) := rfl @[simp] lemma im_ofNat (n : β„•) [n.AtLeastTwo] : (ofNat(n) : β„‚).im = 0 := rfl @[simp, norm_cast] lemma natCast_re (n : β„•) : (n : β„‚).re = n := rfl @[simp, norm_cast] lemma natCast_im (n : β„•) : (n : β„‚).im = 0 := rfl @[simp, norm_cast] lemma intCast_re (n : β„€) : (n : β„‚).re = n := rfl @[simp, norm_cast] lemma intCast_im (n : β„€) : (n : β„‚).im = 0 := rfl @[simp, norm_cast] lemma re_nnratCast (q : β„šβ‰₯0) : (q : β„‚).re = q := rfl @[simp, norm_cast] lemma im_nnratCast (q : β„šβ‰₯0) : (q : β„‚).im = 0 := rfl @[simp, norm_cast] lemma ratCast_re (q : β„š) : (q : β„‚).re = q := rfl @[simp, norm_cast] lemma ratCast_im (q : β„š) : (q : β„‚).im = 0 := rfl /-! ### Ring structure -/ instance addGroupWithOne : AddGroupWithOne β„‚ := { Complex.addCommGroup with natCast_zero := by ext <;> simp natCast_succ _ := by ext <;> simp intCast_ofNat _ := by ext <;> simp intCast_negSucc _ := by ext <;> simp } instance commRing : CommRing β„‚ := { addGroupWithOne with npow := @npowRec _ ⟨(1 : β„‚)⟩ ⟨(Β· * Β·)⟩ add_comm := by intros; ext <;> simp <;> ring left_distrib := by intros; ext <;> simp [mul_re, mul_im] <;> ring right_distrib := by intros; ext <;> simp [mul_re, mul_im] <;> ring zero_mul := by intros; ext <;> simp mul_zero := by intros; ext <;> simp mul_assoc := by intros; ext <;> simp <;> ring one_mul := by intros; ext <;> simp mul_one := by intros; ext <;> simp mul_comm := by intros; ext <;> simp <;> ring } /-- This shortcut instance ensures we do not find `Ring` via the noncomputable `Complex.field` instance. -/ instance : Ring β„‚ := by infer_instance /-- This shortcut instance ensures we do not find `CommSemiring` via the noncomputable `Complex.field` instance. -/ instance : CommSemiring β„‚ := inferInstance /-- This shortcut instance ensures we do not find `Semiring` via the noncomputable `Complex.field` instance. -/ instance : Semiring β„‚ := inferInstance /-- The "real part" map, considered as an additive group homomorphism. -/ def reAddGroupHom : β„‚ β†’+ ℝ where toFun := re map_zero' := zero_re map_add' := add_re @[simp] theorem coe_reAddGroupHom : (reAddGroupHom : β„‚ β†’ ℝ) = re := rfl /-- The "imaginary part" map, considered as an additive group homomorphism. -/ def imAddGroupHom : β„‚ β†’+ ℝ where toFun := im map_zero' := zero_im map_add' := add_im @[simp] theorem coe_imAddGroupHom : (imAddGroupHom : β„‚ β†’ ℝ) = im := rfl lemma re_nsmul (n : β„•) (z : β„‚) : (n β€’ z).re = n β€’ z.re := smul_re .. lemma im_nsmul (n : β„•) (z : β„‚) : (n β€’ z).im = n β€’ z.im := smul_im .. lemma re_zsmul (n : β„€) (z : β„‚) : (n β€’ z).re = n β€’ z.re := smul_re .. lemma im_zsmul (n : β„€) (z : β„‚) : (n β€’ z).im = n β€’ z.im := smul_im .. @[simp] lemma re_nnqsmul (q : β„šβ‰₯0) (z : β„‚) : (q β€’ z).re = q β€’ z.re := smul_re .. @[simp] lemma im_nnqsmul (q : β„šβ‰₯0) (z : β„‚) : (q β€’ z).im = q β€’ z.im := smul_im .. @[simp] lemma re_qsmul (q : β„š) (z : β„‚) : (q β€’ z).re = q β€’ z.re := smul_re .. @[simp] lemma im_qsmul (q : β„š) (z : β„‚) : (q β€’ z).im = q β€’ z.im := smul_im .. @[norm_cast] lemma ofReal_nsmul (n : β„•) (r : ℝ) : ↑(n β€’ r) = n β€’ (r : β„‚) := by simp @[norm_cast] lemma ofReal_zsmul (n : β„€) (r : ℝ) : ↑(n β€’ r) = n β€’ (r : β„‚) := by simp /-! ### Complex conjugation -/ /-- This defines the complex conjugate as the `star` operation of the `StarRing β„‚`. It is recommended to use the ring endomorphism version `starRingEnd`, available under the notation `conj` in the scope `ComplexConjugate`. -/ instance : StarRing β„‚ where star z := ⟨z.re, -z.im⟩ star_involutive x := by simp only [eta, neg_neg] star_mul a b := by ext <;> simp [add_comm] <;> ring star_add a b := by ext <;> simp [add_comm] @[simp] theorem conj_re (z : β„‚) : (conj z).re = z.re := rfl @[simp] theorem conj_im (z : β„‚) : (conj z).im = -z.im := rfl @[simp] theorem conj_ofReal (r : ℝ) : conj (r : β„‚) = r := Complex.ext_iff.2 <| by simp @[simp] theorem conj_I : conj I = -I := Complex.ext_iff.2 <| by simp theorem conj_natCast (n : β„•) : conj (n : β„‚) = n := map_natCast _ _ theorem conj_ofNat (n : β„•) [n.AtLeastTwo] : conj (ofNat(n) : β„‚) = ofNat(n) := map_ofNat _ _ theorem conj_neg_I : conj (-I) = I := by simp theorem conj_eq_iff_real {z : β„‚} : conj z = z ↔ βˆƒ r : ℝ, z = r := ⟨fun h => ⟨z.re, ext rfl <| eq_zero_of_neg_eq (congr_arg im h)⟩, fun ⟨h, e⟩ => by rw [e, conj_ofReal]⟩ theorem conj_eq_iff_re {z : β„‚} : conj z = z ↔ (z.re : β„‚) = z := conj_eq_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp [ofReal], fun h => ⟨_, h.symm⟩⟩ theorem conj_eq_iff_im {z : β„‚} : conj z = z ↔ z.im = 0 := ⟨fun h => add_self_eq_zero.mp (neg_eq_iff_add_eq_zero.mp (congr_arg im h)), fun h => ext rfl (neg_eq_iff_add_eq_zero.mpr (add_self_eq_zero.mpr h))⟩ @[simp] theorem star_def : (Star.star : β„‚ β†’ β„‚) = conj := rfl /-! ### Norm squared -/ /-- The norm squared function. -/ @[pp_nodot] def normSq : β„‚ β†’*β‚€ ℝ where toFun z := z.re * z.re + z.im * z.im map_zero' := by simp map_one' := by simp map_mul' z w := by dsimp ring theorem normSq_apply (z : β„‚) : normSq z = z.re * z.re + z.im * z.im := rfl @[simp] theorem normSq_ofReal (r : ℝ) : normSq r = r * r := by simp [normSq, ofReal] @[simp] theorem normSq_natCast (n : β„•) : normSq n = n * n := normSq_ofReal _ @[simp] theorem normSq_intCast (z : β„€) : normSq z = z * z := normSq_ofReal _ @[simp] theorem normSq_ratCast (q : β„š) : normSq q = q * q := normSq_ofReal _ @[simp] theorem normSq_ofNat (n : β„•) [n.AtLeastTwo] : normSq (ofNat(n) : β„‚) = ofNat(n) * ofNat(n) := normSq_natCast _ @[simp] theorem normSq_mk (x y : ℝ) : normSq ⟨x, y⟩ = x * x + y * y := rfl theorem normSq_add_mul_I (x y : ℝ) : normSq (x + y * I) = x ^ 2 + y ^ 2 := by rw [← mk_eq_add_mul_I, normSq_mk, sq, sq] theorem normSq_eq_conj_mul_self {z : β„‚} : (normSq z : β„‚) = conj z * z := by ext <;> simp [normSq, mul_comm, ofReal] theorem normSq_zero : normSq 0 = 0 := by simp theorem normSq_one : normSq 1 = 1 := by simp @[simp] theorem normSq_I : normSq I = 1 := by simp [normSq] theorem normSq_nonneg (z : β„‚) : 0 ≀ normSq z := add_nonneg (mul_self_nonneg _) (mul_self_nonneg _) theorem normSq_eq_zero {z : β„‚} : normSq z = 0 ↔ z = 0 := ⟨fun h => ext (eq_zero_of_mul_self_add_mul_self_eq_zero h) (eq_zero_of_mul_self_add_mul_self_eq_zero <| (add_comm _ _).trans h), fun h => h.symm β–Έ normSq_zero⟩ @[simp] theorem normSq_pos {z : β„‚} : 0 < normSq z ↔ z β‰  0 := (normSq_nonneg z).lt_iff_ne.trans <| not_congr (eq_comm.trans normSq_eq_zero) @[simp] theorem normSq_neg (z : β„‚) : normSq (-z) = normSq z := by simp [normSq] @[simp] theorem normSq_conj (z : β„‚) : normSq (conj z) = normSq z := by simp [normSq] theorem normSq_mul (z w : β„‚) : normSq (z * w) = normSq z * normSq w := normSq.map_mul z w theorem normSq_add (z w : β„‚) : normSq (z + w) = normSq z + normSq w + 2 * (z * conj w).re := by dsimp [normSq]; ring theorem re_sq_le_normSq (z : β„‚) : z.re * z.re ≀ normSq z := le_add_of_nonneg_right (mul_self_nonneg _) theorem im_sq_le_normSq (z : β„‚) : z.im * z.im ≀ normSq z := le_add_of_nonneg_left (mul_self_nonneg _) theorem mul_conj (z : β„‚) : z * conj z = normSq z := Complex.ext_iff.2 <| by simp [normSq, mul_comm, sub_eq_neg_add, add_comm, ofReal] theorem add_conj (z : β„‚) : z + conj z = (2 * z.re : ℝ) := Complex.ext_iff.2 <| by simp [two_mul, ofReal] /-- The coercion `ℝ β†’ β„‚` as a `RingHom`. -/ def ofRealHom : ℝ β†’+* β„‚ where toFun x := (x : β„‚) map_one' := ofReal_one map_zero' := ofReal_zero map_mul' := ofReal_mul map_add' := ofReal_add @[simp] lemma ofRealHom_eq_coe (r : ℝ) : ofRealHom r = r := rfl variable {Ξ± : Type*} @[simp] lemma ofReal_comp_add (f g : Ξ± β†’ ℝ) : ofReal ∘ (f + g) = ofReal ∘ f + ofReal ∘ g := map_comp_add ofRealHom .. @[simp] lemma ofReal_comp_sub (f g : Ξ± β†’ ℝ) : ofReal ∘ (f - g) = ofReal ∘ f - ofReal ∘ g := map_comp_sub ofRealHom .. @[simp] lemma ofReal_comp_neg (f : Ξ± β†’ ℝ) : ofReal ∘ (-f) = -(ofReal ∘ f) := map_comp_neg ofRealHom _ lemma ofReal_comp_nsmul (n : β„•) (f : Ξ± β†’ ℝ) : ofReal ∘ (n β€’ f) = n β€’ (ofReal ∘ f) := map_comp_nsmul ofRealHom .. lemma ofReal_comp_zsmul (n : β„€) (f : Ξ± β†’ ℝ) : ofReal ∘ (n β€’ f) = n β€’ (ofReal ∘ f) := map_comp_zsmul ofRealHom .. @[simp] lemma ofReal_comp_mul (f g : Ξ± β†’ ℝ) : ofReal ∘ (f * g) = ofReal ∘ f * ofReal ∘ g := map_comp_mul ofRealHom .. @[simp] lemma ofReal_comp_pow (f : Ξ± β†’ ℝ) (n : β„•) : ofReal ∘ (f ^ n) = (ofReal ∘ f) ^ n := map_comp_pow ofRealHom .. @[simp] theorem I_sq : I ^ 2 = -1 := by rw [sq, I_mul_I] @[simp] lemma I_pow_three : I ^ 3 = -I := by rw [pow_succ, I_sq, neg_one_mul] @[simp] theorem I_pow_four : I ^ 4 = 1 := by rw [(by simp : 4 = 2 * 2), pow_mul, I_sq, neg_one_sq] lemma I_pow_eq_pow_mod (n : β„•) : I ^ n = I ^ (n % 4) := by conv_lhs => rw [← Nat.div_add_mod n 4] simp [pow_add, pow_mul, I_pow_four] @[simp] theorem sub_re (z w : β„‚) : (z - w).re = z.re - w.re := rfl @[simp] theorem sub_im (z w : β„‚) : (z - w).im = z.im - w.im := rfl @[simp, norm_cast] theorem ofReal_sub (r s : ℝ) : ((r - s : ℝ) : β„‚) = r - s := Complex.ext_iff.2 <| by simp [ofReal] @[simp, norm_cast] theorem ofReal_pow (r : ℝ) (n : β„•) : ((r ^ n : ℝ) : β„‚) = (r : β„‚) ^ n := by induction n <;> simp [*, ofReal_mul, pow_succ] theorem sub_conj (z : β„‚) : z - conj z = (2 * z.im : ℝ) * I := Complex.ext_iff.2 <| by simp [two_mul, sub_eq_add_neg, ofReal] theorem normSq_sub (z w : β„‚) : normSq (z - w) = normSq z + normSq w - 2 * (z * conj w).re := by rw [sub_eq_add_neg, normSq_add] simp only [RingHom.map_neg, mul_neg, neg_re, normSq_neg] ring /-! ### Inversion -/ noncomputable instance : Inv β„‚ := ⟨fun z => conj z * ((normSq z)⁻¹ : ℝ)⟩ theorem inv_def (z : β„‚) : z⁻¹ = conj z * ((normSq z)⁻¹ : ℝ) := rfl @[simp] theorem inv_re (z : β„‚) : z⁻¹.re = z.re / normSq z := by simp [inv_def, division_def, ofReal] @[simp] theorem inv_im (z : β„‚) : z⁻¹.im = -z.im / normSq z := by simp [inv_def, division_def, ofReal] @[simp, norm_cast] theorem ofReal_inv (r : ℝ) : ((r⁻¹ : ℝ) : β„‚) = (r : β„‚)⁻¹ := Complex.ext_iff.2 <| by simp [ofReal] protected theorem inv_zero : (0⁻¹ : β„‚) = 0 := by rw [← ofReal_zero, ← ofReal_inv, inv_zero] protected theorem mul_inv_cancel {z : β„‚} (h : z β‰  0) : z * z⁻¹ = 1 := by rw [inv_def, ← mul_assoc, mul_conj, ← ofReal_mul, mul_inv_cancelβ‚€ (mt normSq_eq_zero.1 h), ofReal_one] noncomputable instance instDivInvMonoid : DivInvMonoid β„‚ where lemma div_re (z w : β„‚) : (z / w).re = z.re * w.re / normSq w + z.im * w.im / normSq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg] lemma div_im (z w : β„‚) : (z / w).im = z.im * w.re / normSq w - z.re * w.im / normSq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm] /-! ### Field instance and lemmas -/ noncomputable instance instField : Field β„‚ where mul_inv_cancel := @Complex.mul_inv_cancel inv_zero := Complex.inv_zero nnqsmul := (Β· β€’ Β·) qsmul := (Β· β€’ Β·) nnratCast_def q := by ext <;> simp [NNRat.cast_def, div_re, div_im, mul_div_mul_comm] ratCast_def q := by ext <;> simp [Rat.cast_def, div_re, div_im, mul_div_mul_comm] nnqsmul_def n z := Complex.ext_iff.2 <| by simp [NNRat.smul_def, smul_re, smul_im] qsmul_def n z := Complex.ext_iff.2 <| by simp [Rat.smul_def, smul_re, smul_im] @[simp, norm_cast] lemma ofReal_nnqsmul (q : β„šβ‰₯0) (r : ℝ) : ofReal (q β€’ r) = q β€’ r := by simp [NNRat.smul_def] @[simp, norm_cast] lemma ofReal_qsmul (q : β„š) (r : ℝ) : ofReal (q β€’ r) = q β€’ r := by simp [Rat.smul_def] theorem conj_inv (x : β„‚) : conj x⁻¹ = (conj x)⁻¹ := star_invβ‚€ _ @[simp, norm_cast] theorem ofReal_div (r s : ℝ) : ((r / s : ℝ) : β„‚) = r / s := map_divβ‚€ ofRealHom r s @[simp, norm_cast] theorem ofReal_zpow (r : ℝ) (n : β„€) : ((r ^ n : ℝ) : β„‚) = (r : β„‚) ^ n := map_zpowβ‚€ ofRealHom r n @[simp] theorem div_I (z : β„‚) : z / I = -(z * I) := (div_eq_iff_mul_eq I_ne_zero).2 <| by simp [mul_assoc] @[simp] theorem inv_I : I⁻¹ = -I := by rw [inv_eq_one_div, div_I, one_mul] theorem normSq_inv (z : β„‚) : normSq z⁻¹ = (normSq z)⁻¹ := by simp theorem normSq_div (z w : β„‚) : normSq (z / w) = normSq z / normSq w := by simp lemma div_ofReal (z : β„‚) (x : ℝ) : z / x = ⟨z.re / x, z.im / x⟩ := by simp_rw [div_eq_inv_mul, ← ofReal_inv, ofReal_mul'] lemma div_natCast (z : β„‚) (n : β„•) : z / n = ⟨z.re / n, z.im / n⟩ := mod_cast div_ofReal z n lemma div_intCast (z : β„‚) (n : β„€) : z / n = ⟨z.re / n, z.im / n⟩ := mod_cast div_ofReal z n lemma div_ratCast (z : β„‚) (x : β„š) : z / x = ⟨z.re / x, z.im / x⟩ := mod_cast div_ofReal z x lemma div_ofNat (z : β„‚) (n : β„•) [n.AtLeastTwo] : z / ofNat(n) = ⟨z.re / ofNat(n), z.im / ofNat(n)⟩ := div_natCast z n @[simp] lemma div_ofReal_re (z : β„‚) (x : ℝ) : (z / x).re = z.re / x := by rw [div_ofReal] @[simp] lemma div_ofReal_im (z : β„‚) (x : ℝ) : (z / x).im = z.im / x := by rw [div_ofReal] @[simp] lemma div_natCast_re (z : β„‚) (n : β„•) : (z / n).re = z.re / n := by rw [div_natCast] @[simp] lemma div_natCast_im (z : β„‚) (n : β„•) : (z / n).im = z.im / n := by rw [div_natCast] @[simp] lemma div_intCast_re (z : β„‚) (n : β„€) : (z / n).re = z.re / n := by rw [div_intCast] @[simp] lemma div_intCast_im (z : β„‚) (n : β„€) : (z / n).im = z.im / n := by rw [div_intCast] @[simp] lemma div_ratCast_re (z : β„‚) (x : β„š) : (z / x).re = z.re / x := by rw [div_ratCast] @[simp] lemma div_ratCast_im (z : β„‚) (x : β„š) : (z / x).im = z.im / x := by rw [div_ratCast] @[simp] lemma div_ofNat_re (z : β„‚) (n : β„•) [n.AtLeastTwo] : (z / ofNat(n)).re = z.re / ofNat(n) := div_natCast_re z n @[simp] lemma div_ofNat_im (z : β„‚) (n : β„•) [n.AtLeastTwo] : (z / ofNat(n)).im = z.im / ofNat(n) := div_natCast_im z n /-! ### Characteristic zero -/ instance instCharZero : CharZero β„‚ := charZero_of_inj_zero fun n h => by rwa [← ofReal_natCast, ofReal_eq_zero, Nat.cast_eq_zero] at h instance instIsAddTorsionFree : IsAddTorsionFree β„‚ := IsDomain.instIsAddTorsionFreeOfCharZero _ /-- A complex number `z` plus its conjugate `conj z` is `2` times its real part. -/ theorem re_eq_add_conj (z : β„‚) : (z.re : β„‚) = (z + conj z) / 2 := by simp only [add_conj, ofReal_mul, ofReal_ofNat, mul_div_cancel_leftβ‚€ (z.re : β„‚) two_ne_zero] /-- A complex number `z` minus its conjugate `conj z` is `2i` times its imaginary part. -/ theorem im_eq_sub_conj (z : β„‚) : (z.im : β„‚) = (z - conj z) / (2 * I) := by simp only [sub_conj, ofReal_mul, ofReal_ofNat, mul_right_comm, mul_div_cancel_leftβ‚€ _ (mul_ne_zero two_ne_zero I_ne_zero : 2 * I β‰  0)] /-- Show the imaginary number ⟨x, y⟩ as an "x + y*I" string Note that the Real numbers used for x and y will show as Cauchy sequences due to the way Real numbers are represented. -/ unsafe instance instRepr : Repr β„‚ where reprPrec f p := (if p > 65 then (Std.Format.bracket "(" Β· ")") else (Β·)) <| reprPrec f.re 65 ++ " + " ++ reprPrec f.im 70 ++ "*I" section reProdIm /-- The preimage under `equivRealProd` of `s Γ—Λ’ t` is `s Γ—β„‚ t`. -/ lemma preimage_equivRealProd_prod (s t : Set ℝ) : equivRealProd ⁻¹' (s Γ—Λ’ t) = s Γ—β„‚ t := rfl /-- The inequality `s Γ— t βŠ† s₁ Γ— t₁` holds in `β„‚` iff it holds in `ℝ Γ— ℝ`. -/ lemma reProdIm_subset_iff {s s₁ t t₁ : Set ℝ} : s Γ—β„‚ t βŠ† s₁ Γ—β„‚ t₁ ↔ s Γ—Λ’ t βŠ† s₁ Γ—Λ’ t₁ := by rw [← @preimage_equivRealProd_prod s t, ← @preimage_equivRealProd_prod s₁ t₁] exact Equiv.preimage_subset equivRealProd _ _ /-- If `s βŠ† s₁ βŠ† ℝ` and `t βŠ† t₁ βŠ† ℝ`, then `s Γ— t βŠ† s₁ Γ— t₁` in `β„‚`. -/ lemma reProdIm_subset_iff' {s s₁ t t₁ : Set ℝ} : s Γ—β„‚ t βŠ† s₁ Γ—β„‚ t₁ ↔ s βŠ† s₁ ∧ t βŠ† t₁ ∨ s = βˆ… ∨ t = βˆ… := by convert prod_subset_prod_iff exact reProdIm_subset_iff variable {s t : Set ℝ} @[simp] lemma reProdIm_nonempty : (s Γ—β„‚ t).Nonempty ↔ s.Nonempty ∧ t.Nonempty := by simp [Set.Nonempty, reProdIm, Complex.exists] @[simp] lemma reProdIm_eq_empty : s Γ—β„‚ t = βˆ… ↔ s = βˆ… ∨ t = βˆ… := by simp [← not_nonempty_iff_eq_empty, reProdIm_nonempty, -not_and, not_and_or] end reProdIm open scoped Interval section Rectangle /-- A `Rectangle` is an axis-parallel rectangle with corners `z` and `w`. -/ def Rectangle (z w : β„‚) : Set β„‚ := [[z.re, w.re]] Γ—β„‚ [[z.im, w.im]] end Rectangle section Segments /-- A real segment `[a₁, aβ‚‚]` translated by `b * I` is the complex line segment. -/ lemma horizontalSegment_eq (a₁ aβ‚‚ b : ℝ) : (fun (x : ℝ) ↦ x + b * I) '' [[a₁, aβ‚‚]] = [[a₁, aβ‚‚]] Γ—β„‚ {b} := by rw [← preimage_equivRealProd_prod] ext x constructor Β· intro hx obtain ⟨x₁, hx₁, hx₁'⟩ := hx simp [← hx₁', mem_preimage, mem_prod, hx₁] Β· intro hx obtain ⟨x₁, hx₁, hx₁', hx₁''⟩ := hx refine ⟨x.re, x₁, by simp⟩ /-- A vertical segment `[b₁, bβ‚‚]` translated by `a` is the complex line segment. -/ lemma verticalSegment_eq (a b₁ bβ‚‚ : ℝ) : (fun (y : ℝ) ↦ a + y * I) '' [[b₁, bβ‚‚]] = {a} Γ—β„‚ [[b₁, bβ‚‚]] := by rw [← preimage_equivRealProd_prod] ext x constructor Β· intro hx obtain ⟨x₁, hx₁, hx₁'⟩ := hx simp [← hx₁', mem_preimage, mem_prod, hx₁] Β· intro hx simp only [equivRealProd_apply, singleton_prod, mem_image, Prod.mk.injEq, exists_eq_right_right, mem_preimage] at hx obtain ⟨x₁, hx₁, hx₁', hx₁''⟩ := hx refine ⟨x.im, x₁, by simp⟩ end Segments end Complex
.lake/packages/mathlib/Mathlib/Data/Complex/Cardinality.lean
import Mathlib.Analysis.Complex.Cardinality deprecated_module (since := "2025-08-26")
.lake/packages/mathlib/Mathlib/Data/Complex/Trigonometric.lean
import Mathlib.Analysis.Complex.Trigonometric deprecated_module (since := "2025-08-26")
.lake/packages/mathlib/Mathlib/Data/Complex/BigOperators.lean
import Mathlib.Algebra.BigOperators.Balance import Mathlib.Data.Complex.Basic /-! # Finite sums and products of complex numbers -/ open Fintype open scoped BigOperators namespace Complex variable {Ξ± : Type*} (s : Finset Ξ±) @[simp, norm_cast] theorem ofReal_prod (f : Ξ± β†’ ℝ) : ((∏ i ∈ s, f i : ℝ) : β„‚) = ∏ i ∈ s, (f i : β„‚) := map_prod ofRealHom _ _ @[simp, norm_cast] theorem ofReal_sum (f : Ξ± β†’ ℝ) : ((βˆ‘ i ∈ s, f i : ℝ) : β„‚) = βˆ‘ i ∈ s, (f i : β„‚) := map_sum ofRealHom _ _ @[simp, norm_cast] lemma ofReal_expect (f : Ξ± β†’ ℝ) : (𝔼 i ∈ s, f i : ℝ) = 𝔼 i ∈ s, (f i : β„‚) := map_expect ofRealHom .. @[simp, norm_cast] lemma ofReal_balance [Fintype Ξ±] (f : Ξ± β†’ ℝ) (a : Ξ±) : ((balance f a : ℝ) : β„‚) = balance ((↑) ∘ f) a := by simp [balance] @[simp] lemma ofReal_comp_balance {ΞΉ : Type*} [Fintype ΞΉ] (f : ΞΉ β†’ ℝ) : ofReal ∘ balance f = balance (ofReal ∘ f : ΞΉ β†’ β„‚) := funext <| ofReal_balance _ @[simp] theorem re_sum (f : Ξ± β†’ β„‚) : (βˆ‘ i ∈ s, f i).re = βˆ‘ i ∈ s, (f i).re := map_sum reAddGroupHom f s @[simp] lemma re_expect (f : Ξ± β†’ β„‚) : (𝔼 i ∈ s, f i).re = 𝔼 i ∈ s, (f i).re := map_expect (LinearMap.mk reAddGroupHom.toAddHom (by simp)) f s @[simp] lemma re_balance [Fintype Ξ±] (f : Ξ± β†’ β„‚) (a : Ξ±) : re (balance f a) = balance (re ∘ f) a := by simp [balance] @[simp] lemma re_comp_balance {ΞΉ : Type*} [Fintype ΞΉ] (f : ΞΉ β†’ β„‚) : re ∘ balance f = balance (re ∘ f) := funext <| re_balance _ @[simp] theorem im_sum (f : Ξ± β†’ β„‚) : (βˆ‘ i ∈ s, f i).im = βˆ‘ i ∈ s, (f i).im := map_sum imAddGroupHom f s @[simp] lemma im_expect (f : Ξ± β†’ β„‚) : (𝔼 i ∈ s, f i).im = 𝔼 i ∈ s, (f i).im := map_expect (LinearMap.mk imAddGroupHom.toAddHom (by simp)) f s @[simp] lemma im_balance [Fintype Ξ±] (f : Ξ± β†’ β„‚) (a : Ξ±) : im (balance f a) = balance (im ∘ f) a := by simp [balance] @[simp] lemma im_comp_balance {ΞΉ : Type*} [Fintype ΞΉ] (f : ΞΉ β†’ β„‚) : im ∘ balance f = balance (im ∘ f) := funext <| im_balance _ end Complex
.lake/packages/mathlib/Mathlib/Data/Complex/FiniteDimensional.lean
import Mathlib.LinearAlgebra.Complex.FiniteDimensional deprecated_module (since := "2025-08-26")
.lake/packages/mathlib/Mathlib/Data/Real/CompleteField.lean
import Mathlib.Algebra.Order.CompleteField import Mathlib.Data.Real.Sqrt /-! # The reals are a conditionally complete linearly ordered field -/ /-- The reals are a conditionally complete linearly ordered field. -/ noncomputable instance : ConditionallyCompleteLinearOrderedField ℝ := { } /-- There exists no nontrivial ring homomorphism `ℝ β†’+* ℝ`. -/ instance Real.RingHom.unique : Unique (ℝ β†’+* ℝ) where default := RingHom.id ℝ uniq f := congr_arg OrderRingHom.toRingHom (@Subsingleton.elim (ℝ β†’+*o ℝ) _ ⟨f, ringHom_monotone (fun r hr => ⟨√r, sq_sqrt hr⟩) f⟩ default) @[simp] theorem Real.ringHom_apply {F : Type*} [FunLike F ℝ ℝ] [RingHomClass F ℝ ℝ] (f : F) (r : ℝ) : f r = r := DFunLike.congr_fun (Unique.eq_default (RingHomClass.toRingHom f)) r
.lake/packages/mathlib/Mathlib/Data/Real/Sqrt.lean
import Mathlib.Topology.Instances.NNReal.Lemmas import Mathlib.Topology.Order.MonotoneContinuity /-! # Square root of a real number In this file we define * `NNReal.sqrt` to be the square root of a nonnegative real number. * `Real.sqrt` to be the square root of a real number, defined to be zero on negative numbers. Then we prove some basic properties of these functions. ## Implementation notes We define `NNReal.sqrt` as the noncomputable inverse to the function `x ↦ x * x`. We use general theory of inverses of strictly monotone functions to prove that `NNReal.sqrt x` exists. As a side effect, `NNReal.sqrt` is a bundled `OrderIso`, so for `NNReal` numbers we get continuity as well as theorems like `NNReal.sqrt x ≀ y ↔ x ≀ y * y` for free. Then we define `Real.sqrt x` to be `NNReal.sqrt (Real.toNNReal x)`. ## Tags square root -/ open Set Filter open scoped Filter NNReal Topology namespace NNReal variable {x y : ℝβ‰₯0} /-- Square root of a nonnegative real number. -/ @[pp_nodot] noncomputable def sqrt : ℝβ‰₯0 ≃o ℝβ‰₯0 := OrderIso.symm <| powOrderIso 2 two_ne_zero @[simp] lemma sq_sqrt (x : ℝβ‰₯0) : sqrt x ^ 2 = x := sqrt.symm_apply_apply _ @[simp] lemma sqrt_sq (x : ℝβ‰₯0) : sqrt (x ^ 2) = x := sqrt.apply_symm_apply _ @[simp] lemma mul_self_sqrt (x : ℝβ‰₯0) : sqrt x * sqrt x = x := by rw [← sq, sq_sqrt] @[simp] lemma sqrt_mul_self (x : ℝβ‰₯0) : sqrt (x * x) = x := by rw [← sq, sqrt_sq] lemma sqrt_le_sqrt : sqrt x ≀ sqrt y ↔ x ≀ y := sqrt.le_iff_le lemma sqrt_lt_sqrt : sqrt x < sqrt y ↔ x < y := sqrt.lt_iff_lt lemma sqrt_eq_iff_eq_sq : sqrt x = y ↔ x = y ^ 2 := sqrt.toEquiv.apply_eq_iff_eq_symm_apply lemma sqrt_le_iff_le_sq : sqrt x ≀ y ↔ x ≀ y ^ 2 := sqrt.to_galoisConnection _ _ lemma le_sqrt_iff_sq_le : x ≀ sqrt y ↔ x ^ 2 ≀ y := (sqrt.symm.to_galoisConnection _ _).symm @[simp] lemma sqrt_eq_zero : sqrt x = 0 ↔ x = 0 := by simp [sqrt_eq_iff_eq_sq] @[simp] lemma sqrt_eq_one : sqrt x = 1 ↔ x = 1 := by simp [sqrt_eq_iff_eq_sq] @[simp] lemma sqrt_zero : sqrt 0 = 0 := by simp @[simp] lemma sqrt_one : sqrt 1 = 1 := by simp @[simp] lemma sqrt_le_one : sqrt x ≀ 1 ↔ x ≀ 1 := by rw [← sqrt_one, sqrt_le_sqrt, sqrt_one] @[simp] lemma one_le_sqrt : 1 ≀ sqrt x ↔ 1 ≀ x := by rw [← sqrt_one, sqrt_le_sqrt, sqrt_one] theorem sqrt_mul (x y : ℝβ‰₯0) : sqrt (x * y) = sqrt x * sqrt y := by rw [sqrt_eq_iff_eq_sq, mul_pow, sq_sqrt, sq_sqrt] /-- `NNReal.sqrt` as a `MonoidWithZeroHom`. -/ noncomputable def sqrtHom : ℝβ‰₯0 β†’*β‚€ ℝβ‰₯0 := ⟨⟨sqrt, sqrt_zero⟩, sqrt_one, sqrt_mul⟩ theorem sqrt_inv (x : ℝβ‰₯0) : sqrt x⁻¹ = (sqrt x)⁻¹ := map_invβ‚€ sqrtHom x theorem sqrt_div (x y : ℝβ‰₯0) : sqrt (x / y) = sqrt x / sqrt y := map_divβ‚€ sqrtHom x y @[continuity, fun_prop] theorem continuous_sqrt : Continuous sqrt := sqrt.continuous @[simp] theorem sqrt_pos : 0 < sqrt x ↔ 0 < x := by simp [pos_iff_ne_zero] alias ⟨_, sqrt_pos_of_pos⟩ := sqrt_pos attribute [bound] sqrt_pos_of_pos @[simp] theorem isSquare (x : ℝβ‰₯0) : IsSquare x := ⟨_, mul_self_sqrt _ |>.symm⟩ end NNReal namespace Real /-- The square root of a real number. This returns 0 for negative inputs. This has notation `√x`. Note that `√x⁻¹` is parsed as `√(x⁻¹)`. -/ noncomputable def sqrt (x : ℝ) : ℝ := NNReal.sqrt (Real.toNNReal x) -- TODO: replace this with a typeclass @[inherit_doc] prefix:max "√" => Real.sqrt variable {x y : ℝ} @[simp, norm_cast] theorem coe_sqrt {x : ℝβ‰₯0} : (NNReal.sqrt x : ℝ) = √(x : ℝ) := by rw [Real.sqrt, Real.toNNReal_coe] @[continuity] theorem continuous_sqrt : Continuous (√· : ℝ β†’ ℝ) := NNReal.continuous_coe.comp <| NNReal.continuous_sqrt.comp continuous_real_toNNReal theorem sqrt_eq_zero_of_nonpos (h : x ≀ 0) : sqrt x = 0 := by simp [sqrt, Real.toNNReal_eq_zero.2 h] @[simp] theorem sqrt_nonneg (x : ℝ) : 0 ≀ √x := NNReal.coe_nonneg _ @[simp] theorem mul_self_sqrt (h : 0 ≀ x) : √x * √x = x := by rw [Real.sqrt, ← NNReal.coe_mul, NNReal.mul_self_sqrt, Real.coe_toNNReal _ h] @[simp] theorem sqrt_mul_self (h : 0 ≀ x) : √(x * x) = x := (mul_self_inj_of_nonneg (sqrt_nonneg _) h).1 (mul_self_sqrt (mul_self_nonneg _)) theorem sqrt_eq_cases : √x = y ↔ y * y = x ∧ 0 ≀ y ∨ x < 0 ∧ y = 0 := by constructor Β· rintro rfl rcases le_or_gt 0 x with hle | hlt Β· exact Or.inl ⟨mul_self_sqrt hle, sqrt_nonneg x⟩ Β· exact Or.inr ⟨hlt, sqrt_eq_zero_of_nonpos hlt.le⟩ Β· rintro (⟨rfl, hy⟩ | ⟨hx, rfl⟩) exacts [sqrt_mul_self hy, sqrt_eq_zero_of_nonpos hx.le] theorem sqrt_eq_iff_mul_self_eq (hx : 0 ≀ x) (hy : 0 ≀ y) : √x = y ↔ x = y * y := ⟨fun h => by rw [← h, mul_self_sqrt hx], fun h => by rw [h, sqrt_mul_self hy]⟩ theorem sqrt_eq_iff_mul_self_eq_of_pos (h : 0 < y) : √x = y ↔ y * y = x := by simp [sqrt_eq_cases, h.ne', h.le] @[simp] theorem sqrt_eq_one : √x = 1 ↔ x = 1 := calc √x = 1 ↔ 1 * 1 = x := sqrt_eq_iff_mul_self_eq_of_pos zero_lt_one _ ↔ x = 1 := by rw [eq_comm, mul_one] @[simp] theorem sq_sqrt (h : 0 ≀ x) : √x ^ 2 = x := by rw [sq, mul_self_sqrt h] @[simp] theorem sqrt_sq (h : 0 ≀ x) : √(x ^ 2) = x := by rw [sq, sqrt_mul_self h] theorem sqrt_eq_iff_eq_sq (hx : 0 ≀ x) (hy : 0 ≀ y) : √x = y ↔ x = y ^ 2 := by rw [sq, sqrt_eq_iff_mul_self_eq hx hy] theorem sqrt_mul_self_eq_abs (x : ℝ) : √(x * x) = |x| := by rw [← abs_mul_abs_self x, sqrt_mul_self (abs_nonneg _)] theorem sqrt_sq_eq_abs (x : ℝ) : √(x ^ 2) = |x| := by rw [sq, sqrt_mul_self_eq_abs] @[simp, grind =] theorem sqrt_zero : √0 = 0 := by simp [Real.sqrt] @[simp, grind =] theorem sqrt_one : √1 = 1 := by simp [Real.sqrt] @[simp] theorem sqrt_le_sqrt_iff (hy : 0 ≀ y) : √x ≀ √y ↔ x ≀ y := by rw [Real.sqrt, Real.sqrt, NNReal.coe_le_coe, NNReal.sqrt_le_sqrt, toNNReal_le_toNNReal_iff hy] @[simp] theorem sqrt_lt_sqrt_iff (hx : 0 ≀ x) : √x < √y ↔ x < y := lt_iff_lt_of_le_iff_le (sqrt_le_sqrt_iff hx) theorem sqrt_lt_sqrt_iff_of_pos (hy : 0 < y) : √x < √y ↔ x < y := by rw [Real.sqrt, Real.sqrt, NNReal.coe_lt_coe, NNReal.sqrt_lt_sqrt, toNNReal_lt_toNNReal_iff hy] @[bound] theorem sqrt_le_sqrt (h : x ≀ y) : √x ≀ √y := by rw [Real.sqrt, Real.sqrt, NNReal.coe_le_coe, NNReal.sqrt_le_sqrt] exact toNNReal_le_toNNReal h @[gcongr] theorem sqrt_monotone : Monotone Real.sqrt := fun _ _ ↦ sqrt_le_sqrt @[gcongr, bound] theorem sqrt_lt_sqrt (hx : 0 ≀ x) (h : x < y) : √x < √y := (sqrt_lt_sqrt_iff hx).2 h theorem sqrt_le_left (hy : 0 ≀ y) : √x ≀ y ↔ x ≀ y ^ 2 := by rw [sqrt, ← Real.le_toNNReal_iff_coe_le hy, NNReal.sqrt_le_iff_le_sq, sq, ← Real.toNNReal_mul hy, Real.toNNReal_le_toNNReal_iff (mul_self_nonneg y), sq] theorem sqrt_le_iff : √x ≀ y ↔ 0 ≀ y ∧ x ≀ y ^ 2 := by rw [← and_iff_right_of_imp fun h => (sqrt_nonneg x).trans h, and_congr_right_iff] exact sqrt_le_left theorem sqrt_lt (hx : 0 ≀ x) (hy : 0 ≀ y) : √x < y ↔ x < y ^ 2 := by rw [← sqrt_lt_sqrt_iff hx, sqrt_sq hy] theorem sqrt_lt' (hy : 0 < y) : √x < y ↔ x < y ^ 2 := by rw [← sqrt_lt_sqrt_iff_of_pos (pow_pos hy _), sqrt_sq hy.le] /-- Note: if you want to conclude `x ≀ √y`, then use `Real.le_sqrt_of_sq_le`. If you have `x > 0`, consider using `Real.le_sqrt'` -/ theorem le_sqrt (hx : 0 ≀ x) (hy : 0 ≀ y) : x ≀ √y ↔ x ^ 2 ≀ y := le_iff_le_iff_lt_iff_lt.2 <| sqrt_lt hy hx theorem le_sqrt' (hx : 0 < x) : x ≀ √y ↔ x ^ 2 ≀ y := le_iff_le_iff_lt_iff_lt.2 <| sqrt_lt' hx theorem abs_le_sqrt (h : x ^ 2 ≀ y) : |x| ≀ √y := by rw [← sqrt_sq_eq_abs]; exact sqrt_le_sqrt h theorem sq_le (h : 0 ≀ y) : x ^ 2 ≀ y ↔ -√y ≀ x ∧ x ≀ √y := by constructor Β· simpa only [abs_le] using abs_le_sqrt Β· rw [← abs_le, ← sq_abs] exact (le_sqrt (abs_nonneg x) h).mp theorem neg_sqrt_le_of_sq_le (h : x ^ 2 ≀ y) : -√y ≀ x := ((sq_le ((sq_nonneg x).trans h)).mp h).1 theorem le_sqrt_of_sq_le (h : x ^ 2 ≀ y) : x ≀ √y := ((sq_le ((sq_nonneg x).trans h)).mp h).2 @[simp] theorem sqrt_inj (hx : 0 ≀ x) (hy : 0 ≀ y) : √x = √y ↔ x = y := by simp [le_antisymm_iff, hx, hy] @[simp] theorem sqrt_eq_zero (h : 0 ≀ x) : √x = 0 ↔ x = 0 := by simpa using sqrt_inj h le_rfl theorem sqrt_eq_zero' : √x = 0 ↔ x ≀ 0 := by rw [sqrt, NNReal.coe_eq_zero, NNReal.sqrt_eq_zero, Real.toNNReal_eq_zero] theorem sqrt_ne_zero (h : 0 ≀ x) : √x β‰  0 ↔ x β‰  0 := by rw [not_iff_not, sqrt_eq_zero h] theorem sqrt_ne_zero' : √x β‰  0 ↔ 0 < x := by rw [← not_le, not_iff_not, sqrt_eq_zero'] /-- Variant of `sq_sqrt` without a non-negativity assumption on `x`. -/ theorem sq_sqrt' : √x ^ 2 = max x 0 := by rcases lt_trichotomy x 0 with _ | _ | _ <;> grind [sqrt_eq_zero', sq_sqrt] -- Add the rule for `√x ^ 2` to the grind whiteboard whenever we see a real square root. grind_pattern sq_sqrt' => √x -- Check that `grind` can discharge non-zero goals for square roots of positive numerals. example : √7 β‰  0 := by grind @[simp] theorem sqrt_pos : 0 < √x ↔ 0 < x := lt_iff_lt_of_le_iff_le (Iff.trans (by simp [le_antisymm_iff, sqrt_nonneg]) sqrt_eq_zero') alias ⟨_, sqrt_pos_of_pos⟩ := sqrt_pos lemma sqrt_le_sqrt_iff' (hx : 0 < x) : √x ≀ √y ↔ x ≀ y := by obtain hy | hy := le_total y 0 Β· exact iff_of_false ((sqrt_eq_zero_of_nonpos hy).trans_lt <| sqrt_pos.2 hx).not_ge (hy.trans_lt hx).not_ge Β· exact sqrt_le_sqrt_iff hy @[simp] lemma one_le_sqrt : 1 ≀ √x ↔ 1 ≀ x := by rw [← sqrt_one, sqrt_le_sqrt_iff' zero_lt_one, sqrt_one] @[simp] lemma sqrt_le_one : √x ≀ 1 ↔ x ≀ 1 := by rw [← sqrt_one, sqrt_le_sqrt_iff zero_le_one, sqrt_one] @[simp] lemma isSquare_iff : IsSquare x ↔ 0 ≀ x := ⟨(Β·.nonneg), (⟨√x, mul_self_sqrt Β· |>.symm⟩)⟩ end Real namespace Mathlib.Meta.Positivity open Lean Meta Qq Function /-- Extension for the `positivity` tactic: a square root of a strictly positive nonnegative real is positive. -/ @[positivity NNReal.sqrt _] def evalNNRealSqrt : PositivityExt where eval {u Ξ±} _zΞ± _pΞ± e := do match u, Ξ±, e with | 0, ~q(NNReal), ~q(NNReal.sqrt $a) => let ra ← core q(inferInstance) q(inferInstance) a assertInstancesCommute match ra with | .positive pa => pure (.positive q(NNReal.sqrt_pos_of_pos $pa)) | _ => failure -- this case is dealt with by generic nonnegativity of nnreals | _, _, _ => throwError "not NNReal.sqrt" /-- Extension for the `positivity` tactic: a square root is nonnegative, and is strictly positive if its input is. -/ @[positivity √_] def evalSqrt : PositivityExt where eval {u Ξ±} _zΞ± _pΞ± e := do match u, Ξ±, e with | 0, ~q(ℝ), ~q(√$a) => let ra ← catchNone <| core q(inferInstance) q(inferInstance) a assertInstancesCommute match ra with | .positive pa => pure (.positive q(Real.sqrt_pos_of_pos $pa)) | _ => pure (.nonnegative q(Real.sqrt_nonneg $a)) | _, _, _ => throwError "not Real.sqrt" end Mathlib.Meta.Positivity namespace Real lemma one_lt_sqrt_two : 1 < √2 := by rw [← Real.sqrt_one]; gcongr; simp lemma sqrt_two_lt_three_halves : √2 < 3 / 2 := by suffices 2 * √2 < 3 by linarith rw [← sq_lt_sqβ‚€ (by positivity) (by positivity), mul_pow, Real.sq_sqrt (by positivity)] norm_num lemma inv_sqrt_two_sub_one : (√2 - 1)⁻¹ = √2 + 1 := by grind @[simp] theorem sqrt_mul {x : ℝ} (hx : 0 ≀ x) (y : ℝ) : √(x * y) = √x * √y := by simp_rw [Real.sqrt, ← NNReal.coe_mul, NNReal.coe_inj, Real.toNNReal_mul hx, NNReal.sqrt_mul] @[simp] theorem sqrt_mul' (x) {y : ℝ} (hy : 0 ≀ y) : √(x * y) = √x * √y := by rw [mul_comm, sqrt_mul hy, mul_comm] @[simp] theorem sqrt_inv (x : ℝ) : √x⁻¹ = (√x)⁻¹ := by rw [Real.sqrt, Real.toNNReal_inv, NNReal.sqrt_inv, NNReal.coe_inv, Real.sqrt] @[simp] theorem sqrt_div {x : ℝ} (hx : 0 ≀ x) (y : ℝ) : √(x / y) = √x / √y := by rw [division_def, sqrt_mul hx, sqrt_inv, division_def] @[simp] theorem sqrt_div' (x) {y : ℝ} (hy : 0 ≀ y) : √(x / y) = √x / √y := by rw [division_def, sqrt_mul' x (inv_nonneg.2 hy), sqrt_inv, division_def] variable {x y : ℝ} @[simp] theorem div_sqrt : x / √x = √x := by grind theorem sqrt_div_self' : √x / x = 1 / √x := by rw [← div_sqrt, one_div_div, div_sqrt] theorem sqrt_div_self : √x / x = (√x)⁻¹ := by rw [sqrt_div_self', one_div] theorem lt_sqrt (hx : 0 ≀ x) : x < √y ↔ x ^ 2 < y := by rw [← sqrt_lt_sqrt_iff (sq_nonneg _), sqrt_sq hx] theorem sq_lt : x ^ 2 < y ↔ -√y < x ∧ x < √y := by rw [← abs_lt, ← sq_abs, lt_sqrt (abs_nonneg _)] theorem neg_sqrt_lt_of_sq_lt (h : x ^ 2 < y) : -√y < x := (sq_lt.mp h).1 theorem lt_sqrt_of_sq_lt (h : x ^ 2 < y) : x < √y := (sq_lt.mp h).2 theorem lt_sq_of_sqrt_lt (h : √x < y) : x < y ^ 2 := by have hy := x.sqrt_nonneg.trans_lt h rwa [← sqrt_lt_sqrt_iff_of_pos (sq_pos_of_pos hy), sqrt_sq hy.le] /-- The natural square root is at most the real square root -/ theorem nat_sqrt_le_real_sqrt {a : β„•} : ↑(Nat.sqrt a) ≀ √(a : ℝ) := by rw [Real.le_sqrt (Nat.cast_nonneg _) (Nat.cast_nonneg _)] norm_cast exact Nat.sqrt_le' a /-- The real square root is less than the natural square root plus one -/ theorem real_sqrt_lt_nat_sqrt_succ {a : β„•} : √(a : ℝ) < Nat.sqrt a + 1 := by rw [sqrt_lt (by simp)] <;> norm_cast Β· exact Nat.lt_succ_sqrt' a Β· exact Nat.le_add_left 0 (Nat.sqrt a + 1) /-- The real square root is at most the natural square root plus one -/ theorem real_sqrt_le_nat_sqrt_succ {a : β„•} : √(a : ℝ) ≀ Nat.sqrt a + 1 := real_sqrt_lt_nat_sqrt_succ.le /-- The floor of the real square root is the same as the natural square root. -/ @[simp] theorem floor_real_sqrt_eq_nat_sqrt {a : β„•} : ⌊√(a : ℝ)βŒ‹ = Nat.sqrt a := by rw [Int.floor_eq_iff] exact ⟨nat_sqrt_le_real_sqrt, real_sqrt_lt_nat_sqrt_succ⟩ /-- The natural floor of the real square root is the same as the natural square root. -/ @[simp] theorem nat_floor_real_sqrt_eq_nat_sqrt {a : β„•} : ⌊√(a : ℝ)βŒ‹β‚Š = Nat.sqrt a := by rw [Nat.floor_eq_iff (sqrt_nonneg a)] exact ⟨nat_sqrt_le_real_sqrt, real_sqrt_lt_nat_sqrt_succ⟩ /-- Bernoulli's inequality for exponent `1 / 2`, stated using `sqrt`. -/ theorem sqrt_one_add_le (h : -1 ≀ x) : √(1 + x) ≀ 1 + x / 2 := by refine sqrt_le_iff.mpr ⟨by linarith, ?_⟩ calc 1 + x _ ≀ 1 + x + (x / 2) ^ 2 := le_add_of_nonneg_right <| sq_nonneg _ _ = _ := by ring end Real open Real variable {Ξ± : Type*} theorem Filter.Tendsto.sqrt {f : Ξ± β†’ ℝ} {l : Filter Ξ±} {x : ℝ} (h : Tendsto f l (𝓝 x)) : Tendsto (fun x => √(f x)) l (𝓝 (√x)) := (continuous_sqrt.tendsto _).comp h variable [TopologicalSpace Ξ±] {f : Ξ± β†’ ℝ} {s : Set Ξ±} {x : Ξ±} nonrec theorem ContinuousWithinAt.sqrt (h : ContinuousWithinAt f s x) : ContinuousWithinAt (fun x => √(f x)) s x := h.sqrt @[fun_prop] nonrec theorem ContinuousAt.sqrt (h : ContinuousAt f x) : ContinuousAt (fun x => √(f x)) x := h.sqrt @[fun_prop] theorem ContinuousOn.sqrt (h : ContinuousOn f s) : ContinuousOn (fun x => √(f x)) s := fun x hx => (h x hx).sqrt @[continuity, fun_prop] theorem Continuous.sqrt (h : Continuous f) : Continuous fun x => √(f x) := continuous_sqrt.comp h namespace NNReal variable {ΞΉ : Type*} open Finset /-- **Cauchy-Schwarz inequality** for finsets using square roots in `ℝβ‰₯0`. -/ lemma sum_mul_le_sqrt_mul_sqrt (s : Finset ΞΉ) (f g : ΞΉ β†’ ℝβ‰₯0) : βˆ‘ i ∈ s, f i * g i ≀ sqrt (βˆ‘ i ∈ s, f i ^ 2) * sqrt (βˆ‘ i ∈ s, g i ^ 2) := (le_sqrt_iff_sq_le.2 <| sum_mul_sq_le_sq_mul_sq _ _ _).trans_eq <| sqrt_mul _ _ /-- **Cauchy-Schwarz inequality** for finsets using square roots in `ℝβ‰₯0`. -/ lemma sum_sqrt_mul_sqrt_le (s : Finset ΞΉ) (f g : ΞΉ β†’ ℝβ‰₯0) : βˆ‘ i ∈ s, sqrt (f i) * sqrt (g i) ≀ sqrt (βˆ‘ i ∈ s, f i) * sqrt (βˆ‘ i ∈ s, g i) := by simpa [*] using sum_mul_le_sqrt_mul_sqrt _ (fun x ↦ sqrt (f x)) (fun x ↦ sqrt (g x)) end NNReal namespace Real variable {ΞΉ : Type*} {f g : ΞΉ β†’ ℝ} open Finset /-- **Cauchy-Schwarz inequality** for finsets using square roots in `ℝ`. -/ lemma sum_mul_le_sqrt_mul_sqrt (s : Finset ΞΉ) (f g : ΞΉ β†’ ℝ) : βˆ‘ i ∈ s, f i * g i ≀ √(βˆ‘ i ∈ s, f i ^ 2) * √(βˆ‘ i ∈ s, g i ^ 2) := (le_sqrt_of_sq_le <| sum_mul_sq_le_sq_mul_sq _ _ _).trans_eq <| sqrt_mul (sum_nonneg fun _ _ ↦ by positivity) _ /-- **Cauchy-Schwarz inequality** for finsets using square roots in `ℝ`. -/ lemma sum_sqrt_mul_sqrt_le (s : Finset ΞΉ) (hf : βˆ€ i, 0 ≀ f i) (hg : βˆ€ i, 0 ≀ g i) : βˆ‘ i ∈ s, √(f i) * √(g i) ≀ √(βˆ‘ i ∈ s, f i) * √(βˆ‘ i ∈ s, g i) := by simpa [*] using sum_mul_le_sqrt_mul_sqrt _ (fun x ↦ √(f x)) (fun x ↦ √(g x)) end Real
.lake/packages/mathlib/Mathlib/Data/Real/Sign.lean
import Mathlib.Data.Real.Basic /-! # Real sign function This file introduces and contains some results about `Real.sign` which maps negative real numbers to -1, positive real numbers to 1, and 0 to 0. ## Main definitions * `Real.sign r` is $\begin{cases} -1 & \text{if } r < 0, \\ ~~\, 0 & \text{if } r = 0, \\ ~~\, 1 & \text{if } r > 0. \end{cases}$ ## Tags sign function -/ namespace Real /-- The sign function that maps negative real numbers to -1, positive numbers to 1, and 0 otherwise. -/ noncomputable def sign (r : ℝ) : ℝ := if r < 0 then -1 else if 0 < r then 1 else 0 theorem sign_of_neg {r : ℝ} (hr : r < 0) : sign r = -1 := by rw [sign, if_pos hr] theorem sign_of_pos {r : ℝ} (hr : 0 < r) : sign r = 1 := by rw [sign, if_pos hr, if_neg hr.not_gt] @[simp] theorem sign_zero : sign 0 = 0 := by rw [sign, if_neg (lt_irrefl _), if_neg (lt_irrefl _)] @[simp] theorem sign_one : sign 1 = 1 := sign_of_pos <| by simp theorem sign_apply_eq (r : ℝ) : sign r = -1 ∨ sign r = 0 ∨ sign r = 1 := by obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ) Β· exact Or.inl <| sign_of_neg hn Β· exact Or.inr <| Or.inl <| sign_zero Β· exact Or.inr <| Or.inr <| sign_of_pos hp /-- This lemma is useful for working with `ℝˣ` -/ theorem sign_apply_eq_of_ne_zero (r : ℝ) (h : r β‰  0) : sign r = -1 ∨ sign r = 1 := h.lt_or_gt.imp sign_of_neg sign_of_pos @[simp] theorem sign_eq_zero_iff {r : ℝ} : sign r = 0 ↔ r = 0 := by refine ⟨fun h => ?_, fun h => h.symm β–Έ sign_zero⟩ obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ) Β· rw [sign_of_neg hn, neg_eq_zero] at h exact (one_ne_zero h).elim Β· rfl Β· rw [sign_of_pos hp] at h exact (one_ne_zero h).elim theorem sign_intCast (z : β„€) : sign (z : ℝ) = ↑(Int.sign z) := by obtain hn | rfl | hp := lt_trichotomy z (0 : β„€) Β· rw [sign_of_neg (Int.cast_lt_zero.mpr hn), Int.sign_eq_neg_one_of_neg hn, Int.cast_neg, Int.cast_one] Β· rw [Int.cast_zero, sign_zero, Int.sign_zero, Int.cast_zero] Β· rw [sign_of_pos (Int.cast_pos.mpr hp), Int.sign_eq_one_of_pos hp, Int.cast_one] theorem sign_neg {r : ℝ} : sign (-r) = -sign r := by obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ) Β· rw [sign_of_neg hn, sign_of_pos (neg_pos.mpr hn), neg_neg] Β· rw [sign_zero, neg_zero, sign_zero] Β· rw [sign_of_pos hp, sign_of_neg (neg_lt_zero.mpr hp)] theorem sign_mul_nonneg (r : ℝ) : 0 ≀ sign r * r := by obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ) Β· rw [sign_of_neg hn] exact mul_nonneg_of_nonpos_of_nonpos (by simp) hn.le Β· rw [mul_zero] Β· rw [sign_of_pos hp, one_mul] exact hp.le theorem sign_mul_pos_of_ne_zero (r : ℝ) (hr : r β‰  0) : 0 < sign r * r := by refine lt_of_le_of_ne (sign_mul_nonneg r) fun h => hr ?_ have hs0 := (zero_eq_mul.mp h).resolve_right hr exact sign_eq_zero_iff.mp hs0 @[simp] theorem inv_sign (r : ℝ) : (sign r)⁻¹ = sign r := by obtain hn | hz | hp := sign_apply_eq r Β· rw [hn] simp Β· rw [hz] exact inv_zero Β· rw [hp] exact inv_one @[simp] theorem sign_inv (r : ℝ) : sign r⁻¹ = sign r := by obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ) Β· rw [sign_of_neg hn, sign_of_neg (inv_lt_zero.mpr hn)] Β· rw [sign_zero, inv_zero, sign_zero] Β· rw [sign_of_pos hp, sign_of_pos (inv_pos.mpr hp)] end Real
.lake/packages/mathlib/Mathlib/Data/Real/ENatENNReal.lean
import Mathlib.Data.ENat.Basic import Mathlib.Data.ENNReal.Basic /-! # Coercion from `β„•βˆž` to `ℝβ‰₯0∞` In this file we define a coercion from `β„•βˆž` to `ℝβ‰₯0∞` and prove some basic lemmas about this map. -/ assert_not_exists Finset open NNReal ENNReal noncomputable section namespace ENat variable {m n : β„•βˆž} /-- Coercion from `β„•βˆž` to `ℝβ‰₯0∞`. -/ @[coe] def toENNReal : β„•βˆž β†’ ℝβ‰₯0∞ := ENat.map Nat.cast instance hasCoeENNReal : CoeTC β„•βˆž ℝβ‰₯0∞ := ⟨toENNReal⟩ @[simp] theorem map_coe_nnreal : ENat.map ((↑) : β„• β†’ ℝβ‰₯0) = ((↑) : β„•βˆž β†’ ℝβ‰₯0∞) := rfl /-- Coercion `β„•βˆž β†’ ℝβ‰₯0∞` as an `OrderEmbedding`. -/ @[simps! -fullyApplied] def toENNRealOrderEmbedding : β„•βˆž β†ͺo ℝβ‰₯0∞ := Nat.castOrderEmbedding.withTopMap /-- Coercion `β„•βˆž β†’ ℝβ‰₯0∞` as a ring homomorphism. -/ @[simps! -fullyApplied] def toENNRealRingHom : β„•βˆž β†’+* ℝβ‰₯0∞ := .ENatMap (Nat.castRingHom ℝβ‰₯0) Nat.cast_injective @[simp, norm_cast] theorem toENNReal_top : ((⊀ : β„•βˆž) : ℝβ‰₯0∞) = ⊀ := rfl @[simp, norm_cast] theorem toENNReal_coe (n : β„•) : ((n : β„•βˆž) : ℝβ‰₯0∞) = n := rfl @[simp, norm_cast] theorem toENNReal_ofNat (n : β„•) [n.AtLeastTwo] : ((ofNat(n) : β„•βˆž) : ℝβ‰₯0∞) = ofNat(n) := rfl @[simp, norm_cast] theorem toENNReal_inj : (m : ℝβ‰₯0∞) = (n : ℝβ‰₯0∞) ↔ m = n := toENNRealOrderEmbedding.eq_iff_eq @[simp, norm_cast] lemma toENNReal_eq_top : (n : ℝβ‰₯0∞) = ∞ ↔ n = ⊀ := by simp [← toENNReal_inj] @[norm_cast] lemma toENNReal_ne_top : (n : ℝβ‰₯0∞) β‰  ∞ ↔ n β‰  ⊀ := by simp @[simp, norm_cast] theorem toENNReal_le : (m : ℝβ‰₯0∞) ≀ n ↔ m ≀ n := toENNRealOrderEmbedding.le_iff_le @[simp, norm_cast] theorem toENNReal_lt : (m : ℝβ‰₯0∞) < n ↔ m < n := toENNRealOrderEmbedding.lt_iff_lt @[simp, norm_cast] lemma toENNReal_lt_top : (n : ℝβ‰₯0∞) < ∞ ↔ n < ⊀ := by simp [← toENNReal_lt] @[mono] theorem toENNReal_mono : Monotone ((↑) : β„•βˆž β†’ ℝβ‰₯0∞) := toENNRealOrderEmbedding.monotone @[mono] theorem toENNReal_strictMono : StrictMono ((↑) : β„•βˆž β†’ ℝβ‰₯0∞) := toENNRealOrderEmbedding.strictMono @[simp, norm_cast] theorem toENNReal_zero : ((0 : β„•βˆž) : ℝβ‰₯0∞) = 0 := map_zero toENNRealRingHom @[simp, norm_cast] theorem toENNReal_add (m n : β„•βˆž) : ↑(m + n) = (m + n : ℝβ‰₯0∞) := map_add toENNRealRingHom m n @[simp, norm_cast] theorem toENNReal_one : ((1 : β„•βˆž) : ℝβ‰₯0∞) = 1 := map_one toENNRealRingHom @[simp, norm_cast] theorem toENNReal_mul (m n : β„•βˆž) : ↑(m * n) = (m * n : ℝβ‰₯0∞) := map_mul toENNRealRingHom m n @[simp, norm_cast] theorem toENNReal_pow (x : β„•βˆž) (n : β„•) : (x ^ n : β„•βˆž) = (x : ℝβ‰₯0∞) ^ n := RingHom.map_pow toENNRealRingHom x n @[simp, norm_cast] theorem toENNReal_min (m n : β„•βˆž) : ↑(min m n) = (min m n : ℝβ‰₯0∞) := toENNReal_mono.map_min @[simp, norm_cast] theorem toENNReal_max (m n : β„•βˆž) : ↑(max m n) = (max m n : ℝβ‰₯0∞) := toENNReal_mono.map_max @[simp, norm_cast] theorem toENNReal_sub (m n : β„•βˆž) : ↑(m - n) = (m - n : ℝβ‰₯0∞) := WithTop.map_sub Nat.cast_tsub Nat.cast_zero m n end ENat
.lake/packages/mathlib/Mathlib/Data/Real/Star.lean
import Mathlib.Algebra.Star.Basic import Mathlib.Data.Real.Basic /-! # The real numbers are a `*`-ring, with the trivial `*`-structure -/ /-- The real numbers are a `*`-ring, with the trivial `*`-structure. -/ instance : StarRing ℝ := starRingOfComm instance : TrivialStar ℝ := ⟨fun _ => rfl⟩
.lake/packages/mathlib/Mathlib/Data/Real/Pointwise.lean
import Mathlib.Algebra.GroupWithZero.Action.Pointwise.Set import Mathlib.Algebra.Order.Module.Pointwise import Mathlib.Data.Real.Archimedean /-! # Pointwise operations on sets of reals This file relates `sInf (a β€’ s)`/`sSup (a β€’ s)` with `a β€’ sInf s`/`a β€’ sSup s` for `s : Set ℝ`. From these, it relates `β¨… i, a β€’ f i` / `⨆ i, a β€’ f i` with `a β€’ (β¨… i, f i)` / `a β€’ (⨆ i, f i)`, and provides lemmas about distributing `*` over `β¨…` and `⨆`. ## TODO This is true more generally for conditionally complete linear order whose default value is `0`. We don't have those yet. -/ assert_not_exists Finset open Set open Pointwise variable {ΞΉ : Sort*} {Ξ± : Type*} [Field Ξ±] [LinearOrder Ξ±] [IsStrictOrderedRing Ξ±] section MulActionWithZero variable [MulActionWithZero Ξ± ℝ] [IsOrderedModule Ξ± ℝ] {a : Ξ±} theorem Real.sInf_smul_of_nonneg (ha : 0 ≀ a) (s : Set ℝ) : sInf (a β€’ s) = a β€’ sInf s := by obtain rfl | hs := s.eq_empty_or_nonempty Β· rw [smul_set_empty, Real.sInf_empty, smul_zero] obtain rfl | ha' := ha.eq_or_lt Β· rw [zero_smul_set hs, zero_smul] exact csInf_singleton 0 by_cases h : BddBelow s Β· exact ((OrderIso.smulRight ha').map_csInf' hs h).symm Β· rw [Real.sInf_of_not_bddBelow (mt (bddBelow_smul_iff_of_pos ha').1 h), Real.sInf_of_not_bddBelow h, smul_zero] theorem Real.smul_iInf_of_nonneg (ha : 0 ≀ a) (f : ΞΉ β†’ ℝ) : (a β€’ β¨… i, f i) = β¨… i, a β€’ f i := (Real.sInf_smul_of_nonneg ha _).symm.trans <| congr_arg sInf <| (range_comp _ _).symm theorem Real.sSup_smul_of_nonneg (ha : 0 ≀ a) (s : Set ℝ) : sSup (a β€’ s) = a β€’ sSup s := by obtain rfl | hs := s.eq_empty_or_nonempty Β· rw [smul_set_empty, Real.sSup_empty, smul_zero] obtain rfl | ha' := ha.eq_or_lt Β· rw [zero_smul_set hs, zero_smul] exact csSup_singleton 0 by_cases h : BddAbove s Β· exact ((OrderIso.smulRight ha').map_csSup' hs h).symm Β· rw [Real.sSup_of_not_bddAbove (mt (bddAbove_smul_iff_of_pos ha').1 h), Real.sSup_of_not_bddAbove h, smul_zero] theorem Real.smul_iSup_of_nonneg (ha : 0 ≀ a) (f : ΞΉ β†’ ℝ) : (a β€’ ⨆ i, f i) = ⨆ i, a β€’ f i := (Real.sSup_smul_of_nonneg ha _).symm.trans <| congr_arg sSup <| (range_comp _ _).symm end MulActionWithZero section Module variable [Module Ξ± ℝ] [IsOrderedModule Ξ± ℝ] {a : Ξ±} theorem Real.sInf_smul_of_nonpos (ha : a ≀ 0) (s : Set ℝ) : sInf (a β€’ s) = a β€’ sSup s := by obtain rfl | hs := s.eq_empty_or_nonempty Β· rw [smul_set_empty, Real.sInf_empty, Real.sSup_empty, smul_zero] obtain rfl | ha' := ha.eq_or_lt Β· rw [zero_smul_set hs, zero_smul] exact csInf_singleton 0 by_cases h : BddAbove s Β· exact ((OrderIso.smulRightDual ℝ ha').map_csSup' hs h).symm Β· rw [Real.sInf_of_not_bddBelow (mt (bddBelow_smul_iff_of_neg ha').1 h), Real.sSup_of_not_bddAbove h, smul_zero] theorem Real.smul_iSup_of_nonpos (ha : a ≀ 0) (f : ΞΉ β†’ ℝ) : (a β€’ ⨆ i, f i) = β¨… i, a β€’ f i := (Real.sInf_smul_of_nonpos ha _).symm.trans <| congr_arg sInf <| (range_comp _ _).symm theorem Real.sSup_smul_of_nonpos (ha : a ≀ 0) (s : Set ℝ) : sSup (a β€’ s) = a β€’ sInf s := by obtain rfl | hs := s.eq_empty_or_nonempty Β· rw [smul_set_empty, Real.sSup_empty, Real.sInf_empty, smul_zero] obtain rfl | ha' := ha.eq_or_lt Β· rw [zero_smul_set hs, zero_smul] exact csSup_singleton 0 by_cases h : BddBelow s Β· exact ((OrderIso.smulRightDual ℝ ha').map_csInf' hs h).symm Β· rw [Real.sSup_of_not_bddAbove (mt (bddAbove_smul_iff_of_neg ha').1 h), Real.sInf_of_not_bddBelow h, smul_zero] theorem Real.smul_iInf_of_nonpos (ha : a ≀ 0) (f : ΞΉ β†’ ℝ) : (a β€’ β¨… i, f i) = ⨆ i, a β€’ f i := (Real.sSup_smul_of_nonpos ha _).symm.trans <| congr_arg sSup <| (range_comp _ _).symm end Module /-! ## Special cases for real multiplication -/ section Mul variable {r : ℝ} theorem Real.mul_iInf_of_nonneg (ha : 0 ≀ r) (f : ΞΉ β†’ ℝ) : (r * β¨… i, f i) = β¨… i, r * f i := Real.smul_iInf_of_nonneg ha f theorem Real.mul_iSup_of_nonneg (ha : 0 ≀ r) (f : ΞΉ β†’ ℝ) : (r * ⨆ i, f i) = ⨆ i, r * f i := Real.smul_iSup_of_nonneg ha f theorem Real.mul_iInf_of_nonpos (ha : r ≀ 0) (f : ΞΉ β†’ ℝ) : (r * β¨… i, f i) = ⨆ i, r * f i := Real.smul_iInf_of_nonpos ha f theorem Real.mul_iSup_of_nonpos (ha : r ≀ 0) (f : ΞΉ β†’ ℝ) : (r * ⨆ i, f i) = β¨… i, r * f i := Real.smul_iSup_of_nonpos ha f theorem Real.iInf_mul_of_nonneg (ha : 0 ≀ r) (f : ΞΉ β†’ ℝ) : (β¨… i, f i) * r = β¨… i, f i * r := by simp only [Real.mul_iInf_of_nonneg ha, mul_comm] theorem Real.iSup_mul_of_nonneg (ha : 0 ≀ r) (f : ΞΉ β†’ ℝ) : (⨆ i, f i) * r = ⨆ i, f i * r := by simp only [Real.mul_iSup_of_nonneg ha, mul_comm] theorem Real.iInf_mul_of_nonpos (ha : r ≀ 0) (f : ΞΉ β†’ ℝ) : (β¨… i, f i) * r = ⨆ i, f i * r := by simp only [Real.mul_iInf_of_nonpos ha, mul_comm] theorem Real.iSup_mul_of_nonpos (ha : r ≀ 0) (f : ΞΉ β†’ ℝ) : (⨆ i, f i) * r = β¨… i, f i * r := by simp only [Real.mul_iSup_of_nonpos ha, mul_comm] end Mul
.lake/packages/mathlib/Mathlib/Data/Real/ConjExponents.lean
import Mathlib.Data.ENNReal.Holder import Mathlib.Tactic.LinearCombination /-! # Real conjugate exponents This file defines HΓΆlder triple and HΓΆlder conjugate exponents in `ℝ` and `ℝβ‰₯0`. Real numbers `p`, `q` and `r` form a *HΓΆlder triple* if `0 < p` and `0 < q` and `p⁻¹ + q⁻¹ = r⁻¹` (which of course implies `0 < r`). We say `p` and `q` are *HΓΆlder conjugate* if `p`, `q` and `1` are a HΓΆlder triple. In this case, `1 < p` and `1 < q`. This property shows up often in analysis, especially when dealing with `L^p` spaces. These notions mimic the same notions for extended nonnegative reals where `p q r : ℝβ‰₯0∞` are allowed to take the values `0` and `∞`. ## Main declarations * `Real.HolderTriple`: Predicate for two real numbers to be a HΓΆlder triple. * `Real.HolderConjugate`: Predicate for two real numbers to be HΓΆlder conjugate. * `Real.conjExponent`: Conjugate exponent of a real number. * `NNReal.HolderTriple`: Predicate for two nonnegative real numbers to be a HΓΆlder triple. * `NNReal.HolderConjugate`: Predicate for two nonnegative real numbers to be HΓΆlder conjugate. * `NNReal.conjExponent`: Conjugate exponent of a nonnegative real number. * `ENNReal.conjExponent`: Conjugate exponent of an extended nonnegative real number. ## TODO * Eradicate the `1 / p` spelling in lemmas. -/ noncomputable section open scoped ENNReal NNReal namespace Real /-- Real numbers `p q r : ℝ` are said to be a **HΓΆlder triple** if `p` and `q` are positive and `p⁻¹ + q⁻¹ = r⁻¹`. -/ @[mk_iff] structure HolderTriple (p q r : ℝ) : Prop where inv_add_inv_eq_inv : p⁻¹ + q⁻¹ = r⁻¹ left_pos : 0 < p right_pos : 0 < q /-- Real numbers `p q : ℝ` are **HΓΆlder conjugate** if they are positive and satisfy the equality `p⁻¹ + q⁻¹ = 1`. This is an abbreviation for `Real.HolderTriple p q 1`. This condition shows up in many theorems in analysis, notably related to `L^p` norms. It is equivalent that `1 < p` and `p⁻¹ + q⁻¹ = 1`. See `Real.holderConjugate_iff`. -/ abbrev HolderConjugate (p q : ℝ) := HolderTriple p q 1 /-- The conjugate exponent of `p` is `q = p / (p-1)`, so that `p⁻¹ + q⁻¹ = 1`. -/ def conjExponent (p : ℝ) : ℝ := p / (p - 1) variable {a b p q r : ℝ} namespace HolderTriple lemma of_pos (hp : 0 < p) (hq : 0 < q) : HolderTriple p q (p⁻¹ + q⁻¹)⁻¹ where inv_add_inv_eq_inv := inv_inv _ |>.symm left_pos := hp right_pos := hq variable (h : p.HolderTriple q r) include h @[symm] protected lemma symm : q.HolderTriple p r where inv_add_inv_eq_inv := add_comm p⁻¹ q⁻¹ β–Έ h.inv_add_inv_eq_inv left_pos := h.right_pos right_pos := h.left_pos theorem pos : 0 < p := h.left_pos theorem nonneg : 0 ≀ p := h.pos.le theorem ne_zero : p β‰  0 := h.pos.ne' protected lemma inv_pos : 0 < p⁻¹ := inv_pos.2 h.pos protected lemma inv_nonneg : 0 ≀ p⁻¹ := h.inv_pos.le protected lemma inv_ne_zero : p⁻¹ β‰  0 := h.inv_pos.ne' theorem one_div_pos : 0 < 1 / p := _root_.one_div_pos.2 h.pos theorem one_div_nonneg : 0 ≀ 1 / p := le_of_lt h.one_div_pos theorem one_div_ne_zero : 1 / p β‰  0 := ne_of_gt h.one_div_pos /-- For `r`, instead of `p` -/ theorem pos' : 0 < r := inv_pos.mp <| h.inv_add_inv_eq_inv β–Έ add_pos h.inv_pos h.symm.inv_pos /-- For `r`, instead of `p` -/ theorem nonneg' : 0 ≀ r := h.pos'.le /-- For `r`, instead of `p` -/ theorem ne_zero' : r β‰  0 := h.pos'.ne' /-- For `r`, instead of `p` -/ protected lemma inv_pos' : 0 < r⁻¹ := inv_pos.2 h.pos' /-- For `r`, instead of `p` -/ protected lemma inv_nonneg' : 0 ≀ r⁻¹ := h.inv_pos'.le /-- For `r`, instead of `p` -/ protected lemma inv_ne_zero' : r⁻¹ β‰  0 := h.inv_pos'.ne' /-- For `r`, instead of `p` -/ theorem one_div_pos' : 0 < 1 / r := _root_.one_div_pos.2 h.pos' /-- For `r`, instead of `p` -/ theorem one_div_nonneg' : 0 ≀ 1 / r := le_of_lt h.one_div_pos' /-- For `r`, instead of `p` -/ theorem one_div_ne_zero' : 1 / r β‰  0 := ne_of_gt h.one_div_pos' lemma inv_eq : r⁻¹ = p⁻¹ + q⁻¹ := h.inv_add_inv_eq_inv.symm lemma one_div_add_one_div : 1 / p + 1 / q = 1 / r := by simpa using h.inv_add_inv_eq_inv lemma one_div_eq : 1 / r = 1 / p + 1 / q := h.one_div_add_one_div.symm lemma inv_inv_add_inv : (p⁻¹ + q⁻¹)⁻¹ = r := by simp [h.inv_add_inv_eq_inv] protected lemma inv_lt_inv : p⁻¹ < r⁻¹ := calc p⁻¹ = p⁻¹ + 0 := add_zero _ |>.symm _ < p⁻¹ + q⁻¹ := by gcongr; exact h.symm.inv_pos _ = r⁻¹ := h.inv_add_inv_eq_inv lemma lt : r < p := by simpa using inv_strictAntiβ‚€ h.inv_pos h.inv_lt_inv lemma inv_sub_inv_eq_inv : r⁻¹ - q⁻¹ = p⁻¹ := sub_eq_of_eq_add h.inv_eq lemma holderConjugate_div_div : (p / r).HolderConjugate (q / r) where inv_add_inv_eq_inv := by simp [div_eq_mul_inv, ← mul_add, h.inv_add_inv_eq_inv, h.ne_zero'] left_pos := by have := h.left_pos; have := h.pos'; positivity right_pos := by have := h.right_pos; have := h.pos'; positivity end HolderTriple namespace HolderConjugate lemma two_two : HolderConjugate 2 2 where inv_add_inv_eq_inv := by norm_num left_pos := zero_lt_two right_pos := zero_lt_two section variable (h : p.HolderConjugate q) include h @[symm] protected lemma symm : q.HolderConjugate p := HolderTriple.symm h theorem inv_add_inv_eq_one : p⁻¹ + q⁻¹ = 1 := inv_one (G := ℝ) β–Έ h.inv_add_inv_eq_inv theorem sub_one_pos : 0 < p - 1 := sub_pos.2 h.lt theorem sub_one_ne_zero : p - 1 β‰  0 := h.sub_one_pos.ne' theorem conjugate_eq : q = p / (p - 1) := by convert inv_inv q β–Έ congr($(h.symm.inv_sub_inv_eq_inv.symm)⁻¹) using 1 field [h.ne_zero] lemma conjExponent_eq : conjExponent p = q := h.conjugate_eq.symm lemma one_sub_inv : 1 - p⁻¹ = q⁻¹ := sub_eq_of_eq_add h.symm.inv_add_inv_eq_one.symm lemma inv_sub_one : p⁻¹ - 1 = -q⁻¹ := by simpa using congr(-$(h.one_sub_inv)) theorem sub_one_mul_conj : (p - 1) * q = p := mul_comm q (p - 1) β–Έ (eq_div_iff h.sub_one_ne_zero).1 h.conjugate_eq theorem mul_eq_add : p * q = p + q := by simpa only [sub_mul, sub_eq_iff_eq_add, one_mul] using h.sub_one_mul_conj theorem div_conj_eq_sub_one : p / q = p - 1 := by field_simp [h.symm.ne_zero] linear_combination -h.sub_one_mul_conj theorem inv_add_inv_ennreal : (ENNReal.ofReal p)⁻¹ + (ENNReal.ofReal q)⁻¹ = 1 := by rw [← ENNReal.ofReal_one, ← ENNReal.ofReal_inv_of_pos h.pos, ← ENNReal.ofReal_inv_of_pos h.symm.pos, ← ENNReal.ofReal_add h.inv_nonneg h.symm.inv_nonneg, h.inv_add_inv_eq_one] end lemma _root_.Real.holderConjugate_iff : p.HolderConjugate q ↔ 1 < p ∧ p⁻¹ + q⁻¹ = 1 := by refine ⟨fun h ↦ ⟨h.lt, h.inv_add_inv_eq_one⟩, ?_⟩ rintro ⟨hp, h⟩ have hp' := zero_lt_one.trans hp refine ⟨inv_one (G := ℝ) |>.symm β–Έ h, hp', ?_⟩ rw [← inv_lt_oneβ‚€ hp', ← sub_pos] at hp exact inv_pos.mp <| eq_sub_of_add_eq' h β–Έ hp protected lemma inv_inv (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) : a⁻¹.HolderConjugate b⁻¹ where inv_add_inv_eq_inv := by simpa using hab left_pos := inv_pos.mpr ha right_pos := inv_pos.mpr hb lemma inv_one_sub_inv (haβ‚€ : 0 < a) (ha₁ : a < 1) : a⁻¹.HolderConjugate (1 - a)⁻¹ := holderConjugate_iff.mpr ⟨one_lt_invβ‚€ haβ‚€ |>.mpr ha₁, by simp⟩ lemma one_sub_inv_inv (haβ‚€ : 0 < a) (ha₁ : a < 1) : (1 - a)⁻¹.HolderConjugate a⁻¹ := (inv_one_sub_inv haβ‚€ ha₁).symm end HolderConjugate lemma holderConjugate_comm : p.HolderConjugate q ↔ q.HolderConjugate p := ⟨.symm, .symm⟩ lemma holderConjugate_iff_eq_conjExponent (hp : 1 < p) : p.HolderConjugate q ↔ q = p / (p - 1) := ⟨HolderConjugate.conjugate_eq, fun h ↦ holderConjugate_iff.mpr ⟨hp, by simp [field, h]⟩⟩ lemma HolderConjugate.conjExponent (h : 1 < p) : p.HolderConjugate (conjExponent p) := (holderConjugate_iff_eq_conjExponent h).2 rfl lemma holderConjugate_one_div (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) : (1 / a).HolderConjugate (1 / b) := by simpa using HolderConjugate.inv_inv ha hb hab end Real namespace NNReal /-- Nonnegative real numbers `p q r : ℝβ‰₯0` are said to be a **HΓΆlder triple** if `p` and `q` are positive and `p⁻¹ + q⁻¹ = r⁻¹`. -/ @[mk_iff] structure HolderTriple (p q r : ℝβ‰₯0) : Prop where inv_add_inv_eq_inv : p⁻¹ + q⁻¹ = r⁻¹ left_pos : 0 < p right_pos : 0 < q /-- Nonnegative real numbers `p q : ℝβ‰₯0` are **HΓΆlder conjugate** if they are positive and satisfy the equality `p⁻¹ + q⁻¹ = 1`. This is an abbreviation for `NNReal.HolderTriple p q 1`. This condition shows up in many theorems in analysis, notably related to `L^p` norms. It is equivalent that `1 < p` and `p⁻¹ + q⁻¹ = 1`. See `NNReal.holderConjugate_iff`. -/ abbrev HolderConjugate (p q : ℝβ‰₯0) := HolderTriple p q 1 /-- The conjugate exponent of `p` is `q = p/(p-1)`, so that `p⁻¹ + q⁻¹ = 1`. -/ def conjExponent (p : ℝβ‰₯0) : ℝβ‰₯0 := p / (p - 1) @[simp, norm_cast] lemma holderTriple_coe_iff {p q r : ℝβ‰₯0} : Real.HolderTriple (p : ℝ) (q : ℝ) (r : ℝ) ↔ HolderTriple p q r := by rw_mod_cast [Real.holderTriple_iff, holderTriple_iff] alias ⟨_, HolderTriple.coe⟩ := holderTriple_coe_iff @[simp, norm_cast] lemma holderConjugate_coe_iff {p q : ℝβ‰₯0} : Real.HolderConjugate (p : ℝ) (q : ℝ) ↔ HolderConjugate p q := holderTriple_coe_iff (r := 1) alias ⟨_, HolderConjugate.coe⟩ := holderConjugate_coe_iff variable {a b p q r : ℝβ‰₯0} namespace HolderTriple lemma of_pos (hp : 0 < p) (hq : 0 < q) : HolderTriple p q (p⁻¹ + q⁻¹)⁻¹ where inv_add_inv_eq_inv := inv_inv _ |>.symm left_pos := hp right_pos := hq variable (h : p.HolderTriple q r) include h @[symm] protected lemma symm : q.HolderTriple p r where inv_add_inv_eq_inv := add_comm p⁻¹ q⁻¹ β–Έ h.inv_add_inv_eq_inv left_pos := h.right_pos right_pos := h.left_pos theorem pos : 0 < p := h.left_pos theorem nonneg : 0 ≀ p := h.pos.le theorem ne_zero : p β‰  0 := h.pos.ne' protected lemma inv_pos : 0 < p⁻¹ := inv_pos.2 h.pos protected lemma inv_nonneg : 0 ≀ p⁻¹ := h.inv_pos.le protected lemma inv_ne_zero : p⁻¹ β‰  0 := h.inv_pos.ne' theorem one_div_pos : 0 < 1 / p := _root_.one_div_pos.2 h.pos theorem one_div_nonneg : 0 ≀ 1 / p := le_of_lt h.one_div_pos theorem one_div_ne_zero : 1 / p β‰  0 := ne_of_gt h.one_div_pos /-- For `r`, instead of `p` -/ theorem pos' : 0 < r := inv_pos.mp <| h.inv_add_inv_eq_inv β–Έ add_pos h.inv_pos h.symm.inv_pos /-- For `r`, instead of `p` -/ theorem nonneg' : 0 ≀ r := h.pos'.le /-- For `r`, instead of `p` -/ theorem ne_zero' : r β‰  0 := h.pos'.ne' /-- For `r`, instead of `p` -/ protected lemma inv_pos' : 0 < r⁻¹ := inv_pos.2 h.pos' /-- For `r`, instead of `p` -/ protected lemma inv_nonneg' : 0 ≀ r⁻¹ := h.inv_pos'.le /-- For `r`, instead of `p` -/ protected lemma inv_ne_zero' : r⁻¹ β‰  0 := h.inv_pos'.ne' /-- For `r`, instead of `p` -/ theorem one_div_pos' : 0 < 1 / r := _root_.one_div_pos.2 h.pos' /-- For `r`, instead of `p` -/ theorem one_div_nonneg' : 0 ≀ 1 / r := le_of_lt h.one_div_pos' /-- For `r`, instead of `p` -/ theorem one_div_ne_zero' : 1 / r β‰  0 := ne_of_gt h.one_div_pos' lemma inv_eq : r⁻¹ = p⁻¹ + q⁻¹ := h.inv_add_inv_eq_inv.symm lemma one_div_add_one_div : 1 / p + 1 / q = 1 / r := by exact_mod_cast h.coe.one_div_add_one_div lemma one_div_eq : 1 / r = 1 / p + 1 / q := h.one_div_add_one_div.symm lemma inv_inv_add_inv : (p⁻¹ + q⁻¹)⁻¹ = r := by exact_mod_cast h.coe.inv_inv_add_inv protected lemma inv_lt_inv : p⁻¹ < r⁻¹ := h.coe.inv_lt_inv lemma lt : r < p := h.coe.lt lemma inv_sub_inv_eq_inv : r⁻¹ - q⁻¹ = p⁻¹ := by have := h.symm.inv_lt_inv.le exact_mod_cast h.coe.inv_sub_inv_eq_inv lemma holderConjugate_div_div : (p / r).HolderConjugate (q / r) where inv_add_inv_eq_inv := by simp [div_eq_mul_inv, ← mul_add, h.inv_add_inv_eq_inv, h.ne_zero'] left_pos := by have := h.left_pos; have := h.pos'; positivity right_pos := by have := h.right_pos; have := h.pos'; positivity end HolderTriple namespace HolderConjugate lemma two_two : HolderConjugate 2 2 where inv_add_inv_eq_inv := by simpa using add_halves (1 : ℝβ‰₯0) left_pos := zero_lt_two right_pos := zero_lt_two section variable (h : p.HolderConjugate q) include h @[symm] protected lemma symm : q.HolderConjugate p := HolderTriple.symm h theorem inv_add_inv_eq_one : p⁻¹ + q⁻¹ = 1 := inv_one (G := ℝβ‰₯0) β–Έ h.inv_add_inv_eq_inv theorem sub_one_pos : 0 < p - 1 := tsub_pos_of_lt h.lt theorem sub_one_ne_zero : p - 1 β‰  0 := h.sub_one_pos.ne' theorem conjugate_eq : q = p / (p - 1) := by have : ((1 : ℝβ‰₯0) : ℝ) ≀ p := h.coe.lt.le exact_mod_cast NNReal.coe_sub this β–Έ coe_one β–Έ h.coe.conjugate_eq lemma conjExponent_eq : conjExponent p = q := h.conjugate_eq.symm lemma one_sub_inv : 1 - p⁻¹ = q⁻¹ := tsub_eq_of_eq_add h.symm.inv_add_inv_eq_one.symm theorem sub_one_mul_conj : (p - 1) * q = p := mul_comm q (p - 1) β–Έ (eq_div_iff h.sub_one_ne_zero).1 h.conjugate_eq theorem mul_eq_add : p * q = p + q := by simpa [mul_add, add_mul, h.ne_zero, h.symm.ne_zero, add_comm q] using congr(p * $(h.inv_eq) * q) theorem div_conj_eq_sub_one : p / q = p - 1 := by field_simp [h.symm.ne_zero] linear_combination - h.sub_one_mul_conj lemma inv_add_inv_ennreal : (p⁻¹ + q⁻¹ : ℝβ‰₯0∞) = 1 := by norm_cast; exact h.inv_add_inv_eq_one end lemma _root_.NNReal.holderConjugate_iff : p.HolderConjugate q ↔ 1 < p ∧ p⁻¹ + q⁻¹ = 1 := by rw [← holderConjugate_coe_iff, Real.holderConjugate_iff, ← coe_one] exact_mod_cast Iff.rfl protected lemma inv_inv (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) : a⁻¹.HolderConjugate b⁻¹ where inv_add_inv_eq_inv := by simpa using hab left_pos := inv_pos.mpr ha right_pos := inv_pos.mpr hb lemma inv_one_sub_inv (haβ‚€ : 0 < a) (ha₁ : a < 1) : a⁻¹.HolderConjugate (1 - a)⁻¹ := holderConjugate_iff.mpr ⟨one_lt_invβ‚€ haβ‚€ |>.mpr ha₁, by simpa using add_tsub_cancel_of_le ha₁.le⟩ lemma one_sub_inv_inv (haβ‚€ : 0 < a) (ha₁ : a < 1) : (1 - a)⁻¹.HolderConjugate a⁻¹ := (inv_one_sub_inv haβ‚€ ha₁).symm end HolderConjugate lemma holderConjugate_comm : p.HolderConjugate q ↔ q.HolderConjugate p := ⟨.symm, .symm⟩ lemma holderConjugate_iff_eq_conjExponent (hp : 1 < p) : p.HolderConjugate q ↔ q = p / (p - 1) := by rw [← holderConjugate_coe_iff, Real.holderConjugate_iff_eq_conjExponent (by exact_mod_cast hp), ← coe_one, ← NNReal.coe_sub hp.le] exact_mod_cast Iff.rfl lemma HolderConjugate.conjExponent (h : 1 < p) : p.HolderConjugate (conjExponent p) := (holderConjugate_iff_eq_conjExponent h).2 rfl lemma holderConjugate_one_div (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) : (1 / a).HolderConjugate (1 / b) := by simpa using HolderConjugate.inv_inv ha hb hab end NNReal protected lemma Real.HolderTriple.toNNReal {p q r : ℝ} (h : p.HolderTriple q r) : p.toNNReal.HolderTriple q.toNNReal r.toNNReal := by simpa [← NNReal.holderTriple_coe_iff, h.nonneg, h.symm.nonneg, h.nonneg'] protected lemma Real.HolderConjugate.toNNReal {p q : ℝ} (h : p.HolderConjugate q) : p.toNNReal.HolderConjugate q.toNNReal := by simpa using Real.HolderTriple.toNNReal h namespace ENNReal /-- The conjugate exponent of `p` is `q = 1 + (p - 1)⁻¹`, so that `p⁻¹ + q⁻¹ = 1`. -/ noncomputable def conjExponent (p : ℝβ‰₯0∞) : ℝβ‰₯0∞ := 1 + (p - 1)⁻¹ lemma coe_conjExponent {p : ℝβ‰₯0} (hp : 1 < p) : p.conjExponent = conjExponent p := by rw [NNReal.conjExponent, conjExponent] norm_cast rw [← coe_inv (tsub_pos_of_lt hp).ne'] norm_cast field_simp [(tsub_pos_of_lt hp).ne'] rw [tsub_add_cancel_of_le hp.le] variable {a b p q r : ℝβ‰₯0∞} @[simp, norm_cast] lemma holderTriple_coe_iff {p q r : ℝβ‰₯0} (hr : r β‰  0) : HolderTriple (p : ℝβ‰₯0∞) (q : ℝβ‰₯0∞) (r : ℝβ‰₯0∞) ↔ NNReal.HolderTriple p q r := by refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ Β· rw [NNReal.holderTriple_iff] obtain ⟨hp, hq⟩ : p β‰  0 ∧ q β‰  0:= by constructor all_goals rintro rfl apply hr exact_mod_cast (coe_zero β–Έ h).unique _ _ r 0 exact ⟨by exact_mod_cast h.inv_add_inv_eq_inv, hp.bot_lt, hq.bot_lt⟩ Β· rw [holderTriple_iff] have hp := h.ne_zero have hq := h.symm.ne_zero exact_mod_cast h.inv_add_inv_eq_inv alias ⟨_, _root_.NNReal.HolderTriple.coe_ennreal⟩ := holderTriple_coe_iff @[simp, norm_cast] lemma holderConjugate_coe_iff {p q : ℝβ‰₯0} : HolderConjugate (p : ℝβ‰₯0∞) (q : ℝβ‰₯0∞) ↔ NNReal.HolderConjugate p q := holderTriple_coe_iff one_ne_zero alias ⟨_, _root_.NNReal.HolderConjugate.coe_ennreal⟩ := holderConjugate_coe_iff namespace HolderTriple lemma _root_.Real.HolderTriple.ennrealOfReal {p q r : ℝ} (h : p.HolderTriple q r) : HolderTriple (ENNReal.ofReal p) (ENNReal.ofReal q) (ENNReal.ofReal r) := by simpa [holderTriple_iff, ofReal_inv_of_pos, h.pos, h.symm.pos, h.pos', ofReal_add, h.nonneg, h.symm.nonneg] using congr(ENNReal.ofReal $(h.inv_add_inv_eq_inv)) lemma _root_.Real.HolderConjugate.ennrealOfReal {p q : ℝ} (h : p.HolderConjugate q) : HolderConjugate (ENNReal.ofReal p) (ENNReal.ofReal q) := by simpa using Real.HolderTriple.ennrealOfReal h lemma of_toReal (h : Real.HolderTriple p.toReal q.toReal r.toReal) : HolderTriple p q r := by have hp := h.pos have hq := h.symm.pos have hr := h.pos' rw [toReal_pos_iff] at hp hq hr simpa [hp.2.ne, hq.2.ne, hr.2.ne] using h.ennrealOfReal variable (r) in lemma toReal_iff (hp : 0 < p.toReal) (hq : 0 < q.toReal) : Real.HolderTriple p.toReal q.toReal r.toReal ↔ HolderTriple p q r := by refine ⟨of_toReal, fun h ↦ ⟨?_, hp, hq⟩⟩ rw [toReal_pos_iff] at hp hq simpa [toReal_add, Finiteness.inv_ne_top, hp.1.ne', hq.1.ne'] using congr(ENNReal.toReal $(h.inv_add_inv_eq_inv)) variable (r) in lemma toReal (hp : 0 < p.toReal) (hq : 0 < q.toReal) [HolderTriple p q r] : Real.HolderTriple p.toReal q.toReal r.toReal := toReal_iff r hp hq |>.mpr β€Ή_β€Ί lemma of_toNNReal (h : NNReal.HolderTriple p.toNNReal q.toNNReal r.toNNReal) : HolderTriple p q r := .of_toReal <| by simpa only [coe_toNNReal_eq_toReal] using h.coe variable (r) in lemma toNNReal_iff (hp : 0 < p.toNNReal) (hq : 0 < q.toNNReal) : NNReal.HolderTriple p.toNNReal q.toNNReal r.toNNReal ↔ HolderTriple p q r := by simp_rw [← NNReal.holderTriple_coe_iff, coe_toNNReal_eq_toReal] apply toReal_iff r ?_ ?_ all_goals simpa [← coe_toNNReal_eq_toReal] variable (r) in lemma toNNReal (hp : 0 < p.toNNReal) (hq : 0 < q.toNNReal) [HolderTriple p q r] : NNReal.HolderTriple p.toNNReal q.toNNReal r.toNNReal := toNNReal_iff r hp hq |>.mpr β€Ή_β€Ί end HolderTriple namespace HolderConjugate lemma of_toReal (h : p.toReal.HolderConjugate q.toReal) : p.HolderConjugate q := by rw [Real.HolderConjugate] at h exact HolderTriple.of_toReal (toReal_one β–Έ h) lemma toReal_iff (hp : 1 < p.toReal) : p.toReal.HolderConjugate q.toReal ↔ p.HolderConjugate q := by refine ⟨of_toReal, fun h ↦ ?_⟩ have hq : 0 < q.toReal := by rw [toReal_pos_iff] refine ⟨pos q p, lt_top_iff_one_lt q p |>.mpr ?_⟩ contrapose! hp exact toReal_mono one_ne_top hp simpa using HolderTriple.toReal 1 (zero_lt_one.trans hp) hq lemma toReal (hp : 1 < p.toReal) [HolderConjugate p q] : p.toReal.HolderConjugate q.toReal := toReal_iff hp |>.mpr β€Ή_β€Ί lemma of_toNNReal (h : NNReal.HolderConjugate p.toNNReal q.toNNReal) : HolderConjugate p q := .of_toReal <| by simpa only [coe_toNNReal_eq_toReal] using h.coe lemma toNNReal_iff (hp : 1 < p.toNNReal) : NNReal.HolderConjugate p.toNNReal q.toNNReal ↔ HolderConjugate p q := by simp_rw [← NNReal.holderTriple_coe_iff, coe_toNNReal_eq_toReal] apply toReal_iff ?_ all_goals simpa [← coe_toNNReal_eq_toReal] lemma toNNReal (hp : 1 < p.toNNReal) [HolderConjugate p q] : NNReal.HolderConjugate p.toNNReal q.toNNReal := toNNReal_iff hp |>.mpr β€Ή_β€Ί protected lemma conjExponent {p : ℝβ‰₯0∞} (hp : 1 ≀ p) : p.HolderConjugate (conjExponent p) := by have : p β‰  0 := (zero_lt_one.trans_le hp).ne' rw [HolderConjugate, holderTriple_iff, conjExponent, add_comm] refine (AddLECancellable.eq_tsub_iff_add_eq_of_le (Ξ± := ℝβ‰₯0∞) (by simpa) (by simpa)).1 ?_ rw [inv_eq_iff_eq_inv] obtain rfl | hp₁ := hp.eq_or_lt Β· simp obtain rfl | hp := eq_or_ne p ∞ Β· simp calc 1 + (p - 1)⁻¹ = (p - 1 + 1) / (p - 1) := by rw [ENNReal.add_div, ENNReal.div_self ((tsub_pos_of_lt hp₁).ne') (sub_ne_top hp), one_div] _ = (1⁻¹ - p⁻¹)⁻¹ := by rw [tsub_add_cancel_of_le, ← inv_eq_iff_eq_inv, div_eq_mul_inv, ENNReal.mul_inv, inv_inv, ENNReal.mul_sub, ENNReal.inv_mul_cancel, mul_one] <;> simp [*] instance {p : ℝβ‰₯0∞} [Fact (1 ≀ p)] : p.HolderConjugate (conjExponent p) := .conjExponent Fact.out section variable [h : HolderConjugate p q] lemma conjExponent_eq : conjExponent p = q := have : Fact (1 ≀ p) := ⟨one_le p q⟩ unique p (conjExponent p) q lemma conj_eq : q = 1 + (p - 1)⁻¹ := conjExponent_eq.symm lemma mul_eq_add : p * q = p + q := by obtain rfl | hp := eq_or_ne p ∞ Β· simp [ne_zero q ∞] obtain rfl | hq := eq_or_ne q ∞ Β· simp [ne_zero p ∞] simpa [add_comm p, mul_add, add_mul, hp, hq, ne_zero p q, ne_zero q p, ENNReal.mul_inv_cancel, ENNReal.inv_mul_cancel_right] using congr(p * $((inv_add_inv_eq_one p q).symm) * q) lemma div_conj_eq_sub_one : p / q = p - 1 := by obtain rfl | hq := eq_or_ne q ∞ Β· obtain rfl := unique ∞ p 1 simp refine ENNReal.eq_sub_of_add_eq one_ne_top ?_ rw [← ENNReal.div_self (ne_zero q p) hq, ← ENNReal.add_div, ← h.mul_eq_add, mul_div_assoc, ENNReal.div_self (ne_zero q p) hq, mul_one] end protected lemma inv_inv (hab : a + b = 1) : a⁻¹.HolderConjugate b⁻¹ where inv_add_inv_eq_inv := by simpa [inv_inv] using hab lemma inv_one_sub_inv (ha : a ≀ 1) : a⁻¹.HolderConjugate (1 - a)⁻¹ := .inv_inv <| add_tsub_cancel_of_le ha lemma inv_one_sub_inv' (ha : 1 ≀ a) : a.HolderConjugate (1 - a⁻¹)⁻¹ := by simpa using inv_one_sub_inv (ENNReal.inv_le_one.mpr ha) lemma one_sub_inv_inv (ha : a ≀ 1) : (1 - a)⁻¹.HolderConjugate a⁻¹ := (inv_one_sub_inv ha).symm lemma top_one : HolderConjugate ∞ 1 := ⟨by simp⟩ lemma one_top : HolderConjugate 1 ∞ := ⟨by simp⟩ end HolderConjugate lemma isConjExponent_comm : p.HolderConjugate q ↔ q.HolderConjugate p := ⟨(Β·.symm), (Β·.symm)⟩ lemma isConjExponent_iff_eq_conjExponent (hp : 1 ≀ p) : p.HolderConjugate q ↔ q = 1 + (p - 1)⁻¹ := ⟨fun h ↦ h.conj_eq, by rintro rfl; exact .conjExponent hp⟩ end ENNReal
.lake/packages/mathlib/Mathlib/Data/Real/Archimedean.lean
import Mathlib.Algebra.Order.Archimedean.Basic import Mathlib.Algebra.Order.Group.Pointwise.Bounds import Mathlib.Data.Real.Basic import Mathlib.Order.ConditionallyCompleteLattice.Indexed import Mathlib.Order.Interval.Set.Disjoint /-! # The real numbers are an Archimedean floor ring, and a conditionally complete linear order. -/ assert_not_exists Finset open Pointwise CauSeq namespace Real variable {ΞΉ : Sort*} {f : ΞΉ β†’ ℝ} {s : Set ℝ} {a : ℝ} instance instArchimedean : Archimedean ℝ := archimedean_iff_rat_le.2 fun x => Real.ind_mk x fun f => let ⟨M, _, H⟩ := f.bounded' 0 ⟨M, mk_le_of_forall_le ⟨0, fun i _ => Rat.cast_le.2 <| le_of_lt (abs_lt.1 (H i)).2⟩⟩ noncomputable instance : FloorRing ℝ := Archimedean.floorRing _ theorem isCauSeq_iff_lift {f : β„• β†’ β„š} : IsCauSeq abs f ↔ IsCauSeq abs fun i => (f i : ℝ) where mp H Ξ΅ Ξ΅0 := let ⟨δ, Ξ΄0, δΡ⟩ := exists_pos_rat_lt Ξ΅0 (H _ Ξ΄0).imp fun i hi j ij => by dsimp; exact lt_trans (mod_cast hi _ ij) δΡ mpr H Ξ΅ Ξ΅0 := (H _ (Rat.cast_pos.2 Ξ΅0)).imp fun i hi j ij => by dsimp at hi; exact mod_cast hi _ ij theorem of_near (f : β„• β†’ β„š) (x : ℝ) (h : βˆ€ Ξ΅ > 0, βˆƒ i, βˆ€ j β‰₯ i, |(f j : ℝ) - x| < Ξ΅) : βˆƒ h', Real.mk ⟨f, h'⟩ = x := ⟨isCauSeq_iff_lift.2 (CauSeq.of_near _ (const abs x) h), sub_eq_zero.1 <| abs_eq_zero.1 <| (eq_of_le_of_forall_lt_imp_le_of_dense (abs_nonneg _)) fun _Ξ΅ Ξ΅0 => mk_near_of_forall_near <| (h _ Ξ΅0).imp fun _i h j ij => le_of_lt (h j ij)⟩ theorem exists_floor (x : ℝ) : βˆƒ ub : β„€, (ub : ℝ) ≀ x ∧ βˆ€ z : β„€, (z : ℝ) ≀ x β†’ z ≀ ub := Int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x ⟨n, fun _ h' => Int.cast_le.1 <| le_trans h' <| le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x ⟨n, le_of_lt hn⟩) theorem exists_isLUB (hne : s.Nonempty) (hbdd : BddAbove s) : βˆƒ x, IsLUB s x := by rcases hne, hbdd with ⟨⟨L, hL⟩, ⟨U, hU⟩⟩ have : βˆ€ d : β„•, BddAbove { m : β„€ | βˆƒ y ∈ s, (m : ℝ) ≀ y * d } := by obtain ⟨k, hk⟩ := exists_int_gt U refine fun d => ⟨k * d, fun z h => ?_⟩ rcases h with ⟨y, yS, hy⟩ refine Int.cast_le.1 (hy.trans ?_) push_cast exact mul_le_mul_of_nonneg_right ((hU yS).trans hk.le) d.cast_nonneg choose f hf using fun d : β„• => Int.exists_greatest_of_bdd (this d) ⟨⌊L * dβŒ‹, L, hL, Int.floor_le _⟩ have hf₁ : βˆ€ n > 0, βˆƒ y ∈ s, ((f n / n : β„š) : ℝ) ≀ y := fun n n0 => let ⟨y, yS, hy⟩ := (hf n).1 ⟨y, yS, by simpa using (div_le_iffβ‚€ (Nat.cast_pos.2 n0 : (_ : ℝ) < _)).2 hy⟩ have hfβ‚‚ : βˆ€ n > 0, βˆ€ y ∈ s, (y - ((n : β„•) : ℝ)⁻¹) < (f n / n : β„š) := by intro n n0 y yS have := (Int.sub_one_lt_floor _).trans_le (Int.cast_le.2 <| (hf n).2 _ ⟨y, yS, Int.floor_le _⟩) simp only [Rat.cast_div, Rat.cast_intCast, Rat.cast_natCast, gt_iff_lt] rwa [lt_div_iffβ‚€ (Nat.cast_pos.2 n0 : (_ : ℝ) < _), sub_mul, inv_mul_cancelβ‚€] exact ne_of_gt (Nat.cast_pos.2 n0) have hg : IsCauSeq abs (fun n => f n / n : β„• β†’ β„š) := by intro Ξ΅ Ξ΅0 suffices βˆ€ j β‰₯ βŒˆΞ΅β»ΒΉβŒ‰β‚Š, βˆ€ k β‰₯ βŒˆΞ΅β»ΒΉβŒ‰β‚Š, (f j / j - f k / k : β„š) < Ξ΅ by refine ⟨_, fun j ij => abs_lt.2 ⟨?_, this _ ij _ le_rfl⟩⟩ rw [neg_lt, neg_sub] exact this _ le_rfl _ ij intro j ij k ik replace ij := le_trans (Nat.le_ceil _) (Nat.cast_le.2 ij) replace ik := le_trans (Nat.le_ceil _) (Nat.cast_le.2 ik) have j0 := Nat.cast_pos.1 ((inv_pos.2 Ξ΅0).trans_le ij) have k0 := Nat.cast_pos.1 ((inv_pos.2 Ξ΅0).trans_le ik) rcases hf₁ _ j0 with ⟨y, yS, hy⟩ refine lt_of_lt_of_le ((Rat.cast_lt (K := ℝ)).1 ?_) ((inv_le_commβ‚€ Ξ΅0 (Nat.cast_pos.2 k0)).1 ik) simpa using sub_lt_iff_lt_add'.2 (lt_of_le_of_lt hy <| sub_lt_iff_lt_add.1 <| hfβ‚‚ _ k0 _ yS) let g : CauSeq β„š abs := ⟨fun n => f n / n, hg⟩ refine ⟨mk g, ⟨fun x xS => ?_, fun y h => ?_⟩⟩ Β· refine le_of_forall_lt_imp_le_of_dense fun z xz => ?_ obtain ⟨K, hK⟩ := exists_nat_gt (x - z)⁻¹ refine le_mk_of_forall_le ⟨K, fun n nK => ?_⟩ replace xz := sub_pos.2 xz replace hK := hK.le.trans (Nat.cast_le.2 nK) have n0 : 0 < n := Nat.cast_pos.1 ((inv_pos.2 xz).trans_le hK) refine le_trans ?_ (hfβ‚‚ _ n0 _ xS).le rwa [le_sub_comm, inv_le_commβ‚€ (Nat.cast_pos.2 n0 : (_ : ℝ) < _) xz] Β· exact mk_le_of_forall_le ⟨1, fun n n1 => let ⟨x, xS, hx⟩ := hf₁ _ n1 le_trans hx (h xS)⟩ /-- A nonempty, bounded below set of real numbers has a greatest lower bound. -/ theorem exists_isGLB (hne : s.Nonempty) (hbdd : BddBelow s) : βˆƒ x, IsGLB s x := by have hne' : (-s).Nonempty := Set.nonempty_neg.mpr hne have hbdd' : BddAbove (-s) := bddAbove_neg.mpr hbdd use -Classical.choose (Real.exists_isLUB hne' hbdd') rw [← isLUB_neg] exact Classical.choose_spec (Real.exists_isLUB hne' hbdd') open scoped Classical in noncomputable instance : SupSet ℝ := ⟨fun s => if h : s.Nonempty ∧ BddAbove s then Classical.choose (exists_isLUB h.1 h.2) else 0⟩ open scoped Classical in theorem sSup_def (s : Set ℝ) : sSup s = if h : s.Nonempty ∧ BddAbove s then Classical.choose (exists_isLUB h.1 h.2) else 0 := rfl protected theorem isLUB_sSup (h₁ : s.Nonempty) (hβ‚‚ : BddAbove s) : IsLUB s (sSup s) := by simp only [sSup_def, dif_pos (And.intro h₁ hβ‚‚)] apply Classical.choose_spec noncomputable instance : InfSet ℝ := ⟨fun s => -sSup (-s)⟩ theorem sInf_def (s : Set ℝ) : sInf s = -sSup (-s) := rfl protected theorem isGLB_sInf (h₁ : s.Nonempty) (hβ‚‚ : BddBelow s) : IsGLB s (sInf s) := by rw [sInf_def, ← isLUB_neg', neg_neg] exact Real.isLUB_sSup h₁.neg hβ‚‚.neg noncomputable instance : ConditionallyCompleteLinearOrder ℝ where __ := Real.linearOrder __ := Real.lattice le_csSup s a hs ha := (Real.isLUB_sSup ⟨a, ha⟩ hs).1 ha csSup_le s a hs ha := (Real.isLUB_sSup hs ⟨a, ha⟩).2 ha csInf_le s a hs ha := (Real.isGLB_sInf ⟨a, ha⟩ hs).1 ha le_csInf s a hs ha := (Real.isGLB_sInf hs ⟨a, ha⟩).2 ha csSup_of_not_bddAbove s hs := by simp [hs, sSup_def] csInf_of_not_bddBelow s hs := by simp [hs, sInf_def, sSup_def] theorem lt_sInf_add_pos (h : s.Nonempty) {Ξ΅ : ℝ} (hΞ΅ : 0 < Ξ΅) : βˆƒ a ∈ s, a < sInf s + Ξ΅ := exists_lt_of_csInf_lt h <| lt_add_of_pos_right _ hΞ΅ theorem add_neg_lt_sSup (h : s.Nonempty) {Ξ΅ : ℝ} (hΞ΅ : Ξ΅ < 0) : βˆƒ a ∈ s, sSup s + Ξ΅ < a := exists_lt_of_lt_csSup h <| add_lt_iff_neg_left.2 hΞ΅ theorem sInf_le_iff (h : BddBelow s) (h' : s.Nonempty) : sInf s ≀ a ↔ βˆ€ Ξ΅, 0 < Ξ΅ β†’ βˆƒ x ∈ s, x < a + Ξ΅ := by rw [le_iff_forall_pos_lt_add] constructor <;> intro H Ξ΅ Ξ΅_pos Β· exact exists_lt_of_csInf_lt h' (H Ξ΅ Ξ΅_pos) Β· rcases H Ξ΅ Ξ΅_pos with ⟨x, x_in, hx⟩ exact csInf_lt_of_lt h x_in hx theorem le_sSup_iff (h : BddAbove s) (h' : s.Nonempty) : a ≀ sSup s ↔ βˆ€ Ξ΅, Ξ΅ < 0 β†’ βˆƒ x ∈ s, a + Ξ΅ < x := by rw [le_iff_forall_pos_lt_add] refine ⟨fun H Ξ΅ Ξ΅_neg => ?_, fun H Ξ΅ Ξ΅_pos => ?_⟩ Β· exact exists_lt_of_lt_csSup h' (lt_sub_iff_add_lt.mp (H _ (neg_pos.mpr Ξ΅_neg))) Β· rcases H _ (neg_lt_zero.mpr Ξ΅_pos) with ⟨x, x_in, hx⟩ exact sub_lt_iff_lt_add.mp (lt_csSup_of_lt h x_in hx) @[simp] theorem sSup_empty : sSup (βˆ… : Set ℝ) = 0 := dif_neg <| by simp theorem sInf_univ : sInf (@Set.univ ℝ) = 0 := by simp [sInf_def] @[simp] lemma iSup_of_isEmpty [IsEmpty ΞΉ] (f : ΞΉ β†’ ℝ) : ⨆ i, f i = 0 := by dsimp [iSup] convert Real.sSup_empty rw [Set.range_eq_empty_iff] infer_instance @[simp] theorem iSup_const_zero : ⨆ _ : ΞΉ, (0 : ℝ) = 0 := by cases isEmpty_or_nonempty ΞΉ Β· exact Real.iSup_of_isEmpty _ Β· exact ciSup_const lemma sSup_of_not_bddAbove (hs : Β¬BddAbove s) : sSup s = 0 := dif_neg fun h => hs h.2 lemma iSup_of_not_bddAbove (hf : Β¬BddAbove (Set.range f)) : ⨆ i, f i = 0 := sSup_of_not_bddAbove hf theorem sSup_univ : sSup (@Set.univ ℝ) = 0 := Real.sSup_of_not_bddAbove not_bddAbove_univ @[simp] theorem sInf_empty : sInf (βˆ… : Set ℝ) = 0 := by simp [sInf_def, sSup_empty] @[simp] nonrec lemma iInf_of_isEmpty [IsEmpty ΞΉ] (f : ΞΉ β†’ ℝ) : β¨… i, f i = 0 := by rw [iInf_of_isEmpty, sInf_empty] @[simp] theorem iInf_const_zero : β¨… _ : ΞΉ, (0 : ℝ) = 0 := by cases isEmpty_or_nonempty ΞΉ Β· exact Real.iInf_of_isEmpty _ Β· exact ciInf_const theorem sInf_of_not_bddBelow (hs : Β¬BddBelow s) : sInf s = 0 := neg_eq_zero.2 <| sSup_of_not_bddAbove <| mt bddAbove_neg.1 hs theorem iInf_of_not_bddBelow (hf : Β¬BddBelow (Set.range f)) : β¨… i, f i = 0 := sInf_of_not_bddBelow hf /-- As `sSup s = 0` when `s` is an empty set of reals, it suffices to show that all elements of `s` are at most some nonnegative number `a` to show that `sSup s ≀ a`. See also `csSup_le`. -/ protected lemma sSup_le (hs : βˆ€ x ∈ s, x ≀ a) (ha : 0 ≀ a) : sSup s ≀ a := by obtain rfl | hs' := s.eq_empty_or_nonempty exacts [sSup_empty.trans_le ha, csSup_le hs' hs] /-- As `⨆ i, f i = 0` when the domain of the real-valued function `f` is empty, it suffices to show that all values of `f` are at most some nonnegative number `a` to show that `⨆ i, f i ≀ a`. See also `ciSup_le`. -/ protected lemma iSup_le (hf : βˆ€ i, f i ≀ a) (ha : 0 ≀ a) : ⨆ i, f i ≀ a := Real.sSup_le (Set.forall_mem_range.2 hf) ha /-- As `sInf s = 0` when `s` is an empty set of reals, it suffices to show that all elements of `s` are at least some nonpositive number `a` to show that `a ≀ sInf s`. See also `le_csInf`. -/ protected lemma le_sInf (hs : βˆ€ x ∈ s, a ≀ x) (ha : a ≀ 0) : a ≀ sInf s := by obtain rfl | hs' := s.eq_empty_or_nonempty exacts [ha.trans_eq sInf_empty.symm, le_csInf hs' hs] /-- As `β¨… i, f i = 0` when the domain of the real-valued function `f` is empty, it suffices to show that all values of `f` are at least some nonpositive number `a` to show that `a ≀ β¨… i, f i`. See also `le_ciInf`. -/ protected lemma le_iInf (hf : βˆ€ i, a ≀ f i) (ha : a ≀ 0) : a ≀ β¨… i, f i := Real.le_sInf (Set.forall_mem_range.2 hf) ha /-- As `sSup s = 0` when `s` is an empty set of reals, it suffices to show that all elements of `s` are nonpositive to show that `sSup s ≀ 0`. -/ lemma sSup_nonpos (hs : βˆ€ x ∈ s, x ≀ 0) : sSup s ≀ 0 := Real.sSup_le hs le_rfl /-- As `⨆ i, f i = 0` when the domain of the real-valued function `f` is empty, it suffices to show that all values of `f` are nonpositive to show that `⨆ i, f i ≀ 0`. -/ lemma iSup_nonpos (hf : βˆ€ i, f i ≀ 0) : ⨆ i, f i ≀ 0 := Real.iSup_le hf le_rfl /-- As `sInf s = 0` when `s` is an empty set of reals, it suffices to show that all elements of `s` are nonnegative to show that `0 ≀ sInf s`. -/ lemma sInf_nonneg (hs : βˆ€ x ∈ s, 0 ≀ x) : 0 ≀ sInf s := Real.le_sInf hs le_rfl /-- As `β¨… i, f i = 0` when the domain of the real-valued function `f` is empty, it suffices to show that all values of `f` are nonnegative to show that `0 ≀ β¨… i, f i`. -/ lemma iInf_nonneg (hf : βˆ€ i, 0 ≀ f i) : 0 ≀ iInf f := Real.le_iInf hf le_rfl /-- As `sSup s = 0` when `s` is a set of reals that's unbounded above, it suffices to show that `s` contains a nonnegative element to show that `0 ≀ sSup s`. -/ lemma sSup_nonneg' (hs : βˆƒ x ∈ s, 0 ≀ x) : 0 ≀ sSup s := by classical obtain ⟨x, hxs, hx⟩ := hs exact dite _ (fun h ↦ le_csSup_of_le h hxs hx) fun h ↦ (sSup_of_not_bddAbove h).ge /-- As `⨆ i, f i = 0` when the real-valued function `f` is unbounded above, it suffices to show that `f` takes a nonnegative value to show that `0 ≀ ⨆ i, f i`. -/ lemma iSup_nonneg' (hf : βˆƒ i, 0 ≀ f i) : 0 ≀ ⨆ i, f i := sSup_nonneg' <| Set.exists_range_iff.2 hf /-- As `sInf s = 0` when `s` is a set of reals that's unbounded below, it suffices to show that `s` contains a nonpositive element to show that `sInf s ≀ 0`. -/ lemma sInf_nonpos' (hs : βˆƒ x ∈ s, x ≀ 0) : sInf s ≀ 0 := by classical obtain ⟨x, hxs, hx⟩ := hs exact dite _ (fun h ↦ csInf_le_of_le h hxs hx) fun h ↦ (sInf_of_not_bddBelow h).le /-- As `β¨… i, f i = 0` when the real-valued function `f` is unbounded below, it suffices to show that `f` takes a nonpositive value to show that `0 ≀ β¨… i, f i`. -/ lemma iInf_nonpos' (hf : βˆƒ i, f i ≀ 0) : β¨… i, f i ≀ 0 := sInf_nonpos' <| Set.exists_range_iff.2 hf /-- As `sSup s = 0` when `s` is a set of reals that's either empty or unbounded above, it suffices to show that all elements of `s` are nonnegative to show that `0 ≀ sSup s`. -/ lemma sSup_nonneg (hs : βˆ€ x ∈ s, 0 ≀ x) : 0 ≀ sSup s := by obtain rfl | ⟨x, hx⟩ := s.eq_empty_or_nonempty Β· exact sSup_empty.ge Β· exact sSup_nonneg' ⟨x, hx, hs _ hx⟩ /-- As `⨆ i, f i = 0` when the domain of the real-valued function `f` is empty or unbounded above, it suffices to show that all values of `f` are nonnegative to show that `0 ≀ ⨆ i, f i`. -/ lemma iSup_nonneg (hf : βˆ€ i, 0 ≀ f i) : 0 ≀ ⨆ i, f i := sSup_nonneg <| Set.forall_mem_range.2 hf /-- As `sInf s = 0` when `s` is a set of reals that's either empty or unbounded below, it suffices to show that all elements of `s` are nonpositive to show that `sInf s ≀ 0`. -/ lemma sInf_nonpos (hs : βˆ€ x ∈ s, x ≀ 0) : sInf s ≀ 0 := by obtain rfl | ⟨x, hx⟩ := s.eq_empty_or_nonempty Β· exact sInf_empty.le Β· exact sInf_nonpos' ⟨x, hx, hs _ hx⟩ /-- As `β¨… i, f i = 0` when the domain of the real-valued function `f` is empty or unbounded below, it suffices to show that all values of `f` are nonpositive to show that `0 ≀ β¨… i, f i`. -/ lemma iInf_nonpos (hf : βˆ€ i, f i ≀ 0) : β¨… i, f i ≀ 0 := sInf_nonpos <| Set.forall_mem_range.2 hf theorem sInf_le_sSup (s : Set ℝ) (h₁ : BddBelow s) (hβ‚‚ : BddAbove s) : sInf s ≀ sSup s := by rcases s.eq_empty_or_nonempty with (rfl | hne) Β· rw [sInf_empty, sSup_empty] Β· exact csInf_le_csSup h₁ hβ‚‚ hne theorem cauSeq_converges (f : CauSeq ℝ abs) : βˆƒ x, f β‰ˆ const abs x := by let s := {x : ℝ | const abs x < f} have lb : βˆƒ x, x ∈ s := exists_lt f have ub' : βˆ€ x, f < const abs x β†’ βˆ€ y ∈ s, y ≀ x := fun x h y yS => le_of_lt <| const_lt.1 <| CauSeq.lt_trans yS h have ub : βˆƒ x, βˆ€ y ∈ s, y ≀ x := (exists_gt f).imp ub' refine ⟨sSup s, ((lt_total _ _).resolve_left fun h => ?_).resolve_right fun h => ?_⟩ Β· rcases h with ⟨Ρ, Ξ΅0, i, ih⟩ refine (csSup_le lb (ub' _ ?_)).not_gt (sub_lt_self _ (half_pos Ξ΅0)) refine ⟨_, half_pos Ξ΅0, i, fun j ij => ?_⟩ rw [sub_apply, const_apply, sub_right_comm, le_sub_iff_add_le, add_halves] exact ih _ ij Β· rcases h with ⟨Ρ, Ξ΅0, i, ih⟩ refine (le_csSup ub ?_).not_gt ((lt_add_iff_pos_left _).2 (half_pos Ξ΅0)) refine ⟨_, half_pos Ξ΅0, i, fun j ij => ?_⟩ rw [sub_apply, const_apply, add_comm, ← sub_sub, le_sub_iff_add_le, add_halves] exact ih _ ij instance : CauSeq.IsComplete ℝ abs := ⟨cauSeq_converges⟩ open Set theorem iInf_Ioi_eq_iInf_rat_gt {f : ℝ β†’ ℝ} (x : ℝ) (hf : BddBelow (f '' Ioi x)) (hf_mono : Monotone f) : β¨… r : Ioi x, f r = β¨… q : { q' : β„š // x < q' }, f q := by refine le_antisymm ?_ ?_ Β· have : Nonempty { r' : β„š // x < ↑r' } := by obtain ⟨r, hrx⟩ := exists_rat_gt x exact ⟨⟨r, hrx⟩⟩ refine le_ciInf fun r => ?_ obtain ⟨y, hxy, hyr⟩ := exists_rat_btwn r.prop refine ciInf_set_le hf (hxy.trans ?_) exact_mod_cast hyr Β· refine le_ciInf fun q => ?_ have hq := q.prop rw [mem_Ioi] at hq obtain ⟨y, hxy, hyq⟩ := exists_rat_btwn hq refine (ciInf_le ?_ ?_).trans ?_ Β· refine ⟨hf.some, fun z => ?_⟩ rintro ⟨u, rfl⟩ suffices hfu : f u ∈ f '' Ioi x from hf.choose_spec hfu exact ⟨u, u.prop, rfl⟩ Β· exact ⟨y, hxy⟩ Β· refine hf_mono (le_trans ?_ hyq.le) norm_cast theorem not_bddAbove_coe : Β¬ (BddAbove <| range (fun (x : β„š) ↦ (x : ℝ))) := by dsimp only [BddAbove, upperBounds] rw [Set.not_nonempty_iff_eq_empty] ext simpa using exists_rat_gt _ theorem not_bddBelow_coe : Β¬ (BddBelow <| range (fun (x : β„š) ↦ (x : ℝ))) := by dsimp only [BddBelow, lowerBounds] rw [Set.not_nonempty_iff_eq_empty] ext simpa using exists_rat_lt _ theorem iUnion_Iic_rat : ⋃ r : β„š, Iic (r : ℝ) = univ := by exact iUnion_Iic_of_not_bddAbove_range not_bddAbove_coe theorem iInter_Iic_rat : β‹‚ r : β„š, Iic (r : ℝ) = βˆ… := by exact iInter_Iic_eq_empty_iff.mpr not_bddBelow_coe /-- Exponentiation is eventually larger than linear growth. -/ lemma exists_natCast_add_one_lt_pow_of_one_lt (ha : 1 < a) : βˆƒ m : β„•, (m + 1 : ℝ) < a ^ m := by obtain ⟨k, posk, hk⟩ : βˆƒ k : β„•, 0 < k ∧ 1 / k + 1 < a := by contrapose! ha refine le_of_forall_lt_rat_imp_le ?_ intro q hq refine (ha q.den (by positivity)).trans ?_ rw [← le_sub_iff_add_le, div_le_iffβ‚€ (by positivity), sub_mul, one_mul] norm_cast at hq ⊒ rw [← q.num_div_den, one_lt_div (by positivity)] at hq rw [q.mul_den_eq_num] norm_cast at hq ⊒ cutsat use 2 * k ^ 2 calc ((2 * k ^ 2 : β„•) + 1 : ℝ) ≀ 2 ^ (2 * k) := mod_cast Nat.two_mul_sq_add_one_le_two_pow_two_mul _ _ = (1 / k * k + 1 : ℝ) ^ (2 * k) := by simp [posk.ne']; norm_num _ ≀ ((1 / k + 1) ^ k : ℝ) ^ (2 * k) := by gcongr; exact mul_add_one_le_add_one_pow (by simp) _ _ = (1 / k + 1 : ℝ) ^ (2 * k ^ 2) := by rw [← pow_mul, mul_left_comm, sq] _ < a ^ (2 * k ^ 2) := by gcongr lemma exists_nat_pos_inv_lt {b : ℝ} (hb : 0 < b) : βˆƒ (n : β„•), 0 < n ∧ (n : ℝ)⁻¹ < b := by refine (exists_nat_gt b⁻¹).imp fun k hk ↦ ?_ have := (inv_pos_of_pos hb).trans hk refine ⟨Nat.cast_pos.mp this, ?_⟩ rwa [inv_lt_commβ‚€ this hb] end Real
.lake/packages/mathlib/Mathlib/Data/Real/Basic.lean
import Mathlib.Algebra.Order.CauSeq.Completion import Mathlib.Algebra.Order.Ring.Rat import Mathlib.Data.Rat.Cast.Defs /-! # Real numbers from Cauchy sequences This file defines `ℝ` as the type of equivalence classes of Cauchy sequences of rational numbers. This choice is motivated by how easy it is to prove that `ℝ` is a commutative ring, by simply lifting everything to `β„š`. The facts that the real numbers are an Archimedean floor ring, and a conditionally complete linear order, have been deferred to the file `Mathlib/Data/Real/Archimedean.lean`, in order to keep the imports here simple. The fact that the real numbers are a (trivial) *-ring has similarly been deferred to `Mathlib/Data/Real/Star.lean`. -/ assert_not_exists Finset Module Submonoid FloorRing /-- The type `ℝ` of real numbers constructed as equivalence classes of Cauchy sequences of rational numbers. -/ structure Real where ofCauchy :: /-- The underlying Cauchy completion -/ cauchy : CauSeq.Completion.Cauchy (abs : β„š β†’ β„š) @[inherit_doc] notation "ℝ" => Real namespace CauSeq.Completion -- this can't go in `Data.Real.CauSeqCompletion` as the structure on `β„š` isn't available @[simp] theorem ofRat_rat {abv : β„š β†’ β„š} [IsAbsoluteValue abv] (q : β„š) : ofRat (q : β„š) = (q : Cauchy abv) := rfl end CauSeq.Completion namespace Real open CauSeq CauSeq.Completion variable {x : ℝ} theorem ext_cauchy_iff : βˆ€ {x y : Real}, x = y ↔ x.cauchy = y.cauchy | ⟨a⟩, ⟨b⟩ => by rw [ofCauchy.injEq] theorem ext_cauchy {x y : Real} : x.cauchy = y.cauchy β†’ x = y := ext_cauchy_iff.2 /-- The real numbers are isomorphic to the quotient of Cauchy sequences on the rationals. -/ def equivCauchy : ℝ ≃ CauSeq.Completion.Cauchy (abs : β„š β†’ β„š) := ⟨Real.cauchy, Real.ofCauchy, fun ⟨_⟩ => rfl, fun _ => rfl⟩ -- irreducible doesn't work for instances: https://github.com/leanprover-community/lean/issues/511 private irreducible_def zero : ℝ := ⟨0⟩ private irreducible_def one : ℝ := ⟨1⟩ private irreducible_def add : ℝ β†’ ℝ β†’ ℝ | ⟨a⟩, ⟨b⟩ => ⟨a + b⟩ private irreducible_def neg : ℝ β†’ ℝ | ⟨a⟩ => ⟨-a⟩ private irreducible_def mul : ℝ β†’ ℝ β†’ ℝ | ⟨a⟩, ⟨b⟩ => ⟨a * b⟩ private noncomputable irreducible_def inv' : ℝ β†’ ℝ | ⟨a⟩ => ⟨a⁻¹⟩ instance : Zero ℝ := ⟨zero⟩ instance : One ℝ := ⟨one⟩ instance : Add ℝ := ⟨add⟩ instance : Neg ℝ := ⟨neg⟩ instance : Mul ℝ := ⟨mul⟩ instance : Sub ℝ := ⟨fun a b => a + -b⟩ noncomputable instance : Inv ℝ := ⟨inv'⟩ theorem ofCauchy_zero : (⟨0⟩ : ℝ) = 0 := zero_def.symm theorem ofCauchy_one : (⟨1⟩ : ℝ) = 1 := one_def.symm theorem ofCauchy_add (a b) : (⟨a + b⟩ : ℝ) = ⟨a⟩ + ⟨b⟩ := (add_def _ _).symm theorem ofCauchy_neg (a) : (⟨-a⟩ : ℝ) = -⟨a⟩ := (neg_def _).symm theorem ofCauchy_sub (a b) : (⟨a - b⟩ : ℝ) = ⟨a⟩ - ⟨b⟩ := by rw [sub_eq_add_neg, ofCauchy_add, ofCauchy_neg] rfl theorem ofCauchy_mul (a b) : (⟨a * b⟩ : ℝ) = ⟨a⟩ * ⟨b⟩ := (mul_def _ _).symm theorem ofCauchy_inv {f} : (⟨f⁻¹⟩ : ℝ) = ⟨f⟩⁻¹ := show _ = inv' _ by rw [inv'] theorem cauchy_zero : (0 : ℝ).cauchy = 0 := show zero.cauchy = 0 by rw [zero_def] theorem cauchy_one : (1 : ℝ).cauchy = 1 := show one.cauchy = 1 by rw [one_def] theorem cauchy_add : βˆ€ a b, (a + b : ℝ).cauchy = a.cauchy + b.cauchy | ⟨a⟩, ⟨b⟩ => show (add _ _).cauchy = _ by rw [add_def] theorem cauchy_neg : βˆ€ a, (-a : ℝ).cauchy = -a.cauchy | ⟨a⟩ => show (neg _).cauchy = _ by rw [neg_def] theorem cauchy_mul : βˆ€ a b, (a * b : ℝ).cauchy = a.cauchy * b.cauchy | ⟨a⟩, ⟨b⟩ => show (mul _ _).cauchy = _ by rw [mul_def] theorem cauchy_sub : βˆ€ a b, (a - b : ℝ).cauchy = a.cauchy - b.cauchy | ⟨a⟩, ⟨b⟩ => by rw [sub_eq_add_neg, ← cauchy_neg, ← cauchy_add] rfl theorem cauchy_inv : βˆ€ f, (f⁻¹ : ℝ).cauchy = f.cauchy⁻¹ | ⟨f⟩ => show (inv' _).cauchy = _ by rw [inv'] instance instNatCast : NatCast ℝ where natCast n := ⟨n⟩ instance instIntCast : IntCast ℝ where intCast z := ⟨z⟩ instance instNNRatCast : NNRatCast ℝ where nnratCast q := ⟨q⟩ instance instRatCast : RatCast ℝ where ratCast q := ⟨q⟩ lemma ofCauchy_natCast (n : β„•) : (⟨n⟩ : ℝ) = n := rfl lemma ofCauchy_intCast (z : β„€) : (⟨z⟩ : ℝ) = z := rfl lemma ofCauchy_nnratCast (q : β„šβ‰₯0) : (⟨q⟩ : ℝ) = q := rfl lemma ofCauchy_ratCast (q : β„š) : (⟨q⟩ : ℝ) = q := rfl lemma cauchy_natCast (n : β„•) : (n : ℝ).cauchy = n := rfl lemma cauchy_intCast (z : β„€) : (z : ℝ).cauchy = z := rfl lemma cauchy_nnratCast (q : β„šβ‰₯0) : (q : ℝ).cauchy = q := rfl lemma cauchy_ratCast (q : β„š) : (q : ℝ).cauchy = q := rfl instance commRing : CommRing ℝ where natCast n := ⟨n⟩ intCast z := ⟨z⟩ npow := @npowRec ℝ ⟨1⟩ ⟨(Β· * Β·)⟩ nsmul := @nsmulRec ℝ ⟨0⟩ ⟨(Β· + Β·)⟩ zsmul := @zsmulRec ℝ ⟨0⟩ ⟨(Β· + Β·)⟩ ⟨@Neg.neg ℝ _⟩ (@nsmulRec ℝ ⟨0⟩ ⟨(Β· + Β·)⟩) add_zero a := by apply ext_cauchy; simp [cauchy_add, cauchy_zero] zero_add a := by apply ext_cauchy; simp [cauchy_add, cauchy_zero] add_comm a b := by apply ext_cauchy; simp only [cauchy_add, add_comm] add_assoc a b c := by apply ext_cauchy; simp only [cauchy_add, add_assoc] mul_zero a := by apply ext_cauchy; simp [cauchy_mul, cauchy_zero] zero_mul a := by apply ext_cauchy; simp [cauchy_mul, cauchy_zero] mul_one a := by apply ext_cauchy; simp [cauchy_mul, cauchy_one] one_mul a := by apply ext_cauchy; simp [cauchy_mul, cauchy_one] mul_comm a b := by apply ext_cauchy; simp only [cauchy_mul, mul_comm] mul_assoc a b c := by apply ext_cauchy; simp only [cauchy_mul, mul_assoc] left_distrib a b c := by apply ext_cauchy; simp only [cauchy_add, cauchy_mul, mul_add] right_distrib a b c := by apply ext_cauchy; simp only [cauchy_add, cauchy_mul, add_mul] neg_add_cancel a := by apply ext_cauchy; simp [cauchy_add, cauchy_neg, cauchy_zero] natCast_zero := by apply ext_cauchy; simp [cauchy_zero] natCast_succ n := by apply ext_cauchy; simp [cauchy_one, cauchy_add] intCast_negSucc z := by apply ext_cauchy; simp [cauchy_neg, cauchy_natCast] /-- `Real.equivCauchy` as a ring equivalence. -/ @[simps] def ringEquivCauchy : ℝ ≃+* CauSeq.Completion.Cauchy (abs : β„š β†’ β„š) := { equivCauchy with toFun := cauchy invFun := ofCauchy map_add' := cauchy_add map_mul' := cauchy_mul } /-! Extra instances to short-circuit type class resolution. These short-circuits have an additional property of ensuring that a computable path is found; if `Field ℝ` is found first, then decaying it to these typeclasses would result in a `noncomputable` version of them. -/ instance instRing : Ring ℝ := by infer_instance instance : CommSemiring ℝ := by infer_instance instance semiring : Semiring ℝ := by infer_instance instance : CommMonoidWithZero ℝ := by infer_instance instance : MonoidWithZero ℝ := by infer_instance instance : AddCommGroup ℝ := by infer_instance instance : AddGroup ℝ := by infer_instance instance : AddCommMonoid ℝ := by infer_instance instance : AddMonoid ℝ := by infer_instance instance : AddLeftCancelSemigroup ℝ := by infer_instance instance : AddRightCancelSemigroup ℝ := by infer_instance instance : AddCommSemigroup ℝ := by infer_instance instance : AddSemigroup ℝ := by infer_instance instance : CommMonoid ℝ := by infer_instance instance : Monoid ℝ := by infer_instance instance : CommSemigroup ℝ := by infer_instance instance : Semigroup ℝ := by infer_instance instance : Inhabited ℝ := ⟨0⟩ /-- Make a real number from a Cauchy sequence of rationals (by taking the equivalence class). -/ def mk (x : CauSeq β„š abs) : ℝ := ⟨CauSeq.Completion.mk x⟩ theorem mk_eq {f g : CauSeq β„š abs} : mk f = mk g ↔ f β‰ˆ g := ext_cauchy_iff.trans CauSeq.Completion.mk_eq private irreducible_def lt : ℝ β†’ ℝ β†’ Prop | ⟨x⟩, ⟨y⟩ => (Quotient.liftOnβ‚‚ x y (Β· < Β·)) fun _ _ _ _ hf hg => propext <| ⟨fun h => lt_of_eq_of_lt (Setoid.symm hf) (lt_of_lt_of_eq h hg), fun h => lt_of_eq_of_lt hf (lt_of_lt_of_eq h (Setoid.symm hg))⟩ instance : LT ℝ := ⟨lt⟩ theorem lt_cauchy {f g} : (⟨⟦f⟧⟩ : ℝ) < ⟨⟦g⟧⟩ ↔ f < g := show lt _ _ ↔ _ by rw [lt_def]; rfl @[simp] theorem mk_lt {f g : CauSeq β„š abs} : mk f < mk g ↔ f < g := lt_cauchy theorem mk_zero : mk 0 = 0 := by rw [← ofCauchy_zero]; rfl theorem mk_one : mk 1 = 1 := by rw [← ofCauchy_one]; rfl theorem mk_add {f g : CauSeq β„š abs} : mk (f + g) = mk f + mk g := by simp [mk, ← ofCauchy_add] theorem mk_mul {f g : CauSeq β„š abs} : mk (f * g) = mk f * mk g := by simp [mk, ← ofCauchy_mul] theorem mk_neg {f : CauSeq β„š abs} : mk (-f) = -mk f := by simp [mk, ← ofCauchy_neg] @[simp] theorem mk_pos {f : CauSeq β„š abs} : 0 < mk f ↔ Pos f := by rw [← mk_zero, mk_lt] exact iff_of_eq (congr_arg Pos (sub_zero f)) lemma mk_const {x : β„š} : mk (const abs x) = x := rfl private irreducible_def le (x y : ℝ) : Prop := x < y ∨ x = y instance : LE ℝ := ⟨le⟩ private theorem le_def' {x y : ℝ} : x ≀ y ↔ x < y ∨ x = y := iff_of_eq <| le_def _ _ @[simp] theorem mk_le {f g : CauSeq β„š abs} : mk f ≀ mk g ↔ f ≀ g := by simp only [le_def', mk_lt, mk_eq]; rfl @[elab_as_elim] protected theorem ind_mk {C : Real β†’ Prop} (x : Real) (h : βˆ€ y, C (mk y)) : C x := by obtain ⟨x⟩ := x induction x using Quot.induction_on exact h _ instance partialOrder : PartialOrder ℝ where lt_iff_le_not_ge a b := by induction a using Real.ind_mk induction b using Real.ind_mk simpa using lt_iff_le_not_ge le_refl a := by induction a using Real.ind_mk rw [mk_le] le_trans a b c := by induction a using Real.ind_mk induction b using Real.ind_mk induction c using Real.ind_mk simpa using le_trans le_antisymm a b := by induction a using Real.ind_mk induction b using Real.ind_mk simpa [mk_eq] using CauSeq.le_antisymm instance : Preorder ℝ := by infer_instance theorem ratCast_lt {x y : β„š} : (x : ℝ) < (y : ℝ) ↔ x < y := by rw [← mk_const, ← mk_const, mk_lt] exact const_lt protected theorem zero_lt_one : (0 : ℝ) < 1 := by convert ratCast_lt.2 zero_lt_one <;> simp [← ofCauchy_ratCast, ofCauchy_one, ofCauchy_zero] @[deprecated ZeroLEOneClass.factZeroLtOne (since := "2025-05-12")] protected theorem fact_zero_lt_one : Fact ((0 : ℝ) < 1) := ⟨Real.zero_lt_one⟩ instance instNontrivial : Nontrivial ℝ where exists_pair_ne := ⟨0, 1, Real.zero_lt_one.ne⟩ instance instZeroLEOneClass : ZeroLEOneClass ℝ where zero_le_one := le_of_lt Real.zero_lt_one instance instIsOrderedAddMonoid : IsOrderedAddMonoid ℝ where add_le_add_left := by simp only [le_iff_eq_or_lt] rintro a b ⟨rfl, h⟩ Β· simp only [lt_self_iff_false, or_false, forall_const] Β· refine fun c => Or.inr ?_ induction a using Real.ind_mk with | _ a => induction b using Real.ind_mk with | _ b => induction c using Real.ind_mk with | _ c => simp only [mk_lt, ← mk_add] at * change Pos _ at * rwa [add_sub_add_left_eq_sub] @[deprecated (since := "2025-09-15")] protected alias add_lt_add_iff_left := _root_.add_lt_add_iff_left instance instIsStrictOrderedRing : IsStrictOrderedRing ℝ := .of_mul_pos fun a b ↦ by induction a using Real.ind_mk induction b using Real.ind_mk simpa only [mk_lt, mk_pos, ← mk_mul] using CauSeq.mul_pos instance instIsOrderedRing : IsOrderedRing ℝ := inferInstance instance instIsOrderedCancelAddMonoid : IsOrderedCancelAddMonoid ℝ := inferInstance private irreducible_def sup : ℝ β†’ ℝ β†’ ℝ | ⟨x⟩, ⟨y⟩ => ⟨Quotient.mapβ‚‚ (Β· βŠ” Β·) (fun _ _ hx _ _ hy => sup_equiv_sup hx hy) x y⟩ instance : Max ℝ := ⟨sup⟩ theorem ofCauchy_sup (a b) : (⟨⟦a βŠ” b⟧⟩ : ℝ) = ⟨⟦a⟧⟩ βŠ” ⟨⟦b⟧⟩ := show _ = sup _ _ by rw [sup_def] rfl @[simp] theorem mk_sup (a b) : (mk (a βŠ” b) : ℝ) = mk a βŠ” mk b := ofCauchy_sup _ _ private irreducible_def inf : ℝ β†’ ℝ β†’ ℝ | ⟨x⟩, ⟨y⟩ => ⟨Quotient.mapβ‚‚ (Β· βŠ“ Β·) (fun _ _ hx _ _ hy => inf_equiv_inf hx hy) x y⟩ instance : Min ℝ := ⟨inf⟩ theorem ofCauchy_inf (a b) : (⟨⟦a βŠ“ b⟧⟩ : ℝ) = ⟨⟦a⟧⟩ βŠ“ ⟨⟦b⟧⟩ := show _ = inf _ _ by rw [inf_def] rfl @[simp] theorem mk_inf (a b) : (mk (a βŠ“ b) : ℝ) = mk a βŠ“ mk b := ofCauchy_inf _ _ instance : DistribLattice ℝ where sup := (Β· βŠ” Β·) le_sup_left := by intro a b induction a using Real.ind_mk induction b using Real.ind_mk dsimp only; rw [← mk_sup, mk_le] exact CauSeq.le_sup_left le_sup_right := by intro a b induction a using Real.ind_mk induction b using Real.ind_mk dsimp only; rw [← mk_sup, mk_le] exact CauSeq.le_sup_right sup_le := by intro a b c induction a using Real.ind_mk induction b using Real.ind_mk induction c using Real.ind_mk simp_rw [← mk_sup, mk_le] exact CauSeq.sup_le inf := (Β· βŠ“ Β·) inf_le_left := by intro a b induction a using Real.ind_mk induction b using Real.ind_mk dsimp only; rw [← mk_inf, mk_le] exact CauSeq.inf_le_left inf_le_right := by intro a b induction a using Real.ind_mk induction b using Real.ind_mk dsimp only; rw [← mk_inf, mk_le] exact CauSeq.inf_le_right le_inf := by intro a b c induction a using Real.ind_mk induction b using Real.ind_mk induction c using Real.ind_mk simp_rw [← mk_inf, mk_le] exact CauSeq.le_inf le_sup_inf := by intro a b c induction a using Real.ind_mk induction b using Real.ind_mk induction c using Real.ind_mk apply Eq.le simp only [← mk_sup, ← mk_inf] exact congr_arg mk (CauSeq.sup_inf_distrib_left ..).symm -- Extra instances to short-circuit type class resolution instance lattice : Lattice ℝ := inferInstance instance : SemilatticeInf ℝ := inferInstance instance : SemilatticeSup ℝ := inferInstance instance leTotal_R : IsTotal ℝ (Β· ≀ Β·) := ⟨by intro a b induction a using Real.ind_mk induction b using Real.ind_mk simpa using CauSeq.le_total ..⟩ open scoped Classical in noncomputable instance linearOrder : LinearOrder ℝ := Lattice.toLinearOrder ℝ instance : IsDomain ℝ := IsStrictOrderedRing.isDomain noncomputable instance instDivInvMonoid : DivInvMonoid ℝ where lemma ofCauchy_div (f g) : (⟨f / g⟩ : ℝ) = (⟨f⟩ : ℝ) / (⟨g⟩ : ℝ) := by simp_rw [div_eq_mul_inv, ofCauchy_mul, ofCauchy_inv] noncomputable instance instField : Field ℝ where mul_inv_cancel := by rintro ⟨a⟩ h rw [mul_comm] simp only [← ofCauchy_inv, ← ofCauchy_mul, ← ofCauchy_one, ← ofCauchy_zero, Ne, ofCauchy.injEq] at * exact CauSeq.Completion.inv_mul_cancel h inv_zero := by simp [← ofCauchy_zero, ← ofCauchy_inv] nnqsmul := _ nnqsmul_def := fun _ _ => rfl qsmul := _ qsmul_def := fun _ _ => rfl nnratCast_def q := by rw [← ofCauchy_nnratCast, NNRat.cast_def, ofCauchy_div, ofCauchy_natCast, ofCauchy_natCast] ratCast_def q := by rw [← ofCauchy_ratCast, Rat.cast_def, ofCauchy_div, ofCauchy_natCast, ofCauchy_intCast] -- Extra instances to short-circuit type class resolution noncomputable instance : DivisionRing ℝ := by infer_instance noncomputable instance decidableLT (a b : ℝ) : Decidable (a < b) := by infer_instance noncomputable instance decidableLE (a b : ℝ) : Decidable (a ≀ b) := by infer_instance noncomputable instance decidableEq (a b : ℝ) : Decidable (a = b) := by infer_instance /-- Show an underlying Cauchy sequence for real numbers. The representative chosen is the one passed in the VM to `Quot.mk`, so two Cauchy sequences converging to the same number may be printed differently. -/ unsafe instance : Repr ℝ where reprPrec r p := Repr.addAppParen ("Real.ofCauchy " ++ repr r.cauchy) p theorem le_mk_of_forall_le {f : CauSeq β„š abs} : (βˆƒ i, βˆ€ j β‰₯ i, x ≀ f j) β†’ x ≀ mk f := by intro h induction x using Real.ind_mk apply le_of_not_gt rw [mk_lt] rintro ⟨K, K0, hK⟩ obtain ⟨i, H⟩ := exists_forall_ge_and h (exists_forall_ge_and hK (f.cauchy₃ <| half_pos K0)) apply not_lt_of_ge (H _ le_rfl).1 rw [← mk_const, mk_lt] refine ⟨_, half_pos K0, i, fun j ij => ?_⟩ have := add_le_add (H _ ij).2.1 (le_of_lt (abs_lt.1 <| (H _ le_rfl).2.2 _ ij).1) rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this theorem mk_le_of_forall_le {f : CauSeq β„š abs} {x : ℝ} (h : βˆƒ i, βˆ€ j β‰₯ i, (f j : ℝ) ≀ x) : mk f ≀ x := by obtain ⟨i, H⟩ := h rw [← neg_le_neg_iff, ← mk_neg] exact le_mk_of_forall_le ⟨i, fun j ij => by simp [H _ ij]⟩ theorem mk_near_of_forall_near {f : CauSeq β„š abs} {x : ℝ} {Ξ΅ : ℝ} (H : βˆƒ i, βˆ€ j β‰₯ i, |(f j : ℝ) - x| ≀ Ξ΅) : |mk f - x| ≀ Ξ΅ := abs_sub_le_iff.2 ⟨sub_le_iff_le_add'.2 <| mk_le_of_forall_le <| H.imp fun _ h j ij => sub_le_iff_le_add'.1 (abs_sub_le_iff.1 <| h j ij).1, sub_le_comm.1 <| le_mk_of_forall_le <| H.imp fun _ h j ij => sub_le_comm.1 (abs_sub_le_iff.1 <| h j ij).2⟩ lemma mul_add_one_le_add_one_pow {a : ℝ} (ha : 0 ≀ a) (b : β„•) : a * b + 1 ≀ (a + 1) ^ b := by rcases ha.eq_or_lt with rfl | ha' Β· simp clear ha induction b generalizing a with | zero => simp | succ b hb => calc a * ↑(b + 1) + 1 = (0 + 1) ^ b * a + (a * b + 1) := by simp [mul_add, add_assoc, add_left_comm] _ ≀ (a + 1) ^ b * a + (a + 1) ^ b := by gcongr Β· norm_num Β· exact hb ha' _ = (a + 1) ^ (b + 1) := by simp [pow_succ, mul_add] end Real /-- A function `f : R β†’ ℝ` is power-multiplicative if for all `r ∈ R` and all positive `n ∈ β„•`, `f (r ^ n) = (f r) ^ n`. -/ def IsPowMul {R : Type*} [Pow R β„•] (f : R β†’ ℝ) := βˆ€ (a : R) {n : β„•}, 1 ≀ n β†’ f (a ^ n) = f a ^ n lemma IsPowMul.map_one_le_one {R : Type*} [Monoid R] {f : R β†’ ℝ} (hf : IsPowMul f) : f 1 ≀ 1 := by have hf1 : (f 1)^2 = f 1 := by conv_rhs => rw [← one_pow 2, hf _ one_le_two] rcases eq_zero_or_one_of_sq_eq_self hf1 with h | h <;> rw [h] exact zero_le_one /-- A ring homomorphism `f : Ξ± β†’+* Ξ²` is bounded with respect to the functions `nΞ± : Ξ± β†’ ℝ` and `nΞ² : Ξ² β†’ ℝ` if there exists a positive constant `C` such that for all `x` in `Ξ±`, `nΞ² (f x) ≀ C * nΞ± x`. -/ def RingHom.IsBoundedWrt {Ξ± : Type*} [Ring Ξ±] {Ξ² : Type*} [Ring Ξ²] (nΞ± : Ξ± β†’ ℝ) (nΞ² : Ξ² β†’ ℝ) (f : Ξ± β†’+* Ξ²) : Prop := βˆƒ C : ℝ, 0 < C ∧ βˆ€ x : Ξ±, nΞ² (f x) ≀ C * nΞ± x
.lake/packages/mathlib/Mathlib/Data/Real/Cardinality.lean
import Mathlib.Analysis.Real.Cardinality deprecated_module (since := "2025-08-26")
.lake/packages/mathlib/Mathlib/Data/Real/EReal.lean
import Mathlib.Data.EReal.Basic deprecated_module (since := "2025-04-13")
.lake/packages/mathlib/Mathlib/Data/Real/Hyperreal.lean
import Mathlib.Analysis.Real.Hyperreal deprecated_module (since := "2025-08-26")
.lake/packages/mathlib/Mathlib/Data/Real/Embedding.lean
import Mathlib.Algebra.Order.Group.Pointwise.CompleteLattice import Mathlib.Algebra.Order.Hom.Monoid import Mathlib.Algebra.Order.Module.Defs import Mathlib.Data.Real.Archimedean /-! # Embedding of archimedean groups into reals This file provides embedding of any archimedean groups into reals. ## Main declarations * `Archimedean.embedReal` defines an injective `M β†’+o ℝ` for archimedean group `M` with a positive `1` element. `1` is preserved by the map. * `Archimedean.exists_orderAddMonoidHom_real_injective` states there exists an injective `M β†’+o ℝ` for any archimedean group `M` without specifying the `1` element in `M`. -/ variable {M : Type*} variable [AddCommGroup M] [LinearOrder M] [IsOrderedAddMonoid M] [One M] theorem mul_smul_one_lt_iff {num : β„€} {n den : β„•} (hn : 0 < n) {x : M} : (num * n) β€’ 1 < (n * den : β„€) β€’ x ↔ num β€’ 1 < den β€’ x := by rw [mul_comm num, mul_smul, mul_smul, natCast_zsmul x den] exact ⟨fun h ↦ lt_of_smul_lt_smul_left h (Int.natCast_nonneg n), fun h ↦ zsmul_lt_zsmul_right (Int.natCast_pos.mpr hn) h⟩ /-- For `u v : β„š` and `x y : M`, one can informally write `u < x β†’ v < y β†’ u + v < x + y`. We formalize this using smul. -/ theorem num_smul_one_lt_den_smul_add {u v : β„š} {x y : M} (hu : u.num β€’ 1 < u.den β€’ x) (hv : v.num β€’ 1 < v.den β€’ y) : (u + v).num β€’ 1 < (u + v).den β€’ (x + y) := by have hu' : (u.num * v.den) β€’ 1 < (u.den * v.den : β„€) β€’ x := by simpa [mul_comm] using (mul_smul_one_lt_iff v.den_pos).mpr hu suffices ((u + v).num * u.den * v.den) β€’ 1 < ((u + v).den : β„€) β€’ (u.den * v.den : β„€) β€’ (x + y) by refine (mul_smul_one_lt_iff (mul_pos u.den_pos v.den_pos)).mp ?_ rwa [Nat.cast_mul, ← mul_assoc, mul_comm _ ((u + v).den : β„€), ← smul_eq_mul ((u + v).den : β„€), smul_assoc] rw [Rat.add_num_den', mul_comm, ← smul_smul] rw [smul_lt_smul_iff_of_pos_left (by simpa using (u + v).den_pos)] rw [add_smul, smul_add] exact add_lt_add hu' ((mul_smul_one_lt_iff u.den_pos).mpr hv) /-- Given `x` from `M`, one can informally write that, by transitivity, `num / den ≀ x β†’ x ≀ n β†’ num / den ≀ n` for `den : β„•` and `num n : β„•`. To avoid writing division for integer `num` and `den`, we express this in terms of multiplication. -/ theorem num_le_nat_mul_den [ZeroLEOneClass M] [NeZero (1 : M)] {num : β„€} {den : β„•} {x : M} (h : num β€’ 1 ≀ den β€’ x) {n : β„€} (hn : x ≀ n β€’ 1) : num ≀ n * den := by refine le_of_smul_le_smul_right (h.trans ?_) (by simp) rw [mul_comm, ← smul_smul] simpa using nsmul_le_nsmul_right hn den namespace Archimedean /-- Set of rational numbers that are less than the "number" `x / 1`. Formally, these are numbers `p / q` such that `p β€’ 1 < q β€’ x`. -/ abbrev ratLt (x : M) : Set β„š := {r | r.num β€’ 1 < r.den β€’ x} theorem mkRat_mem_ratLt {num : β„€} {den : β„•} (hden : den β‰  0) {x : M} : mkRat num den ∈ ratLt x ↔ num β€’ 1 < den β€’ x := by rw [Set.mem_setOf] obtain ⟨m, hm0, hnum, hden⟩ := Rat.mkRat_num_den hden (show mkRat num den = _ by rfl) conv in num β€’ 1 => rw [hnum, mul_comm, ← smul_smul, natCast_zsmul] conv in den β€’ x => rw [hden, mul_comm, ← smul_smul] exact (smul_lt_smul_iff_of_pos_left (Nat.zero_lt_of_ne_zero hm0)).symm /-- `ratLt` as a set of real numbers. -/ abbrev ratLt' (x : M) : Set ℝ := (Rat.castHom ℝ) '' (ratLt x) /-- Mapping `M` to `ℝ`, defined as the supremum of `ratLt' x`. -/ noncomputable abbrev embedRealFun (x : M) := sSup (ratLt' x) variable [ZeroLEOneClass M] [NeZero (1 : M)] [Archimedean M] theorem ratLt_bddAbove (x : M) : BddAbove (ratLt x) := by obtain ⟨n, hn⟩ := Archimedean.arch x zero_lt_one use n rw [ratLt, mem_upperBounds] intro ⟨num, den, _, _⟩ rw [Rat.le_iff] suffices num β€’ 1 < den β€’ x β†’ num ≀ n * den by simpa using this intro h exact num_le_nat_mul_den h.le (by simpa using hn) theorem ratLt_nonempty (x : M) : (ratLt x).Nonempty := by obtain hneg | rfl | hxpos := lt_trichotomy x 0 Β· obtain ⟨n, hn⟩ := Archimedean.arch (-x - x) zero_lt_one use Rat.ofInt (-n) suffices -(n β€’ 1) < x by simpa using this exact neg_lt.mpr (lt_of_lt_of_le (by simpa using hneg) hn) Β· exact ⟨Rat.ofInt (-1), by simp⟩ Β· obtain ⟨n, hn⟩ := Archimedean.arch 1 hxpos use Rat.mk' 1 (n + 1) (by simp) (by simp) simpa using hn.trans_lt <| (nsmul_lt_nsmul_iff_left hxpos).mpr (by simp) open Pointwise in theorem ratLt_add (x y : M) : ratLt (x + y) = ratLt x + ratLt y := by ext a rw [Set.mem_add] constructor Β· /- Given `a ∈ ratLt 1 (x + y)`, find `u ∈ ratLt 1 x`, `v ∈ ratLt 1 y` such that `u + v = a`. In a naive attempt, one can take the denominator `d` of `a`, and find the largest `u = p / d < x / 1`. However, `d` could be too "coarse", and `v = a - u` could be 1/d too large than `y / 1`. To ensure a large enough denominator, we take `d * k`, where `1 + 1 ≀ k β€’ (d β€’ (x + y) - a.num β€’ 1)`. -/ intro h rw [Set.mem_setOf_eq] at h obtain ⟨k, hk⟩ := Archimedean.arch (1 + 1) <| sub_pos.mpr h have hk0 : k β‰  0 := by contrapose! hk simp [hk] have hka0 : k * a.den β‰  0 := mul_ne_zero hk0 a.den_ne_zero obtain ⟨m, ⟨hm1, hm2⟩, _⟩ := existsUnique_add_zsmul_mem_Ico zero_lt_one 0 (k β€’ a.den β€’ x - 1) refine ⟨mkRat m (k * a.den), ?_, mkRat (k * a.num - m) (k * a.den), ?_, ?_⟩ Β· rw [mkRat_mem_ratLt hka0, ← smul_smul] simpa using hm2 Β· have hk' : 1 + (k β€’ a.num β€’ 1 - k β€’ a.den β€’ y) ≀ k β€’ a.den β€’ x - 1 := by rw [smul_add, smul_sub, smul_add, le_sub_iff_add_le, ← sub_le_iff_le_add] at hk rw [le_sub_iff_add_le] convert hk using 1 abel have : k β€’ a.num β€’ 1 - k β€’ a.den β€’ y < m β€’ 1 := lt_of_lt_of_le (lt_add_of_pos_left _ zero_lt_one) (by simpa using hk'.trans hm1) rw [mkRat_mem_ratLt hka0, sub_smul, sub_lt_comm, ← smul_smul, ← smul_smul, natCast_zsmul] exact this Β· rw [Rat.mkRat_add_mkRat_of_den _ _ hka0] rw [add_sub_cancel, Rat.mkRat_mul_left hk0, Rat.mkRat_num_den'] Β· -- `u ∈ ratLt 1 x`, `v ∈ ratLt 1 y` β†’ `u + v ∈ ratLt 1 (x + y)` intro ⟨u, hu, v, hv, huv⟩ rw [← huv] rw [Set.mem_setOf_eq] at hu hv ⊒ exact num_smul_one_lt_den_smul_add hu hv theorem ratLt'_bddAbove (x : M) : BddAbove (ratLt' x) := Monotone.map_bddAbove Rat.cast_mono <| ratLt_bddAbove x theorem ratLt'_nonempty (x : M) : (ratLt' x).Nonempty := Set.image_nonempty.mpr (ratLt_nonempty x) open Pointwise in theorem ratLt'_add (x y : M) : ratLt' (x + y) = ratLt' x + ratLt' y := by rw [ratLt', ratLt_add, Set.image_add] variable (M) in theorem embedRealFun_zero : embedRealFun (0 : M) = 0 := by apply le_antisymm Β· apply csSup_le (ratLt'_nonempty 0) intro x unfold ratLt' ratLt suffices βˆ€ (y : β„š), y.num β€’ (1 : M) < 0 β†’ y = x β†’ x ≀ 0 by simpa using this intro y hy hyx rw [← hyx, Rat.cast_nonpos, ← Rat.num_nonpos] exact (neg_of_smul_neg_right hy zero_le_one).le Β· rw [le_csSup_iff (ratLt'_bddAbove (0 : M)) (ratLt'_nonempty 0)] intro x rw [mem_upperBounds] suffices (βˆ€ (y : β„š), y.num β€’ (1 : M) < 0 β†’ y ≀ x) β†’ 0 ≀ x by simpa using this intro h have h' (y : β„š) (hy: y < 0) : y ≀ x := by exact h _ <| (smul_neg_iff_of_neg_left (by simpa using hy)).mpr zero_lt_one contrapose! h' obtain ⟨y, hxy, hy⟩ := exists_rat_btwn h' exact ⟨y, by simpa using hy, hxy⟩ theorem embedRealFun_add (x y : M) : embedRealFun (x + y) = embedRealFun x + embedRealFun y := by rw [embedRealFun, ratLt'_add, csSup_add (ratLt'_nonempty x) (ratLt'_bddAbove x) (ratLt'_nonempty y) (ratLt'_bddAbove y)] variable (M) in theorem embedRealFun_strictMono : StrictMono (embedRealFun (M := M)) := by intro x y h have hyz : 0 < y - x := sub_pos.mpr h have hy : y = y - x + x := (sub_add_cancel y x).symm apply lt_of_sub_pos rw [hy, embedRealFun_add, add_sub_cancel_right] obtain ⟨n, hn⟩ := Archimedean.arch 1 hyz have : (Rat.mk' 1 (n + 1) (by simp) (by simp) : ℝ) ∈ ratLt' (y - x) := by simpa using hn.trans_lt <| nsmul_lt_nsmul_left hyz (show n < n + 1 by simp) exact lt_csSup_of_lt (ratLt'_bddAbove (y - x)) this (by simp [← Rat.num_pos]) variable (M) in /-- The bundled `M β†’+o ℝ` for archimedean `M` that preserves `1`. -/ noncomputable def embedReal : M β†’+o ℝ where toFun := embedRealFun map_zero' := embedRealFun_zero M map_add' := embedRealFun_add monotone' := (embedRealFun_strictMono M).monotone theorem embedReal_apply (a : M) : embedReal M a = embedRealFun a := by rfl variable (M) in theorem embedReal_injective : Function.Injective (embedReal M) := (embedRealFun_strictMono M).injective @[simp] theorem embedReal_one : (embedReal M) 1 = 1 := by rw [embedReal_apply] apply le_antisymm Β· apply csSup_le (ratLt'_nonempty 1) suffices βˆ€ (x : β„š), x.num β€’ (1 : M) < (x.den : β„€) β€’ (1 : M) β†’ (x : ℝ) ≀ 1 by simpa using this intro x hx suffices x ≀ 1 by norm_cast simpa [Rat.le_iff] using ((smul_lt_smul_iff_of_pos_right zero_lt_one).mp hx).le Β· rw [le_csSup_iff (ratLt'_bddAbove (1 : M)) (ratLt'_nonempty 1)] simp_rw [mem_upperBounds] suffices βˆ€ (x : ℝ), (βˆ€ (y : β„š), y.num β€’ (1 : M) < (y.den : β„€) β€’ 1 β†’ y ≀ x) β†’ 1 ≀ x by simpa using this intro x h have h' (y : β„š) (hy : y < 1) : y ≀ x := h _ ((smul_lt_smul_iff_of_pos_right zero_lt_one).mpr (by simpa using (Rat.lt_iff _ _).mp hy)) contrapose! h' obtain ⟨y, hxy, hy⟩ := exists_rat_btwn h' exact ⟨y, (by norm_cast at hy), hxy⟩ omit [One M] [ZeroLEOneClass M] [NeZero (1 : M)] in variable (M) in theorem exists_orderAddMonoidHom_real_injective : βˆƒ f : M β†’+o ℝ, Function.Injective f := by cases subsingleton_or_nontrivial M Β· exact ⟨0, Function.injective_of_subsingleton _⟩ Β· obtain ⟨a, ha⟩ := exists_ne (0 : M) let one : One M := ⟨|a|⟩ have : ZeroLEOneClass M := ⟨abs_nonneg a⟩ have : NeZero (1 : M) := ⟨abs_ne_zero.mpr ha⟩ exact ⟨embedReal M, embedReal_injective M⟩ end Archimedean
.lake/packages/mathlib/Mathlib/Data/Real/Irrational.lean
import Mathlib.NumberTheory.Real.Irrational deprecated_module (since := "2025-10-13")
.lake/packages/mathlib/Mathlib/Data/Real/StarOrdered.lean
import Mathlib.Algebra.Order.Star.Basic import Mathlib.Data.NNReal.Star import Mathlib.Data.Real.Sqrt /-! # `ℝ` and `ℝβ‰₯0` are *-ordered rings. -/ open scoped NNReal /-- Although the instance `RCLike.toStarOrderedRing` exists, it is locked behind the `ComplexOrder` scope because currently the order on `β„‚` is not enabled globally. But we want `StarOrderedRing ℝ` to be available globally, so we include this instance separately. In addition, providing this instance here makes it available earlier in the import hierarchy; otherwise in order to access it we would need to import `Mathlib/Analysis/RCLike/Basic.lean`. -/ instance Real.instStarOrderedRing : StarOrderedRing ℝ := StarOrderedRing.of_nonneg_iff' add_le_add_left fun r => by refine ⟨fun hr => ⟨√r, (mul_self_sqrt hr).symm⟩, ?_⟩ rintro ⟨s, rfl⟩ exact mul_self_nonneg s instance NNReal.instStarOrderedRing : StarOrderedRing ℝβ‰₯0 := by refine .of_le_iff fun x y ↦ ⟨fun h ↦ ?_, ?_⟩ Β· obtain ⟨d, rfl⟩ := exists_add_of_le h refine ⟨sqrt d, ?_⟩ simp only [star_trivial, mul_self_sqrt] Β· rintro ⟨p, -, rfl⟩ exact le_self_add
.lake/packages/mathlib/Mathlib/Data/Real/Pi/Wallis.lean
import Mathlib.Analysis.Real.Pi.Wallis deprecated_module (since := "2025-08-26")
.lake/packages/mathlib/Mathlib/Data/Real/Pi/Irrational.lean
import Mathlib.Analysis.Real.Pi.Irrational deprecated_module (since := "2025-08-26")
.lake/packages/mathlib/Mathlib/Data/Real/Pi/Leibniz.lean
import Mathlib.Analysis.Real.Pi.Leibniz deprecated_module (since := "2025-08-26")
.lake/packages/mathlib/Mathlib/Data/Real/Pi/Bounds.lean
import Mathlib.Analysis.Real.Pi.Bounds deprecated_module (since := "2025-08-26")
.lake/packages/mathlib/Mathlib/Data/Seq/Computation.lean
import Mathlib.Data.Nat.Find import Mathlib.Data.Stream.Init import Mathlib.Tactic.Common /-! # Coinductive formalization of unbounded computations. This file provides a `Computation` type where `Computation Ξ±` is the type of unbounded computations returning `Ξ±`. -/ open Function universe u v w /- coinductive Computation (Ξ± : Type u) : Type u | pure : Ξ± β†’ Computation Ξ± | think : Computation Ξ± β†’ Computation Ξ± -/ /-- `Computation Ξ±` is the type of unbounded computations returning `Ξ±`. An element of `Computation Ξ±` is an infinite sequence of `Option Ξ±` such that if `f n = some a` for some `n` then it is constantly `some a` after that. -/ def Computation (Ξ± : Type u) : Type u := { f : Stream' (Option Ξ±) // βˆ€ ⦃n a⦄, f n = some a β†’ f (n + 1) = some a } namespace Computation variable {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w} -- constructors /-- `pure a` is the computation that immediately terminates with result `a`. -/ def pure (a : Ξ±) : Computation Ξ± := ⟨Stream'.const (some a), fun _ _ => id⟩ instance : CoeTC Ξ± (Computation Ξ±) := ⟨pure⟩ -- note [use has_coe_t] /-- `think c` is the computation that delays for one "tick" and then performs computation `c`. -/ def think (c : Computation Ξ±) : Computation Ξ± := ⟨Stream'.cons none c.1, fun n a h => by rcases n with - | n Β· contradiction Β· exact c.2 h⟩ /-- `thinkN c n` is the computation that delays for `n` ticks and then performs computation `c`. -/ def thinkN (c : Computation Ξ±) : β„• β†’ Computation Ξ± | 0 => c | n + 1 => think (thinkN c n) -- check for immediate result /-- `head c` is the first step of computation, either `some a` if `c = pure a` or `none` if `c = think c'`. -/ def head (c : Computation Ξ±) : Option Ξ± := c.1.head -- one step of computation /-- `tail c` is the remainder of computation, either `c` if `c = pure a` or `c'` if `c = think c'`. -/ def tail (c : Computation Ξ±) : Computation Ξ± := ⟨c.1.tail, fun _ _ h => c.2 h⟩ /-- `empty Ξ±` is the computation that never returns, an infinite sequence of `think`s. -/ def empty (Ξ±) : Computation Ξ± := ⟨Stream'.const none, fun _ _ => id⟩ instance : Inhabited (Computation Ξ±) := ⟨empty _⟩ /-- `runFor c n` evaluates `c` for `n` steps and returns the result, or `none` if it did not terminate after `n` steps. -/ def runFor : Computation Ξ± β†’ β„• β†’ Option Ξ± := Subtype.val /-- `destruct c` is the destructor for `Computation Ξ±` as a coinductive type. It returns `inl a` if `c = pure a` and `inr c'` if `c = think c'`. -/ def destruct (c : Computation Ξ±) : Ξ± βŠ• (Computation Ξ±) := match c.1 0 with | none => Sum.inr (tail c) | some a => Sum.inl a /-- `run c` is an unsound meta function that runs `c` to completion, possibly resulting in an infinite loop in the VM. -/ unsafe def run : Computation Ξ± β†’ Ξ± | c => match destruct c with | Sum.inl a => a | Sum.inr ca => run ca theorem destruct_eq_pure {s : Computation Ξ±} {a : Ξ±} : destruct s = Sum.inl a β†’ s = pure a := by dsimp [destruct] cases f0 : s.1 0 <;> intro h Β· contradiction Β· apply Subtype.eq funext n induction n with | zero => injection h with h'; rwa [h'] at f0 | succ n IH => exact s.2 IH theorem destruct_eq_think {s : Computation Ξ±} {s'} : destruct s = Sum.inr s' β†’ s = think s' := by dsimp [destruct] rcases f0 : s.1 0 with - | a' <;> intro h Β· injection h with h' rw [← h'] obtain ⟨f, al⟩ := s apply Subtype.eq dsimp [think, tail] rw [← f0] exact (Stream'.eta f).symm Β· contradiction @[simp] theorem destruct_pure (a : Ξ±) : destruct (pure a) = Sum.inl a := rfl @[simp] theorem destruct_think : βˆ€ s : Computation Ξ±, destruct (think s) = Sum.inr s | ⟨_, _⟩ => rfl @[simp] theorem destruct_empty : destruct (empty Ξ±) = Sum.inr (empty Ξ±) := rfl @[simp] theorem head_pure (a : Ξ±) : head (pure a) = some a := rfl @[simp] theorem head_think (s : Computation Ξ±) : head (think s) = none := rfl @[simp] theorem head_empty : head (empty Ξ±) = none := rfl @[simp] theorem tail_pure (a : Ξ±) : tail (pure a) = pure a := rfl @[simp] theorem tail_think (s : Computation Ξ±) : tail (think s) = s := rfl @[simp] theorem tail_empty : tail (empty Ξ±) = empty Ξ± := rfl theorem think_empty : empty Ξ± = think (empty Ξ±) := destruct_eq_think destruct_empty /-- Recursion principle for computations, compare with `List.recOn`. -/ @[elab_as_elim] def recOn {motive : Computation Ξ± β†’ Sort v} (s : Computation Ξ±) (pure : βˆ€ a, motive (pure a)) (think : βˆ€ s, motive (think s)) : motive s := match H : destruct s with | Sum.inl v => by rw [destruct_eq_pure H] apply pure | Sum.inr v => match v with | ⟨a, s'⟩ => by rw [destruct_eq_think H] apply think /-- Corecursor constructor for `corec` -/ def Corec.f (f : Ξ² β†’ Ξ± βŠ• Ξ²) : Ξ± βŠ• Ξ² β†’ Option Ξ± Γ— (Ξ± βŠ• Ξ²) | Sum.inl a => (some a, Sum.inl a) | Sum.inr b => (match f b with | Sum.inl a => some a | Sum.inr _ => none, f b) /-- `corec f b` is the corecursor for `Computation Ξ±` as a coinductive type. If `f b = inl a` then `corec f b = pure a`, and if `f b = inl b'` then `corec f b = think (corec f b')`. -/ def corec (f : Ξ² β†’ Ξ± βŠ• Ξ²) (b : Ξ²) : Computation Ξ± := by refine ⟨Stream'.corec' (Corec.f f) (Sum.inr b), fun n a' h => ?_⟩ rw [Stream'.corec'_eq] change Stream'.corec' (Corec.f f) (Corec.f f (Sum.inr b)).2 n = some a' revert h; generalize Sum.inr b = o induction n generalizing o with | zero => change (Corec.f f o).1 = some a' β†’ (Corec.f f (Corec.f f o).2).1 = some a' rcases o with _ | b <;> intro h Β· exact h unfold Corec.f at *; split <;> simp_all | succ n IH => rw [Stream'.corec'_eq (Corec.f f) (Corec.f f o).2, Stream'.corec'_eq (Corec.f f) o] exact IH (Corec.f f o).2 /-- left map of `βŠ•` -/ def lmap (f : Ξ± β†’ Ξ²) : Ξ± βŠ• Ξ³ β†’ Ξ² βŠ• Ξ³ | Sum.inl a => Sum.inl (f a) | Sum.inr b => Sum.inr b /-- right map of `βŠ•` -/ def rmap (f : Ξ² β†’ Ξ³) : Ξ± βŠ• Ξ² β†’ Ξ± βŠ• Ξ³ | Sum.inl a => Sum.inl a | Sum.inr b => Sum.inr (f b) attribute [simp] lmap rmap @[simp] theorem corec_eq (f : Ξ² β†’ Ξ± βŠ• Ξ²) (b : Ξ²) : destruct (corec f b) = rmap (corec f) (f b) := by dsimp [corec, destruct] rw [show Stream'.corec' (Corec.f f) (Sum.inr b) 0 = Sum.rec Option.some (fun _ ↦ none) (f b) by dsimp [Corec.f, Stream'.corec', Stream'.corec, Stream'.map, Stream'.get, Stream'.iterate] match (f b) with | Sum.inl x => rfl | Sum.inr x => rfl ] rcases h : f b with a | b'; Β· rfl dsimp [Corec.f, destruct] apply congr_arg; apply Subtype.eq dsimp [corec, tail] rw [Stream'.corec'_eq, Stream'.tail_cons] dsimp [Corec.f]; rw [h] section Bisim variable (R : Computation Ξ± β†’ Computation Ξ± β†’ Prop) /-- bisimilarity relation -/ local infixl:50 " ~ " => R /-- Bisimilarity over a sum of `Computation`s -/ def BisimO : Ξ± βŠ• (Computation Ξ±) β†’ Ξ± βŠ• (Computation Ξ±) β†’ Prop | Sum.inl a, Sum.inl a' => a = a' | Sum.inr s, Sum.inr s' => R s s' | _, _ => False attribute [simp] BisimO attribute [nolint simpNF] BisimO.eq_3 /-- Attribute expressing bisimilarity over two `Computation`s -/ def IsBisimulation := βˆ€ ⦃s₁ s₂⦄, s₁ ~ sβ‚‚ β†’ BisimO R (destruct s₁) (destruct sβ‚‚) -- If two computations are bisimilar, then they are equal theorem eq_of_bisim (bisim : IsBisimulation R) {s₁ sβ‚‚} (r : s₁ ~ sβ‚‚) : s₁ = sβ‚‚ := by apply Subtype.eq apply Stream'.eq_of_bisim fun x y => βˆƒ s s' : Computation Ξ±, s.1 = x ∧ s'.1 = y ∧ R s s' Β· dsimp [Stream'.IsBisimulation] intro t₁ tβ‚‚ e match t₁, tβ‚‚, e with | _, _, ⟨s, s', rfl, rfl, r⟩ => suffices head s = head s' ∧ R (tail s) (tail s') from And.imp id (fun r => ⟨tail s, tail s', by cases s; rfl, by cases s'; rfl, r⟩) this have h := bisim r; revert r h refine recOn s ?_ ?_ <;> intro r' <;> refine recOn s' ?_ ?_ <;> intro a' r h Β· constructor <;> dsimp at h Β· rw [h] Β· rw [h] at r rw [tail_pure, tail_pure, h] assumption Β· rw [destruct_pure, destruct_think] at h exact False.elim h Β· rw [destruct_pure, destruct_think] at h exact False.elim h Β· simp_all Β· exact ⟨s₁, sβ‚‚, rfl, rfl, r⟩ end Bisim -- It's more of a stretch to use ∈ for this relation, but it -- asserts that the computation limits to the given value. /-- Assertion that a `Computation` limits to a given value -/ protected def Mem (s : Computation Ξ±) (a : Ξ±) := some a ∈ s.1 instance : Membership Ξ± (Computation Ξ±) := ⟨Computation.Mem⟩ theorem le_stable (s : Computation Ξ±) {a m n} (h : m ≀ n) : s.1 m = some a β†’ s.1 n = some a := by obtain ⟨f, al⟩ := s induction h with | refl => exact id | step _ IH => exact fun h2 ↦ al (IH h2) theorem mem_unique {s : Computation Ξ±} {a b : Ξ±} : a ∈ s β†’ b ∈ s β†’ a = b | ⟨m, ha⟩, ⟨n, hb⟩ => by injection (le_stable s (le_max_left m n) ha.symm).symm.trans (le_stable s (le_max_right m n) hb.symm) theorem Mem.left_unique : Relator.LeftUnique ((Β· ∈ Β·) : Ξ± β†’ Computation Ξ± β†’ Prop) := fun _ _ _ => mem_unique /-- `Terminates s` asserts that the computation `s` eventually terminates with some value. -/ class Terminates (s : Computation Ξ±) : Prop where /-- assertion that there is some term `a` such that the `Computation` terminates -/ term : βˆƒ a, a ∈ s theorem terminates_iff (s : Computation Ξ±) : Terminates s ↔ βˆƒ a, a ∈ s := ⟨fun h => h.1, Terminates.mk⟩ theorem terminates_of_mem {s : Computation Ξ±} {a : Ξ±} (h : a ∈ s) : Terminates s := ⟨⟨a, h⟩⟩ theorem terminates_def (s : Computation Ξ±) : Terminates s ↔ βˆƒ n, (s.1 n).isSome := ⟨fun ⟨⟨a, n, h⟩⟩ => ⟨n, by dsimp [Stream'.get] at h rw [← h] exact rfl⟩, fun ⟨n, h⟩ => ⟨⟨Option.get _ h, n, (Option.eq_some_of_isSome h).symm⟩⟩⟩ theorem ret_mem (a : Ξ±) : a ∈ pure a := Exists.intro 0 rfl theorem eq_of_pure_mem {a a' : Ξ±} (h : a' ∈ pure a) : a' = a := mem_unique h (ret_mem _) @[simp] theorem mem_pure_iff (a b : Ξ±) : a ∈ pure b ↔ a = b := ⟨eq_of_pure_mem, fun h => h β–Έ ret_mem _⟩ instance ret_terminates (a : Ξ±) : Terminates (pure a) := terminates_of_mem (ret_mem _) theorem think_mem {s : Computation Ξ±} {a} : a ∈ s β†’ a ∈ think s | ⟨n, h⟩ => ⟨n + 1, h⟩ instance think_terminates (s : Computation Ξ±) : βˆ€ [Terminates s], Terminates (think s) | ⟨⟨a, n, h⟩⟩ => ⟨⟨a, n + 1, h⟩⟩ theorem of_think_mem {s : Computation Ξ±} {a} : a ∈ think s β†’ a ∈ s | ⟨n, h⟩ => by rcases n with - | n' Β· contradiction Β· exact ⟨n', h⟩ theorem of_think_terminates {s : Computation Ξ±} : Terminates (think s) β†’ Terminates s | ⟨⟨a, h⟩⟩ => ⟨⟨a, of_think_mem h⟩⟩ theorem notMem_empty (a : Ξ±) : a βˆ‰ empty Ξ± := fun ⟨n, h⟩ => by contradiction @[deprecated (since := "2025-05-23")] alias not_mem_empty := notMem_empty theorem not_terminates_empty : Β¬Terminates (empty Ξ±) := fun ⟨⟨a, h⟩⟩ => notMem_empty a h theorem eq_empty_of_not_terminates {s} (H : Β¬Terminates s) : s = empty Ξ± := by apply Subtype.eq; funext n rcases h : s.val n; Β· rfl refine absurd ?_ H; exact ⟨⟨_, _, h.symm⟩⟩ theorem thinkN_mem {s : Computation Ξ±} {a} : βˆ€ n, a ∈ thinkN s n ↔ a ∈ s | 0 => Iff.rfl | n + 1 => Iff.trans ⟨of_think_mem, think_mem⟩ (thinkN_mem n) instance thinkN_terminates (s : Computation Ξ±) : βˆ€ [Terminates s] (n), Terminates (thinkN s n) | ⟨⟨a, h⟩⟩, n => ⟨⟨a, (thinkN_mem n).2 h⟩⟩ theorem of_thinkN_terminates (s : Computation Ξ±) (n) : Terminates (thinkN s n) β†’ Terminates s | ⟨⟨a, h⟩⟩ => ⟨⟨a, (thinkN_mem _).1 h⟩⟩ /-- `Promises s a`, or `s ~> a`, asserts that although the computation `s` may not terminate, if it does, then the result is `a`. -/ def Promises (s : Computation Ξ±) (a : Ξ±) : Prop := βˆ€ ⦃a'⦄, a' ∈ s β†’ a = a' /-- `Promises s a`, or `s ~> a`, asserts that although the computation `s` may not terminate, if it does, then the result is `a`. -/ scoped infixl:50 " ~> " => Promises theorem mem_promises {s : Computation Ξ±} {a : Ξ±} : a ∈ s β†’ s ~> a := fun h _ => mem_unique h theorem empty_promises (a : Ξ±) : empty Ξ± ~> a := fun _ h => absurd h (notMem_empty _) section get variable (s : Computation Ξ±) [h : Terminates s] /-- `length s` gets the number of steps of a terminating computation -/ def length : β„• := Nat.find ((terminates_def _).1 h) /-- `get s` returns the result of a terminating computation -/ def get : Ξ± := Option.get _ (Nat.find_spec <| (terminates_def _).1 h) theorem get_mem : get s ∈ s := Exists.intro (length s) (Option.eq_some_of_isSome _).symm theorem get_eq_of_mem {a} : a ∈ s β†’ get s = a := mem_unique (get_mem _) theorem mem_of_get_eq {a} : get s = a β†’ a ∈ s := by intro h; rw [← h]; apply get_mem @[simp] theorem get_think : get (think s) = get s := get_eq_of_mem _ <| let ⟨n, h⟩ := get_mem s ⟨n + 1, h⟩ @[simp] theorem get_thinkN (n) : get (thinkN s n) = get s := get_eq_of_mem _ <| (thinkN_mem _).2 (get_mem _) theorem get_promises : s ~> get s := fun _ => get_eq_of_mem _ theorem mem_of_promises {a} (p : s ~> a) : a ∈ s := by obtain ⟨h⟩ := h obtain ⟨a', h⟩ := h rw [p h] exact h theorem get_eq_of_promises {a} : s ~> a β†’ get s = a := get_eq_of_mem _ ∘ mem_of_promises _ end get /-- `Results s a n` completely characterizes a terminating computation: it asserts that `s` terminates after exactly `n` steps, with result `a`. -/ def Results (s : Computation Ξ±) (a : Ξ±) (n : β„•) := βˆƒ h : a ∈ s, @length _ s (terminates_of_mem h) = n theorem results_of_terminates (s : Computation Ξ±) [_T : Terminates s] : Results s (get s) (length s) := ⟨get_mem _, rfl⟩ theorem results_of_terminates' (s : Computation Ξ±) [T : Terminates s] {a} (h : a ∈ s) : Results s a (length s) := by rw [← get_eq_of_mem _ h]; apply results_of_terminates theorem Results.mem {s : Computation Ξ±} {a n} : Results s a n β†’ a ∈ s | ⟨m, _⟩ => m theorem Results.terminates {s : Computation Ξ±} {a n} (h : Results s a n) : Terminates s := terminates_of_mem h.mem theorem Results.length {s : Computation Ξ±} {a n} [_T : Terminates s] : Results s a n β†’ length s = n | ⟨_, h⟩ => h theorem Results.val_unique {s : Computation Ξ±} {a b m n} (h1 : Results s a m) (h2 : Results s b n) : a = b := mem_unique h1.mem h2.mem theorem Results.len_unique {s : Computation Ξ±} {a b m n} (h1 : Results s a m) (h2 : Results s b n) : m = n := by haveI := h1.terminates; haveI := h2.terminates; rw [← h1.length, h2.length] theorem exists_results_of_mem {s : Computation Ξ±} {a} (h : a ∈ s) : βˆƒ n, Results s a n := haveI := terminates_of_mem h ⟨_, results_of_terminates' s h⟩ @[simp] theorem get_pure (a : Ξ±) : get (pure a) = a := get_eq_of_mem _ ⟨0, rfl⟩ @[simp] theorem length_pure (a : Ξ±) : length (pure a) = 0 := let h := Computation.ret_terminates a Nat.eq_zero_of_le_zero <| Nat.find_min' ((terminates_def (pure a)).1 h) rfl theorem results_pure (a : Ξ±) : Results (pure a) a 0 := ⟨ret_mem a, length_pure _⟩ @[simp] theorem length_think (s : Computation Ξ±) [h : Terminates s] : length (think s) = length s + 1 := by apply le_antisymm Β· exact Nat.find_min' _ (Nat.find_spec ((terminates_def _).1 h)) Β· have : (Option.isSome ((think s).val (length (think s))) : Prop) := Nat.find_spec ((terminates_def _).1 s.think_terminates) revert this; rcases length (think s) with - | n <;> intro this Β· simp [think, Stream'.cons] at this Β· apply Nat.succ_le_succ apply Nat.find_min' apply this theorem results_think {s : Computation Ξ±} {a n} (h : Results s a n) : Results (think s) a (n + 1) := haveI := h.terminates ⟨think_mem h.mem, by rw [length_think, h.length]⟩ theorem of_results_think {s : Computation Ξ±} {a n} (h : Results (think s) a n) : βˆƒ m, Results s a m ∧ n = m + 1 := by haveI := of_think_terminates h.terminates have := results_of_terminates' _ (of_think_mem h.mem) exact ⟨_, this, Results.len_unique h (results_think this)⟩ @[simp] theorem results_think_iff {s : Computation Ξ±} {a n} : Results (think s) a (n + 1) ↔ Results s a n := ⟨fun h => by let ⟨n', r, e⟩ := of_results_think h injection e with h'; rwa [h'], results_think⟩ theorem results_thinkN {s : Computation Ξ±} {a m} : βˆ€ n, Results s a m β†’ Results (thinkN s n) a (m + n) | 0, h => h | n + 1, h => results_think (results_thinkN n h) theorem results_thinkN_pure (a : Ξ±) (n) : Results (thinkN (pure a) n) a n := by have := results_thinkN n (results_pure a); rwa [Nat.zero_add] at this @[simp] theorem length_thinkN (s : Computation Ξ±) [_h : Terminates s] (n) : length (thinkN s n) = length s + n := (results_thinkN n (results_of_terminates _)).length theorem eq_thinkN {s : Computation Ξ±} {a n} (h : Results s a n) : s = thinkN (pure a) n := by induction n generalizing s with | zero | succ n IH <;> induction s using recOn with | pure a' | think s Β· rw [← eq_of_pure_mem h.mem] rfl Β· obtain ⟨n, h⟩ := of_results_think h cases h contradiction Β· have := h.len_unique (results_pure _) contradiction Β· rw [IH (results_think_iff.1 h)] rfl theorem eq_thinkN' (s : Computation Ξ±) [_h : Terminates s] : s = thinkN (pure (get s)) (length s) := eq_thinkN (results_of_terminates _) /-- Recursor based on membership -/ def memRecOn {C : Computation Ξ± β†’ Sort v} {a s} (M : a ∈ s) (h1 : C (pure a)) (h2 : βˆ€ s, C s β†’ C (think s)) : C s := by haveI T := terminates_of_mem M rw [eq_thinkN' s, get_eq_of_mem s M] generalize length s = n induction n with | zero => exact h1 | succ n IH => exact h2 _ IH /-- Recursor based on assertion of `Terminates` -/ def terminatesRecOn {C : Computation Ξ± β†’ Sort v} (s) [Terminates s] (h1 : βˆ€ a, C (pure a)) (h2 : βˆ€ s, C s β†’ C (think s)) : C s := memRecOn (get_mem s) (h1 _) h2 /-- Map a function on the result of a computation. -/ def map (f : Ξ± β†’ Ξ²) : Computation Ξ± β†’ Computation Ξ² | ⟨s, al⟩ => ⟨s.map fun o => Option.casesOn o none (some ∘ f), fun n b => by dsimp [Stream'.map, Stream'.get] rcases e : s n with - | a <;> intro h Β· contradiction Β· rw [al e]; exact h⟩ /-- bind over a `Sum` of `Computation` -/ def Bind.g : Ξ² βŠ• Computation Ξ² β†’ Ξ² βŠ• (Computation Ξ± βŠ• Computation Ξ²) | Sum.inl b => Sum.inl b | Sum.inr cb' => Sum.inr <| Sum.inr cb' /-- bind over a function mapping `Ξ±` to a `Computation` -/ def Bind.f (f : Ξ± β†’ Computation Ξ²) : Computation Ξ± βŠ• Computation Ξ² β†’ Ξ² βŠ• (Computation Ξ± βŠ• Computation Ξ²) | Sum.inl ca => match destruct ca with | Sum.inl a => Bind.g <| destruct (f a) | Sum.inr ca' => Sum.inr <| Sum.inl ca' | Sum.inr cb => Bind.g <| destruct cb /-- Compose two computations into a monadic `bind` operation. -/ def bind (c : Computation Ξ±) (f : Ξ± β†’ Computation Ξ²) : Computation Ξ² := corec (Bind.f f) (Sum.inl c) instance : Bind Computation := ⟨@bind⟩ theorem has_bind_eq_bind {Ξ²} (c : Computation Ξ±) (f : Ξ± β†’ Computation Ξ²) : c >>= f = bind c f := rfl /-- Flatten a computation of computations into a single computation. -/ def join (c : Computation (Computation Ξ±)) : Computation Ξ± := c >>= id @[simp] theorem map_pure (f : Ξ± β†’ Ξ²) (a) : map f (pure a) = pure (f a) := rfl @[simp] theorem map_think (f : Ξ± β†’ Ξ²) : βˆ€ s, map f (think s) = think (map f s) | ⟨s, al⟩ => by apply Subtype.eq; dsimp [think, map]; rw [Stream'.map_cons] @[simp] theorem destruct_map (f : Ξ± β†’ Ξ²) (s) : destruct (map f s) = lmap f (rmap (map f) (destruct s)) := by induction s using recOn <;> simp @[simp] theorem map_id : βˆ€ s : Computation Ξ±, map id s = s | ⟨f, al⟩ => by apply Subtype.eq; simp only [map, comp_apply, id_eq] have e : @Option.rec Ξ± (fun _ => Option Ξ±) none some = id := by ext ⟨⟩ <;> rfl have h : ((fun x : Option Ξ± => x) = id) := rfl simp [e, h, Stream'.map_id] theorem map_comp (f : Ξ± β†’ Ξ²) (g : Ξ² β†’ Ξ³) : βˆ€ s : Computation Ξ±, map (g ∘ f) s = map g (map f s) | ⟨s, al⟩ => by apply Subtype.eq; dsimp [map] apply congr_arg fun f : _ β†’ Option Ξ³ => Stream'.map f s ext ⟨⟩ <;> rfl @[simp] theorem ret_bind (a) (f : Ξ± β†’ Computation Ξ²) : bind (pure a) f = f a := by apply eq_of_bisim fun c₁ cβ‚‚ => c₁ = bind (pure a) f ∧ cβ‚‚ = f a ∨ c₁ = corec (Bind.f f) (Sum.inr cβ‚‚) Β· intro c₁ cβ‚‚ h match c₁, cβ‚‚, h with | _, _, Or.inl ⟨rfl, rfl⟩ => simp only [BisimO, bind, Bind.f, corec_eq, rmap, destruct_pure] rcases destruct (f a) with b | cb <;> simp [Bind.g] | _, c, Or.inr rfl => simp only [BisimO, Bind.f, corec_eq, rmap] rcases destruct c with b | cb <;> simp [Bind.g] Β· simp @[simp] theorem think_bind (c) (f : Ξ± β†’ Computation Ξ²) : bind (think c) f = think (bind c f) := destruct_eq_think <| by simp [bind, Bind.f] @[simp] theorem bind_pure (f : Ξ± β†’ Ξ²) (s) : bind s (pure ∘ f) = map f s := by apply eq_of_bisim fun c₁ cβ‚‚ => c₁ = cβ‚‚ ∨ βˆƒ s, c₁ = bind s (pure ∘ f) ∧ cβ‚‚ = map f s Β· intro c₁ cβ‚‚ h match c₁, cβ‚‚, h with | _, cβ‚‚, Or.inl (Eq.refl _) => rcases destruct cβ‚‚ with b | cb <;> simp | _, _, Or.inr ⟨s, rfl, rfl⟩ => induction s using recOn with | pure s => simp | think s => simpa using Or.inr ⟨s, rfl, rfl⟩ Β· exact Or.inr ⟨s, rfl, rfl⟩ @[simp] theorem bind_pure' (s : Computation Ξ±) : bind s pure = s := by simpa using bind_pure id s @[simp] theorem bind_assoc (s : Computation Ξ±) (f : Ξ± β†’ Computation Ξ²) (g : Ξ² β†’ Computation Ξ³) : bind (bind s f) g = bind s fun x : Ξ± => bind (f x) g := by apply eq_of_bisim fun c₁ cβ‚‚ => c₁ = cβ‚‚ ∨ βˆƒ s, c₁ = bind (bind s f) g ∧ cβ‚‚ = bind s fun x : Ξ± => bind (f x) g Β· intro c₁ cβ‚‚ h match c₁, cβ‚‚, h with | _, cβ‚‚, Or.inl (Eq.refl _) => rcases destruct cβ‚‚ with b | cb <;> simp | _, _, Or.inr ⟨s, rfl, rfl⟩ => induction s using recOn with | pure s => simp only [BisimO, ret_bind]; generalize f s = fs induction fs using recOn with | pure t => rw [ret_bind]; rcases destruct (g t) with b | cb <;> simp | think => simp | think s => simpa [BisimO] using Or.inr ⟨s, rfl, rfl⟩ Β· exact Or.inr ⟨s, rfl, rfl⟩ theorem results_bind {s : Computation Ξ±} {f : Ξ± β†’ Computation Ξ²} {a b m n} (h1 : Results s a m) (h2 : Results (f a) b n) : Results (bind s f) b (n + m) := by have := h1.mem; revert m apply memRecOn this _ fun s IH => _ Β· intro _ h1 rw [ret_bind] rw [h1.len_unique (results_pure _)] exact h2 Β· intro _ h3 _ h1 rw [think_bind] obtain ⟨m', h⟩ := of_results_think h1 obtain ⟨h1, e⟩ := h rw [e] exact results_think (h3 h1) theorem mem_bind {s : Computation Ξ±} {f : Ξ± β†’ Computation Ξ²} {a b} (h1 : a ∈ s) (h2 : b ∈ f a) : b ∈ bind s f := let ⟨_, h1⟩ := exists_results_of_mem h1 let ⟨_, h2⟩ := exists_results_of_mem h2 (results_bind h1 h2).mem instance terminates_bind (s : Computation Ξ±) (f : Ξ± β†’ Computation Ξ²) [Terminates s] [Terminates (f (get s))] : Terminates (bind s f) := terminates_of_mem (mem_bind (get_mem s) (get_mem (f (get s)))) @[simp] theorem get_bind (s : Computation Ξ±) (f : Ξ± β†’ Computation Ξ²) [Terminates s] [Terminates (f (get s))] : get (bind s f) = get (f (get s)) := get_eq_of_mem _ (mem_bind (get_mem s) (get_mem (f (get s)))) @[simp] theorem length_bind (s : Computation Ξ±) (f : Ξ± β†’ Computation Ξ²) [_T1 : Terminates s] [_T2 : Terminates (f (get s))] : length (bind s f) = length (f (get s)) + length s := (results_of_terminates _).len_unique <| results_bind (results_of_terminates _) (results_of_terminates _) theorem of_results_bind {s : Computation Ξ±} {f : Ξ± β†’ Computation Ξ²} {b k} : Results (bind s f) b k β†’ βˆƒ a m n, Results s a m ∧ Results (f a) b n ∧ k = n + m := by induction k generalizing s with | zero | succ n IH <;> induction s using recOn with intro h | pure a | think s' Β· simp only [ret_bind] at h exact ⟨_, _, _, results_pure _, h, rfl⟩ Β· have := congr_arg head (eq_thinkN h) contradiction Β· simp only [ret_bind] at h exact ⟨_, _, n + 1, results_pure _, h, rfl⟩ Β· simp only [think_bind, results_think_iff] at h let ⟨a, m, n', h1, h2, e'⟩ := IH h rw [e'] exact ⟨a, m.succ, n', results_think h1, h2, rfl⟩ theorem exists_of_mem_bind {s : Computation Ξ±} {f : Ξ± β†’ Computation Ξ²} {b} (h : b ∈ bind s f) : βˆƒ a ∈ s, b ∈ f a := let ⟨_, h⟩ := exists_results_of_mem h let ⟨a, _, _, h1, h2, _⟩ := of_results_bind h ⟨a, h1.mem, h2.mem⟩ theorem bind_promises {s : Computation Ξ±} {f : Ξ± β†’ Computation Ξ²} {a b} (h1 : s ~> a) (h2 : f a ~> b) : bind s f ~> b := fun b' bB => by rcases exists_of_mem_bind bB with ⟨a', a's, ba'⟩ rw [← h1 a's] at ba'; exact h2 ba' instance monad : Monad Computation where map := @map pure := @pure bind := @bind instance : LawfulMonad Computation := LawfulMonad.mk' (id_map := @map_id) (bind_pure_comp := @bind_pure) (pure_bind := @ret_bind) (bind_assoc := @bind_assoc) theorem has_map_eq_map {Ξ²} (f : Ξ± β†’ Ξ²) (c : Computation Ξ±) : f <$> c = map f c := rfl @[simp] theorem pure_def (a) : (return a : Computation Ξ±) = pure a := rfl @[simp] theorem map_pure' {Ξ± Ξ²} : βˆ€ (f : Ξ± β†’ Ξ²) (a), f <$> pure a = pure (f a) := map_pure @[simp] theorem map_think' {Ξ± Ξ²} : βˆ€ (f : Ξ± β†’ Ξ²) (s), f <$> think s = think (f <$> s) := map_think theorem mem_map (f : Ξ± β†’ Ξ²) {a} {s : Computation Ξ±} (m : a ∈ s) : f a ∈ map f s := by rw [← bind_pure]; apply mem_bind m; apply ret_mem theorem exists_of_mem_map {f : Ξ± β†’ Ξ²} {b : Ξ²} {s : Computation Ξ±} (h : b ∈ map f s) : βˆƒ a, a ∈ s ∧ f a = b := by rw [← bind_pure] at h let ⟨a, as, fb⟩ := exists_of_mem_bind h exact ⟨a, as, mem_unique (ret_mem _) fb⟩ instance terminates_map (f : Ξ± β†’ Ξ²) (s : Computation Ξ±) [Terminates s] : Terminates (map f s) := by rw [← bind_pure]; exact terminates_of_mem (mem_bind (get_mem s) (get_mem (Ξ± := Ξ²) (f (get s)))) theorem terminates_map_iff (f : Ξ± β†’ Ξ²) (s : Computation Ξ±) : Terminates (map f s) ↔ Terminates s := ⟨fun ⟨⟨_, h⟩⟩ => let ⟨_, h1, _⟩ := exists_of_mem_map h ⟨⟨_, h1⟩⟩, @Computation.terminates_map _ _ _ _⟩ -- Parallel computation /-- `c₁ <|> cβ‚‚` calculates `c₁` and `cβ‚‚` simultaneously, returning the first one that gives a result. -/ def orElse (c₁ : Computation Ξ±) (cβ‚‚ : Unit β†’ Computation Ξ±) : Computation Ξ± := @Computation.corec Ξ± (Computation Ξ± Γ— Computation Ξ±) (fun ⟨c₁, cβ‚‚βŸ© => match destruct c₁ with | Sum.inl a => Sum.inl a | Sum.inr c₁' => match destruct cβ‚‚ with | Sum.inl a => Sum.inl a | Sum.inr cβ‚‚' => Sum.inr (c₁', cβ‚‚')) (c₁, cβ‚‚ ()) instance instAlternativeComputation : Alternative Computation := { Computation.monad with orElse := @orElse failure := @empty } @[simp] theorem ret_orElse (a : Ξ±) (cβ‚‚ : Computation Ξ±) : (pure a <|> cβ‚‚) = pure a := destruct_eq_pure <| by unfold_projs simp [orElse] @[simp] theorem orElse_pure (c₁ : Computation Ξ±) (a : Ξ±) : (think c₁ <|> pure a) = pure a := destruct_eq_pure <| by unfold_projs simp [orElse] @[simp] theorem orElse_think (c₁ cβ‚‚ : Computation Ξ±) : (think c₁ <|> think cβ‚‚) = think (c₁ <|> cβ‚‚) := destruct_eq_think <| by unfold_projs simp [orElse] @[simp] theorem empty_orElse (c) : (empty Ξ± <|> c) = c := by apply eq_of_bisim (fun c₁ cβ‚‚ => (empty Ξ± <|> cβ‚‚) = c₁) _ rfl intro s' s h; rw [← h] induction s using recOn with rw [think_empty] | pure s => simp | think s => simp only [BisimO, orElse_think, destruct_think]; rw [← think_empty] @[simp] theorem orElse_empty (c : Computation Ξ±) : (c <|> empty Ξ±) = c := by apply eq_of_bisim (fun c₁ cβ‚‚ => (cβ‚‚ <|> empty Ξ±) = c₁) _ rfl intro s' s h; rw [← h] induction s using recOn with rw [think_empty] | pure s => simp | think s => simp only [BisimO, orElse_think, destruct_think]; rw [← think_empty] /-- `c₁ ~ cβ‚‚` asserts that `c₁` and `cβ‚‚` either both terminate with the same result, or both loop forever. -/ def Equiv (c₁ cβ‚‚ : Computation Ξ±) : Prop := βˆ€ a, a ∈ c₁ ↔ a ∈ cβ‚‚ /-- equivalence relation for computations -/ scoped infixl:50 " ~ " => Equiv @[refl] theorem Equiv.refl (s : Computation Ξ±) : s ~ s := fun _ => Iff.rfl @[symm] theorem Equiv.symm {s t : Computation Ξ±} : s ~ t β†’ t ~ s := fun h a => (h a).symm @[trans] theorem Equiv.trans {s t u : Computation Ξ±} : s ~ t β†’ t ~ u β†’ s ~ u := fun h1 h2 a => (h1 a).trans (h2 a) theorem Equiv.equivalence : Equivalence (@Equiv Ξ±) := ⟨@Equiv.refl _, @Equiv.symm _, @Equiv.trans _⟩ theorem equiv_of_mem {s t : Computation Ξ±} {a} (h1 : a ∈ s) (h2 : a ∈ t) : s ~ t := fun a' => ⟨fun ma => by rw [mem_unique ma h1]; exact h2, fun ma => by rw [mem_unique ma h2]; exact h1⟩ theorem terminates_congr {c₁ cβ‚‚ : Computation Ξ±} (h : c₁ ~ cβ‚‚) : Terminates c₁ ↔ Terminates cβ‚‚ := by simp only [terminates_iff, exists_congr h] theorem promises_congr {c₁ cβ‚‚ : Computation Ξ±} (h : c₁ ~ cβ‚‚) (a) : c₁ ~> a ↔ cβ‚‚ ~> a := forall_congr' fun a' => imp_congr (h a') Iff.rfl theorem get_equiv {c₁ cβ‚‚ : Computation Ξ±} (h : c₁ ~ cβ‚‚) [Terminates c₁] [Terminates cβ‚‚] : get c₁ = get cβ‚‚ := get_eq_of_mem _ <| (h _).2 <| get_mem _ theorem think_equiv (s : Computation Ξ±) : think s ~ s := fun _ => ⟨of_think_mem, think_mem⟩ theorem thinkN_equiv (s : Computation Ξ±) (n) : thinkN s n ~ s := fun _ => thinkN_mem n theorem bind_congr {s1 s2 : Computation Ξ±} {f1 f2 : Ξ± β†’ Computation Ξ²} (h1 : s1 ~ s2) (h2 : βˆ€ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 := fun b => ⟨fun h => let ⟨a, ha, hb⟩ := exists_of_mem_bind h mem_bind ((h1 a).1 ha) ((h2 a b).1 hb), fun h => let ⟨a, ha, hb⟩ := exists_of_mem_bind h mem_bind ((h1 a).2 ha) ((h2 a b).2 hb)⟩ theorem equiv_pure_of_mem {s : Computation Ξ±} {a} (h : a ∈ s) : s ~ pure a := equiv_of_mem h (ret_mem _) /-- `LiftRel R ca cb` is a generalization of `Equiv` to relations other than equality. It asserts that if `ca` terminates with `a`, then `cb` terminates with some `b` such that `R a b`, and if `cb` terminates with `b` then `ca` terminates with some `a` such that `R a b`. -/ def LiftRel (R : Ξ± β†’ Ξ² β†’ Prop) (ca : Computation Ξ±) (cb : Computation Ξ²) : Prop := (βˆ€ {a}, a ∈ ca β†’ βˆƒ b, b ∈ cb ∧ R a b) ∧ βˆ€ {b}, b ∈ cb β†’ βˆƒ a, a ∈ ca ∧ R a b theorem LiftRel.swap (R : Ξ± β†’ Ξ² β†’ Prop) (ca : Computation Ξ±) (cb : Computation Ξ²) : LiftRel (swap R) cb ca ↔ LiftRel R ca cb := @and_comm _ _ theorem lift_eq_iff_equiv (c₁ cβ‚‚ : Computation Ξ±) : LiftRel (Β· = Β·) c₁ cβ‚‚ ↔ c₁ ~ cβ‚‚ := ⟨fun ⟨h1, h2⟩ a => ⟨fun a1 => by let ⟨b, b2, ab⟩ := h1 a1; rwa [ab], fun a2 => by let ⟨b, b1, ab⟩ := h2 a2; rwa [← ab]⟩, fun e => ⟨fun {a} a1 => ⟨a, (e _).1 a1, rfl⟩, fun {a} a2 => ⟨a, (e _).2 a2, rfl⟩⟩⟩ theorem LiftRel.refl (R : Ξ± β†’ Ξ± β†’ Prop) (H : Reflexive R) : Reflexive (LiftRel R) := fun _ => ⟨fun {a} as => ⟨a, as, H a⟩, fun {b} bs => ⟨b, bs, H b⟩⟩ theorem LiftRel.symm (R : Ξ± β†’ Ξ± β†’ Prop) (H : Symmetric R) : Symmetric (LiftRel R) := fun _ _ ⟨l, r⟩ => ⟨fun {_} a2 => let ⟨b, b1, ab⟩ := r a2 ⟨b, b1, H ab⟩, fun {_} a1 => let ⟨b, b2, ab⟩ := l a1 ⟨b, b2, H ab⟩⟩ theorem LiftRel.trans (R : Ξ± β†’ Ξ± β†’ Prop) (H : Transitive R) : Transitive (LiftRel R) := fun _ _ _ ⟨l1, r1⟩ ⟨l2, r2⟩ => ⟨fun {_} a1 => let ⟨_, b2, ab⟩ := l1 a1 let ⟨c, c3, bc⟩ := l2 b2 ⟨c, c3, H ab bc⟩, fun {_} c3 => let ⟨_, b2, bc⟩ := r2 c3 let ⟨a, a1, ab⟩ := r1 b2 ⟨a, a1, H ab bc⟩⟩ theorem LiftRel.equiv (R : Ξ± β†’ Ξ± β†’ Prop) : Equivalence R β†’ Equivalence (LiftRel R) | ⟨refl, symm, trans⟩ => ⟨LiftRel.refl R refl, @LiftRel.symm _ R @symm, @LiftRel.trans _ R @trans⟩ theorem LiftRel.imp {R S : Ξ± β†’ Ξ² β†’ Prop} (H : βˆ€ {a b}, R a b β†’ S a b) (s t) : LiftRel R s t β†’ LiftRel S s t | ⟨l, r⟩ => ⟨fun {_} as => let ⟨b, bt, ab⟩ := l as ⟨b, bt, H ab⟩, fun {_} bt => let ⟨a, as, ab⟩ := r bt ⟨a, as, H ab⟩⟩ theorem terminates_of_liftRel {R : Ξ± β†’ Ξ² β†’ Prop} {s t} : LiftRel R s t β†’ (Terminates s ↔ Terminates t) | ⟨l, r⟩ => ⟨fun ⟨⟨_, as⟩⟩ => let ⟨b, bt, _⟩ := l as ⟨⟨b, bt⟩⟩, fun ⟨⟨_, bt⟩⟩ => let ⟨a, as, _⟩ := r bt ⟨⟨a, as⟩⟩⟩ theorem rel_of_liftRel {R : Ξ± β†’ Ξ² β†’ Prop} {ca cb} : LiftRel R ca cb β†’ βˆ€ {a b}, a ∈ ca β†’ b ∈ cb β†’ R a b | ⟨l, _⟩, a, b, ma, mb => by let ⟨b', mb', ab'⟩ := l ma rw [mem_unique mb mb']; exact ab' theorem liftRel_of_mem {R : Ξ± β†’ Ξ² β†’ Prop} {a b ca cb} (ma : a ∈ ca) (mb : b ∈ cb) (ab : R a b) : LiftRel R ca cb := ⟨fun {a'} ma' => by rw [mem_unique ma' ma]; exact ⟨b, mb, ab⟩, fun {b'} mb' => by rw [mem_unique mb' mb]; exact ⟨a, ma, ab⟩⟩ theorem exists_of_liftRel_left {R : Ξ± β†’ Ξ² β†’ Prop} {ca cb} (H : LiftRel R ca cb) {a} (h : a ∈ ca) : βˆƒ b, b ∈ cb ∧ R a b := H.left h theorem exists_of_liftRel_right {R : Ξ± β†’ Ξ² β†’ Prop} {ca cb} (H : LiftRel R ca cb) {b} (h : b ∈ cb) : βˆƒ a, a ∈ ca ∧ R a b := H.right h theorem liftRel_def {R : Ξ± β†’ Ξ² β†’ Prop} {ca cb} : LiftRel R ca cb ↔ (Terminates ca ↔ Terminates cb) ∧ βˆ€ {a b}, a ∈ ca β†’ b ∈ cb β†’ R a b := ⟨fun h => ⟨terminates_of_liftRel h, fun {a b} ma mb => by let ⟨b', mb', ab⟩ := h.left ma rwa [mem_unique mb mb']⟩, fun ⟨l, r⟩ => ⟨fun {_} ma => let ⟨⟨b, mb⟩⟩ := l.1 ⟨⟨_, ma⟩⟩ ⟨b, mb, r ma mb⟩, fun {_} mb => let ⟨⟨a, ma⟩⟩ := l.2 ⟨⟨_, mb⟩⟩ ⟨a, ma, r ma mb⟩⟩⟩ theorem liftRel_bind {Ξ΄} (R : Ξ± β†’ Ξ² β†’ Prop) (S : Ξ³ β†’ Ξ΄ β†’ Prop) {s1 : Computation Ξ±} {s2 : Computation Ξ²} {f1 : Ξ± β†’ Computation Ξ³} {f2 : Ξ² β†’ Computation Ξ΄} (h1 : LiftRel R s1 s2) (h2 : βˆ€ {a b}, R a b β†’ LiftRel S (f1 a) (f2 b)) : LiftRel S (bind s1 f1) (bind s2 f2) := let ⟨l1, r1⟩ := h1 ⟨fun {_} cB => let ⟨_, a1, cβ‚βŸ© := exists_of_mem_bind cB let ⟨_, b2, ab⟩ := l1 a1 let ⟨l2, _⟩ := h2 ab let ⟨_, d2, cd⟩ := l2 c₁ ⟨_, mem_bind b2 d2, cd⟩, fun {_} dB => let ⟨_, b1, d1⟩ := exists_of_mem_bind dB let ⟨_, a2, ab⟩ := r1 b1 let ⟨_, r2⟩ := h2 ab let ⟨_, cβ‚‚, cd⟩ := r2 d1 ⟨_, mem_bind a2 cβ‚‚, cd⟩⟩ @[simp] theorem liftRel_pure_left (R : Ξ± β†’ Ξ² β†’ Prop) (a : Ξ±) (cb : Computation Ξ²) : LiftRel R (pure a) cb ↔ βˆƒ b, b ∈ cb ∧ R a b := ⟨fun ⟨l, _⟩ => l (ret_mem _), fun ⟨b, mb, ab⟩ => ⟨fun {a'} ma' => by rw [eq_of_pure_mem ma']; exact ⟨b, mb, ab⟩, fun {b'} mb' => ⟨_, ret_mem _, by rw [mem_unique mb' mb]; exact ab⟩⟩⟩ @[simp] theorem liftRel_pure_right (R : Ξ± β†’ Ξ² β†’ Prop) (ca : Computation Ξ±) (b : Ξ²) : LiftRel R ca (pure b) ↔ βˆƒ a, a ∈ ca ∧ R a b := by rw [LiftRel.swap, liftRel_pure_left] theorem liftRel_pure (R : Ξ± β†’ Ξ² β†’ Prop) (a : Ξ±) (b : Ξ²) : LiftRel R (pure a) (pure b) ↔ R a b := by simp @[simp] theorem liftRel_think_left (R : Ξ± β†’ Ξ² β†’ Prop) (ca : Computation Ξ±) (cb : Computation Ξ²) : LiftRel R (think ca) cb ↔ LiftRel R ca cb := and_congr (forall_congr' fun _ => imp_congr ⟨of_think_mem, think_mem⟩ Iff.rfl) (forall_congr' fun _ => imp_congr Iff.rfl <| exists_congr fun _ => and_congr ⟨of_think_mem, think_mem⟩ Iff.rfl) @[simp] theorem liftRel_think_right (R : Ξ± β†’ Ξ² β†’ Prop) (ca : Computation Ξ±) (cb : Computation Ξ²) : LiftRel R ca (think cb) ↔ LiftRel R ca cb := by rw [← LiftRel.swap R, ← LiftRel.swap R]; apply liftRel_think_left theorem liftRel_mem_cases {R : Ξ± β†’ Ξ² β†’ Prop} {ca cb} (Ha : βˆ€ a ∈ ca, LiftRel R ca cb) (Hb : βˆ€ b ∈ cb, LiftRel R ca cb) : LiftRel R ca cb := ⟨fun {_} ma => (Ha _ ma).left ma, fun {_} mb => (Hb _ mb).right mb⟩ theorem liftRel_congr {R : Ξ± β†’ Ξ² β†’ Prop} {ca ca' : Computation Ξ±} {cb cb' : Computation Ξ²} (ha : ca ~ ca') (hb : cb ~ cb') : LiftRel R ca cb ↔ LiftRel R ca' cb' := and_congr (forall_congr' fun _ => imp_congr (ha _) <| exists_congr fun _ => and_congr (hb _) Iff.rfl) (forall_congr' fun _ => imp_congr (hb _) <| exists_congr fun _ => and_congr (ha _) Iff.rfl) theorem liftRel_map {Ξ΄} (R : Ξ± β†’ Ξ² β†’ Prop) (S : Ξ³ β†’ Ξ΄ β†’ Prop) {s1 : Computation Ξ±} {s2 : Computation Ξ²} {f1 : Ξ± β†’ Ξ³} {f2 : Ξ² β†’ Ξ΄} (h1 : LiftRel R s1 s2) (h2 : βˆ€ {a b}, R a b β†’ S (f1 a) (f2 b)) : LiftRel S (map f1 s1) (map f2 s2) := by rw [← bind_pure, ← bind_pure]; apply liftRel_bind _ _ h1; simpa theorem map_congr {s1 s2 : Computation Ξ±} {f : Ξ± β†’ Ξ²} (h1 : s1 ~ s2) : map f s1 ~ map f s2 := by rw [← lift_eq_iff_equiv] exact liftRel_map Eq _ ((lift_eq_iff_equiv _ _).2 h1) fun {a} b => congr_arg _ /-- Alternate definition of `LiftRel` over relations between `Computation`s -/ def LiftRelAux (R : Ξ± β†’ Ξ² β†’ Prop) (C : Computation Ξ± β†’ Computation Ξ² β†’ Prop) : Ξ± βŠ• (Computation Ξ±) β†’ Ξ² βŠ• (Computation Ξ²) β†’ Prop | Sum.inl a, Sum.inl b => R a b | Sum.inl a, Sum.inr cb => βˆƒ b, b ∈ cb ∧ R a b | Sum.inr ca, Sum.inl b => βˆƒ a, a ∈ ca ∧ R a b | Sum.inr ca, Sum.inr cb => C ca cb variable {R : Ξ± β†’ Ξ² β†’ Prop} {C : Computation Ξ± β†’ Computation Ξ² β†’ Prop} @[simp] lemma liftRelAux_inl_inl {a : Ξ±} {b : Ξ²} : LiftRelAux R C (Sum.inl a) (Sum.inl b) = R a b := rfl @[simp] lemma liftRelAux_inl_inr {a : Ξ±} {cb} : LiftRelAux R C (Sum.inl a) (Sum.inr cb) = βˆƒ b, b ∈ cb ∧ R a b := rfl @[simp] lemma liftRelAux_inr_inl {b : Ξ²} {ca} : LiftRelAux R C (Sum.inr ca) (Sum.inl b) = βˆƒ a, a ∈ ca ∧ R a b := rfl @[simp] lemma liftRelAux_inr_inr {ca cb} : LiftRelAux R C (Sum.inr ca) (Sum.inr cb) = C ca cb := rfl @[simp] theorem LiftRelAux.ret_left (R : Ξ± β†’ Ξ² β†’ Prop) (C : Computation Ξ± β†’ Computation Ξ² β†’ Prop) (a cb) : LiftRelAux R C (Sum.inl a) (destruct cb) ↔ βˆƒ b, b ∈ cb ∧ R a b := by induction cb using recOn with | pure b => exact ⟨fun h => ⟨_, ret_mem _, h⟩, fun ⟨b', mb, h⟩ => by rw [mem_unique (ret_mem _) mb]; exact h⟩ | think cb => rw [destruct_think] exact ⟨fun ⟨b, h, r⟩ => ⟨b, think_mem h, r⟩, fun ⟨b, h, r⟩ => ⟨b, of_think_mem h, r⟩⟩ theorem LiftRelAux.swap (R : Ξ± β†’ Ξ² β†’ Prop) (C) (a b) : LiftRelAux (swap R) (swap C) b a = LiftRelAux R C a b := by rcases a with a | ca <;> rcases b with b | cb <;> simp only [LiftRelAux] @[simp] theorem LiftRelAux.ret_right (R : Ξ± β†’ Ξ² β†’ Prop) (C : Computation Ξ± β†’ Computation Ξ² β†’ Prop) (b ca) : LiftRelAux R C (destruct ca) (Sum.inl b) ↔ βˆƒ a, a ∈ ca ∧ R a b := by rw [← LiftRelAux.swap, LiftRelAux.ret_left] theorem LiftRelRec.lem {R : Ξ± β†’ Ξ² β†’ Prop} (C : Computation Ξ± β†’ Computation Ξ² β†’ Prop) (H : βˆ€ {ca cb}, C ca cb β†’ LiftRelAux R C (destruct ca) (destruct cb)) (ca cb) (Hc : C ca cb) (a) (ha : a ∈ ca) : LiftRel R ca cb := by revert cb refine memRecOn (C := (fun ca ↦ βˆ€ (cb : Computation Ξ²), C ca cb β†’ LiftRel R ca cb)) ha ?_ (fun ca' IH => ?_) <;> intro cb Hc <;> have h := H Hc Β· simp only [destruct_pure, LiftRelAux.ret_left] at h simp [h] Β· simp only [liftRel_think_left] induction cb using recOn with | pure b => simpa using h | think cb => simpa [h] using IH _ h theorem liftRel_rec {R : Ξ± β†’ Ξ² β†’ Prop} (C : Computation Ξ± β†’ Computation Ξ² β†’ Prop) (H : βˆ€ {ca cb}, C ca cb β†’ LiftRelAux R C (destruct ca) (destruct cb)) (ca cb) (Hc : C ca cb) : LiftRel R ca cb := liftRel_mem_cases (LiftRelRec.lem C (@H) ca cb Hc) fun b hb => (LiftRel.swap _ _ _).2 <| LiftRelRec.lem (swap C) (fun {_ _} h => cast (LiftRelAux.swap _ _ _ _).symm <| H h) cb ca Hc b hb end Computation
.lake/packages/mathlib/Mathlib/Data/Seq/Seq.lean
import Mathlib.Data.Seq.Basic deprecated_module (since := "2025-08-26")
.lake/packages/mathlib/Mathlib/Data/Seq/Basic.lean
import Mathlib.Data.Seq.Defs import Mathlib.Data.ENat.Basic import Mathlib.Tactic.ENatToNat import Mathlib.Tactic.ApplyFun /-! # Basic properties of sequences (possibly infinite lists) This file provides some basic lemmas about possibly infinite lists represented by the type `Stream'.Seq`. -/ universe u v w namespace Stream' namespace Seq variable {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w} section length theorem length'_of_terminates {s : Seq Ξ±} (h : s.Terminates) : s.length' = s.length h := by simp [length', h] theorem length'_of_not_terminates {s : Seq Ξ±} (h : Β¬ s.Terminates) : s.length' = ⊀ := by simp [length', h] @[simp] theorem length_nil : length (nil : Seq Ξ±) terminates_nil = 0 := rfl @[simp] theorem length'_nil : length' (nil : Seq Ξ±) = 0 := by simp -implicitDefEqProofs [length'] theorem length_cons {x : Ξ±} {s : Seq Ξ±} (h : s.Terminates) : (cons x s).length (terminates_cons_iff.mpr h) = s.length h + 1 := by apply Nat.find_comp_succ simp @[simp] theorem length'_cons (x : Ξ±) (s : Seq Ξ±) : (cons x s).length' = s.length' + 1 := by by_cases h : (cons x s).Terminates <;> have h' := h <;> rw [terminates_cons_iff] at h' Β· simp [length'_of_terminates h, length'_of_terminates h', length_cons h'] Β· simp [length'_of_not_terminates h, length'_of_not_terminates h'] @[simp] theorem length_eq_zero {s : Seq Ξ±} {h : s.Terminates} : s.length h = 0 ↔ s = nil := by simp [length, TerminatedAt] @[simp] theorem length'_eq_zero_iff_nil (s : Seq Ξ±) : s.length' = 0 ↔ s = nil := by cases s <;> simp theorem length'_ne_zero_iff_cons (s : Seq Ξ±) : s.length' β‰  0 ↔ βˆƒ x s', s = cons x s' := by cases s <;> simp /-- The statement of `length_le_iff'` does not assume that the sequence terminates. For a simpler statement of the theorem where the sequence is known to terminate see `length_le_iff`. -/ theorem length_le_iff' {s : Seq Ξ±} {n : β„•} : (βˆƒ h, s.length h ≀ n) ↔ s.TerminatedAt n := by simp only [length, Nat.find_le_iff, TerminatedAt, Terminates, exists_prop] refine ⟨?_, ?_⟩ Β· rintro ⟨_, k, hkn, hk⟩ exact le_stable s hkn hk Β· intro hn exact ⟨⟨n, hn⟩, ⟨n, le_rfl, hn⟩⟩ /-- The statement of `length_le_iff` assumes that the sequence terminates. For a statement of the where the sequence is not known to terminate see `length_le_iff'`. -/ theorem length_le_iff {s : Seq Ξ±} {n : β„•} {h : s.Terminates} : s.length h ≀ n ↔ s.TerminatedAt n := by rw [← length_le_iff']; simp [h] theorem length'_le_iff {s : Seq Ξ±} {n : β„•} : s.length' ≀ n ↔ s.TerminatedAt n := by by_cases h : s.Terminates Β· simpa [length'_of_terminates h] using length_le_iff Β· simpa [length'_of_not_terminates h] using forall_not_of_not_exists h n /-- The statement of `lt_length_iff'` does not assume that the sequence terminates. For a simpler statement of the theorem where the sequence is known to terminate see `lt_length_iff`. -/ theorem lt_length_iff' {s : Seq Ξ±} {n : β„•} : (βˆ€ h : s.Terminates, n < s.length h) ↔ βˆƒ a, a ∈ s.get? n := by simp only [Terminates, TerminatedAt, length, Nat.lt_find_iff, forall_exists_index, Option.mem_def, ← Option.ne_none_iff_exists', ne_eq] refine ⟨?_, ?_⟩ Β· intro h hn exact h n hn n le_rfl hn Β· intro hn _ _ k hkn hk exact hn <| le_stable s hkn hk /-- The statement of `length_le_iff` assumes that the sequence terminates. For a statement of the where the sequence is not known to terminate see `length_le_iff'`. -/ theorem lt_length_iff {s : Seq Ξ±} {n : β„•} {h : s.Terminates} : n < s.length h ↔ βˆƒ a, a ∈ s.get? n := by rw [← lt_length_iff']; simp [h] theorem lt_length'_iff {s : Seq Ξ±} {n : β„•} : n < s.length' ↔ βˆƒ a, a ∈ s.get? n := by by_cases h : s.Terminates Β· simpa [length'_of_terminates h] using lt_length_iff Β· simp only [length'_of_not_terminates h, ENat.coe_lt_top, Option.mem_def, true_iff] rw [not_terminates_iff] at h rw [← Option.isSome_iff_exists] exact h n end length section OfStream @[simp] theorem ofStream_cons (a : Ξ±) (s) : ofStream (a::s) = cons a (ofStream s) := by apply Subtype.eq; simp only [ofStream, cons]; rw [Stream'.map_cons] end OfStream section OfList theorem terminatedAt_ofList (l : List Ξ±) : (ofList l).TerminatedAt l.length := by simp [ofList, TerminatedAt] theorem terminates_ofList (l : List Ξ±) : (ofList l).Terminates := ⟨_, terminatedAt_ofList l⟩ end OfList section Take @[simp] theorem take_nil {n : β„•} : (nil (Ξ± := Ξ±)).take n = List.nil := by cases n <;> rfl @[simp] theorem take_zero {s : Seq Ξ±} : s.take 0 = [] := by cases s <;> rfl @[simp] theorem take_succ_cons {n : β„•} {x : Ξ±} {s : Seq Ξ±} : (cons x s).take (n + 1) = x :: s.take n := by rfl @[simp] theorem getElem?_take : βˆ€ (n k : β„•) (s : Seq Ξ±), (s.take k)[n]? = if n < k then s.get? n else none | n, 0, s => by simp [take] | n, k+1, s => by rw [take] cases h : destruct s with | none => simp [destruct_eq_none h] | some a => match a with | (x, r) => rw [destruct_eq_cons h] match n with | 0 => simp | n+1 => simp [List.getElem?_cons_succ, getElem?_take] theorem get?_mem_take {s : Seq Ξ±} {m n : β„•} (h_mn : m < n) {x : Ξ±} (h_get : s.get? m = some x) : x ∈ s.take n := by induction m generalizing n s with | zero => obtain ⟨l, hl⟩ := Nat.exists_add_one_eq.mpr h_mn rw [← hl, take, head_eq_some h_get] simp | succ k ih => obtain ⟨l, hl⟩ := Nat.exists_eq_add_of_lt h_mn subst hl have : βˆƒ y, s.get? 0 = some y := by apply ge_stable _ _ h_get simp obtain ⟨y, hy⟩ := this rw [take, head_eq_some hy] simp right apply ih (by cutsat) rwa [get?_tail] theorem length_take_le {s : Seq Ξ±} {n : β„•} : (s.take n).length ≀ n := by induction n generalizing s with | zero => simp | succ m ih => rw [take] cases s.destruct with | none => simp | some v => obtain ⟨x, r⟩ := v simpa using ih theorem length_take_of_le_length {s : Seq Ξ±} {n : β„•} (hle : βˆ€ h : s.Terminates, n ≀ s.length h) : (s.take n).length = n := by induction n generalizing s with | zero => simp [take] | succ n ih => rw [take, destruct] let ⟨a, ha⟩ := lt_length_iff'.1 (fun ht => lt_of_lt_of_le (Nat.succ_pos _) (hle ht)) simp [Option.mem_def.1 ha] rw [ih] intro h simp only [length, tail, Nat.le_find_iff, TerminatedAt, get?_mk, Stream'.tail] intro m hmn hs have := lt_length_iff'.1 (fun ht => (Nat.lt_of_succ_le (hle ht))) rw [le_stable s (Nat.succ_le_of_lt hmn) hs] at this simp at this end Take section ToList @[simp] theorem length_toList (s : Seq Ξ±) (h : s.Terminates) : (toList s h).length = length s h := by rw [toList, length_take_of_le_length] intro _ exact le_rfl @[simp] theorem getElem?_toList (s : Seq Ξ±) (h : s.Terminates) (n : β„•) : (toList s h)[n]? = s.get? n := by ext k simp only [toList, getElem?_take, Nat.lt_find_iff, length, Option.ite_none_right_eq_some, and_iff_right_iff_imp, TerminatedAt] intro h m hmn let ⟨a, ha⟩ := ge_stable s hmn h simp [ha] @[simp] theorem ofList_toList (s : Seq Ξ±) (h : s.Terminates) : ofList (toList s h) = s := by ext n; simp [ofList] @[simp] theorem toList_ofList (l : List Ξ±) : toList (ofList l) (terminates_ofList l) = l := ofList_injective (by simp) @[simp] theorem toList_nil : toList (nil : Seq Ξ±) ⟨0, terminatedAt_zero_iff.2 rfl⟩ = [] := by ext; simp [nil, toList, const] theorem getLast?_toList (s : Seq Ξ±) (h : s.Terminates) : (toList s h).getLast? = s.get? (s.length h - 1) := by rw [List.getLast?_eq_getElem?, getElem?_toList, length_toList] end ToList section Append @[simp] theorem cons_append (a : Ξ±) (s t) : append (cons a s) t = cons a (append s t) := destruct_eq_cons <| by dsimp [append]; rw [corec_eq] dsimp [append]; rw [destruct_cons] @[simp] theorem nil_append (s : Seq Ξ±) : append nil s = s := by apply coinduction2; intro s dsimp [append]; rw [corec_eq] dsimp [append] cases s Β· trivial Β· rw [destruct_cons] dsimp exact ⟨rfl, _, rfl, rfl⟩ @[simp] theorem append_nil (s : Seq Ξ±) : append s nil = s := by apply coinduction2 s; intro s cases s Β· trivial Β· rw [cons_append, destruct_cons, destruct_cons] dsimp exact ⟨rfl, _, rfl, rfl⟩ @[simp] theorem append_assoc (s t u : Seq Ξ±) : append (append s t) u = append s (append t u) := by apply eq_of_bisim fun s1 s2 => βˆƒ s t u, s1 = append (append s t) u ∧ s2 = append s (append t u) Β· intro s1 s2 h exact match s1, s2, h with | _, _, ⟨s, t, u, rfl, rfl⟩ => by cases s <;> simp case nil => cases t <;> simp case nil => cases u <;> simp case cons _ u => refine ⟨nil, nil, u, ?_, ?_⟩ <;> simp case cons _ t => refine ⟨nil, t, u, ?_, ?_⟩ <;> simp case cons _ s => exact ⟨s, t, u, rfl, rfl⟩ Β· exact ⟨s, t, u, rfl, rfl⟩ theorem of_mem_append {s₁ sβ‚‚ : Seq Ξ±} {a : Ξ±} (h : a ∈ append s₁ sβ‚‚) : a ∈ s₁ ∨ a ∈ sβ‚‚ := by have := h; revert this generalize e : append s₁ sβ‚‚ = ss; intro h; revert s₁ apply mem_rec_on h _ intro b s' o s₁ cases s₁ with | nil => intro m _ apply Or.inr simpa using m | cons c t₁ => intro m e have this := congr_arg destruct e rcases show a = c ∨ a ∈ append t₁ sβ‚‚ by simpa using m with e' | m Β· rw [e'] exact Or.inl (mem_cons _ _) Β· obtain ⟨i1, i2⟩ := show c = b ∧ append t₁ sβ‚‚ = s' by simpa rcases o with e' | IH Β· simp [i1, e'] Β· exact Or.imp_left (mem_cons_of_mem _) (IH m i2) theorem mem_append_left {s₁ sβ‚‚ : Seq Ξ±} {a : Ξ±} (h : a ∈ s₁) : a ∈ append s₁ sβ‚‚ := by apply mem_rec_on h; intros; simp [*] @[simp] theorem ofList_append (l l' : List Ξ±) : ofList (l ++ l') = append (ofList l) (ofList l') := by induction l <;> simp [*] @[simp] theorem ofStream_append (l : List Ξ±) (s : Stream' Ξ±) : ofStream (l ++β‚› s) = append (ofList l) (ofStream s) := by induction l <;> simp [*, Stream'.nil_append_stream, Stream'.cons_append_stream] end Append section Map @[simp] theorem map_get? (f : Ξ± β†’ Ξ²) : βˆ€ s n, get? (map f s) n = (get? s n).map f | ⟨_, _⟩, _ => rfl @[simp] theorem map_nil (f : Ξ± β†’ Ξ²) : map f nil = nil := rfl @[simp] theorem map_cons (f : Ξ± β†’ Ξ²) (a) : βˆ€ s, map f (cons a s) = cons (f a) (map f s) | ⟨s, al⟩ => by apply Subtype.eq; dsimp [cons, map]; rw [Stream'.map_cons]; rfl @[simp] theorem map_id : βˆ€ s : Seq Ξ±, map id s = s | ⟨s, al⟩ => by apply Subtype.eq; dsimp [map] rw [Option.map_id, Stream'.map_id] @[simp] theorem map_tail (f : Ξ± β†’ Ξ²) : βˆ€ s, map f (tail s) = tail (map f s) | ⟨s, al⟩ => by apply Subtype.eq; dsimp [tail, map] theorem map_comp (f : Ξ± β†’ Ξ²) (g : Ξ² β†’ Ξ³) : βˆ€ s : Seq Ξ±, map (g ∘ f) s = map g (map f s) | ⟨s, al⟩ => by apply Subtype.eq; dsimp [map] apply congr_arg fun f : _ β†’ Option Ξ³ => Stream'.map f s ext ⟨⟩ <;> rfl @[simp] theorem terminatedAt_map_iff {f : Ξ± β†’ Ξ²} {s : Seq Ξ±} {n : β„•} : (map f s).TerminatedAt n ↔ s.TerminatedAt n := by simp [TerminatedAt] @[simp] theorem terminates_map_iff {f : Ξ± β†’ Ξ²} {s : Seq Ξ±} : (map f s).Terminates ↔ s.Terminates := by simp [Terminates] @[simp] theorem length_map {s : Seq Ξ±} {f : Ξ± β†’ Ξ²} (h : (s.map f).Terminates) : (s.map f).length h = s.length (terminates_map_iff.1 h) := by rw [length] congr ext simp @[simp] theorem length'_map {s : Seq Ξ±} {f : Ξ± β†’ Ξ²} : (s.map f).length' = s.length' := by by_cases h : (s.map f).Terminates <;> have h' := h <;> rw [terminates_map_iff] at h' Β· rw [length'_of_terminates h, length'_of_terminates h', length_map h] Β· rw [length'_of_not_terminates h, length'_of_not_terminates h'] theorem mem_map (f : Ξ± β†’ Ξ²) {a : Ξ±} : βˆ€ {s : Seq Ξ±}, a ∈ s β†’ f a ∈ map f s | ⟨_, _⟩ => Stream'.mem_map (Option.map f) theorem exists_of_mem_map {f} {b : Ξ²} : βˆ€ {s : Seq Ξ±}, b ∈ map f s β†’ βˆƒ a, a ∈ s ∧ f a = b := fun {s} h => by match s with | ⟨g, al⟩ => let ⟨o, om, oe⟩ := @Stream'.exists_of_mem_map _ _ (Option.map f) (some b) g h rcases o with - | a Β· injection oe Β· injection oe with h'; exact ⟨a, om, h'⟩ @[simp] theorem map_append (f : Ξ± β†’ Ξ²) (s t) : map f (append s t) = append (map f s) (map f t) := by apply eq_of_bisim (fun s1 s2 => βˆƒ s t, s1 = map f (append s t) ∧ s2 = append (map f s) (map f t)) _ ⟨s, t, rfl, rfl⟩ intro s1 s2 h exact match s1, s2, h with | _, _, ⟨s, t, rfl, rfl⟩ => by cases s <;> simp case nil => cases t <;> simp case cons _ t => refine ⟨nil, t, ?_, ?_⟩ <;> simp case cons _ s => exact ⟨s, t, rfl, rfl⟩ end Map section Join @[simp] theorem join_nil : join nil = (nil : Seq Ξ±) := destruct_eq_none rfl -- Not a simp lemmas as `join_cons` is more general theorem join_cons_nil (a : Ξ±) (S) : join (cons (a, nil) S) = cons a (join S) := destruct_eq_cons <| by simp [join] -- Not a simp lemmas as `join_cons` is more general theorem join_cons_cons (a b : Ξ±) (s S) : join (cons (a, cons b s) S) = cons a (join (cons (b, s) S)) := destruct_eq_cons <| by simp [join] @[simp] theorem join_cons (a : Ξ±) (s S) : join (cons (a, s) S) = cons a (append s (join S)) := by apply eq_of_bisim (fun s1 s2 => s1 = s2 ∨ βˆƒ a s S, s1 = join (cons (a, s) S) ∧ s2 = cons a (append s (join S))) _ (Or.inr ⟨a, s, S, rfl, rfl⟩) intro s1 s2 h exact match s1, s2, h with | s, _, Or.inl <| Eq.refl s => by cases s; Β· trivial Β· rw [destruct_cons] exact ⟨rfl, Or.inl rfl⟩ | _, _, Or.inr ⟨a, s, S, rfl, rfl⟩ => by cases s Β· simp [join_cons_nil] Β· simpa [join_cons_cons, join_cons_nil] using Or.inr ⟨_, _, S, rfl, rfl⟩ @[simp] theorem join_append (S T : Seq (Seq1 Ξ±)) : join (append S T) = append (join S) (join T) := by apply eq_of_bisim fun s1 s2 => βˆƒ s S T, s1 = append s (join (append S T)) ∧ s2 = append s (append (join S) (join T)) Β· intro s1 s2 h exact match s1, s2, h with | _, _, ⟨s, S, T, rfl, rfl⟩ => by cases s <;> simp case nil => cases S <;> simp case nil => cases T with | nil => simp | cons s T => obtain ⟨a, s⟩ := s; simp only [join_cons, destruct_cons, true_and] refine ⟨s, nil, T, ?_, ?_⟩ <;> simp case cons s S => obtain ⟨a, s⟩ := s simpa using ⟨s, S, T, rfl, rfl⟩ case cons _ s => exact ⟨s, S, T, rfl, rfl⟩ Β· refine ⟨nil, S, T, ?_, ?_⟩ <;> simp end Join section Drop @[simp] theorem drop_get? {n m : β„•} {s : Seq Ξ±} : (s.drop n).get? m = s.get? (n + m) := by induction n generalizing m with | zero => simp [drop] | succ k ih => simp [Seq.get?_tail, drop] convert ih using 2 cutsat theorem dropn_add (s : Seq Ξ±) (m) : βˆ€ n, drop s (m + n) = drop (drop s m) n | 0 => rfl | n + 1 => congr_arg tail (dropn_add s _ n) theorem dropn_tail (s : Seq Ξ±) (n) : drop (tail s) n = drop s (n + 1) := by rw [Nat.add_comm]; symm; apply dropn_add @[simp] theorem head_dropn (s : Seq Ξ±) (n) : head (drop s n) = get? s n := by induction n generalizing s with | zero => rfl | succ n IH => rw [← get?_tail, ← dropn_tail]; apply IH @[simp] theorem drop_zero {s : Seq Ξ±} : s.drop 0 = s := rfl @[simp] theorem drop_succ_cons {x : Ξ±} {s : Seq Ξ±} {n : β„•} : (cons x s).drop (n + 1) = s.drop n := by simp [← dropn_tail] @[simp] theorem drop_nil {n : β„•} : (@nil Ξ±).drop n = nil := by induction n with | zero => simp [drop] | succ m ih => simp [← dropn_tail, ih] @[simp] theorem drop_length' {n : β„•} {s : Seq Ξ±} : (s.drop n).length' = s.length' - n := by cases n with | zero => simp | succ n => cases s with | nil => simp | cons x s => simp only [drop_succ_cons, length'_cons, Nat.cast_add, Nat.cast_one] convert drop_length' using 1 generalize s.length' = m enat_to_nat omega theorem take_drop {s : Seq Ξ±} {n m : β„•} : (s.take n).drop m = (s.drop m).take (n - m) := by induction m generalizing n s with | zero => simp [drop] | succ k ih => cases s Β· simp cases n with | zero => simp | succ l => simp only [take, destruct_cons, List.drop_succ_cons, Nat.reduceSubDiff] rw [ih] congr 1 rw [drop_succ_cons] end Drop section ZipWith @[simp] theorem get?_zipWith (f : Ξ± β†’ Ξ² β†’ Ξ³) (s s' n) : (zipWith f s s').get? n = Option.mapβ‚‚ f (s.get? n) (s'.get? n) := rfl @[simp] theorem get?_zip (s : Seq Ξ±) (t : Seq Ξ²) (n : β„•) : get? (zip s t) n = Option.mapβ‚‚ Prod.mk (get? s n) (get? t n) := get?_zipWith _ _ _ _ @[simp] theorem nats_get? (n : β„•) : nats.get? n = some n := rfl @[simp] theorem get?_enum (s : Seq Ξ±) (n : β„•) : get? (enum s) n = Option.map (Prod.mk n) (get? s n) := get?_zip _ _ _ @[simp] theorem zipWith_nil_left {f : Ξ± β†’ Ξ² β†’ Ξ³} {s} : zipWith f nil s = nil := rfl @[simp] theorem zipWith_nil_right {f : Ξ± β†’ Ξ² β†’ Ξ³} {s} : zipWith f s nil = nil := by ext1 simp @[simp] theorem zipWith_cons_cons {f : Ξ± β†’ Ξ² β†’ Ξ³} {x s x' s'} : zipWith f (cons x s) (cons x' s') = cons (f x x') (zipWith f s s') := by ext1 n cases n <;> simp @[simp] theorem zip_nil_left {s : Seq Ξ±} : zip (@nil Ξ±) s = nil := rfl @[simp] theorem zip_nil_right {s : Seq Ξ±} : zip s (@nil Ξ±) = nil := zipWith_nil_right @[simp] theorem zip_cons_cons {s s' : Seq Ξ±} {x x'} : zip (cons x s) (cons x' s') = cons (x, x') (zip s s') := zipWith_cons_cons @[simp] theorem enum_nil : enum (nil : Seq Ξ±) = nil := rfl @[simp] theorem enum_cons (s : Seq Ξ±) (x : Ξ±) : enum (cons x s) = cons (0, x) (map (Prod.map Nat.succ id) (enum s)) := by ext ⟨n⟩ : 1 Β· simp Β· simp only [get?_enum, get?_cons_succ, map_get?, Option.map_map] congr universe u' v' variable {Ξ±' : Type u'} {Ξ²' : Type v'} theorem zipWith_map (s₁ : Seq Ξ±) (sβ‚‚ : Seq Ξ²) (f₁ : Ξ± β†’ Ξ±') (fβ‚‚ : Ξ² β†’ Ξ²') (g : Ξ±' β†’ Ξ²' β†’ Ξ³) : zipWith g (s₁.map f₁) (sβ‚‚.map fβ‚‚) = zipWith (fun a b ↦ g (f₁ a) (fβ‚‚ b)) s₁ sβ‚‚ := by ext1 n simp only [get?_zipWith, map_get?] cases s₁.get? n <;> cases sβ‚‚.get? n <;> simp theorem zipWith_map_left (s₁ : Seq Ξ±) (sβ‚‚ : Seq Ξ²) (f : Ξ± β†’ Ξ±') (g : Ξ±' β†’ Ξ² β†’ Ξ³) : zipWith g (s₁.map f) sβ‚‚ = zipWith (fun a b ↦ g (f a) b) s₁ sβ‚‚ := by convert zipWith_map _ _ _ (@id Ξ²) _ simp theorem zipWith_map_right (s₁ : Seq Ξ±) (sβ‚‚ : Seq Ξ²) (f : Ξ² β†’ Ξ²') (g : Ξ± β†’ Ξ²' β†’ Ξ³) : zipWith g s₁ (sβ‚‚.map f) = zipWith (fun a b ↦ g a (f b)) s₁ sβ‚‚ := by convert zipWith_map _ _ (@id Ξ±) _ _ simp theorem zip_map (s₁ : Seq Ξ±) (sβ‚‚ : Seq Ξ²) (f₁ : Ξ± β†’ Ξ±') (fβ‚‚ : Ξ² β†’ Ξ²') : (s₁.map f₁).zip (sβ‚‚.map fβ‚‚) = (s₁.zip sβ‚‚).map (Prod.map f₁ fβ‚‚) := by ext1 n simp cases s₁.get? n <;> cases sβ‚‚.get? n <;> simp theorem zip_map_left (s₁ : Seq Ξ±) (sβ‚‚ : Seq Ξ²) (f : Ξ± β†’ Ξ±') : (s₁.map f).zip sβ‚‚ = (s₁.zip sβ‚‚).map (Prod.map f id) := by convert zip_map _ _ _ _ simp theorem zip_map_right (s₁ : Seq Ξ±) (sβ‚‚ : Seq Ξ²) (f : Ξ² β†’ Ξ²') : s₁.zip (sβ‚‚.map f) = (s₁.zip sβ‚‚).map (Prod.map id f) := by convert zip_map _ _ _ _ simp end ZipWith section Fold @[simp] theorem fold_nil (init : Ξ²) (f : Ξ² β†’ Ξ± β†’ Ξ²) : nil.fold init f = cons init nil := by unfold fold simp [corec_nil] @[simp] theorem fold_cons (init : Ξ²) (f : Ξ² β†’ Ξ± β†’ Ξ²) (x : Ξ±) (s : Seq Ξ±) : (cons x s).fold init f = cons init (s.fold (f init x) f) := by unfold fold dsimp only congr rw [corec_cons] simp @[simp] theorem fold_head (init : Ξ²) (f : Ξ² β†’ Ξ± β†’ Ξ²) (s : Seq Ξ±) : (s.fold init f).head = init := by simp [fold] end Fold section Update variable (hd x : Ξ±) (tl : Seq Ξ±) (f : Ξ± β†’ Ξ±) theorem get?_update (s : Seq Ξ±) (n : β„•) (m : β„•) : (s.update n f).get? m = if m = n then (s.get? m).map f else s.get? m := by simp [update, Function.update] split_ifs with h_if Β· simp [h_if] Β· rfl @[simp] theorem update_nil (n : β„•) : update nil n f = nil := by ext1 m simp [get?_update] @[simp] theorem set_nil (n : β„•) (x : Ξ±) : set nil n x = nil := update_nil _ _ @[simp] theorem update_cons_zero : (cons hd tl).update 0 f = cons (f hd) tl := by ext1 n cases n <;> simp [get?_update] @[simp] theorem set_cons_zero (hd' : Ξ±) : (cons hd tl).set 0 hd' = cons hd' tl := update_cons_zero _ _ _ @[simp] theorem update_cons_succ (n : β„•) : (cons hd tl).update (n + 1) f = cons hd (tl.update n f) := by ext1 n cases n <;> simp [get?_update] @[simp] theorem set_cons_succ (n : β„•) : (cons hd tl).set (n + 1) x = cons hd (tl.set n x) := update_cons_succ _ _ _ _ theorem get?_set_of_not_terminatedAt {s : Seq Ξ±} {n : β„•} (h_not_terminated : Β¬ s.TerminatedAt n) : (s.set n x).get? n = x := by simpa [set, update, ← Option.ne_none_iff_exists'] using h_not_terminated theorem get?_set_of_terminatedAt {s : Seq Ξ±} {n : β„•} (h_terminated : s.TerminatedAt n) : (s.set n x).get? n = .none := by simpa [set, get?_update] using h_terminated theorem get?_set_of_ne (s : Seq Ξ±) {m n : β„•} (h : n β‰  m) : (s.set m x).get? n = s.get? n := by simp [set, get?_update, h] theorem drop_set_of_lt (s : Seq Ξ±) {m n : β„•} (h : m < n) : (s.set m x).drop n = s.drop n := by ext1 i simp [get?_set_of_ne _ _ (show n + i β‰  m by cutsat)] end Update section All theorem all_cons {p : Ξ± β†’ Prop} {hd : Ξ±} {tl : Seq Ξ±} (h_hd : p hd) (h_tl : βˆ€ x ∈ tl, p x) : (βˆ€ x ∈ (cons hd tl), p x) := by simp only [mem_cons_iff, forall_eq_or_imp] at * exact ⟨h_hd, h_tl⟩ theorem all_get {p : Ξ± β†’ Prop} {s : Seq Ξ±} (h : βˆ€ x ∈ s, p x) {n : β„•} {x : Ξ±} (hx : s.get? n = .some x) : p x := by exact h _ (get?_mem hx) theorem all_of_get {p : Ξ± β†’ Prop} {s : Seq Ξ±} (h : βˆ€ n x, s.get? n = .some x β†’ p x) : βˆ€ x ∈ s, p x := by simp only [mem_iff_exists_get?] grind private lemma all_coind_drop_motive {s : Seq Ξ±} (motive : Seq Ξ± β†’ Prop) (base : motive s) (step : βˆ€ hd tl, motive (.cons hd tl) β†’ motive tl) (n : β„•) : motive (s.drop n) := by induction n with | zero => simpa | succ m ih => simp only [drop] generalize s.drop m = t at * cases t Β· simpa Β· exact step _ _ ih /-- Coinductive principle for `All`. -/ theorem all_coind {s : Seq Ξ±} {p : Ξ± β†’ Prop} (motive : Seq Ξ± β†’ Prop) (base : motive s) (step : βˆ€ hd tl, motive (.cons hd tl) β†’ p hd ∧ motive tl) : βˆ€ x ∈ s, p x := by apply all_of_get intro n have := all_coind_drop_motive motive base (fun hd tl ih ↦ (step hd tl ih).right) n rw [← head_dropn] generalize s.drop n = s' at this cases s' with | nil => simp | cons hd tl => simp [(step hd tl this).left] theorem map_all_iff {Ξ² : Type u} {f : Ξ± β†’ Ξ²} {p : Ξ² β†’ Prop} {s : Seq Ξ±} : (βˆ€ x ∈ (s.map f), p x) ↔ (βˆ€ x ∈ s, (p ∘ f) x) := by refine ⟨fun _ _ hx ↦ ?_, fun _ _ hx ↦ ?_⟩ Β· solve_by_elim [mem_map f hx] Β· obtain ⟨_, _, hx'⟩ := exists_of_mem_map hx rw [← hx'] solve_by_elim theorem take_all {s : Seq Ξ±} {p : Ξ± β†’ Prop} (h_all : βˆ€ x ∈ s, p x) {n : β„•} {x : Ξ±} (hx : x ∈ s.take n) : p x := by induction n generalizing s with | zero => simp [take] at hx | succ m ih => cases s with | nil => simp at hx | cons hd tl => simp only [take_succ_cons, List.mem_cons, mem_cons_iff, forall_eq_or_imp] at hx h_all rcases hx with (rfl | hx) exacts [h_all.left, ih h_all.right hx] theorem set_all {p : Ξ± β†’ Prop} {s : Seq Ξ±} (h_all : βˆ€ x ∈ s, p x) {n : β„•} {x : Ξ±} (hx : p x) : βˆ€ y ∈ (s.set n x), p y := by intro y hy simp only [mem_iff_exists_get?] at hy obtain ⟨m, hy⟩ := hy rcases eq_or_ne n m with (rfl | h_nm) Β· by_cases h_term : s.TerminatedAt n Β· simp [get?_set_of_terminatedAt _ h_term] at hy Β· simp_all [get?_set_of_not_terminatedAt _ h_term] Β· rw [get?_set_of_ne _ _ h_nm.symm] at hy apply h_all _ (get?_mem hy.symm) end All section Pairwise @[simp] theorem Pairwise.nil {R : Ξ± β†’ Ξ± β†’ Prop} : Pairwise R (@nil Ξ±) := by simp [Pairwise] theorem Pairwise.cons {R : Ξ± β†’ Ξ± β†’ Prop} {hd : Ξ±} {tl : Seq Ξ±} (h_hd : βˆ€ x ∈ tl, R hd x) (h_tl : Pairwise R tl) : Pairwise R (cons hd tl) := by simp only [Pairwise] at * intro i j h_ij x hx y hy cases j with | zero => simp at h_ij | succ k => simp only [get?_cons_succ] at hy cases i with | zero => simp only [get?_cons_zero, Option.mem_def, Option.some.injEq] at hx exact hx β–Έ all_get h_hd hy | succ n => exact h_tl n k (by omega) x hx y hy theorem Pairwise.cons_elim {R : Ξ± β†’ Ξ± β†’ Prop} {hd : Ξ±} {tl : Seq Ξ±} (h : Pairwise R (.cons hd tl)) : (βˆ€ x ∈ tl, R hd x) ∧ Pairwise R tl := by simp only [Pairwise] at * refine ⟨?_, fun i j h_ij ↦ h (i + 1) (j + 1) (by omega)⟩ intro x hx rw [mem_iff_exists_get?] at hx obtain ⟨n, hx⟩ := hx simpa [← hx] using h 0 (n + 1) (by omega) @[simp] theorem Pairwise_cons_nil {R : Ξ± β†’ Ξ± β†’ Prop} {hd : Ξ±} : Pairwise R (cons hd nil) := by apply Pairwise.cons <;> simp theorem Pairwise_cons_cons_head {R : Ξ± β†’ Ξ± β†’ Prop} {hd tl_hd : Ξ±} {tl_tl : Seq Ξ±} (h : Pairwise R (cons hd (cons tl_hd tl_tl))) : R hd tl_hd := by simp only [Pairwise] at h simpa using h 0 1 Nat.one_pos theorem Pairwise.cons_cons_of_trans {R : Ξ± β†’ Ξ± β†’ Prop} [IsTrans _ R] {hd tl_hd : Ξ±} {tl_tl : Seq Ξ±} (h_hd : R hd tl_hd) (h_tl : Pairwise R (.cons tl_hd tl_tl)) : Pairwise R (.cons hd (.cons tl_hd tl_tl)) := by apply Pairwise.cons _ h_tl simp only [mem_cons_iff, forall_eq_or_imp] exact ⟨h_hd, fun x hx ↦ Trans.simple h_hd ((cons_elim h_tl).left x hx)⟩ /-- Coinductive principle for `Pairwise`. -/ theorem Pairwise.coind {R : Ξ± β†’ Ξ± β†’ Prop} {s : Seq Ξ±} (motive : Seq Ξ± β†’ Prop) (base : motive s) (step : βˆ€ hd tl, motive (.cons hd tl) β†’ (βˆ€ x ∈ tl, R hd x) ∧ motive tl) : Pairwise R s := by simp only [Pairwise] intro i j h_ij x hx y hy obtain ⟨k, hj⟩ := Nat.exists_eq_add_of_lt h_ij rw [← head_dropn] at hx rw [hj, ← head_dropn, Nat.add_assoc, dropn_add, head_dropn] at hy have := all_coind_drop_motive motive base (fun hd tl ih ↦ (step hd tl ih).right) i generalize s.drop i = s' at * cases s' with | nil => simp at hx | cons hd tl => simp at hx hy exact hx β–Έ all_get (step hd tl this).left hy /-- Coinductive principle for `Pairwise` that assumes that `R` is transitive. Compared to `Pairwise.coind`, this allows you to prove `R hd tl.head` instead of `tl.All (R hd Β·)` in `step`. -/ theorem Pairwise.coind_trans {R : Ξ± β†’ Ξ± β†’ Prop} [IsTrans Ξ± R] {s : Seq Ξ±} (motive : Seq Ξ± β†’ Prop) (base : motive s) (step : βˆ€ hd tl, motive (.cons hd tl) β†’ (βˆ€ x ∈ tl.head, R hd x) ∧ motive tl) : Pairwise R s := by have h_succ {n} {x y} (hx : s.get? n = some x) (hy : s.get? (n + 1) = some y) : R x y := by rw [← head_dropn] at hx have := all_coind_drop_motive motive base (fun hd tl ih ↦ (step hd tl ih).right) exact (step x (s.drop (n + 1)) (head_eq_some hx β–Έ this n)).left _ (by simpa) simp only [Pairwise] intro i j h_ij x hx y hy obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_lt h_ij clear h_ij induction k generalizing y with | zero => exact h_succ hx hy | succ k ih => obtain ⟨z, hz⟩ := ge_stable (m := i + k + 1) _ (by omega) hy exact _root_.trans (ih z hz) <| h_succ hz hy theorem Pairwise_tail {R : Ξ± β†’ Ξ± β†’ Prop} {s : Seq Ξ±} (h : s.Pairwise R) : s.tail.Pairwise R := by cases s Β· simp Β· simp [h.cons_elim.right] theorem Pairwise_drop {R : Ξ± β†’ Ξ± β†’ Prop} {s : Seq Ξ±} (h : s.Pairwise R) {n : β„•} : (s.drop n).Pairwise R := by induction n with | zero => simpa | succ m ih => simp [drop, Pairwise_tail ih] end Pairwise /-- Coinductive principle for proving `b.length' ≀ a.length'` for two sequences `a` and `b`. -/ theorem at_least_as_long_as_coind {a : Seq Ξ±} {b : Seq Ξ²} (motive : Seq Ξ± β†’ Seq Ξ² β†’ Prop) (base : motive a b) (step : βˆ€ a b, motive a b β†’ (βˆ€ b_hd b_tl, (b = .cons b_hd b_tl) β†’ βˆƒ a_hd a_tl, a = .cons a_hd a_tl ∧ motive a_tl b_tl)) : b.length' ≀ a.length' := by have (n) (hb : b.drop n β‰  .nil) : motive (a.drop n) (b.drop n) := by induction n with | zero => simpa | succ m ih => simp only [drop] at hb ⊒ generalize b.drop m = tb at * cases tb with | nil => simp at hb | cons tb_hd tb_tl => simp only [ne_eq, cons_ne_nil, not_false_eq_true, forall_const] at ih obtain ⟨a_hd, a_tl, ha, h_tail⟩ := step (a.drop m) (.cons tb_hd tb_tl) ih _ _ rfl simpa [ha] by_cases ha : a.Terminates; swap Β· simp [length'_of_not_terminates ha] simp [length'_of_terminates ha, length'_le_iff] by_contra! hb have hb_cons : b.drop (a.length ha) β‰  .nil := by intro hb' simp only [← length'_eq_zero_iff_nil, drop_length', tsub_eq_zero_iff_le, length'_le_iff] at hb' contradiction specialize this (a.length ha) hb_cons generalize b.drop (a.length ha) = b' at * cases b' with | nil => contradiction | cons b_hd b_tl => obtain ⟨a_hd, a_tl, ha', _⟩ := step _ _ this _ _ rfl apply_fun length' at ha' simp only [drop_length', length'_of_terminates ha, tsub_self, length'_cons] at ha' generalize a_tl.length' = u at ha' enat_to_nat omega instance : Functor Seq where map := @map instance : LawfulFunctor Seq where id_map := @map_id comp_map := @map_comp map_const := rfl end Seq namespace Seq1 variable {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w} open Stream'.Seq /-- Convert a `Seq1` to a sequence. -/ def toSeq : Seq1 Ξ± β†’ Seq Ξ± | (a, s) => Seq.cons a s instance coeSeq : Coe (Seq1 Ξ±) (Seq Ξ±) := ⟨toSeq⟩ /-- Map a function on a `Seq1` -/ def map (f : Ξ± β†’ Ξ²) : Seq1 Ξ± β†’ Seq1 Ξ² | (a, s) => (f a, Seq.map f s) theorem map_pair {f : Ξ± β†’ Ξ²} {a s} : map f (a, s) = (f a, Seq.map f s) := rfl theorem map_id : βˆ€ s : Seq1 Ξ±, map id s = s | ⟨a, s⟩ => by simp [map] /-- Flatten a nonempty sequence of nonempty sequences -/ def join : Seq1 (Seq1 Ξ±) β†’ Seq1 Ξ± | ((a, s), S) => match destruct s with | none => (a, Seq.join S) | some s' => (a, Seq.join (Seq.cons s' S)) @[simp] theorem join_nil (a : Ξ±) (S) : join ((a, nil), S) = (a, Seq.join S) := rfl @[simp] theorem join_cons (a b : Ξ±) (s S) : join ((a, Seq.cons b s), S) = (a, Seq.join (Seq.cons (b, s) S)) := by dsimp [join]; rw [destruct_cons] /-- The `return` operator for the `Seq1` monad, which produces a singleton sequence. -/ def ret (a : Ξ±) : Seq1 Ξ± := (a, nil) instance [Inhabited Ξ±] : Inhabited (Seq1 Ξ±) := ⟨ret default⟩ /-- The `bind` operator for the `Seq1` monad, which maps `f` on each element of `s` and appends the results together. (Not all of `s` may be evaluated, because the first few elements of `s` may already produce an infinite result.) -/ def bind (s : Seq1 Ξ±) (f : Ξ± β†’ Seq1 Ξ²) : Seq1 Ξ² := join (map f s) @[simp] theorem join_map_ret (s : Seq Ξ±) : Seq.join (Seq.map ret s) = s := by apply coinduction2 s; intro s; cases s <;> simp [ret] @[simp] theorem bind_ret (f : Ξ± β†’ Ξ²) : βˆ€ s, bind s (ret ∘ f) = map f s | ⟨a, s⟩ => by simp [bind, map, map_comp, ret] @[simp] theorem ret_bind (a : Ξ±) (f : Ξ± β†’ Seq1 Ξ²) : bind (ret a) f = f a := by simp only [bind, map, ret.eq_1, map_nil] obtain ⟨a, s⟩ := f a cases s <;> simp @[simp] theorem map_join' (f : Ξ± β†’ Ξ²) (S) : Seq.map f (Seq.join S) = Seq.join (Seq.map (map f) S) := by apply Seq.eq_of_bisim fun s1 s2 => βˆƒ s S, s1 = Seq.append s (Seq.map f (Seq.join S)) ∧ s2 = append s (Seq.join (Seq.map (map f) S)) Β· intro s1 s2 h exact match s1, s2, h with | _, _, ⟨s, S, rfl, rfl⟩ => by cases s <;> simp case nil => cases S <;> simp case cons x S => obtain ⟨a, s⟩ := x simpa [map] using ⟨_, _, rfl, rfl⟩ case cons _ s => exact ⟨s, S, rfl, rfl⟩ Β· refine ⟨nil, S, ?_, ?_⟩ <;> simp @[simp] theorem map_join (f : Ξ± β†’ Ξ²) : βˆ€ S, map f (join S) = join (map (map f) S) | ((a, s), S) => by cases s <;> simp [map] @[simp] theorem join_join (SS : Seq (Seq1 (Seq1 Ξ±))) : Seq.join (Seq.join SS) = Seq.join (Seq.map join SS) := by apply Seq.eq_of_bisim fun s1 s2 => βˆƒ s SS, s1 = Seq.append s (Seq.join (Seq.join SS)) ∧ s2 = Seq.append s (Seq.join (Seq.map join SS)) Β· intro s1 s2 h exact match s1, s2, h with | _, _, ⟨s, SS, rfl, rfl⟩ => by cases s <;> simp case nil => cases SS <;> simp case cons S SS => obtain ⟨s, S⟩ := S; obtain ⟨x, s⟩ := s simp only [Seq.join_cons, join_append, destruct_cons] cases s <;> simp case nil => exact ⟨_, _, rfl, rfl⟩ case cons x s => refine ⟨Seq.cons x (append s (Seq.join S)), SS, ?_, ?_⟩ <;> simp case cons _ s => exact ⟨s, SS, rfl, rfl⟩ Β· refine ⟨nil, SS, ?_, ?_⟩ <;> simp @[simp] theorem bind_assoc (s : Seq1 Ξ±) (f : Ξ± β†’ Seq1 Ξ²) (g : Ξ² β†’ Seq1 Ξ³) : bind (bind s f) g = bind s fun x : Ξ± => bind (f x) g := by obtain ⟨a, s⟩ := s simp only [bind, map_pair, map_join] rw [← map_comp] simp only [show (fun x => join (map g (f x))) = join ∘ (map g ∘ f) from rfl] rw [map_comp _ join] generalize Seq.map (map g ∘ f) s = SS rcases map g (f a) with ⟨⟨a, s⟩, S⟩ induction s using recOn with | nil => ?_ | cons x s_1 => ?_ <;> induction S using recOn with | nil => simp | cons x_1 s_2 => ?_ Β· obtain ⟨x, t⟩ := x_1 cases t <;> simp Β· obtain ⟨y, t⟩ := x_1; simp instance monad : Monad Seq1 where map := @map pure := @ret bind := @bind instance lawfulMonad : LawfulMonad Seq1 := LawfulMonad.mk' (id_map := @map_id) (bind_pure_comp := @bind_ret) (pure_bind := @ret_bind) (bind_assoc := @bind_assoc) end Seq1 end Stream'
.lake/packages/mathlib/Mathlib/Data/Seq/WSeq.lean
import Mathlib.Data.WSeq.Basic import Mathlib.Data.WSeq.Defs import Mathlib.Data.WSeq.Productive import Mathlib.Data.WSeq.Relation deprecated_module (since := "2025-04-13")
.lake/packages/mathlib/Mathlib/Data/Seq/Defs.lean
import Mathlib.Data.Option.NAry import Mathlib.Data.Seq.Computation import Mathlib.Data.ENat.Defs /-! # Possibly infinite lists This file provides `Stream'.Seq Ξ±`, a type representing possibly infinite lists (referred here as sequences). It is encoded as an infinite stream of options such that if `f n = none`, then `f m = none` for all `m β‰₯ n`. ## Main definitions * `Seq Ξ±`: The type of possibly infinite lists (sequences) encoded as streams of options. It is encoded as `Stream' (Option Ξ±)` such that if `f n = none`, then `f m = none` for all `m β‰₯ n`. It has two "constructors": `nil` and `cons`, and a destructor `destruct`. * `Seq1 Ξ±`: The type of nonempty sequences * `Seq.get?`: Extract the nth element of a sequence (if it exists). * `Seq.corec`: Corecursion principle for `Seq Ξ±` as a coinductive type. * `Seq.Terminates`: Predicate for when a sequence is finite. One can convert between sequences and other types: `List`, `Stream'`, `MLList` using corresponding functions defined in this file. There are also a number of operations and predicates on sequences mirroring those on lists: `Seq.map`, `Seq.zip`, `Seq.zipWith`, `Seq.unzip`, `Seq.fold`, `Seq.update`, `Seq.drop`, `Seq.splitAt`, `Seq.append`, `Seq.join`, `Seq.enum`, `Seq.Pairwire`, as well as a cases principle `Seq.recOn` which allows one to reason about sequences by cases (`nil` and `cons`). ## Main statements * `eq_of_bisim`: Bisimulation principle for sequences. -/ namespace Stream' universe u v w /- coinductive seq (Ξ± : Type u) : Type u | nil : seq Ξ± | cons : Ξ± β†’ seq Ξ± β†’ seq Ξ± -/ /-- A stream `s : Option Ξ±` is a sequence if `s.get n = none` implies `s.get (n + 1) = none`. -/ def IsSeq {Ξ± : Type u} (s : Stream' (Option Ξ±)) : Prop := βˆ€ {n : β„•}, s n = none β†’ s (n + 1) = none /-- `Seq Ξ±` is the type of possibly infinite lists (referred here as sequences). It is encoded as an infinite stream of options such that if `f n = none`, then `f m = none` for all `m β‰₯ n`. -/ def Seq (Ξ± : Type u) : Type u := { f : Stream' (Option Ξ±) // f.IsSeq } /-- `Seq1 Ξ±` is the type of nonempty sequences. -/ def Seq1 (Ξ±) := Ξ± Γ— Seq Ξ± namespace Seq variable {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w} /-- Get the nth element of a sequence (if it exists) -/ def get? : Seq Ξ± β†’ β„• β†’ Option Ξ± := Subtype.val @[simp] theorem val_eq_get (s : Seq Ξ±) (n : β„•) : s.val n = s.get? n := rfl @[simp] theorem get?_mk (f hf) : @get? Ξ± ⟨f, hf⟩ = f := rfl theorem le_stable (s : Seq Ξ±) {m n} (h : m ≀ n) : s.get? m = none β†’ s.get? n = none := by obtain ⟨f, al⟩ := s induction h with | refl => exact id | step _ IH => exact fun h2 ↦ al (IH h2) /-- If `s.get? n = some aβ‚™` for some value `aβ‚™`, then there is also some value `aβ‚˜` such that `s.get? = some aβ‚˜` for `m ≀ n`. -/ theorem ge_stable (s : Seq Ξ±) {aβ‚™ : Ξ±} {n m : β„•} (m_le_n : m ≀ n) (s_nth_eq_some : s.get? n = some aβ‚™) : βˆƒ aβ‚˜ : Ξ±, s.get? m = some aβ‚˜ := have : s.get? n β‰  none := by simp [s_nth_eq_some] have : s.get? m β‰  none := mt (s.le_stable m_le_n) this Option.ne_none_iff_exists'.mp this @[ext] protected theorem ext {s t : Seq Ξ±} (h : βˆ€ n : β„•, s.get? n = t.get? n) : s = t := Subtype.eq <| funext h /-! ### Constructors -/ /-- The empty sequence -/ def nil : Seq Ξ± := ⟨Stream'.const none, fun {_} _ => rfl⟩ instance : Inhabited (Seq Ξ±) := ⟨nil⟩ /-- Prepend an element to a sequence -/ def cons (a : Ξ±) (s : Seq Ξ±) : Seq Ξ± := ⟨some a::s.1, by rintro (n | _) h Β· contradiction Β· exact s.2 h⟩ @[simp] theorem val_cons (s : Seq Ξ±) (x : Ξ±) : (cons x s).val = some x::s.val := rfl @[simp] theorem get?_nil (n : β„•) : (@nil Ξ±).get? n = none := rfl @[simp] theorem get?_zero_eq_none {s : Seq Ξ±} : s.get? 0 = none ↔ s = nil := by refine ⟨fun h => ?_, fun h => h β–Έ rfl⟩ ext1 n exact le_stable s (Nat.zero_le _) h @[simp] theorem get?_cons_zero (a : Ξ±) (s : Seq Ξ±) : (cons a s).get? 0 = some a := rfl @[simp] theorem get?_cons_succ (a : Ξ±) (s : Seq Ξ±) (n : β„•) : (cons a s).get? (n + 1) = s.get? n := rfl @[simp] theorem cons_ne_nil {x : Ξ±} {s : Seq Ξ±} : (cons x s) β‰  .nil := by intro h simpa using congrArg (Β·.get? 0) h @[simp] theorem nil_ne_cons {x : Ξ±} {s : Seq Ξ±} : .nil β‰  (cons x s) := cons_ne_nil.symm theorem cons_injective2 : Function.Injective2 (cons : Ξ± β†’ Seq Ξ± β†’ Seq Ξ±) := fun x y s t h => ⟨by rw [← Option.some_inj, ← get?_cons_zero, h, get?_cons_zero], Seq.ext fun n => by simp_rw [← get?_cons_succ x s n, h, get?_cons_succ]⟩ theorem cons_left_injective (s : Seq Ξ±) : Function.Injective fun x => cons x s := cons_injective2.left _ theorem cons_right_injective (x : Ξ±) : Function.Injective (cons x) := cons_injective2.right _ theorem cons_eq_cons {x x' : Ξ±} {s s' : Seq Ξ±} : (cons x s = cons x' s') ↔ (x = x' ∧ s = s') := by constructor Β· apply cons_injective2 Β· intro ⟨_, _⟩ congr /-! ### Destructors -/ /-- Get the first element of a sequence -/ def head (s : Seq Ξ±) : Option Ξ± := get? s 0 /-- Get the tail of a sequence (or `nil` if the sequence is `nil`) -/ def tail (s : Seq Ξ±) : Seq Ξ± := ⟨s.1.tail, fun n' => by obtain ⟨f, al⟩ := s exact al n'⟩ /-- Destructor for a sequence, resulting in either `none` (for `nil`) or `some (a, s)` (for `cons a s`). -/ def destruct (s : Seq Ξ±) : Option (Seq1 Ξ±) := (fun a' => (a', s.tail)) <$> get? s 0 -- Porting note: needed universe annotation to avoid universe issues theorem head_eq_destruct (s : Seq Ξ±) : head s = Prod.fst <$> destruct.{u} s := by unfold destruct head; cases get? s 0 <;> rfl @[simp] theorem get?_tail (s : Seq Ξ±) (n) : get? (tail s) n = get? s (n + 1) := rfl @[simp] theorem destruct_nil : destruct (nil : Seq Ξ±) = none := rfl @[simp] theorem destruct_cons (a : Ξ±) : βˆ€ s, destruct (cons a s) = some (a, s) | ⟨f, al⟩ => by unfold cons destruct Functor.map apply congr_arg fun s => some (a, s) apply Subtype.eq; dsimp [tail] theorem destruct_eq_none {s : Seq Ξ±} : destruct s = none β†’ s = nil := by dsimp [destruct] rcases f0 : get? s 0 <;> intro h Β· apply Subtype.eq funext n induction n with | zero => exact f0 | succ n IH => exact s.2 IH Β· contradiction theorem destruct_eq_cons {s : Seq Ξ±} {a s'} : destruct s = some (a, s') β†’ s = cons a s' := by dsimp [destruct] rcases f0 : get? s 0 with - | a' <;> intro h Β· contradiction Β· obtain ⟨f, al⟩ := s injections _ h1 h2 rw [← h2] apply Subtype.eq dsimp [tail, cons] rw [h1] at f0 rw [← f0] exact (Stream'.eta f).symm @[simp] theorem head_nil : head (nil : Seq Ξ±) = none := rfl @[simp] theorem head_cons (a : Ξ±) (s) : head (cons a s) = some a := by rw [head_eq_destruct, destruct_cons, Option.map_eq_map, Option.map_some] @[simp] theorem tail_nil : tail (nil : Seq Ξ±) = nil := rfl @[simp] theorem tail_cons (a : Ξ±) (s) : tail (cons a s) = s := rfl theorem head_eq_some {s : Seq Ξ±} {x : Ξ±} (h : s.head = some x) : s = cons x s.tail := by ext1 n cases n <;> simp only [get?_cons_zero, get?_cons_succ, get?_tail] exact h theorem head_eq_none {s : Seq Ξ±} (h : s.head = none) : s = nil := get?_zero_eq_none.mp h @[simp] theorem head_eq_none_iff {s : Seq Ξ±} : s.head = none ↔ s = nil := by constructor Β· apply head_eq_none Β· intro h simp [h] /-! ### Recursion and corecursion principles -/ /-- Recursion principle for sequences, compare with `List.recOn`. -/ @[cases_eliminator] def recOn {motive : Seq Ξ± β†’ Sort v} (s : Seq Ξ±) (nil : motive nil) (cons : βˆ€ x s, motive (cons x s)) : motive s := by rcases H : destruct s with - | v Β· rw [destruct_eq_none H] apply nil Β· obtain ⟨a, s'⟩ := v rw [destruct_eq_cons H] apply cons /-- Functorial action of the functor `Option (Ξ± Γ— _)` -/ @[simp] def omap (f : Ξ² β†’ Ξ³) : Option (Ξ± Γ— Ξ²) β†’ Option (Ξ± Γ— Ξ³) | none => none | some (a, b) => some (a, f b) /-- Corecursor over pairs of `Option` values -/ def Corec.f (f : Ξ² β†’ Option (Ξ± Γ— Ξ²)) : Option Ξ² β†’ Option Ξ± Γ— Option Ξ² | none => (none, none) | some b => match f b with | none => (none, none) | some (a, b') => (some a, some b') /-- Corecursor for `Seq Ξ±` as a coinductive type. Iterates `f` to produce new elements of the sequence until `none` is obtained. -/ def corec (f : Ξ² β†’ Option (Ξ± Γ— Ξ²)) (b : Ξ²) : Seq Ξ± := by refine ⟨Stream'.corec' (Corec.f f) (some b), fun {n} h => ?_⟩ rw [Stream'.corec'_eq] change Stream'.corec' (Corec.f f) (Corec.f f (some b)).2 n = none revert h; generalize some b = o induction n generalizing o with | zero => change (Corec.f f o).1 = none β†’ (Corec.f f (Corec.f f o).2).1 = none rcases o with - | b <;> intro h Β· rfl dsimp [Corec.f] at h dsimp [Corec.f] revert h; rcases h₁ : f b with - | s <;> intro h Β· rfl Β· obtain ⟨a, b'⟩ := s contradiction | succ n IH => rw [Stream'.corec'_eq (Corec.f f) (Corec.f f o).2, Stream'.corec'_eq (Corec.f f) o] exact IH (Corec.f f o).2 @[simp] theorem corec_eq (f : Ξ² β†’ Option (Ξ± Γ— Ξ²)) (b : Ξ²) : destruct (corec f b) = omap (corec f) (f b) := by dsimp [corec, destruct, get] rw [show Stream'.corec' (Corec.f f) (some b) 0 = (Corec.f f (some b)).1 from rfl] dsimp [Corec.f] rcases h : f b with - | s; Β· rfl obtain ⟨a, b'⟩ := s; dsimp [Corec.f] apply congr_arg fun b' => some (a, b') apply Subtype.eq dsimp [corec, tail] rw [Stream'.corec'_eq, Stream'.tail_cons] dsimp [Corec.f]; rw [h] theorem corec_nil (f : Ξ² β†’ Option (Ξ± Γ— Ξ²)) (b : Ξ²) (h : f b = .none) : corec f b = nil := by apply destruct_eq_none simp [h] theorem corec_cons {f : Ξ² β†’ Option (Ξ± Γ— Ξ²)} {b : Ξ²} {x : Ξ±} {s : Ξ²} (h : f b = .some (x, s)) : corec f b = cons x (corec f s) := by apply destruct_eq_cons simp [h] /-! ### Bisimulation -/ section Bisim variable (R : Seq Ξ± β†’ Seq Ξ± β†’ Prop) local infixl:50 " ~ " => R /-- Bisimilarity relation over `Option` of `Seq1 Ξ±` -/ def BisimO : Option (Seq1 Ξ±) β†’ Option (Seq1 Ξ±) β†’ Prop | none, none => True | some (a, s), some (a', s') => a = a' ∧ R s s' | _, _ => False attribute [simp] BisimO attribute [nolint simpNF] BisimO.eq_3 /-- a relation is bisimilar if it meets the `BisimO` test -/ def IsBisimulation := βˆ€ ⦃s₁ s₂⦄, s₁ ~ sβ‚‚ β†’ BisimO R (destruct s₁) (destruct sβ‚‚) /-- If two streams are bisimilar, then they are equal. There are also versions `eq_of_bisim'` and `eq_of_bisim_strong` that does not mention `IsBisimulation` and look more like an induction principles. -/ theorem eq_of_bisim (bisim : IsBisimulation R) {s₁ sβ‚‚} (r : s₁ ~ sβ‚‚) : s₁ = sβ‚‚ := by apply Subtype.eq apply Stream'.eq_of_bisim fun x y => βˆƒ s s' : Seq Ξ±, s.1 = x ∧ s'.1 = y ∧ R s s' Β· dsimp [Stream'.IsBisimulation] intro t₁ tβ‚‚ e exact match t₁, tβ‚‚, e with | _, _, ⟨s, s', rfl, rfl, r⟩ => by suffices head s = head s' ∧ R (tail s) (tail s') from And.imp id (fun r => ⟨tail s, tail s', by cases s using Subtype.recOn; rfl, by cases s' using Subtype.recOn; rfl, r⟩) this have := bisim r; revert r this cases s <;> cases s' Β· intro r _ constructor Β· rfl Β· assumption Β· intro _ this rw [destruct_nil, destruct_cons] at this exact False.elim this Β· intro _ this rw [destruct_nil, destruct_cons] at this exact False.elim this Β· simp Β· exact ⟨s₁, sβ‚‚, rfl, rfl, r⟩ /-- Coinductive principle for equality on sequences. This is a version of `eq_of_bisim` that looks more like an induction principle. -/ theorem eq_of_bisim' {s₁ sβ‚‚ : Seq Ξ±} (motive : Seq Ξ± β†’ Seq Ξ± β†’ Prop) (base : motive s₁ sβ‚‚) (step : βˆ€ s₁ sβ‚‚, motive s₁ sβ‚‚ β†’ (s₁ = nil ∧ sβ‚‚ = nil) ∨ (βˆƒ x s₁' sβ‚‚', s₁ = cons x s₁' ∧ sβ‚‚ = cons x sβ‚‚' ∧ motive s₁' sβ‚‚')) : s₁ = sβ‚‚ := by apply eq_of_bisim motive _ base intro s₁ sβ‚‚ h rcases step s₁ sβ‚‚ h with ⟨h_nil₁, h_nilβ‚‚βŸ© | ⟨_, _, _, h₁, hβ‚‚, _⟩ Β· simp [h_nil₁, h_nilβ‚‚] Β· simpa [h₁, hβ‚‚] /-- Coinductive principle for equality on sequences. This is a version of `eq_of_bisim'` that requires proving only `s₁ = sβ‚‚` instead of `s₁ = nil ∧ sβ‚‚ = nil` in `step`. -/ theorem eq_of_bisim_strong {s₁ sβ‚‚ : Seq Ξ±} (motive : Seq Ξ± β†’ Seq Ξ± β†’ Prop) (base : motive s₁ sβ‚‚) (step : βˆ€ s₁ sβ‚‚, motive s₁ sβ‚‚ β†’ (s₁ = sβ‚‚) ∨ (βˆƒ x s₁' sβ‚‚', s₁ = cons x s₁' ∧ sβ‚‚ = cons x sβ‚‚' ∧ (motive s₁' sβ‚‚'))) : s₁ = sβ‚‚ := by let motive' : Seq Ξ± β†’ Seq Ξ± β†’ Prop := fun s₁ sβ‚‚ => s₁ = sβ‚‚ ∨ motive s₁ sβ‚‚ apply eq_of_bisim' motive' (by grind) intro s₁ sβ‚‚ ih simp only [motive'] at ih ⊒ rcases ih with (rfl | ih) Β· cases s₁ <;> grind rcases step s₁ sβ‚‚ ih with (rfl | ⟨hd, s₁', sβ‚‚', _⟩) Β· cases s₁ <;> grind Β· grind end Bisim theorem coinduction : βˆ€ {s₁ sβ‚‚ : Seq Ξ±}, head s₁ = head sβ‚‚ β†’ (βˆ€ (Ξ² : Type u) (fr : Seq Ξ± β†’ Ξ²), fr s₁ = fr sβ‚‚ β†’ fr (tail s₁) = fr (tail sβ‚‚)) β†’ s₁ = sβ‚‚ | _, _, hh, ht => Subtype.eq (Stream'.coinduction hh fun Ξ² fr => ht Ξ² fun s => fr s.1) theorem coinduction2 (s) (f g : Seq Ξ± β†’ Seq Ξ²) (H : βˆ€ s, BisimO (fun s1 s2 : Seq Ξ² => βˆƒ s : Seq Ξ±, s1 = f s ∧ s2 = g s) (destruct (f s)) (destruct (g s))) : f s = g s := by refine eq_of_bisim (fun s1 s2 => βˆƒ s, s1 = f s ∧ s2 = g s) ?_ ⟨s, rfl, rfl⟩ intro s1 s2 h; rcases h with ⟨s, h1, h2⟩ rw [h1, h2]; apply H /-! ### Termination -/ /-- A sequence has terminated at position `n` if the value at position `n` equals `none`. -/ def TerminatedAt (s : Seq Ξ±) (n : β„•) : Prop := s.get? n = none /-- It is decidable whether a sequence terminates at a given position. -/ instance terminatedAtDecidable (s : Seq Ξ±) (n : β„•) : Decidable (s.TerminatedAt n) := decidable_of_iff' (s.get? n).isNone <| by unfold TerminatedAt; cases s.get? n <;> simp /-- A sequence terminates if there is some position `n` at which it has terminated. -/ def Terminates (s : Seq Ξ±) : Prop := βˆƒ n : β„•, s.TerminatedAt n /-- The length of a terminating sequence. -/ def length (s : Seq Ξ±) (h : s.Terminates) : β„• := Nat.find h open Classical in /-- The `ENat`-valued length of a sequence. For non-terminating sequences, it is `⊀`. -/ noncomputable def length' (s : Seq Ξ±) : β„•βˆž := if h : s.Terminates then s.length h else ⊀ /-- If a sequence terminated at position `n`, it also terminated at `m β‰₯ n`. -/ theorem terminated_stable : βˆ€ (s : Seq Ξ±) {m n : β„•}, m ≀ n β†’ s.TerminatedAt m β†’ s.TerminatedAt n := le_stable theorem not_terminates_iff {s : Seq Ξ±} : Β¬s.Terminates ↔ βˆ€ n, (s.get? n).isSome := by simp only [Terminates, TerminatedAt, ← Ne.eq_def, Option.ne_none_iff_isSome, not_exists, iff_self] theorem terminatedAt_nil {n : β„•} : TerminatedAt (nil : Seq Ξ±) n := rfl @[simp] theorem cons_not_terminatedAt_zero {x : Ξ±} {s : Seq Ξ±} : Β¬(cons x s).TerminatedAt 0 := by simp [TerminatedAt] @[simp] theorem cons_terminatedAt_succ_iff {x : Ξ±} {s : Seq Ξ±} {n : β„•} : (cons x s).TerminatedAt (n + 1) ↔ s.TerminatedAt n := by simp [TerminatedAt] @[simp] theorem terminates_nil : Terminates (nil : Seq Ξ±) := ⟨0, rfl⟩ @[simp] theorem terminates_cons_iff {x : Ξ±} {s : Seq Ξ±} : (cons x s).Terminates ↔ s.Terminates := by constructor <;> intro ⟨n, h⟩ Β· exact ⟨n, cons_terminatedAt_succ_iff.mp (terminated_stable _ (Nat.le_succ _) h)⟩ Β· exact ⟨n + 1, cons_terminatedAt_succ_iff.mpr h⟩ theorem terminatedAt_zero_iff {s : Seq Ξ±} : s.TerminatedAt 0 ↔ s = nil := by refine ⟨?_, ?_⟩ Β· intro h ext n rw [le_stable _ (Nat.zero_le _) h] simp Β· rintro rfl simp [TerminatedAt] /-! ### Membership -/ /-- member definition for `Seq` -/ protected def Mem (s : Seq Ξ±) (a : Ξ±) := some a ∈ s.1 instance : Membership Ξ± (Seq Ξ±) := ⟨Seq.Mem⟩ -- Cannot be @[simp] because `n` can not be inferred by `simp`. theorem get?_mem {s : Seq Ξ±} {n : β„•} {x : Ξ±} (h : s.get? n = .some x) : x ∈ s := ⟨n, h.symm⟩ theorem mem_iff_exists_get? {s : Seq Ξ±} {x : Ξ±} : x ∈ s ↔ βˆƒ i, some x = s.get? i where mp h := by change (some x ∈ s.1) at h rwa [Stream'.mem_iff_exists_get_eq] at h mpr h := get?_mem h.choose_spec.symm @[simp] theorem notMem_nil (a : Ξ±) : a βˆ‰ @nil Ξ± := fun ⟨_, (h : some a = none)⟩ => by injection h @[deprecated (since := "2025-05-23")] alias not_mem_nil := notMem_nil theorem mem_cons (a : Ξ±) : βˆ€ s : Seq Ξ±, a ∈ cons a s | ⟨_, _⟩ => Stream'.mem_cons (some a) _ theorem mem_cons_of_mem (y : Ξ±) {a : Ξ±} : βˆ€ {s : Seq Ξ±}, a ∈ s β†’ a ∈ cons y s | ⟨_, _⟩ => Stream'.mem_cons_of_mem (some y) theorem eq_or_mem_of_mem_cons {a b : Ξ±} : βˆ€ {s : Seq Ξ±}, a ∈ cons b s β†’ a = b ∨ a ∈ s | ⟨_, _⟩, h => (Stream'.eq_or_mem_of_mem_cons h).imp_left fun h => by injection h @[simp] theorem mem_cons_iff {a b : Ξ±} {s : Seq Ξ±} : a ∈ cons b s ↔ a = b ∨ a ∈ s := ⟨eq_or_mem_of_mem_cons, by rintro (rfl | m) <;> [apply mem_cons; exact mem_cons_of_mem _ m]⟩ theorem mem_rec_on {C : Seq Ξ± β†’ Prop} {a s} (M : a ∈ s) (h1 : βˆ€ b s', a = b ∨ C s' β†’ C (cons b s')) : C s := by obtain ⟨k, e⟩ := M; unfold Stream'.get at e induction k generalizing s with | zero => have TH : s = cons a (tail s) := by apply destruct_eq_cons unfold destruct get? Functor.map rw [← e] rfl rw [TH] apply h1 _ _ (Or.inl rfl) | succ k IH => cases s with | nil => injection e | cons b s' => have h_eq : (cons b s').val (Nat.succ k) = s'.val k := by cases s' using Subtype.recOn; rfl rw [h_eq] at e apply h1 _ _ (Or.inr (IH e)) /-! ### Converting from/to other types -/ /-- Embed a list as a sequence -/ @[coe] def ofList (l : List Ξ±) : Seq Ξ± := ⟨(l[Β·]?), fun {n} h => by rw [List.getElem?_eq_none_iff] at h ⊒ exact Nat.le_succ_of_le h⟩ instance coeList : Coe (List Ξ±) (Seq Ξ±) := ⟨ofList⟩ @[simp] theorem ofList_nil : ofList [] = (nil : Seq Ξ±) := rfl @[simp] theorem ofList_get? (l : List Ξ±) (n : β„•) : (ofList l).get? n = l[n]? := rfl @[simp] theorem ofList_cons (a : Ξ±) (l : List Ξ±) : ofList (a::l) = cons a (ofList l) := by ext1 (_ | n) <;> simp theorem ofList_injective : Function.Injective (ofList : List Ξ± β†’ _) := fun _ _ h => List.ext_getElem? fun _ => congr_fun (Subtype.ext_iff.1 h) _ /-- Embed an infinite stream as a sequence -/ @[coe] def ofStream (s : Stream' Ξ±) : Seq Ξ± := ⟨s.map some, fun {n} h => by contradiction⟩ instance coeStream : Coe (Stream' Ξ±) (Seq Ξ±) := ⟨ofStream⟩ section MLList /-- Embed a `MLList Ξ±` as a sequence. Note that even though this is non-meta, it will produce infinite sequences if used with cyclic `MLList`s created by meta constructions. -/ def ofMLList : MLList Id Ξ± β†’ Seq Ξ± := corec fun l => match l.uncons with | .none => none | .some (a, l') => some (a, l') instance coeMLList : Coe (MLList Id Ξ±) (Seq Ξ±) := ⟨ofMLList⟩ /-- Translate a sequence into a `MLList`. -/ unsafe def toMLList : Seq Ξ± β†’ MLList Id Ξ± | s => match destruct s with | none => .nil | some (a, s') => .cons a (toMLList s') end MLList /-- Translate a sequence to a list. This function will run forever if run on an infinite sequence. -/ unsafe def forceToList (s : Seq Ξ±) : List Ξ± := (toMLList s).force /-- Take the first `n` elements of the sequence (producing a list) -/ def take : β„• β†’ Seq Ξ± β†’ List Ξ± | 0, _ => [] | n + 1, s => match destruct s with | none => [] | some (x, r) => List.cons x (take n r) /-- Convert a sequence which is known to terminate into a list -/ def toList (s : Seq Ξ±) (h : s.Terminates) : List Ξ± := take (length s h) s /-- Convert a sequence which is known not to terminate into a stream -/ def toStream (s : Seq Ξ±) (h : Β¬s.Terminates) : Stream' Ξ± := fun n => Option.get _ <| not_terminates_iff.1 h n /-- Convert a sequence into either a list or a stream depending on whether it is finite or infinite. (Without decidability of the infiniteness predicate, this is not constructively possible.) -/ def toListOrStream (s : Seq Ξ±) [Decidable s.Terminates] : List Ξ± βŠ• Stream' Ξ± := if h : s.Terminates then Sum.inl (toList s h) else Sum.inr (toStream s h) /-- Convert a sequence into a list, embedded in a computation to allow for the possibility of infinite sequences (in which case the computation never returns anything). -/ def toList' {Ξ±} (s : Seq Ξ±) : Computation (List Ξ±) := @Computation.corec (List Ξ±) (List Ξ± Γ— Seq Ξ±) (fun ⟨l, s⟩ => match destruct s with | none => Sum.inl l.reverse | some (a, s') => Sum.inr (a::l, s')) ([], s) /-! ### Operations on sequences -/ /-- Append two sequences. If `s₁` is infinite, then `s₁ ++ sβ‚‚ = s₁`, otherwise it puts `sβ‚‚` at the location of the `nil` in `s₁`. -/ def append (s₁ sβ‚‚ : Seq Ξ±) : Seq Ξ± := @corec Ξ± (Seq Ξ± Γ— Seq Ξ±) (fun ⟨s₁, sβ‚‚βŸ© => match destruct s₁ with | none => omap (fun sβ‚‚ => (nil, sβ‚‚)) (destruct sβ‚‚) | some (a, s₁') => some (a, s₁', sβ‚‚)) (s₁, sβ‚‚) /-- Map a function over a sequence. -/ def map (f : Ξ± β†’ Ξ²) : Seq Ξ± β†’ Seq Ξ² | ⟨s, al⟩ => ⟨s.map (Option.map f), fun {n} => by dsimp [Stream'.map, Stream'.get] rcases e : s n with - | e <;> intro Β· rw [al e] assumption Β· contradiction⟩ /-- Flatten a sequence of sequences. (It is required that the sequences be nonempty to ensure productivity; in the case of an infinite sequence of `nil`, the first element is never generated.) -/ def join : Seq (Seq1 Ξ±) β†’ Seq Ξ± := corec fun S => match destruct S with | none => none | some ((a, s), S') => some (a, match destruct s with | none => S' | some s' => cons s' S') /-- Remove the first `n` elements from the sequence. -/ def drop (s : Seq Ξ±) : β„• β†’ Seq Ξ± | 0 => s | n + 1 => tail (drop s n) /-- Split a sequence at `n`, producing a finite initial segment and an infinite tail. -/ def splitAt : β„• β†’ Seq Ξ± β†’ List Ξ± Γ— Seq Ξ± | 0, s => ([], s) | n + 1, s => match destruct s with | none => ([], nil) | some (x, s') => let (l, r) := splitAt n s' (List.cons x l, r) /-- Combine two sequences with a function -/ def zipWith (f : Ξ± β†’ Ξ² β†’ Ξ³) (s₁ : Seq Ξ±) (sβ‚‚ : Seq Ξ²) : Seq Ξ³ := ⟨fun n => Option.mapβ‚‚ f (s₁.get? n) (sβ‚‚.get? n), fun {_} hn => Option.mapβ‚‚_eq_none_iff.2 <| (Option.mapβ‚‚_eq_none_iff.1 hn).imp s₁.2 sβ‚‚.2⟩ /-- Pair two sequences into a sequence of pairs -/ def zip : Seq Ξ± β†’ Seq Ξ² β†’ Seq (Ξ± Γ— Ξ²) := zipWith Prod.mk /-- Separate a sequence of pairs into two sequences -/ def unzip (s : Seq (Ξ± Γ— Ξ²)) : Seq Ξ± Γ— Seq Ξ² := (map Prod.fst s, map Prod.snd s) /-- The sequence of natural numbers some 0, some 1, ... -/ def nats : Seq β„• := Stream'.nats /-- Enumerate a sequence by tagging each element with its index. -/ def enum (s : Seq Ξ±) : Seq (β„• Γ— Ξ±) := Seq.zip nats s /-- Folds a sequence using `f`, producing a sequence of intermediate values, i.e. `[init, f init s.head, f (f init s.head) s.tail.head, ...]`. -/ def fold (s : Seq Ξ±) (init : Ξ²) (f : Ξ² β†’ Ξ± β†’ Ξ²) : Seq Ξ² := let f : Ξ² Γ— Seq Ξ± β†’ Option (Ξ² Γ— (Ξ² Γ— Seq Ξ±)) := fun (acc, x) => match destruct x with | none => .none | some (x, s) => .some (f acc x, f acc x, s) cons init <| corec f (init, s) /-- Applies `f` to the `n`th element of the sequence, if it exists, replacing that element with the result. -/ def update (s : Seq Ξ±) (n : β„•) (f : Ξ± β†’ Ξ±) : Seq Ξ± where val := Function.update s.val n ((s.val n).map f) property := by have (i : β„•) : Function.update s.val n ((s.get? n).map f) i = none ↔ s.get? i = none := by by_cases hi : i = n <;> simp [Function.update, hi] simp only [IsSeq, val_eq_get, this] exact @s.prop /-- Sets the value of sequence `s` at index `n` to `a`. If the `n`th element does not exist (`s` terminates earlier), the sequence is left unchanged. -/ def set (s : Seq Ξ±) (n : β„•) (a : Ξ±) : Seq Ξ± := update s n fun _ ↦ a /-- `Pairwise R s` means that all the elements with earlier indices are `R`-related to all the elements with later indices. ``` Pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3 ``` For example if `R = (Β· β‰  Β·)` then it asserts `s` has no duplicates, and if `R = (Β· < Β·)` then it asserts that `s` is (strictly) sorted. -/ def Pairwise (R : Ξ± β†’ Ξ± β†’ Prop) (s : Seq Ξ±) : Prop := βˆ€ i j, i < j β†’ βˆ€ x ∈ s.get? i, βˆ€ y ∈ s.get? j, R x y end Seq end Stream'
.lake/packages/mathlib/Mathlib/Data/Seq/Parallel.lean
import Mathlib.Data.WSeq.Relation /-! # Parallel computation Parallel computation of a computable sequence of computations by a diagonal enumeration. The important theorems of this operation are proven as terminates_parallel and exists_of_mem_parallel. (This operation is nondeterministic in the sense that it does not honor sequence equivalence (irrelevance of computation time).) -/ universe u v namespace Computation open Stream' variable {Ξ± : Type u} {Ξ² : Type v} private def parallel.aux2 : List (Computation Ξ±) β†’ Ξ± βŠ• (List (Computation Ξ±)) := List.foldr (fun c o => match o with | Sum.inl a => Sum.inl a | Sum.inr ls => rmap (fun c' => c' :: ls) (destruct c)) (Sum.inr []) private def parallel.aux1 : List (Computation Ξ±) Γ— WSeq (Computation Ξ±) β†’ Ξ± βŠ• (List (Computation Ξ±) Γ— WSeq (Computation Ξ±)) | (l, S) => rmap (fun l' => match Seq.destruct S with | none => (l', Seq.nil) | some (none, S') => (l', S') | some (some c, S') => (c :: l', S')) (parallel.aux2 l) /-- Parallel computation of an infinite stream of computations, taking the first result -/ def parallel (S : WSeq (Computation Ξ±)) : Computation Ξ± := corec parallel.aux1 ([], S) theorem terminates_parallel.aux : βˆ€ {l : List (Computation Ξ±)} {S c}, c ∈ l β†’ Terminates c β†’ Terminates (corec parallel.aux1 (l, S)) := by have lem1 : βˆ€ l S, (βˆƒ a : Ξ±, parallel.aux2 l = Sum.inl a) β†’ Terminates (corec parallel.aux1 (l, S)) := by intro l S e obtain ⟨a, e⟩ := e have : corec parallel.aux1 (l, S) = return a := by apply destruct_eq_pure simp only [parallel.aux1, rmap, corec_eq] rw [e] rw [this] exact ret_terminates a intro l S c m T revert l S apply @terminatesRecOn _ _ c T _ _ Β· intro a l S m apply lem1 induction l with | nil => simp at m | cons c l IH => ?_ simp only [List.mem_cons] at m rcases m with e | m Β· rw [← e] simp only [parallel.aux2, rmap, List.foldr_cons, destruct_pure] split <;> simp Β· obtain ⟨a', e⟩ := IH m simp only [parallel.aux2, rmap, List.foldr_cons] at ⊒ e rw [e] exact ⟨a', rfl⟩ Β· intro s IH l S m have H1 (l') (e' : parallel.aux2 l = Sum.inr l') : s ∈ l' := by induction l generalizing l' with | nil => simp at m | cons c l IH' => ?_ simp only [List.mem_cons] at m rcases m with e | m <;> simp only [parallel.aux2, rmap, List.foldr_cons] at e' Β· rw [← e] at e' -- Porting note: `revert e'` is required. revert e' split Β· simp Β· simp only [destruct_think, Sum.inr.injEq] rintro rfl simp Β· rcases e : List.foldr (fun c o => match o with | Sum.inl a => Sum.inl a | Sum.inr ls => rmap (fun c' => c' :: ls) (destruct c)) (Sum.inr List.nil) l with a' | ls <;> erw [e] at e' Β· contradiction have := IH' m _ e grind rcases h : parallel.aux2 l with a | l' Β· exact lem1 _ _ ⟨a, h⟩ Β· have H2 : corec parallel.aux1 (l, S) = think _ := destruct_eq_think (by simp only [parallel.aux1, rmap, corec_eq] rw [h]) rw [H2] refine @Computation.think_terminates _ _ ?_ have := H1 _ h rcases Seq.destruct S with (_ | ⟨_ | c, S'⟩) <;> apply IH <;> simp [this] theorem terminates_parallel {S : WSeq (Computation Ξ±)} {c} (h : c ∈ S) [T : Terminates c] : Terminates (parallel S) := by suffices βˆ€ (n) (l : List (Computation Ξ±)) (S c), c ∈ l ∨ some (some c) = Seq.get? S n β†’ Terminates c β†’ Terminates (corec parallel.aux1 (l, S)) from let ⟨n, h⟩ := h this n [] S c (Or.inr h) T intro n; induction n <;> intro l S c o T case zero => rcases o with a | a Β· exact terminates_parallel.aux a T have H : Seq.destruct S = some (some c, Seq.tail S) := by simp [Seq.destruct, (Β· <$> Β·), ← a] rcases h : parallel.aux2 l with a | l' Β· have C : corec parallel.aux1 (l, S) = pure a := by apply destruct_eq_pure rw [corec_eq, parallel.aux1] rw [h] simp only [rmap] rw [C] infer_instance Β· have C : corec parallel.aux1 (l, S) = _ := destruct_eq_think (by simp only [corec_eq, rmap, parallel.aux1.eq_1] rw [h, H]) rw [C] refine @Computation.think_terminates _ _ ?_ apply terminates_parallel.aux _ T simp case succ n IH => rcases o with a | a Β· exact terminates_parallel.aux a T rcases h : parallel.aux2 l with a | l' Β· have C : corec parallel.aux1 (l, S) = pure a := by apply destruct_eq_pure rw [corec_eq, parallel.aux1] rw [h] simp only [rmap] rw [C] infer_instance Β· have C : corec parallel.aux1 (l, S) = _ := destruct_eq_think (by simp only [corec_eq, rmap, parallel.aux1.eq_1] rw [h]) rw [C] refine @Computation.think_terminates _ _ ?_ have TT : βˆ€ l', Terminates (corec parallel.aux1 (l', S.tail)) := by intro apply IH _ _ _ (Or.inr _) T rw [a, Seq.get?_tail] rcases e : Seq.get? S 0 with - | o Β· grind [Seq.get?_zero_eq_none, Seq.get?_nil] Β· have D : Seq.destruct S = some (o, S.tail) := by dsimp [Seq.destruct] rw [e] rfl rw [D] cases o <;> simp [TT] theorem exists_of_mem_parallel {S : WSeq (Computation Ξ±)} {a} (h : a ∈ parallel S) : βˆƒ c ∈ S, a ∈ c := by suffices βˆ€ C, a ∈ C β†’ βˆ€ (l : List (Computation Ξ±)) (S), corec parallel.aux1 (l, S) = C β†’ βˆƒ c, (c ∈ l ∨ c ∈ S) ∧ a ∈ c from let ⟨c, h1, h2⟩ := this _ h [] S rfl ⟨c, h1.resolve_left <| List.not_mem_nil, h2⟩ let F : List (Computation Ξ±) β†’ Ξ± βŠ• (List (Computation Ξ±)) β†’ Prop := by intro l a rcases a with a | l' Β· exact βˆƒ c ∈ l, a ∈ c Β· exact βˆ€ a', (βˆƒ c ∈ l', a' ∈ c) β†’ βˆƒ c ∈ l, a' ∈ c have lem1 (l) : F l (parallel.aux2 l) := by induction l <;> simp only [parallel.aux2, List.foldr] case nil => intro a h assumption case cons c l IH => simp only [parallel.aux2] at IH -- Porting note: `revert IH` & `intro IH` are required. revert IH cases List.foldr (fun c o => match o with | Sum.inl a => Sum.inl a | Sum.inr ls => rmap (fun c' => c' :: ls) (destruct c)) (Sum.inr List.nil) l <;> intro IH <;> simp only Β· rcases IH with ⟨c', cl, ac⟩ exact ⟨c', List.Mem.tail _ cl, ac⟩ Β· rcases h : destruct c with a | c' <;> simp only [rmap] Β· refine ⟨c, List.mem_cons_self, ?_⟩ rw [destruct_eq_pure h] apply ret_mem Β· intro a' h rcases h with ⟨d, dm, ad⟩ rcases List.mem_cons.mp dm with e | dl Β· rw [e] at ad refine ⟨c, List.mem_cons_self, ?_⟩ rw [destruct_eq_think h] exact think_mem ad Β· obtain ⟨d, dm⟩ := IH a' ⟨d, dl, ad⟩ obtain ⟨dm, ad⟩ := dm exact ⟨d, List.Mem.tail _ dm, ad⟩ intro C aC -- Porting note: `revert this e'` & `intro this e'` are required. apply memRecOn aC <;> [skip; intro C' IH] <;> intro l S e <;> have e' := congr_arg destruct e <;> have := lem1 l <;> simp only [parallel.aux1, corec_eq, destruct_pure, destruct_think] at e' <;> revert this e' <;> rcases parallel.aux2 l with a' | l' <;> intro this e' <;> [injection e' with h'; injection e'; injection e'; injection e' with h'] Β· rw [h'] at this rcases this with ⟨c, cl, ac⟩ exact ⟨c, Or.inl cl, ac⟩ Β· rcases e : Seq.destruct S with - | a <;> rw [e] at h' Β· exact let ⟨d, o, ad⟩ := IH _ _ h' let ⟨c, cl, ac⟩ := this a ⟨d, o.resolve_right (WSeq.notMem_nil _), ad⟩ ⟨c, Or.inl cl, ac⟩ Β· obtain ⟨o, S'⟩ := a obtain - | c := o <;> simp only at h' <;> rcases IH _ _ h' with ⟨d, dl | dS', ad⟩ Β· exact let ⟨c, cl, ac⟩ := this a ⟨d, dl, ad⟩ ⟨c, Or.inl cl, ac⟩ Β· refine ⟨d, Or.inr ?_, ad⟩ rw [Seq.destruct_eq_cons e] exact Seq.mem_cons_of_mem _ dS' Β· simp only [List.mem_cons] at dl rcases dl with dc | dl Β· rw [dc] at ad refine ⟨c, Or.inr ?_, ad⟩ rw [Seq.destruct_eq_cons e] apply Seq.mem_cons Β· exact let ⟨c, cl, ac⟩ := this a ⟨d, dl, ad⟩ ⟨c, Or.inl cl, ac⟩ Β· refine ⟨d, Or.inr ?_, ad⟩ rw [Seq.destruct_eq_cons e] exact Seq.mem_cons_of_mem _ dS' theorem map_parallel (f : Ξ± β†’ Ξ²) (S) : map f (parallel S) = parallel (S.map (map f)) := by refine eq_of_bisim (fun c1 c2 => βˆƒ l S, c1 = map f (corec parallel.aux1 (l, S)) ∧ c2 = corec parallel.aux1 (l.map (map f), S.map (map f))) ?_ ⟨[], S, rfl, rfl⟩ intro c1 c2 h exact match c1, c2, h with | _, _, ⟨l, S, rfl, rfl⟩ => by have : parallel.aux2 (l.map (map f)) = lmap f (rmap (List.map (map f)) (parallel.aux2 l)) := by simp only [parallel.aux2, rmap, lmap] induction l with | nil => simp | cons c l IH => simp only [List.map_cons, List.foldr_cons, destruct_map, lmap, rmap] rw [IH] cases List.foldr _ _ _ Β· simp Β· cases destruct c <;> simp simp only [BisimO, destruct_map, lmap, rmap, corec_eq, parallel.aux1.eq_1] rw [this] rcases parallel.aux2 l with a | l' Β· simp simp only [lmap, rmap] induction S using WSeq.recOn <;> simpa using ⟨_, _, rfl, rfl⟩ theorem parallel_empty (S : WSeq (Computation Ξ±)) (h : S.head ~> none) : parallel S = empty _ := eq_empty_of_not_terminates fun ⟨⟨a, m⟩⟩ => by let ⟨c, cs, _⟩ := exists_of_mem_parallel m let ⟨n, nm⟩ := WSeq.exists_get?_of_mem cs let ⟨c', h'⟩ := WSeq.head_some_of_get?_some nm injection h h' /-- Induction principle for parallel computations. The reason this isn't trivial from `exists_of_mem_parallel` is because it eliminates to `Sort`. -/ def parallelRec {S : WSeq (Computation Ξ±)} (C : Ξ± β†’ Sort v) (H : βˆ€ s ∈ S, βˆ€ a ∈ s, C a) {a} (h : a ∈ parallel S) : C a := by let T : WSeq (Computation (Ξ± Γ— Computation Ξ±)) := S.map fun c => c.map fun a => (a, c) have : S = T.map (map fun c => c.1) := by rw [← WSeq.map_comp] refine (WSeq.map_id _).symm.trans (congr_arg (fun f => WSeq.map f S) ?_) funext c dsimp [id, Function.comp_def] rw [← map_comp] exact (map_id _).symm have pe := congr_arg parallel this rw [← map_parallel] at pe have h' := h rw [pe] at h' haveI : Terminates (parallel T) := (terminates_map_iff _ _).1 ⟨⟨_, h'⟩⟩ rcases e : get (parallel T) with ⟨a', c⟩ have : a ∈ c ∧ c ∈ S := by rcases exists_of_mem_map h' with ⟨d, dT, cd⟩ rw [get_eq_of_mem _ dT] at e cases e dsimp at cd cases cd rcases exists_of_mem_parallel dT with ⟨d', dT', ad'⟩ rcases WSeq.exists_of_mem_map dT' with ⟨c', cs', e'⟩ rw [← e'] at ad' rcases exists_of_mem_map ad' with ⟨a', ac', e'⟩ injection e' with i1 i2 constructor Β· rwa [i1, i2] at ac' Β· rwa [i2] at cs' obtain ⟨ac, cs⟩ := this apply H _ cs _ ac theorem parallel_promises {S : WSeq (Computation Ξ±)} {a} (H : βˆ€ s ∈ S, s ~> a) : parallel S ~> a := fun _ ma' => let ⟨_, cs, ac⟩ := exists_of_mem_parallel ma' H _ cs ac theorem mem_parallel {S : WSeq (Computation Ξ±)} {a} (H : βˆ€ s ∈ S, s ~> a) {c} (cs : c ∈ S) (ac : a ∈ c) : a ∈ parallel S := by haveI := terminates_of_mem ac haveI := terminates_parallel cs exact mem_of_promises _ (parallel_promises H) theorem parallel_congr_lem {S T : WSeq (Computation Ξ±)} {a} (H : S.LiftRel Equiv T) : (βˆ€ s ∈ S, s ~> a) ↔ βˆ€ t ∈ T, t ~> a := ⟨fun h1 _ tT => let ⟨_, sS, se⟩ := WSeq.exists_of_liftRel_right H tT (promises_congr se _).1 (h1 _ sS), fun h2 _ sS => let ⟨_, tT, se⟩ := WSeq.exists_of_liftRel_left H sS (promises_congr se _).2 (h2 _ tT)⟩ -- The parallel operation is only deterministic when all computation paths lead to the same value theorem parallel_congr_left {S T : WSeq (Computation Ξ±)} {a} (h1 : βˆ€ s ∈ S, s ~> a) (H : S.LiftRel Equiv T) : parallel S ~ parallel T := let h2 := (parallel_congr_lem H).1 h1 fun a' => ⟨fun h => by have aa := parallel_promises h1 h rw [← aa] rw [← aa] at h exact let ⟨s, sS, as⟩ := exists_of_mem_parallel h let ⟨t, tT, st⟩ := WSeq.exists_of_liftRel_left H sS let aT := (st _).1 as mem_parallel h2 tT aT, fun h => by have aa := parallel_promises h2 h rw [← aa] rw [← aa] at h exact let ⟨s, sS, as⟩ := exists_of_mem_parallel h let ⟨t, tT, st⟩ := WSeq.exists_of_liftRel_right H sS let aT := (st _).2 as mem_parallel h1 tT aT⟩ theorem parallel_congr_right {S T : WSeq (Computation Ξ±)} {a} (h2 : βˆ€ t ∈ T, t ~> a) (H : S.LiftRel Equiv T) : parallel S ~ parallel T := parallel_congr_left ((parallel_congr_lem H).2 h2) H end Computation
.lake/packages/mathlib/Mathlib/Data/Finite/Sum.lean
import Mathlib.Data.Fintype.Sum /-! # Finiteness of sum types -/ variable {Ξ± Ξ² : Type*} namespace Finite instance [Finite Ξ±] [Finite Ξ²] : Finite (Ξ± βŠ• Ξ²) := by haveI := Fintype.ofFinite Ξ± haveI := Fintype.ofFinite Ξ² infer_instance theorem sum_left (Ξ²) [Finite (Ξ± βŠ• Ξ²)] : Finite Ξ± := of_injective (Sum.inl : Ξ± β†’ Ξ± βŠ• Ξ²) Sum.inl_injective theorem sum_right (Ξ±) [Finite (Ξ± βŠ• Ξ²)] : Finite Ξ² := of_injective (Sum.inr : Ξ² β†’ Ξ± βŠ• Ξ²) Sum.inr_injective instance {Ξ± Ξ² : Sort*} [Finite Ξ±] [Finite Ξ²] : Finite (Ξ± βŠ•' Ξ²) := of_equiv _ ((Equiv.psumEquivSum _ _).symm.trans (Equiv.plift.psumCongr Equiv.plift)) theorem psum_left {Ξ± Ξ² : Sort*} [Finite (Ξ± βŠ•' Ξ²)] : Finite Ξ± := of_injective (PSum.inl : Ξ± β†’ Ξ± βŠ•' Ξ²) PSum.inl_injective theorem psum_right {Ξ± Ξ² : Sort*} [Finite (Ξ± βŠ•' Ξ²)] : Finite Ξ² := of_injective (PSum.inr : Ξ² β†’ Ξ± βŠ•' Ξ²) PSum.inr_injective end Finite
.lake/packages/mathlib/Mathlib/Data/Finite/Card.lean
import Mathlib.SetTheory.Cardinal.Finite /-! # Cardinality of finite types The cardinality of a finite type `Ξ±` is given by `Nat.card Ξ±`. This function has the "junk value" of `0` for infinite types, but to ensure the function has valid output, one just needs to know that it's possible to produce a `Finite` instance for the type. (Note: we could have defined a `Finite.card` that required you to supply a `Finite` instance, but (a) the function would be `noncomputable` anyway so there is no need to supply the instance and (b) the function would have a more complicated dependent type that easily leads to "motive not type correct" errors.) ## Implementation notes Theorems about `Nat.card` are sometimes incidentally true for both finite and infinite types. If removing a finiteness constraint results in no loss in legibility, we remove it. We generally put such theorems into the `SetTheory.Cardinal.Finite` module. -/ assert_not_exists Field noncomputable section variable {Ξ± Ξ² Ξ³ : Type*} /-- There is (noncomputably) an equivalence between a finite type `Ξ±` and `Fin (Nat.card Ξ±)`. -/ def Finite.equivFin (Ξ± : Type*) [Finite Ξ±] : Ξ± ≃ Fin (Nat.card Ξ±) := by have := (Finite.exists_equiv_fin Ξ±).choose_spec.some rwa [Nat.card_eq_of_equiv_fin this] /-- Similar to `Finite.equivFin` but with control over the term used for the cardinality. -/ def Finite.equivFinOfCardEq [Finite Ξ±] {n : β„•} (h : Nat.card Ξ± = n) : Ξ± ≃ Fin n := by subst h apply Finite.equivFin open scoped Classical in theorem Nat.card_eq (Ξ± : Type*) : Nat.card Ξ± = if _ : Finite Ξ± then @Fintype.card Ξ± (Fintype.ofFinite Ξ±) else 0 := by cases finite_or_infinite Ξ± Β· letI := Fintype.ofFinite Ξ± simp only [this, *, Nat.card_eq_fintype_card, dif_pos] Β· simp only [*, card_eq_zero_of_infinite, not_finite_iff_infinite.mpr, dite_false] theorem Finite.card_pos_iff [Finite Ξ±] : 0 < Nat.card Ξ± ↔ Nonempty Ξ± := by haveI := Fintype.ofFinite Ξ± rw [Nat.card_eq_fintype_card, Fintype.card_pos_iff] theorem Finite.card_pos [Finite Ξ±] [h : Nonempty Ξ±] : 0 < Nat.card Ξ± := Finite.card_pos_iff.mpr h namespace Finite theorem card_eq [Finite Ξ±] [Finite Ξ²] : Nat.card Ξ± = Nat.card Ξ² ↔ Nonempty (Ξ± ≃ Ξ²) := by haveI := Fintype.ofFinite Ξ± haveI := Fintype.ofFinite Ξ² simp only [Nat.card_eq_fintype_card, Fintype.card_eq] theorem card_le_one_iff_subsingleton [Finite Ξ±] : Nat.card Ξ± ≀ 1 ↔ Subsingleton Ξ± := by haveI := Fintype.ofFinite Ξ± simp only [Nat.card_eq_fintype_card, Fintype.card_le_one_iff_subsingleton] theorem one_lt_card_iff_nontrivial [Finite Ξ±] : 1 < Nat.card Ξ± ↔ Nontrivial Ξ± := by haveI := Fintype.ofFinite Ξ± simp only [Nat.card_eq_fintype_card, Fintype.one_lt_card_iff_nontrivial] theorem one_lt_card [Finite Ξ±] [h : Nontrivial Ξ±] : 1 < Nat.card Ξ± := one_lt_card_iff_nontrivial.mpr h @[simp] theorem card_option [Finite Ξ±] : Nat.card (Option Ξ±) = Nat.card Ξ± + 1 := by haveI := Fintype.ofFinite Ξ± simp only [Nat.card_eq_fintype_card, Fintype.card_option] @[deprecated (since := "2025-10-02")] alias card_le_of_injective := Nat.card_le_card_of_injective theorem card_le_of_embedding [Finite Ξ²] (f : Ξ± β†ͺ Ξ²) : Nat.card Ξ± ≀ Nat.card Ξ² := Nat.card_le_card_of_injective _ f.injective @[deprecated (since := "2025-10-02")] alias card_le_of_surjective := Nat.card_le_card_of_surjective theorem card_eq_zero_iff [Finite Ξ±] : Nat.card Ξ± = 0 ↔ IsEmpty Ξ± := by haveI := Fintype.ofFinite Ξ± simp only [Nat.card_eq_fintype_card, Fintype.card_eq_zero_iff] /-- If `f` is injective, then `Nat.card Ξ± ≀ Nat.card Ξ²`. We must also assume `Nat.card Ξ² = 0 β†’ Nat.card Ξ± = 0` since `Nat.card` is defined to be `0` for infinite types. -/ theorem card_le_of_injective' {f : Ξ± β†’ Ξ²} (hf : Function.Injective f) (h : Nat.card Ξ² = 0 β†’ Nat.card Ξ± = 0) : Nat.card Ξ± ≀ Nat.card Ξ² := (or_not_of_imp h).casesOn (fun h => le_of_eq_of_le h (Nat.zero_le _)) fun h => @Nat.card_le_card_of_injective Ξ± Ξ² (Nat.finite_of_card_ne_zero h) f hf /-- If `f` is an embedding, then `Nat.card Ξ± ≀ Nat.card Ξ²`. We must also assume `Nat.card Ξ² = 0 β†’ Nat.card Ξ± = 0` since `Nat.card` is defined to be `0` for infinite types. -/ theorem card_le_of_embedding' (f : Ξ± β†ͺ Ξ²) (h : Nat.card Ξ² = 0 β†’ Nat.card Ξ± = 0) : Nat.card Ξ± ≀ Nat.card Ξ² := card_le_of_injective' f.2 h /-- If `f` is surjective, then `Nat.card Ξ² ≀ Nat.card Ξ±`. We must also assume `Nat.card Ξ± = 0 β†’ Nat.card Ξ² = 0` since `Nat.card` is defined to be `0` for infinite types. -/ theorem card_le_of_surjective' {f : Ξ± β†’ Ξ²} (hf : Function.Surjective f) (h : Nat.card Ξ± = 0 β†’ Nat.card Ξ² = 0) : Nat.card Ξ² ≀ Nat.card Ξ± := (or_not_of_imp h).casesOn (fun h => le_of_eq_of_le h (Nat.zero_le _)) fun h => @Nat.card_le_card_of_surjective Ξ± Ξ² (Nat.finite_of_card_ne_zero h) f hf /-- NB: `Nat.card` is defined to be `0` for infinite types. -/ theorem card_eq_zero_of_surjective {f : Ξ± β†’ Ξ²} (hf : Function.Surjective f) (h : Nat.card Ξ² = 0) : Nat.card Ξ± = 0 := by cases finite_or_infinite Ξ² Β· haveI := card_eq_zero_iff.mp h haveI := Function.isEmpty f exact Nat.card_of_isEmpty Β· haveI := Infinite.of_surjective f hf exact Nat.card_eq_zero_of_infinite /-- NB: `Nat.card` is defined to be `0` for infinite types. -/ theorem card_eq_zero_of_injective [Nonempty Ξ±] {f : Ξ± β†’ Ξ²} (hf : Function.Injective f) (h : Nat.card Ξ± = 0) : Nat.card Ξ² = 0 := card_eq_zero_of_surjective (Function.invFun_surjective hf) h /-- NB: `Nat.card` is defined to be `0` for infinite types. -/ theorem card_eq_zero_of_embedding [Nonempty Ξ±] (f : Ξ± β†ͺ Ξ²) (h : Nat.card Ξ± = 0) : Nat.card Ξ² = 0 := card_eq_zero_of_injective f.2 h @[deprecated (since := "2025-10-02")] alias card_sum := Nat.card_sum theorem card_image_le {s : Set Ξ±} [Finite s] (f : Ξ± β†’ Ξ²) : Nat.card (f '' s) ≀ Nat.card s := Nat.card_le_card_of_surjective _ Set.imageFactorization_surjective theorem card_range_le [Finite Ξ±] (f : Ξ± β†’ Ξ²) : Nat.card (Set.range f) ≀ Nat.card Ξ± := Nat.card_le_card_of_surjective _ Set.rangeFactorization_surjective theorem card_subtype_le [Finite Ξ±] (p : Ξ± β†’ Prop) : Nat.card { x // p x } ≀ Nat.card Ξ± := by classical haveI := Fintype.ofFinite Ξ± simpa only [Nat.card_eq_fintype_card] using Fintype.card_subtype_le p theorem card_subtype_lt [Finite Ξ±] {p : Ξ± β†’ Prop} {x : Ξ±} (hx : Β¬p x) : Nat.card { x // p x } < Nat.card Ξ± := by classical haveI := Fintype.ofFinite Ξ± simpa only [Nat.card_eq_fintype_card, gt_iff_lt] using Fintype.card_subtype_lt hx end Finite namespace ENat theorem card_eq_coe_natCard (Ξ± : Type*) [Finite Ξ±] : card Ξ± = Nat.card Ξ± := by unfold ENat.card apply symm rw [Cardinal.natCast_eq_toENat_iff] exact Nat.cast_card end ENat namespace Set theorem card_union_le (s t : Set Ξ±) : Nat.card (β†₯(s βˆͺ t)) ≀ Nat.card s + Nat.card t := by rcases _root_.finite_or_infinite (β†₯(s βˆͺ t)) with h | h Β· rw [finite_coe_iff, finite_union, ← finite_coe_iff, ← finite_coe_iff] at h cases h rw [← @Nat.cast_le Cardinal, Nat.cast_add, Nat.cast_card, Nat.cast_card, Nat.cast_card] exact Cardinal.mk_union_le s t Β· exact Nat.card_eq_zero_of_infinite.trans_le (zero_le _) namespace Finite variable {s t : Set Ξ±} theorem card_lt_card (ht : t.Finite) (hsub : s βŠ‚ t) : Nat.card s < Nat.card t := by have : Fintype t := Finite.fintype ht have : Fintype s := Finite.fintype (subset ht (subset_of_ssubset hsub)) simp only [Nat.card_eq_fintype_card] exact Set.card_lt_card hsub theorem eq_of_subset_of_card_le (ht : t.Finite) (hsub : s βŠ† t) (hcard : Nat.card t ≀ Nat.card s) : s = t := (eq_or_ssubset_of_subset hsub).elim id fun h ↦ absurd hcard <| not_le_of_gt <| ht.card_lt_card h theorem equiv_image_eq_iff_subset (e : Ξ± ≃ Ξ±) (hs : s.Finite) : e '' s = s ↔ e '' s βŠ† s := ⟨fun h ↦ by rw [h], fun h ↦ hs.eq_of_subset_of_card_le h <| ge_of_eq (Nat.card_congr (e.image s).symm)⟩ end Finite theorem eq_top_of_card_le_of_finite [Finite Ξ±] {s : Set Ξ±} (h : Nat.card Ξ± ≀ Nat.card s) : s = ⊀ := Set.Finite.eq_of_subset_of_card_le univ.toFinite (subset_univ s) <| Nat.card_congr (Equiv.Set.univ Ξ±) β–Έ h end Set
.lake/packages/mathlib/Mathlib/Data/Finite/Sigma.lean
import Mathlib.Data.Fintype.EquivFin import Mathlib.Data.Fintype.Sigma /-! # Finiteness of sigma types -/ variable {Ξ± : Type*} namespace Finite instance {Ξ² : Ξ± β†’ Type*} [Finite Ξ±] [βˆ€ a, Finite (Ξ² a)] : Finite (Ξ£ a, Ξ² a) := by letI := Fintype.ofFinite Ξ± letI := fun a => Fintype.ofFinite (Ξ² a) infer_instance instance {ΞΉ : Sort*} {Ο€ : ΞΉ β†’ Sort*} [Finite ΞΉ] [βˆ€ i, Finite (Ο€ i)] : Finite (Ξ£' i, Ο€ i) := of_equiv _ (Equiv.psigmaEquivSigmaPLift Ο€).symm end Finite
.lake/packages/mathlib/Mathlib/Data/Finite/Prod.lean
import Mathlib.Data.Set.Finite.Basic import Mathlib.Data.Fintype.Prod import Mathlib.Data.Fintype.Pi import Mathlib.Algebra.Order.Group.Multiset import Mathlib.Data.Vector.Basic import Mathlib.Tactic.ApplyFun import Mathlib.Data.ULift import Mathlib.Data.Set.NAry /-! # Finiteness of products -/ assert_not_exists IsOrderedRing MonoidWithZero variable {Ξ± Ξ² : Type*} namespace Finite instance [Finite Ξ±] [Finite Ξ²] : Finite (Ξ± Γ— Ξ²) := by haveI := Fintype.ofFinite Ξ± haveI := Fintype.ofFinite Ξ² infer_instance instance {Ξ± Ξ² : Sort*} [Finite Ξ±] [Finite Ξ²] : Finite (PProd Ξ± Ξ²) := of_equiv _ Equiv.pprodEquivProdPLift.symm theorem prod_left (Ξ²) [Finite (Ξ± Γ— Ξ²)] [Nonempty Ξ²] : Finite Ξ± := of_surjective (Prod.fst : Ξ± Γ— Ξ² β†’ Ξ±) Prod.fst_surjective theorem prod_right (Ξ±) [Finite (Ξ± Γ— Ξ²)] [Nonempty Ξ±] : Finite Ξ² := of_surjective (Prod.snd : Ξ± Γ— Ξ² β†’ Ξ²) Prod.snd_surjective end Finite lemma Prod.finite_iff [Nonempty Ξ±] [Nonempty Ξ²] : Finite (Ξ± Γ— Ξ²) ↔ Finite Ξ± ∧ Finite Ξ² where mp _ := ⟨.prod_left Ξ², .prod_right α⟩ mpr | ⟨_, _⟩ => inferInstance instance Pi.finite {Ξ± : Sort*} {Ξ² : Ξ± β†’ Sort*} [Finite Ξ±] [βˆ€ a, Finite (Ξ² a)] : Finite (βˆ€ a, Ξ² a) := by classical haveI := Fintype.ofFinite (PLift Ξ±) haveI := fun a => Fintype.ofFinite (PLift (Ξ² a)) exact Finite.of_equiv (βˆ€ a : PLift Ξ±, PLift (Ξ² (Equiv.plift a))) (Equiv.piCongr Equiv.plift fun _ => Equiv.plift) instance Function.Embedding.finite {Ξ± Ξ² : Sort*} [Finite Ξ²] : Finite (Ξ± β†ͺ Ξ²) := by rcases isEmpty_or_nonempty (Ξ± β†ͺ Ξ²) with _ | h Β· infer_instance Β· refine h.elim fun f => ?_ haveI : Finite Ξ± := Finite.of_injective _ f.injective exact Finite.of_injective _ DFunLike.coe_injective instance Equiv.finite_right {Ξ± Ξ² : Sort*} [Finite Ξ²] : Finite (Ξ± ≃ Ξ²) := Finite.of_injective Equiv.toEmbedding fun e₁ eβ‚‚ h => Equiv.ext <| by convert DFunLike.congr_fun h using 0 instance Equiv.finite_left {Ξ± Ξ² : Sort*} [Finite Ξ±] : Finite (Ξ± ≃ Ξ²) := Finite.of_equiv _ ⟨Equiv.symm, Equiv.symm, Equiv.symm_symm, Equiv.symm_symm⟩ @[to_additive] instance MulEquiv.finite_left {Ξ± Ξ² : Type*} [Mul Ξ±] [Mul Ξ²] [Finite Ξ±] : Finite (Ξ± ≃* Ξ²) := Finite.of_injective toEquiv toEquiv_injective @[to_additive] instance MulEquiv.finite_right {Ξ± Ξ² : Type*} [Mul Ξ±] [Mul Ξ²] [Finite Ξ²] : Finite (Ξ± ≃* Ξ²) := Finite.of_injective toEquiv toEquiv_injective open Set Function variable {Ξ³ : Type*} namespace Set /-! ### Fintype instances Every instance here should have a corresponding `Set.Finite` constructor in the next section. -/ section FintypeInstances instance fintypeProd (s : Set Ξ±) (t : Set Ξ²) [Fintype s] [Fintype t] : Fintype (s Γ—Λ’ t : Set (Ξ± Γ— Ξ²)) := Fintype.ofFinset (s.toFinset Γ—Λ’ t.toFinset) <| by simp instance fintypeOffDiag [DecidableEq Ξ±] (s : Set Ξ±) [Fintype s] : Fintype s.offDiag := Fintype.ofFinset s.toFinset.offDiag <| by simp /-- `image2 f s t` is `Fintype` if `s` and `t` are. -/ instance fintypeImage2 [DecidableEq Ξ³] (f : Ξ± β†’ Ξ² β†’ Ξ³) (s : Set Ξ±) (t : Set Ξ²) [hs : Fintype s] [ht : Fintype t] : Fintype (image2 f s t : Set Ξ³) := by rw [← image_prod] apply Set.fintypeImage end FintypeInstances end Set /-! ### Finite instances There is seemingly some overlap between the following instances and the `Fintype` instances in `Data.Set.Finite`. While every `Fintype` instance gives a `Finite` instance, those instances that depend on `Fintype` or `Decidable` instances need an additional `Finite` instance to be able to generally apply. Some set instances do not appear here since they are consequences of others, for example `Subtype.Finite` for subsets of a finite type. -/ namespace Finite.Set instance finite_prod (s : Set Ξ±) (t : Set Ξ²) [Finite s] [Finite t] : Finite (s Γ—Λ’ t : Set (Ξ± Γ— Ξ²)) := Finite.of_equiv _ (Equiv.Set.prod s t).symm instance finite_image2 (f : Ξ± β†’ Ξ² β†’ Ξ³) (s : Set Ξ±) (t : Set Ξ²) [Finite s] [Finite t] : Finite (image2 f s t : Set Ξ³) := by rw [← image_prod] infer_instance end Finite.Set namespace Set /-! ### Constructors for `Set.Finite` Every constructor here should have a corresponding `Fintype` instance in the previous section (or in the `Fintype` module). The implementation of these constructors ideally should be no more than `Set.toFinite`, after possibly setting up some `Fintype` and classical `Decidable` instances. -/ section SetFiniteConstructors section Prod variable {s : Set Ξ±} {t : Set Ξ²} protected theorem Finite.prod (hs : s.Finite) (ht : t.Finite) : (s Γ—Λ’ t : Set (Ξ± Γ— Ξ²)).Finite := by have := hs.to_subtype have := ht.to_subtype apply toFinite theorem Finite.of_prod_left (h : (s Γ—Λ’ t : Set (Ξ± Γ— Ξ²)).Finite) : t.Nonempty β†’ s.Finite := fun ⟨b, hb⟩ => (h.image Prod.fst).subset fun a ha => ⟨(a, b), ⟨ha, hb⟩, rfl⟩ theorem Finite.of_prod_right (h : (s Γ—Λ’ t : Set (Ξ± Γ— Ξ²)).Finite) : s.Nonempty β†’ t.Finite := fun ⟨a, ha⟩ => (h.image Prod.snd).subset fun b hb => ⟨(a, b), ⟨ha, hb⟩, rfl⟩ protected theorem Infinite.prod_left (hs : s.Infinite) (ht : t.Nonempty) : (s Γ—Λ’ t).Infinite := fun h => hs <| h.of_prod_left ht protected theorem Infinite.prod_right (ht : t.Infinite) (hs : s.Nonempty) : (s Γ—Λ’ t).Infinite := fun h => ht <| h.of_prod_right hs protected theorem infinite_prod : (s Γ—Λ’ t).Infinite ↔ s.Infinite ∧ t.Nonempty ∨ t.Infinite ∧ s.Nonempty := by refine ⟨fun h => ?_, ?_⟩ Β· simp_rw [Set.Infinite, @and_comm Β¬_, ← Classical.not_imp] by_contra! exact h ((this.1 h.nonempty.snd).prod <| this.2 h.nonempty.fst) Β· rintro (h | h) Β· exact h.1.prod_left h.2 Β· exact h.1.prod_right h.2 theorem finite_prod : (s Γ—Λ’ t).Finite ↔ (s.Finite ∨ t = βˆ…) ∧ (t.Finite ∨ s = βˆ…) := by simp only [← not_infinite, Set.infinite_prod, not_or, not_and_or, not_nonempty_iff_eq_empty] protected theorem Finite.offDiag {s : Set Ξ±} (hs : s.Finite) : s.offDiag.Finite := (hs.prod hs).subset s.offDiag_subset_prod protected theorem Finite.image2 (f : Ξ± β†’ Ξ² β†’ Ξ³) (hs : s.Finite) (ht : t.Finite) : (image2 f s t).Finite := by have := hs.to_subtype have := ht.to_subtype apply toFinite end Prod end SetFiniteConstructors /-! ### Properties -/ theorem Finite.toFinset_prod {s : Set Ξ±} {t : Set Ξ²} (hs : s.Finite) (ht : t.Finite) : hs.toFinset Γ—Λ’ ht.toFinset = (hs.prod ht).toFinset := Finset.ext <| by simp theorem Finite.toFinset_offDiag {s : Set Ξ±} [DecidableEq Ξ±] (hs : s.Finite) : hs.offDiag.toFinset = hs.toFinset.offDiag := Finset.ext <| by simp theorem finite_image_fst_and_snd_iff {s : Set (Ξ± Γ— Ξ²)} : (Prod.fst '' s).Finite ∧ (Prod.snd '' s).Finite ↔ s.Finite := ⟨fun h => (h.1.prod h.2).subset fun _ h => ⟨mem_image_of_mem _ h, mem_image_of_mem _ h⟩, fun h => ⟨h.image _, h.image _⟩⟩ /-! ### Infinite sets -/ variable {s t : Set Ξ±} section Image2 variable {f : Ξ± β†’ Ξ² β†’ Ξ³} {s : Set Ξ±} {t : Set Ξ²} {a : Ξ±} {b : Ξ²} protected theorem Infinite.image2_left (hs : s.Infinite) (hb : b ∈ t) (hf : InjOn (fun a => f a b) s) : (image2 f s t).Infinite := (hs.image hf).mono <| image_subset_image2_left hb protected theorem Infinite.image2_right (ht : t.Infinite) (ha : a ∈ s) (hf : InjOn (f a) t) : (image2 f s t).Infinite := (ht.image hf).mono <| image_subset_image2_right ha theorem infinite_image2 (hfs : βˆ€ b ∈ t, InjOn (fun a => f a b) s) (hft : βˆ€ a ∈ s, InjOn (f a) t) : (image2 f s t).Infinite ↔ s.Infinite ∧ t.Nonempty ∨ t.Infinite ∧ s.Nonempty := by refine ⟨fun h => Set.infinite_prod.1 ?_, ?_⟩ Β· rw [← image_uncurry_prod] at h exact h.of_image _ Β· rintro (⟨hs, b, hb⟩ | ⟨ht, a, ha⟩) Β· exact hs.image2_left hb (hfs _ hb) Β· exact ht.image2_right ha (hft _ ha) lemma finite_image2 (hfs : βˆ€ b ∈ t, InjOn (f Β· b) s) (hft : βˆ€ a ∈ s, InjOn (f a) t) : (image2 f s t).Finite ↔ s.Finite ∧ t.Finite ∨ s = βˆ… ∨ t = βˆ… := by rw [← not_infinite, infinite_image2 hfs hft] simp [not_or, -not_and, not_and_or, not_nonempty_iff_eq_empty] aesop end Image2 end Set
.lake/packages/mathlib/Mathlib/Data/Finite/Perm.lean
import Mathlib.Data.Fintype.Perm import Mathlib.SetTheory.Cardinal.Finite /-! # Properties of `Equiv.Perm` on `Finite` types -/ assert_not_exists Field namespace Nat theorem card_perm {Ξ± : Type*} [Finite Ξ±] : Nat.card (Equiv.Perm Ξ±) = (Nat.card Ξ±)! := by classical have := Fintype.ofFinite Ξ± rw [card_eq_fintype_card, card_eq_fintype_card, Fintype.card_perm] end Nat
.lake/packages/mathlib/Mathlib/Data/Finite/Vector.lean
import Mathlib.Data.Fintype.Vector /-! # Finiteness of vector types -/ variable {Ξ± : Type*} instance List.Vector.finite [Finite Ξ±] {n : β„•} : Finite (Vector Ξ± n) := by haveI := Fintype.ofFinite Ξ± infer_instance instance [Finite Ξ±] {n : β„•} : Finite (Sym Ξ± n) := by classical haveI := Fintype.ofFinite Ξ± infer_instance
.lake/packages/mathlib/Mathlib/Data/Finite/Defs.lean
import Mathlib.Data.Set.CoeSort import Mathlib.Logic.Equiv.Defs import Mathlib.Tactic.Set import Mathlib.Util.AssertExists /-! # Definition of the `Finite` typeclass This file defines a typeclass `Finite` saying that `Ξ± : Sort*` is finite. A type is `Finite` if it is equivalent to `Fin n` for some `n`. We also define `Infinite Ξ±` as a typeclass equivalent to `Β¬Finite Ξ±`. The `Finite` predicate has no computational relevance and, being `Prop`-valued, gets to enjoy proof irrelevance -- it represents the mere fact that the type is finite. While the `Finite` class also represents finiteness of a type, a key difference is that a `Fintype` instance represents finiteness in a computable way: it gives a concrete algorithm to produce a `Finset` whose elements enumerate the terms of the given type. As such, one generally relies on congruence lemmas when rewriting expressions involving `Fintype` instances. Every `Fintype` instance automatically gives a `Finite` instance, see `Fintype.finite`, but not vice versa. Every `Fintype` instance should be computable since they are meant for computation. If it's not possible to write a computable `Fintype` instance, one should prefer writing a `Finite` instance instead. ## Main definitions * `Finite Ξ±` denotes that `Ξ±` is a finite type. * `Infinite Ξ±` denotes that `Ξ±` is an infinite type. * `Set.Finite : Set Ξ± β†’ Prop` * `Set.Infinite : Set Ξ± β†’ Prop` * `Set.toFinite` to prove `Set.Finite` for a `Set` from a `Finite` instance. ## Implementation notes This file defines both the type-level `Finite` class and the set-level `Set.Finite` definition. The definition of `Finite Ξ±` is not just `Nonempty (Fintype Ξ±)` since `Fintype` requires that `Ξ± : Type*`, and the definition in this module allows for `Ξ± : Sort*`. This means we can write the instance `Finite.prop`. A finite set is defined to be a set whose coercion to a type has a `Finite` instance. There are two components to finiteness constructions. The first is `Fintype` instances for each construction. This gives a way to actually compute a `Finset` that represents the set, and these may be accessed using `set.toFinset`. This gets the `Finset` in the correct form, since otherwise `Finset.univ : Finset s` is a `Finset` for the subtype for `s`. The second component is "constructors" for `Set.Finite` that give proofs that `Fintype` instances exist classically given other `Set.Finite` proofs. Unlike the `Fintype` instances, these *do not* use any decidability instances since they do not compute anything. ## Tags finite, fintype, finite sets -/ assert_not_exists Finset MonoidWithZero IsOrderedRing universe u v open Function variable {Ξ± Ξ² : Sort*} /-- A type is `Finite` if it is in bijective correspondence to some `Fin n`. This is similar to `Fintype`, but `Finite` is a proposition rather than data. A particular benefit to this is that `Finite` instances are definitionally equal to one another (due to proof irrelevance) rather than being merely propositionally equal, and, furthermore, `Finite` instances generally avoid the need for `Decidable` instances. One other notable difference is that `Finite` allows there to be `Finite p` instances for all `p : Prop`, which is not allowed by `Fintype` due to universe constraints. An application of this is that `Finite (x ∈ s β†’ Ξ² x)` follows from the general instance for pi types, assuming `[βˆ€ x, Finite (Ξ² x)]`. Implementation note: this is a reason `Finite Ξ±` is not defined as `Nonempty (Fintype Ξ±)`. Every `Fintype` instance provides a `Finite` instance via `Finite.of_fintype`. Conversely, one can noncomputably create a `Fintype` instance from a `Finite` instance via `Fintype.ofFinite`. In a proof one might write ```lean have := Fintype.ofFinite Ξ± ``` to obtain such an instance. Do not write noncomputable `Fintype` instances; instead write `Finite` instances and use this `Fintype.ofFinite` interface. The `Fintype` instances should be relied upon to be computable for evaluation purposes. Theorems should use `Finite` instead of `Fintype`, unless definitions in the theorem statement require `Fintype`. Definitions should prefer `Finite` as well, unless it is important that the definitions are meant to be computable in the reduction or `#eval` sense. -/ class inductive Finite (Ξ± : Sort*) : Prop | intro {n : β„•} : Ξ± ≃ Fin n β†’ Finite _ theorem finite_iff_exists_equiv_fin {Ξ± : Sort*} : Finite Ξ± ↔ βˆƒ n, Nonempty (Ξ± ≃ Fin n) := ⟨fun ⟨e⟩ => ⟨_, ⟨e⟩⟩, fun ⟨_, ⟨e⟩⟩ => ⟨e⟩⟩ theorem Finite.exists_equiv_fin (Ξ± : Sort*) [h : Finite Ξ±] : βˆƒ n : β„•, Nonempty (Ξ± ≃ Fin n) := finite_iff_exists_equiv_fin.mp h theorem Finite.of_equiv (Ξ± : Sort*) [h : Finite Ξ±] (f : Ξ± ≃ Ξ²) : Finite Ξ² := let ⟨e⟩ := h; ⟨f.symm.trans e⟩ theorem Equiv.finite_iff (f : Ξ± ≃ Ξ²) : Finite Ξ± ↔ Finite Ξ² := ⟨fun _ => Finite.of_equiv _ f, fun _ => Finite.of_equiv _ f.symm⟩ theorem Function.Bijective.finite_iff {f : Ξ± β†’ Ξ²} (h : Bijective f) : Finite Ξ± ↔ Finite Ξ² := (Equiv.ofBijective f h).finite_iff theorem Finite.ofBijective [Finite Ξ±] {f : Ξ± β†’ Ξ²} (h : Bijective f) : Finite Ξ² := h.finite_iff.mp β€Ή_β€Ί variable (Ξ±) in theorem Finite.nonempty_decidableEq [Finite Ξ±] : Nonempty (DecidableEq Ξ±) := let ⟨_n, ⟨e⟩⟩ := Finite.exists_equiv_fin Ξ±; ⟨e.decidableEq⟩ instance [Finite Ξ±] : Finite (PLift Ξ±) := Finite.of_equiv Ξ± Equiv.plift.symm instance {Ξ± : Type v} [Finite Ξ±] : Finite (ULift.{u} Ξ±) := Finite.of_equiv Ξ± Equiv.ulift.symm /-- A type is said to be infinite if it is not finite. Note that `Infinite Ξ±` is equivalent to `IsEmpty (Fintype Ξ±)` or `IsEmpty (Finite Ξ±)`. -/ class Infinite (Ξ± : Sort*) : Prop where /-- assertion that `Ξ±` is `Β¬Finite` -/ not_finite : Β¬Finite Ξ± @[simp, push] theorem not_finite_iff_infinite : Β¬Finite Ξ± ↔ Infinite Ξ± := ⟨Infinite.mk, fun h => h.1⟩ @[simp, push] theorem not_infinite_iff_finite : Β¬Infinite Ξ± ↔ Finite Ξ± := not_finite_iff_infinite.not_right.symm theorem Equiv.infinite_iff (e : Ξ± ≃ Ξ²) : Infinite Ξ± ↔ Infinite Ξ² := not_finite_iff_infinite.symm.trans <| e.finite_iff.not.trans not_finite_iff_infinite instance [Infinite Ξ±] : Infinite (PLift Ξ±) := Equiv.plift.infinite_iff.2 β€Ή_β€Ί instance {Ξ± : Type v} [Infinite Ξ±] : Infinite (ULift.{u} Ξ±) := Equiv.ulift.infinite_iff.2 β€Ή_β€Ί theorem finite_or_infinite (Ξ± : Sort*) : Finite Ξ± ∨ Infinite Ξ± := or_iff_not_imp_left.2 not_finite_iff_infinite.1 /-- `Infinite Ξ±` is not `Finite` -/ theorem not_finite (Ξ± : Sort*) [Infinite Ξ±] [Finite Ξ±] : False := @Infinite.not_finite Ξ± β€Ή_β€Ί β€Ή_β€Ί protected theorem Finite.false [Infinite Ξ±] (_ : Finite Ξ±) : False := not_finite Ξ± protected theorem Infinite.false [Finite Ξ±] (_ : Infinite Ξ±) : False := @Infinite.not_finite Ξ± β€Ή_β€Ί β€Ή_β€Ί alias ⟨Finite.of_not_infinite, Finite.not_infinite⟩ := not_infinite_iff_finite instance Bool.instFinite : Finite Bool := .intro finTwoEquiv.symm instance Prop.instFinite : Finite Prop := .of_equiv _ Equiv.propEquivBool.symm section Set /-! ### Finite sets -/ variable {Ξ± : Type u} {Ξ² : Type v} namespace Set /-- A set is finite if the corresponding `Subtype` is finite, i.e., if there exists a natural `n : β„•` and an equivalence `s ≃ Fin n`. -/ protected def Finite (s : Set Ξ±) : Prop := Finite s -- The `protected` attribute does not take effect within the same namespace block. end Set namespace Set theorem finite_coe_iff {s : Set Ξ±} : Finite s ↔ s.Finite := .rfl /-- Constructor for `Set.Finite` using a `Finite` instance. -/ theorem toFinite (s : Set Ξ±) [Finite s] : s.Finite := β€Ή_β€Ί /-- Projection of `Set.Finite` to its `Finite` instance. This is intended to be used with dot notation. See also `Set.Finite.Fintype` and `Set.Finite.nonempty_fintype`. -/ protected theorem Finite.to_subtype {s : Set Ξ±} (h : s.Finite) : Finite s := h /-- A set is infinite if it is not finite. This is protected so that it does not conflict with global `Infinite`. -/ protected def Infinite (s : Set Ξ±) : Prop := Β¬s.Finite @[simp] theorem not_infinite {s : Set Ξ±} : Β¬s.Infinite ↔ s.Finite := not_not alias ⟨_, Finite.not_infinite⟩ := not_infinite attribute [simp] Finite.not_infinite /-- See also `finite_or_infinite`, `fintypeOrInfinite`. -/ protected theorem finite_or_infinite (s : Set Ξ±) : s.Finite ∨ s.Infinite := em _ protected theorem infinite_or_finite (s : Set Ξ±) : s.Infinite ∨ s.Finite := em' _ end Set theorem Equiv.set_finite_iff {s : Set Ξ±} {t : Set Ξ²} (hst : s ≃ t) : s.Finite ↔ t.Finite := by simp_rw [← Set.finite_coe_iff, hst.finite_iff] namespace Set /-! ### Infinite sets -/ variable {s t : Set Ξ±} theorem infinite_coe_iff {s : Set Ξ±} : Infinite s ↔ s.Infinite := not_finite_iff_infinite.symm.trans finite_coe_iff.not alias ⟨_, Infinite.to_subtype⟩ := infinite_coe_iff end Set end Set
.lake/packages/mathlib/Mathlib/Data/Finite/Set.lean
import Mathlib.Data.Fintype.EquivFin /-! # Lemmas about `Finite` and `Set`s In this file we prove two lemmas about `Finite` and `Set`s. ## Tags finiteness, finite sets -/ open Set universe u v w variable {Ξ± : Type u} {Ξ² : Type v} {ΞΉ : Sort w} theorem Finite.Set.finite_of_finite_image (s : Set Ξ±) {f : Ξ± β†’ Ξ²} (h : s.InjOn f) [Finite (f '' s)] : Finite s := Finite.of_equiv _ (Equiv.ofBijective _ h.bijOn_image.bijective).symm theorem Finite.of_injective_finite_range {f : ΞΉ β†’ Ξ±} (hf : Function.Injective f) [Finite (range f)] : Finite ΞΉ := Finite.of_injective (Set.rangeFactorization f) (hf.codRestrict _)
.lake/packages/mathlib/Mathlib/Data/NNRat/Lemmas.lean
import Mathlib.Algebra.Field.Rat import Mathlib.Algebra.Group.Indicator import Mathlib.Algebra.Order.Field.Rat import Mathlib.Data.Rat.Lemmas import Mathlib.Tactic.Zify /-! # Field and action structures on the nonnegative rationals This file provides additional results about `NNRat` that cannot live in earlier files due to import cycles. -/ open Function open scoped NNRat namespace NNRat variable {Ξ± : Type*} {q : β„šβ‰₯0} @[simp, norm_cast] lemma coe_indicator (s : Set Ξ±) (f : Ξ± β†’ β„šβ‰₯0) (a : Ξ±) : ((s.indicator f a : β„šβ‰₯0) : β„š) = s.indicator (fun x ↦ ↑(f x)) a := (coeHom : β„šβ‰₯0 β†’+ β„š).map_indicator _ _ _ end NNRat open NNRat namespace Rat variable {p q : β„š} lemma toNNRat_inv (q : β„š) : toNNRat q⁻¹ = (toNNRat q)⁻¹ := by obtain hq | hq := le_total q 0 Β· rw [toNNRat_eq_zero.mpr hq, inv_zero, toNNRat_eq_zero.mpr (inv_nonpos.mpr hq)] Β· nth_rw 1 [← Rat.coe_toNNRat q hq] rw [← coe_inv, toNNRat_coe] lemma toNNRat_div (hp : 0 ≀ p) : toNNRat (p / q) = toNNRat p / toNNRat q := by rw [div_eq_mul_inv, div_eq_mul_inv, ← toNNRat_inv, ← toNNRat_mul hp] lemma toNNRat_div' (hq : 0 ≀ q) : toNNRat (p / q) = toNNRat p / toNNRat q := by rw [div_eq_inv_mul, div_eq_inv_mul, toNNRat_mul (inv_nonneg.2 hq), toNNRat_inv] end Rat /-! ### Numerator and denominator -/ namespace NNRat variable {q : β„šβ‰₯0} /-- A recursor for nonnegative rationals in terms of numerators and denominators. -/ protected def rec {Ξ± : β„šβ‰₯0 β†’ Sort*} (h : βˆ€ m n : β„•, Ξ± (m / n)) (q : β„šβ‰₯0) : Ξ± q := by rw [← num_div_den q]; apply h theorem mul_num (q₁ qβ‚‚ : β„šβ‰₯0) : (q₁ * qβ‚‚).num = q₁.num * qβ‚‚.num / Nat.gcd (q₁.num * qβ‚‚.num) (q₁.den * qβ‚‚.den) := by zify convert Rat.mul_num q₁ qβ‚‚ <;> norm_cast theorem mul_den (q₁ qβ‚‚ : β„šβ‰₯0) : (q₁ * qβ‚‚).den = q₁.den * qβ‚‚.den / Nat.gcd (q₁.num * qβ‚‚.num) (q₁.den * qβ‚‚.den) := by convert Rat.mul_den q₁ qβ‚‚ norm_cast /-- A version of `NNRat.mul_den` without division. -/ theorem den_mul_den_eq_den_mul_gcd (q₁ qβ‚‚ : β„šβ‰₯0) : q₁.den * qβ‚‚.den = (q₁ * qβ‚‚).den * ((q₁.num * qβ‚‚.num).gcd (q₁.den * qβ‚‚.den)) := by convert Rat.den_mul_den_eq_den_mul_gcd q₁ qβ‚‚ norm_cast /-- A version of `NNRat.mul_num` without division. -/ theorem num_mul_num_eq_num_mul_gcd (q₁ qβ‚‚ : β„šβ‰₯0) : q₁.num * qβ‚‚.num = (q₁ * qβ‚‚).num * ((q₁.num * qβ‚‚.num).gcd (q₁.den * qβ‚‚.den)) := by zify convert Rat.num_mul_num_eq_num_mul_gcd q₁ qβ‚‚ <;> norm_cast end NNRat
.lake/packages/mathlib/Mathlib/Data/NNRat/Order.lean
import Mathlib.Data.NNRat.Defs import Mathlib.Algebra.Order.Ring.Rat import Mathlib.Algebra.Order.Nonneg.Ring /-! # Bundled ordered algebra structures on `β„šβ‰₯0` -/ instance : IsStrictOrderedRing β„šβ‰₯0 := Nonneg.isStrictOrderedRing -- TODO: `deriving instance OrderedSub for NNRat` doesn't work yet, so we add the instance manually instance NNRat.instOrderedSub : OrderedSub β„šβ‰₯0 := Nonneg.orderedSub instance NNRat.instCanonicallyOrderedAdd : CanonicallyOrderedAdd β„šβ‰₯0 := Nonneg.canonicallyOrderedAdd
.lake/packages/mathlib/Mathlib/Data/NNRat/Defs.lean
import Mathlib.Algebra.Order.Group.Unbundled.Int import Mathlib.Algebra.Order.Nonneg.Basic import Mathlib.Algebra.Order.Ring.Unbundled.Rat import Mathlib.Algebra.Ring.Rat import Mathlib.Data.Set.Operations import Mathlib.Order.Bounds.Defs import Mathlib.Order.GaloisConnection.Defs /-! # Nonnegative rationals This file defines the nonnegative rationals as a subtype of `Rat` and provides its basic algebraic order structure. Note that `NNRat` is not declared as a `Semifield` here. See `Mathlib/Algebra/Field/Rat.lean` for that instance. We also define an instance `CanLift β„š β„šβ‰₯0`. This instance can be used by the `lift` tactic to replace `x : β„š` and `hx : 0 ≀ x` in the proof context with `x : β„šβ‰₯0` while replacing all occurrences of `x` with `↑x`. This tactic also works for a function `f : Ξ± β†’ β„š` with a hypothesis `hf : βˆ€ x, 0 ≀ f x`. ## Notation `β„šβ‰₯0` is notation for `NNRat` in scope `NNRat`. ## Huge warning Whenever you state a lemma about the coercion `β„šβ‰₯0 β†’ β„š`, check that Lean inserts `NNRat.cast`, not `Subtype.val`. Else your lemma will never apply. -/ assert_not_exists CompleteLattice IsOrderedMonoid library_note2 Β«specialised high priority simp lemmaΒ» /-- It sometimes happens that a `@[simp]` lemma declared early in the library can be proved by `simp` using later, more general simp lemmas. In that case, the following reasons might be arguments for the early lemma to be tagged `@[simp high]` (rather than `@[simp, nolint simpNF]` or un``@[simp]``ed): 1. There is a significant portion of the library which needs the early lemma to be available via `simp` and which doesn't have access to the more general lemmas. 2. The more general lemmas have more complicated typeclass assumptions, causing rewrites with them to be slower. -/ open Function instance Rat.instPosMulMono : PosMulMono β„š where mul_le_mul_of_nonneg_left r hr p q hpq := by simpa [mul_sub, sub_nonneg] using Rat.mul_nonneg hr (sub_nonneg.2 hpq) deriving instance CommSemiring for NNRat deriving instance LinearOrder for NNRat deriving instance Sub for NNRat deriving instance Inhabited for NNRat namespace NNRat variable {p q : β„šβ‰₯0} instance instNontrivial : Nontrivial β„šβ‰₯0 where exists_pair_ne := ⟨1, 0, by decide⟩ instance instOrderBot : OrderBot β„šβ‰₯0 where bot := 0 bot_le q := q.2 @[simp] lemma val_eq_cast (q : β„šβ‰₯0) : q.1 = q := rfl instance instCharZero : CharZero β„šβ‰₯0 where cast_injective a b hab := by simpa using congr_arg num hab instance canLift : CanLift β„š β„šβ‰₯0 (↑) fun q ↦ 0 ≀ q where prf q hq := ⟨⟨q, hq⟩, rfl⟩ @[ext] theorem ext : (p : β„š) = (q : β„š) β†’ p = q := Subtype.ext protected theorem coe_injective : Injective ((↑) : β„šβ‰₯0 β†’ β„š) := Subtype.coe_injective -- See note [specialised high priority simp lemma] @[simp high, norm_cast] theorem coe_inj : (p : β„š) = q ↔ p = q := Subtype.coe_inj theorem ne_iff {x y : β„šβ‰₯0} : (x : β„š) β‰  (y : β„š) ↔ x β‰  y := NNRat.coe_inj.not -- TODO: We have to write `NNRat.cast` explicitly, else the statement picks up `Subtype.val` instead @[simp, norm_cast] lemma coe_mk (q : β„š) (hq) : NNRat.cast ⟨q, hq⟩ = q := rfl lemma Β«forallΒ» {p : β„šβ‰₯0 β†’ Prop} : (βˆ€ q, p q) ↔ βˆ€ q hq, p ⟨q, hq⟩ := Subtype.forall lemma Β«existsΒ» {p : β„šβ‰₯0 β†’ Prop} : (βˆƒ q, p q) ↔ βˆƒ q hq, p ⟨q, hq⟩ := Subtype.exists /-- Reinterpret a rational number `q` as a non-negative rational number. Returns `0` if `q ≀ 0`. -/ def _root_.Rat.toNNRat (q : β„š) : β„šβ‰₯0 := ⟨max q 0, le_max_right _ _⟩ theorem _root_.Rat.coe_toNNRat (q : β„š) (hq : 0 ≀ q) : (q.toNNRat : β„š) = q := max_eq_left hq theorem _root_.Rat.le_coe_toNNRat (q : β„š) : q ≀ q.toNNRat := le_max_left _ _ open Rat (toNNRat) @[simp] theorem coe_nonneg (q : β„šβ‰₯0) : (0 : β„š) ≀ q := q.2 @[simp, norm_cast] lemma coe_zero : ((0 : β„šβ‰₯0) : β„š) = 0 := rfl @[simp] lemma num_zero : num 0 = 0 := rfl @[simp] lemma den_zero : den 0 = 1 := rfl @[simp, norm_cast] lemma coe_one : ((1 : β„šβ‰₯0) : β„š) = 1 := rfl @[simp] lemma num_one : num 1 = 1 := rfl @[simp] lemma den_one : den 1 = 1 := rfl @[simp, norm_cast] theorem coe_add (p q : β„šβ‰₯0) : ((p + q : β„šβ‰₯0) : β„š) = p + q := rfl @[simp, norm_cast] theorem coe_mul (p q : β„šβ‰₯0) : ((p * q : β„šβ‰₯0) : β„š) = p * q := rfl @[simp, norm_cast] lemma coe_pow (q : β„šβ‰₯0) (n : β„•) : (↑(q ^ n) : β„š) = (q : β„š) ^ n := rfl @[simp] lemma num_pow (q : β„šβ‰₯0) (n : β„•) : (q ^ n).num = q.num ^ n := by simp [num, Int.natAbs_pow] @[simp] lemma den_pow (q : β„šβ‰₯0) (n : β„•) : (q ^ n).den = q.den ^ n := rfl @[simp, norm_cast] theorem coe_sub (h : q ≀ p) : ((p - q : β„šβ‰₯0) : β„š) = p - q := max_eq_left <| le_sub_comm.2 <| by rwa [sub_zero] -- See note [specialised high priority simp lemma] @[simp high] theorem coe_eq_zero : (q : β„š) = 0 ↔ q = 0 := by norm_cast theorem coe_ne_zero : (q : β„š) β‰  0 ↔ q β‰  0 := coe_eq_zero.not @[simp] theorem mk_zero : (⟨0, le_rfl⟩ : β„šβ‰₯0) = 0 := rfl @[norm_cast] theorem coe_le_coe : (p : β„š) ≀ q ↔ p ≀ q := Iff.rfl @[norm_cast] theorem coe_lt_coe : (p : β„š) < q ↔ p < q := Iff.rfl @[norm_cast] theorem coe_pos : (0 : β„š) < q ↔ 0 < q := Iff.rfl theorem coe_mono : Monotone ((↑) : β„šβ‰₯0 β†’ β„š) := fun _ _ ↦ coe_le_coe.2 theorem toNNRat_mono : Monotone toNNRat := fun _ _ h ↦ max_le_max h le_rfl @[simp] theorem toNNRat_coe (q : β„šβ‰₯0) : toNNRat q = q := ext <| max_eq_left q.2 @[simp] theorem toNNRat_coe_nat (n : β„•) : toNNRat n = n := ext <| by simp only [Nat.cast_nonneg', Rat.coe_toNNRat]; rfl /-- `toNNRat` and `(↑) : β„šβ‰₯0 β†’ β„š` form a Galois insertion. -/ protected def gi : GaloisInsertion toNNRat (↑) := GaloisInsertion.monotoneIntro coe_mono toNNRat_mono Rat.le_coe_toNNRat toNNRat_coe /-- Coercion `β„šβ‰₯0 β†’ β„š` as a `RingHom`. -/ def coeHom : β„šβ‰₯0 β†’+* β„š where toFun := (↑) map_one' := coe_one map_mul' := coe_mul map_zero' := coe_zero map_add' := coe_add @[simp, norm_cast] lemma coe_natCast (n : β„•) : (↑(↑n : β„šβ‰₯0) : β„š) = n := rfl @[simp] theorem mk_natCast (n : β„•) : @Eq β„šβ‰₯0 (⟨(n : β„š), Nat.cast_nonneg' n⟩ : β„šβ‰₯0) n := rfl @[simp] theorem coe_coeHom : ⇑coeHom = ((↑) : β„šβ‰₯0 β†’ β„š) := rfl @[norm_cast] theorem nsmul_coe (q : β„šβ‰₯0) (n : β„•) : ↑(n β€’ q) = n β€’ (q : β„š) := coeHom.toAddMonoidHom.map_nsmul _ _ theorem bddAbove_coe {s : Set β„šβ‰₯0} : BddAbove ((↑) '' s : Set β„š) ↔ BddAbove s := ⟨fun ⟨b, hb⟩ ↦ ⟨toNNRat b, fun ⟨y, _⟩ hys ↦ show y ≀ max b 0 from (hb <| Set.mem_image_of_mem _ hys).trans <| le_max_left _ _⟩, fun ⟨b, hb⟩ ↦ ⟨b, fun _ ⟨_, hx, Eq⟩ ↦ Eq β–Έ hb hx⟩⟩ theorem bddBelow_coe (s : Set β„šβ‰₯0) : BddBelow (((↑) : β„šβ‰₯0 β†’ β„š) '' s) := ⟨0, fun _ ⟨q, _, h⟩ ↦ h β–Έ q.2⟩ @[norm_cast] theorem coe_max (x y : β„šβ‰₯0) : ((max x y : β„šβ‰₯0) : β„š) = max (x : β„š) (y : β„š) := coe_mono.map_max @[norm_cast] theorem coe_min (x y : β„šβ‰₯0) : ((min x y : β„šβ‰₯0) : β„š) = min (x : β„š) (y : β„š) := coe_mono.map_min theorem sub_def (p q : β„šβ‰₯0) : p - q = toNNRat (p - q) := rfl @[simp] theorem abs_coe (q : β„šβ‰₯0) : |(q : β„š)| = q := abs_of_nonneg q.2 -- See note [specialised high priority simp lemma] @[simp high] theorem nonpos_iff_eq_zero (q : β„šβ‰₯0) : q ≀ 0 ↔ q = 0 := ⟨fun h => le_antisymm h q.2, fun h => h.symm β–Έ q.2⟩ end NNRat open NNRat namespace Rat variable {p q : β„š} @[simp] theorem toNNRat_zero : toNNRat 0 = 0 := rfl @[simp] theorem toNNRat_one : toNNRat 1 = 1 := rfl @[simp] theorem toNNRat_pos : 0 < toNNRat q ↔ 0 < q := by simp [toNNRat, ← coe_lt_coe] @[simp] theorem toNNRat_eq_zero : toNNRat q = 0 ↔ q ≀ 0 := by simpa [-toNNRat_pos] using (@toNNRat_pos q).not alias ⟨_, toNNRat_of_nonpos⟩ := toNNRat_eq_zero @[simp] theorem toNNRat_le_toNNRat_iff (hp : 0 ≀ p) : toNNRat q ≀ toNNRat p ↔ q ≀ p := by simp [← coe_le_coe, toNNRat, hp] @[simp] theorem toNNRat_lt_toNNRat_iff' : toNNRat q < toNNRat p ↔ q < p ∧ 0 < p := by simp [← coe_lt_coe, toNNRat] theorem toNNRat_lt_toNNRat_iff (h : 0 < p) : toNNRat q < toNNRat p ↔ q < p := toNNRat_lt_toNNRat_iff'.trans (and_iff_left h) theorem toNNRat_lt_toNNRat_iff_of_nonneg (hq : 0 ≀ q) : toNNRat q < toNNRat p ↔ q < p := toNNRat_lt_toNNRat_iff'.trans ⟨And.left, fun h ↦ ⟨h, hq.trans_lt h⟩⟩ @[simp] theorem toNNRat_add (hq : 0 ≀ q) (hp : 0 ≀ p) : toNNRat (q + p) = toNNRat q + toNNRat p := NNRat.ext <| by simp [toNNRat, hq, hp, add_nonneg] theorem toNNRat_add_le : toNNRat (q + p) ≀ toNNRat q + toNNRat p := coe_le_coe.1 <| max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) <| coe_nonneg _ theorem toNNRat_le_iff_le_coe {p : β„šβ‰₯0} : toNNRat q ≀ p ↔ q ≀ ↑p := NNRat.gi.gc q p theorem le_toNNRat_iff_coe_le {q : β„šβ‰₯0} (hp : 0 ≀ p) : q ≀ toNNRat p ↔ ↑q ≀ p := by rw [← coe_le_coe, Rat.coe_toNNRat p hp] theorem le_toNNRat_iff_coe_le' {q : β„šβ‰₯0} (hq : 0 < q) : q ≀ toNNRat p ↔ ↑q ≀ p := (le_or_gt 0 p).elim le_toNNRat_iff_coe_le fun hp ↦ by simp only [(hp.trans_le q.coe_nonneg).not_ge, toNNRat_eq_zero.2 hp.le, hq.not_ge] theorem toNNRat_lt_iff_lt_coe {p : β„šβ‰₯0} (hq : 0 ≀ q) : toNNRat q < p ↔ q < ↑p := by rw [← coe_lt_coe, Rat.coe_toNNRat q hq] theorem lt_toNNRat_iff_coe_lt {q : β„šβ‰₯0} : q < toNNRat p ↔ ↑q < p := NNRat.gi.gc.lt_iff_lt theorem toNNRat_mul (hp : 0 ≀ p) : toNNRat (p * q) = toNNRat p * toNNRat q := by rcases le_total 0 q with hq | hq Β· ext; simp [toNNRat, hp, hq, mul_nonneg] Β· have hpq := mul_nonpos_of_nonneg_of_nonpos hp hq rw [toNNRat_eq_zero.2 hq, toNNRat_eq_zero.2 hpq, mul_zero] end Rat /-- The absolute value on `β„š` as a map to `β„šβ‰₯0`. -/ @[pp_nodot] def Rat.nnabs (x : β„š) : β„šβ‰₯0 := ⟨abs x, abs_nonneg x⟩ @[norm_cast, simp] theorem Rat.coe_nnabs (x : β„š) : (Rat.nnabs x : β„š) = abs x := rfl /-! ### Numerator and denominator -/ namespace NNRat variable {p q : β„šβ‰₯0} @[norm_cast] lemma num_coe (q : β„šβ‰₯0) : (q : β„š).num = q.num := by simp only [num, Int.natCast_natAbs, Rat.num_nonneg, coe_nonneg, abs_of_nonneg] theorem natAbs_num_coe : (q : β„š).num.natAbs = q.num := rfl @[norm_cast] lemma den_coe : (q : β„š).den = q.den := rfl @[simp] lemma num_ne_zero : q.num β‰  0 ↔ q β‰  0 := by simp [num] @[simp] lemma num_pos : 0 < q.num ↔ 0 < q := by simpa [num, -nonpos_iff_eq_zero] using nonpos_iff_eq_zero _ |>.not.symm @[simp] lemma den_pos (q : β„šβ‰₯0) : 0 < q.den := Rat.den_pos _ @[simp] lemma den_ne_zero (q : β„šβ‰₯0) : q.den β‰  0 := Rat.den_ne_zero _ lemma coprime_num_den (q : β„šβ‰₯0) : q.num.Coprime q.den := by simpa [num, den] using Rat.reduced _ -- TODO: Rename `Rat.coe_nat_num`, `Rat.intCast_den`, `Rat.ofNat_num`, `Rat.ofNat_den` @[simp, norm_cast] lemma num_natCast (n : β„•) : num n = n := rfl @[simp, norm_cast] lemma den_natCast (n : β„•) : den n = 1 := rfl @[simp] lemma num_ofNat (n : β„•) [n.AtLeastTwo] : num ofNat(n) = OfNat.ofNat n := rfl @[simp] lemma den_ofNat (n : β„•) [n.AtLeastTwo] : den ofNat(n) = 1 := rfl theorem ext_num_den (hn : p.num = q.num) (hd : p.den = q.den) : p = q := by refine ext <| Rat.ext ?_ hd simpa [num_coe] theorem ext_num_den_iff : p = q ↔ p.num = q.num ∧ p.den = q.den := ⟨by rintro rfl; exact ⟨rfl, rfl⟩, fun h ↦ ext_num_den h.1 h.2⟩ /-- Form the quotient `n / d` where `n d : β„•`. See also `Rat.divInt` and `mkRat`. -/ def divNat (n d : β„•) : β„šβ‰₯0 := ⟨.divInt n d, Rat.divInt_nonneg (Int.ofNat_zero_le n) (Int.ofNat_zero_le d)⟩ variable {n₁ nβ‚‚ d₁ dβ‚‚ : β„•} @[simp, norm_cast] lemma coe_divNat (n d : β„•) : (divNat n d : β„š) = .divInt n d := rfl lemma mk_divInt (n d : β„•) : ⟨.divInt n d, Rat.divInt_nonneg (Int.ofNat_zero_le n) (Int.ofNat_zero_le d)⟩ = divNat n d := rfl lemma divNat_inj (h₁ : d₁ β‰  0) (hβ‚‚ : dβ‚‚ β‰  0) : divNat n₁ d₁ = divNat nβ‚‚ dβ‚‚ ↔ n₁ * dβ‚‚ = nβ‚‚ * d₁ := by rw [← coe_inj]; simp [Rat.mkRat_eq_iff, h₁, hβ‚‚]; norm_cast @[simp] lemma divNat_zero (n : β„•) : divNat n 0 = 0 := by simp [divNat] @[simp] lemma num_divNat_den (q : β„šβ‰₯0) : divNat q.num q.den = q := ext <| by rw [← (q : β„š).mkRat_num_den']; simp [num_coe, den_coe] lemma natCast_eq_divNat (n : β„•) : (n : β„šβ‰₯0) = divNat n 1 := (num_divNat_den _).symm lemma divNat_mul_divNat (n₁ nβ‚‚ : β„•) {d₁ dβ‚‚} : divNat n₁ d₁ * divNat nβ‚‚ dβ‚‚ = divNat (n₁ * nβ‚‚) (d₁ * dβ‚‚) := by ext; push_cast; exact Rat.divInt_mul_divInt _ _ lemma divNat_mul_left {a : β„•} (ha : a β‰  0) (n d : β„•) : divNat (a * n) (a * d) = divNat n d := by ext; push_cast; exact Rat.divInt_mul_left (mod_cast ha) lemma divNat_mul_right {a : β„•} (ha : a β‰  0) (n d : β„•) : divNat (n * a) (d * a) = divNat n d := by ext; push_cast; exact Rat.divInt_mul_right (mod_cast ha) @[simp] lemma mul_den_eq_num (q : β„šβ‰₯0) : q * q.den = q.num := by ext push_cast rw [← Int.cast_natCast, ← den_coe, ← Int.cast_natCast q.num, ← num_coe] exact Rat.mul_den_eq_num _ @[simp] lemma den_mul_eq_num (q : β„šβ‰₯0) : q.den * q = q.num := by rw [mul_comm, mul_den_eq_num] /-- Define a (dependent) function or prove `βˆ€ r : β„š, p r` by dealing with nonnegative rational numbers of the form `n / d` with `d β‰  0` and `n`, `d` coprime. -/ @[elab_as_elim] def numDenCasesOn.{u} {C : β„šβ‰₯0 β†’ Sort u} (q) (H : βˆ€ n d, d β‰  0 β†’ n.Coprime d β†’ C (divNat n d)) : C q := by rw [← q.num_divNat_den]; exact H _ _ q.den_ne_zero q.coprime_num_den lemma add_def (q r : β„šβ‰₯0) : q + r = divNat (q.num * r.den + r.num * q.den) (q.den * r.den) := by ext; simp [Rat.add_def', Rat.mkRat_eq_divInt, num_coe, den_coe] lemma mul_def (q r : β„šβ‰₯0) : q * r = divNat (q.num * r.num) (q.den * r.den) := by ext; simp [Rat.mul_eq_mkRat, Rat.mkRat_eq_divInt, num_coe, den_coe] theorem lt_def {p q : β„šβ‰₯0} : p < q ↔ p.num * q.den < q.num * p.den := by rw [← NNRat.coe_lt_coe, Rat.lt_iff]; norm_cast theorem le_def {p q : β„šβ‰₯0} : p ≀ q ↔ p.num * q.den ≀ q.num * p.den := by rw [← NNRat.coe_le_coe, Rat.le_iff]; norm_cast end NNRat namespace Mathlib.Tactic.Qify @[qify_simps] lemma nnratCast_eq (a b : β„šβ‰₯0) : a = b ↔ (a : β„š) = (b : β„š) := NNRat.coe_inj.symm @[qify_simps] lemma nnratCast_le (a b : β„šβ‰₯0) : a ≀ b ↔ (a : β„š) ≀ (b : β„š) := NNRat.coe_le_coe.symm @[qify_simps] lemma nnratCast_lt (a b : β„šβ‰₯0) : a < b ↔ (a : β„š) < (b : β„š) := NNRat.coe_lt_coe.symm @[qify_simps] lemma nnratCast_ne (a b : β„šβ‰₯0) : a β‰  b ↔ (a : β„š) β‰  (b : β„š) := NNRat.ne_iff.symm end Mathlib.Tactic.Qify
.lake/packages/mathlib/Mathlib/Data/NNRat/Floor.lean
import Mathlib.Algebra.Order.Floor.Semiring import Mathlib.Data.NNRat.Order import Mathlib.Data.Rat.Floor /-! # Floor Function for Non-negative Rational Numbers ## Summary We define the `FloorSemiring` instance on `β„šβ‰₯0`, and relate its operators to `NNRat.cast`. Note that we cannot talk about `Int.fract`, which currently only works for rings. ## Tags nnrat, rationals, β„šβ‰₯0, floor -/ assert_not_exists Finset namespace NNRat instance : FloorSemiring β„šβ‰₯0 where floor q := ⌊q.valβŒ‹β‚Š ceil q := ⌈q.valβŒ‰β‚Š floor_of_neg h := by simpa using h.trans zero_lt_one gc_floor {a n} h := by rw [← NNRat.coe_le_coe, Nat.le_floor_iff] <;> norm_cast gc_ceil {a b} := by rw [← NNRat.coe_le_coe, Nat.ceil_le]; norm_cast @[simp, norm_cast] theorem floor_coe (q : β„šβ‰₯0) : ⌊(q : β„š)βŒ‹β‚Š = ⌊qβŒ‹β‚Š := rfl @[simp, norm_cast] theorem ceil_coe (q : β„šβ‰₯0) : ⌈(q : β„š)βŒ‰β‚Š = ⌈qβŒ‰β‚Š := rfl @[simp, norm_cast] theorem coe_floor (q : β„šβ‰₯0) : β†‘βŒŠqβŒ‹β‚Š = ⌊(q : β„š)βŒ‹ := Int.natCast_floor_eq_floor q.coe_nonneg @[simp, norm_cast] theorem coe_ceil (q : β„šβ‰₯0) : β†‘βŒˆqβŒ‰β‚Š = ⌈(q : β„š)βŒ‰ := Int.natCast_ceil_eq_ceil q.coe_nonneg protected theorem floor_def (q : β„šβ‰₯0) : ⌊qβŒ‹β‚Š = q.num / q.den := by rw [← Int.natCast_inj, NNRat.coe_floor, Rat.floor_def', Int.natCast_ediv, den_coe, num_coe] section Semifield variable {K} [Semifield K] [LinearOrder K] [IsStrictOrderedRing K] [FloorSemiring K] @[simp, norm_cast] theorem floor_cast (x : β„šβ‰₯0) : ⌊(x : K)βŒ‹β‚Š = ⌊xβŒ‹β‚Š := (Nat.floor_eq_iff x.cast_nonneg).2 (mod_cast (Nat.floor_eq_iff x.cast_nonneg).1 (Eq.refl ⌊xβŒ‹β‚Š)) @[simp, norm_cast] theorem ceil_cast (x : β„šβ‰₯0) : ⌈(x : K)βŒ‰β‚Š = ⌈xβŒ‰β‚Š := by obtain rfl | hx := eq_or_ne x 0 Β· simp Β· refine (Nat.ceil_eq_iff ?_).2 (mod_cast (Nat.ceil_eq_iff ?_).1 (Eq.refl ⌈xβŒ‰β‚Š)) <;> simpa end Semifield section Field variable {K} [Field K] [LinearOrder K] [IsStrictOrderedRing K] [FloorRing K] @[simp, norm_cast] theorem intFloor_cast (x : β„šβ‰₯0) : ⌊(x : K)βŒ‹ = ⌊(x : β„š)βŒ‹ := by rw [Int.floor_eq_iff, ← coe_floor] norm_cast norm_cast rw [Nat.cast_add_one, ← Nat.floor_eq_iff (zero_le _)] @[simp, norm_cast] theorem intCeil_cast (x : β„šβ‰₯0) : ⌈(x : K)βŒ‰ = ⌈(x : β„š)βŒ‰ := by rw [Int.ceil_eq_iff, ← coe_ceil, sub_lt_iff_lt_add] constructor Β· have := NNRat.cast_strictMono (K := K) <| Nat.ceil_lt_add_one <| zero_le x rw [NNRat.cast_add, NNRat.cast_one] at this refine Eq.trans_lt ?_ this norm_cast Β· rw [Int.cast_natCast, NNRat.cast_le_natCast] exact Nat.le_ceil _ end Field @[norm_cast] theorem floor_natCast_div_natCast (n d : β„•) : ⌊(↑n / ↑d : β„šβ‰₯0)βŒ‹β‚Š = n / d := Rat.natFloor_natCast_div_natCast n d end NNRat namespace Mathlib.Meta.NormNum open Qq /-! ### `norm_num` extension for `Nat.ceil` -/ theorem IsNat.natCeil {R : Type*} [Semiring R] [LinearOrder R] [IsStrictOrderedRing R] [FloorSemiring R] (r : R) (m : β„•) : IsNat r m β†’ IsNat (⌈rβŒ‰β‚Š) m := by rintro ⟨⟨⟩⟩ exact ⟨by simp⟩ theorem IsInt.natCeil {R : Type*} [Ring R] [LinearOrder R] [IsStrictOrderedRing R] [FloorSemiring R] (r : R) (m : β„•) : IsInt r (.negOfNat m) β†’ IsNat (⌈rβŒ‰β‚Š) 0 := by rintro ⟨⟨⟩⟩ exact ⟨by simp⟩ theorem IsNNRat.natCeil {R : Type*} [Semifield R] [LinearOrder R] [IsStrictOrderedRing R] [FloorSemiring R] (r : R) (n d : β„•) (h : IsNNRat r n d) (res : β„•) (hres : ⌈(n / d : β„šβ‰₯0)βŒ‰β‚Š = res) : IsNat ⌈rβŒ‰β‚Š res := by constructor rw [← hres, h.to_eq rfl rfl, ← @NNRat.ceil_cast R] simp theorem IsRat.natCeil {R : Type*} [Field R] [LinearOrder R] [IsStrictOrderedRing R] [FloorSemiring R] (r : R) (n d : β„•) (h : IsRat r (.negOfNat n) d) : IsNat ⌈rβŒ‰β‚Š 0 := by constructor simp [h.neg_to_eq, div_nonneg] open Lean in /-- `norm_num` extension for `Nat.ceil` -/ @[norm_num ⌈_βŒ‰β‚Š] def evalNatCeil : NormNumExt where eval {u Ξ±Z} e := do match u, Ξ±Z, e with | 0, ~q(β„•), ~q(@Nat.ceil $Ξ± $instSemiring $instPartialOrder $instFloorSemiring $x) => match ← derive x with | .isBool .. => failure | .isNat sΞ± nb pb => do let instLinearOrder ← synthInstanceQ q(LinearOrder $Ξ±) let instIsStrictOrderedRing ← synthInstanceQ q(IsStrictOrderedRing $Ξ±) assertInstancesCommute return .isNat q(inferInstance) nb q(IsNat.natCeil $x _ $pb) | .isNegNat sΞ± nb pb => do let instLinearOrder ← synthInstanceQ q(LinearOrder $Ξ±) let instIsStrictOrderedRing ← synthInstanceQ q(IsStrictOrderedRing $Ξ±) assertInstancesCommute return .isNat q(inferInstance) (mkRawNatLit 0) q(IsInt.natCeil _ _ $pb) | .isNNRat _ q n d h => do let instSemifield ← synthInstanceQ q(Semifield $Ξ±) let instLinearOrder ← synthInstanceQ q(LinearOrder $Ξ±) let instIsStrictOrderedRing ← synthInstanceQ q(IsStrictOrderedRing $Ξ±) assertInstancesCommute have z : Q(β„•) := mkRawNatLit (⌈qβŒ‰β‚Š) letI : $z =Q ⌈($n / $d : NNRat)βŒ‰β‚Š := ⟨⟩ return .isNat q(inferInstance) z q(IsNNRat.natCeil _ $n $d $h $z rfl) | .isNegNNRat _ q n d h => do let instField ← synthInstanceQ q(Field $Ξ±) let instLinearOrder ← synthInstanceQ q(LinearOrder $Ξ±) let instIsStrictOrderedRing ← synthInstanceQ q(IsStrictOrderedRing $Ξ±) assertInstancesCommute return .isNat q(inferInstance) (mkRawNatLit 0) q(IsRat.natCeil _ _ _ $h) | _, _, _ => failure end Mathlib.Meta.NormNum
.lake/packages/mathlib/Mathlib/Data/NNRat/BigOperators.lean
import Mathlib.Algebra.Order.BigOperators.Ring.Finset import Mathlib.Data.NNRat.Defs /-! # Casting lemmas for non-negative rational numbers involving sums and products -/ variable {Ξ± : Type*} namespace NNRat section DivisionSemiring variable {K : Type*} [DivisionSemiring K] [CharZero K] @[norm_cast] theorem cast_listSum (l : List β„šβ‰₯0) : (l.sum : K) = (l.map (↑)).sum := map_list_sum (castHom _) _ @[deprecated (since := "2025-06-30")] alias coe_list_sum := cast_listSum @[norm_cast] theorem cast_listProd (l : List β„šβ‰₯0) : (l.prod : K) = (l.map (↑)).prod := map_list_prod (castHom _) _ @[deprecated (since := "2025-06-30")] alias coe_list_prod := cast_listProd @[norm_cast] theorem cast_multisetSum (s : Multiset β„šβ‰₯0) : (s.sum : K) = (s.map (↑)).sum := map_multiset_sum (castHom _) _ @[deprecated (since := "2025-06-30")] alias coe_multiset_sum := cast_multisetSum @[norm_cast] theorem cast_sum (s : Finset Ξ±) (f : Ξ± β†’ β„šβ‰₯0) : ↑(βˆ‘ a ∈ s, f a) = βˆ‘ a ∈ s, (f a : K) := map_sum (castHom _) _ _ @[deprecated (since := "2025-06-30")] alias coe_sum := cast_sum end DivisionSemiring section Semifield variable {K : Type*} [Semifield K] [CharZero K] @[norm_cast] theorem cast_multisetProd (s : Multiset β„šβ‰₯0) : (s.prod : K) = (s.map (↑)).prod := map_multiset_prod (castHom _) _ @[deprecated (since := "2025-06-30")] alias coe_multiset_prod := cast_multisetProd @[norm_cast] theorem cast_prod (s : Finset Ξ±) (f : Ξ± β†’ β„šβ‰₯0) : ↑(∏ a ∈ s, f a) = ∏ a ∈ s, (f a : K) := map_prod (castHom _) _ _ @[deprecated (since := "2025-06-30")] alias coe_prod := cast_prod end Semifield section Rat theorem toNNRat_sum_of_nonneg {s : Finset Ξ±} {f : Ξ± β†’ β„š} (hf : βˆ€ a, a ∈ s β†’ 0 ≀ f a) : (βˆ‘ a ∈ s, f a).toNNRat = βˆ‘ a ∈ s, (f a).toNNRat := by rw [← coe_inj, cast_sum, Rat.coe_toNNRat _ (Finset.sum_nonneg hf)] exact Finset.sum_congr rfl fun x hxs ↦ by rw [Rat.coe_toNNRat _ (hf x hxs)] theorem toNNRat_prod_of_nonneg {s : Finset Ξ±} {f : Ξ± β†’ β„š} (hf : βˆ€ a ∈ s, 0 ≀ f a) : (∏ a ∈ s, f a).toNNRat = ∏ a ∈ s, (f a).toNNRat := by rw [← coe_inj, cast_prod, Rat.coe_toNNRat _ (Finset.prod_nonneg hf)] exact Finset.prod_congr rfl fun x hxs ↦ by rw [Rat.coe_toNNRat _ (hf x hxs)] end Rat end NNRat
.lake/packages/mathlib/Mathlib/Data/Nat/ModEq.lean
import Mathlib.Algebra.Order.Group.Unbundled.Int import Mathlib.Algebra.Ring.Nat import Mathlib.Data.Int.GCD import Mathlib.Data.Nat.GCD.Basic /-! # Congruences modulo a natural number This file defines the equivalence relation `a ≑ b [MOD n]` on the natural numbers, and proves basic properties about it such as the Chinese Remainder Theorem `modEq_and_modEq_iff_modEq_mul`. ## Notation `a ≑ b [MOD n]` is notation for `Nat.ModEq n a b`, which is defined to mean `a % n = b % n`. ## Tags ModEq, congruence, mod, MOD, modulo -/ assert_not_exists IsOrderedMonoid Function.support namespace Nat /-- Modular equality. `n.ModEq a b`, or `a ≑ b [MOD n]`, means that `a % n = b % n`. -/ def ModEq (n a b : β„•) := a % n = b % n @[inherit_doc] notation:50 a " ≑ " b " [MOD " n "]" => ModEq n a b variable {m n a b c d : β„•} -- Since `ModEq` is semi-reducible, we need to provide the decidable instance manually instance : Decidable (ModEq n a b) := inferInstanceAs <| Decidable (a % n = b % n) namespace ModEq @[refl] protected theorem refl (a : β„•) : a ≑ a [MOD n] := rfl protected theorem rfl : a ≑ a [MOD n] := ModEq.refl _ instance : IsRefl _ (ModEq n) := ⟨ModEq.refl⟩ @[symm] protected theorem symm : a ≑ b [MOD n] β†’ b ≑ a [MOD n] := Eq.symm @[trans] protected theorem trans : a ≑ b [MOD n] β†’ b ≑ c [MOD n] β†’ a ≑ c [MOD n] := Eq.trans instance : Trans (ModEq n) (ModEq n) (ModEq n) where trans := Nat.ModEq.trans protected theorem comm : a ≑ b [MOD n] ↔ b ≑ a [MOD n] := ⟨ModEq.symm, ModEq.symm⟩ end ModEq theorem modEq_zero_iff_dvd : a ≑ 0 [MOD n] ↔ n ∣ a := by rw [ModEq, zero_mod, dvd_iff_mod_eq_zero] theorem _root_.Dvd.dvd.modEq_zero_nat (h : n ∣ a) : a ≑ 0 [MOD n] := modEq_zero_iff_dvd.2 h theorem _root_.Dvd.dvd.zero_modEq_nat (h : n ∣ a) : 0 ≑ a [MOD n] := h.modEq_zero_nat.symm theorem modEq_iff_dvd : a ≑ b [MOD n] ↔ (n : β„€) ∣ b - a := by rw [ModEq, eq_comm, ← Int.natCast_inj, Int.natCast_mod, Int.natCast_mod, Int.emod_eq_emod_iff_emod_sub_eq_zero, Int.dvd_iff_emod_eq_zero] alias ⟨ModEq.dvd, modEq_of_dvd⟩ := modEq_iff_dvd /-- A variant of `modEq_iff_dvd` with `Nat` divisibility -/ theorem modEq_iff_dvd' (h : a ≀ b) : a ≑ b [MOD n] ↔ n ∣ b - a := by rw [modEq_iff_dvd, ← Int.natCast_dvd_natCast, Int.ofNat_sub h] theorem mod_modEq (a n) : a % n ≑ a [MOD n] := mod_mod _ _ namespace ModEq theorem modulus_mul_add : m * a + b ≑ b [MOD m] := by simp [Nat.ModEq] @[deprecated (since := "2025-10-16")] alias self_mul_add := modulus_mul_add lemma of_dvd (d : m ∣ n) (h : a ≑ b [MOD n]) : a ≑ b [MOD m] := modEq_of_dvd <| Int.ofNat_dvd.mpr d |>.trans h.dvd protected theorem mul_left' (c : β„•) (h : a ≑ b [MOD n]) : c * a ≑ c * b [MOD c * n] := by unfold ModEq at *; rw [mul_mod_mul_left, mul_mod_mul_left, h] protected theorem mul_left (c : β„•) (h : a ≑ b [MOD n]) : c * a ≑ c * b [MOD n] := (h.mul_left' _).of_dvd (dvd_mul_left _ _) protected theorem mul_right' (c : β„•) (h : a ≑ b [MOD n]) : a * c ≑ b * c [MOD n * c] := by rw [mul_comm a, mul_comm b, mul_comm n]; exact h.mul_left' c protected theorem mul_right (c : β„•) (h : a ≑ b [MOD n]) : a * c ≑ b * c [MOD n] := by rw [mul_comm a, mul_comm b]; exact h.mul_left c @[gcongr] protected theorem mul (h₁ : a ≑ b [MOD n]) (hβ‚‚ : c ≑ d [MOD n]) : a * c ≑ b * d [MOD n] := (hβ‚‚.mul_left _).trans (h₁.mul_right _) @[gcongr] protected theorem pow (m : β„•) (h : a ≑ b [MOD n]) : a ^ m ≑ b ^ m [MOD n] := by induction m with | zero => rfl | succ d hd => rw [Nat.pow_succ, Nat.pow_succ] exact hd.mul h @[gcongr] protected theorem add (h₁ : a ≑ b [MOD n]) (hβ‚‚ : c ≑ d [MOD n]) : a + c ≑ b + d [MOD n] := by rw [modEq_iff_dvd, Int.natCast_add, Int.natCast_add, add_sub_add_comm] exact Int.dvd_add h₁.dvd hβ‚‚.dvd protected theorem add_left (c : β„•) (h : a ≑ b [MOD n]) : c + a ≑ c + b [MOD n] := ModEq.rfl.add h protected theorem add_right (c : β„•) (h : a ≑ b [MOD n]) : a + c ≑ b + c [MOD n] := h.add ModEq.rfl protected theorem add_left_cancel (h₁ : a ≑ b [MOD n]) (hβ‚‚ : a + c ≑ b + d [MOD n]) : c ≑ d [MOD n] := by simp only [modEq_iff_dvd, Int.natCast_add] at * rw [add_sub_add_comm] at hβ‚‚ convert Int.dvd_sub hβ‚‚ h₁ using 1 rw [add_sub_cancel_left] protected theorem add_left_cancel' (c : β„•) (h : c + a ≑ c + b [MOD n]) : a ≑ b [MOD n] := ModEq.rfl.add_left_cancel h @[simp] protected theorem add_iff_left (h : a ≑ b [MOD n]) : a + c ≑ b + d [MOD n] ↔ c ≑ d [MOD n] := ⟨h.add_left_cancel, h.add⟩ protected theorem add_right_cancel (h₁ : c ≑ d [MOD n]) (hβ‚‚ : a + c ≑ b + d [MOD n]) : a ≑ b [MOD n] := by rw [add_comm a, add_comm b] at hβ‚‚ exact h₁.add_left_cancel hβ‚‚ protected theorem add_right_cancel' (c : β„•) (h : a + c ≑ b + c [MOD n]) : a ≑ b [MOD n] := ModEq.rfl.add_right_cancel h @[simp] protected theorem add_iff_right (h : c ≑ d [MOD n]) : a + c ≑ b + d [MOD n] ↔ a ≑ b [MOD n] := ⟨h.add_right_cancel, (.add Β· h)⟩ protected lemma sub' (h : c ≀ a ↔ d ≀ b) (hab : a ≑ b [MOD n]) (hcd : c ≑ d [MOD n]) : a - c ≑ b - d [MOD n] := by obtain hac | hca := lt_or_ge a c Β· rw [Nat.sub_eq_zero_of_le hac.le, Nat.sub_eq_zero_of_le ((lt_iff_lt_of_le_iff_le h).1 hac).le] rw [modEq_iff_dvd, Int.natCast_sub hca, Int.natCast_sub <| h.1 hca, sub_sub_sub_comm] exact Int.dvd_sub hab.dvd hcd.dvd protected lemma sub_left' (h : b ≀ a ↔ c ≀ a) (hbc : b ≑ c [MOD n]) : a - b ≑ a - c [MOD n] := .sub' h .rfl hbc protected lemma sub_right' (h : a ≀ b ↔ a ≀ c) (hbc : b ≑ c [MOD n]) : b - a ≑ c - a [MOD n] := .sub' h hbc .rfl @[gcongr] protected lemma sub (hca : c ≀ a) (hdb : d ≀ b) (hab : a ≑ b [MOD n]) (hcd : c ≑ d [MOD n]) : a - c ≑ b - d [MOD n] := .sub' (iff_of_true hca hdb) hab hcd @[gcongr] protected lemma sub_left (hba : b ≀ a) (hca : c ≀ a) (hbc : b ≑ c [MOD n]) : a - b ≑ a - c [MOD n] := .sub hba hca .rfl hbc @[gcongr] protected lemma sub_right (hab : a ≀ b) (hac : a ≀ c) (hbc : b ≑ c [MOD n]) : b - a ≑ c - a [MOD n] := .sub hab hac hbc .rfl /-- Cancel left multiplication on both sides of the `≑` and in the modulus. For cancelling left multiplication in the modulus, see `Nat.ModEq.of_mul_left`. -/ protected theorem mul_left_cancel' {a b c m : β„•} (hc : c β‰  0) : c * a ≑ c * b [MOD c * m] β†’ a ≑ b [MOD m] := by simp only [modEq_iff_dvd, Int.natCast_mul, ← Int.mul_sub] exact fun h => (Int.dvd_of_mul_dvd_mul_left (Int.ofNat_ne_zero.mpr hc) h) protected theorem mul_left_cancel_iff' {a b c m : β„•} (hc : c β‰  0) : c * a ≑ c * b [MOD c * m] ↔ a ≑ b [MOD m] := ⟨ModEq.mul_left_cancel' hc, ModEq.mul_left' _⟩ /-- Cancel right multiplication on both sides of the `≑` and in the modulus. For cancelling right multiplication in the modulus, see `Nat.ModEq.of_mul_right`. -/ protected theorem mul_right_cancel' {a b c m : β„•} (hc : c β‰  0) : a * c ≑ b * c [MOD m * c] β†’ a ≑ b [MOD m] := by simp only [modEq_iff_dvd, Int.natCast_mul, ← Int.sub_mul] exact fun h => (Int.dvd_of_mul_dvd_mul_right (Int.ofNat_ne_zero.mpr hc) h) protected theorem mul_right_cancel_iff' {a b c m : β„•} (hc : c β‰  0) : a * c ≑ b * c [MOD m * c] ↔ a ≑ b [MOD m] := ⟨ModEq.mul_right_cancel' hc, ModEq.mul_right' _⟩ /-- Cancel left multiplication in the modulus. For cancelling left multiplication on both sides of the `≑`, see `nat.modeq.mul_left_cancel'`. -/ lemma of_mul_left (m : β„•) (h : a ≑ b [MOD m * n]) : a ≑ b [MOD n] := by rw [modEq_iff_dvd] at * exact (dvd_mul_left (n : β„€) (m : β„€)).trans h /-- Cancel right multiplication in the modulus. For cancelling right multiplication on both sides of the `≑`, see `nat.modeq.mul_right_cancel'`. -/ lemma of_mul_right (m : β„•) : a ≑ b [MOD n * m] β†’ a ≑ b [MOD n] := mul_comm m n β–Έ of_mul_left _ theorem of_div (h : a / c ≑ b / c [MOD m / c]) (ha : c ∣ a) (ha : c ∣ b) (ha : c ∣ m) : a ≑ b [MOD m] := by convert h.mul_left' c <;> rwa [Nat.mul_div_cancel'] end ModEq @[simp] theorem modulus_modEq_zero : n ≑ 0 [MOD n] := by simp [ModEq] @[simp] theorem add_modEq_left_iff : a + b ≑ a [MOD n] ↔ n ∣ b := by simp [modEq_iff_dvd, Int.natCast_dvd_natCast] @[simp] theorem add_modEq_right_iff : a + b ≑ b [MOD n] ↔ n ∣ a := by rw [add_comm, add_modEq_left_iff] @[simp] theorem left_modEq_add_iff : a ≑ a + b [MOD n] ↔ n ∣ b := by rw [ModEq.comm, add_modEq_left_iff] @[simp] theorem right_modEq_add_iff : b ≑ a + b [MOD n] ↔ n ∣ a := by rw [ModEq.comm, add_modEq_right_iff] @[simp] theorem add_modulus_modEq_iff : a + n ≑ b [MOD n] ↔ a ≑ b [MOD n] := by simp [ModEq] @[simp] theorem modulus_add_modEq_iff : n + a ≑ b [MOD n] ↔ a ≑ b [MOD n] := by rw [add_comm, add_modulus_modEq_iff] @[simp] theorem modEq_add_modulus_iff : a ≑ b + n [MOD n] ↔ a ≑ b [MOD n] := by simp [ModEq] @[simp] theorem modEq_modulus_add_iff : a ≑ n + b [MOD n] ↔ a ≑ b [MOD n] := by simp [ModEq] @[simp] theorem add_mul_modulus_modEq_iff : a + b * n ≑ c [MOD n] ↔ a ≑ c [MOD n] := by simp [ModEq] @[simp] theorem mul_modulus_add_modEq_iff : b * n + a ≑ c [MOD n] ↔ a ≑ c [MOD n] := by rw [add_comm, add_mul_modulus_modEq_iff] @[simp] theorem modEq_add_mul_modulus_iff : a ≑ b + c * n [MOD n] ↔ a ≑ b [MOD n] := by simp [ModEq] @[simp] theorem modEq_mul_modulus_add_iff : a ≑ b * n + c [MOD n] ↔ a ≑ c [MOD n] := by rw [add_comm, modEq_add_mul_modulus_iff] @[simp] theorem add_modulus_mul_modEq_iff : a + n * b ≑ c [MOD n] ↔ a ≑ c [MOD n] := by simp [ModEq] @[simp] theorem modulus_mul_add_modEq_iff : n * b + a ≑ c [MOD n] ↔ a ≑ c [MOD n] := by rw [add_comm, add_modulus_mul_modEq_iff] @[simp] theorem modEq_add_modulus_mul_iff : a ≑ b + n * c [MOD n] ↔ a ≑ b [MOD n] := by simp [ModEq] @[simp] theorem modEq_modulus_mul_add_iff : a ≑ n * b + c [MOD n] ↔ a ≑ c [MOD n] := by rw [add_comm, modEq_add_modulus_mul_iff] @[simp] theorem sub_modulus_modEq_iff (h : n ≀ a) : a - n ≑ b [MOD n] ↔ a ≑ b [MOD n] := by rw [← add_modulus_modEq_iff, Nat.sub_add_cancel h] @[simp] theorem modEq_sub_modulus_iff (h : n ≀ b) : a ≑ b - n [MOD n] ↔ a ≑ b [MOD n] := by rw [← modEq_add_modulus_iff, Nat.sub_add_cancel h] lemma modEq_sub (h : b ≀ a) : a ≑ b [MOD a - b] := (modEq_of_dvd <| by rw [Int.ofNat_sub h]).symm lemma modEq_one : a ≑ b [MOD 1] := modEq_of_dvd <| one_dvd _ @[simp] lemma modEq_zero_iff : a ≑ b [MOD 0] ↔ a = b := by rw [ModEq, mod_zero, mod_zero] lemma add_modEq_left : n + a ≑ a [MOD n] := by simp lemma add_modEq_right : a + n ≑ a [MOD n] := by simp namespace ModEq theorem le_of_lt_add (h1 : a ≑ b [MOD m]) (h2 : a < b + m) : a ≀ b := (le_total a b).elim id fun h3 => Nat.le_of_sub_eq_zero (eq_zero_of_dvd_of_lt ((modEq_iff_dvd' h3).mp h1.symm) (by cutsat)) theorem add_le_of_lt (h1 : a ≑ b [MOD m]) (h2 : a < b) : a + m ≀ b := le_of_lt_add (add_modEq_right.trans h1) (by cutsat) theorem dvd_iff (h : a ≑ b [MOD m]) (hdm : d ∣ m) : d ∣ a ↔ d ∣ b := by simp only [← modEq_zero_iff_dvd] replace h := h.of_dvd hdm exact ⟨h.symm.trans, h.trans⟩ theorem gcd_eq (h : a ≑ b [MOD m]) : gcd a m = gcd b m := by have h1 := gcd_dvd_right a m have h2 := gcd_dvd_right b m exact dvd_antisymm (dvd_gcd ((h.dvd_iff h1).mp (gcd_dvd_left a m)) h1) (dvd_gcd ((h.dvd_iff h2).mpr (gcd_dvd_left b m)) h2) lemma eq_of_abs_lt (h : a ≑ b [MOD m]) (h2 : |(b : β„€) - a| < m) : a = b := by apply Int.ofNat.inj rw [eq_comm, ← sub_eq_zero] exact Int.eq_zero_of_abs_lt_dvd h.dvd h2 lemma eq_of_lt_of_lt (h : a ≑ b [MOD m]) (ha : a < m) (hb : b < m) : a = b := h.eq_of_abs_lt <| Int.abs_sub_lt_of_lt_lt ha hb /-- To cancel a common factor `c` from a `ModEq` we must divide the modulus `m` by `gcd m c` -/ lemma cancel_left_div_gcd (hm : 0 < m) (h : c * a ≑ c * b [MOD m]) : a ≑ b [MOD m / gcd m c] := by let d := gcd m c have hmd := gcd_dvd_left m c have hcd := gcd_dvd_right m c rw [modEq_iff_dvd] refine @Int.dvd_of_dvd_mul_right_of_gcd_one (m / d) (c / d) (b - a) ?_ ?_ Β· show (m / d : β„€) ∣ c / d * (b - a) rw [mul_comm, ← Int.mul_ediv_assoc (b - a) (Int.natCast_dvd_natCast.mpr hcd), mul_comm] apply Int.ediv_dvd_ediv (Int.natCast_dvd_natCast.mpr hmd) rw [Int.mul_sub] exact modEq_iff_dvd.mp h Β· show Int.gcd (m / d) (c / d) = 1 simp only [d, ← Int.natCast_div, Int.gcd_natCast_natCast (m / d) (c / d), gcd_div hmd hcd, Nat.div_self (gcd_pos_of_pos_left c hm)] /-- To cancel a common factor `c` from a `ModEq` we must divide the modulus `m` by `gcd m c` -/ lemma cancel_right_div_gcd (hm : 0 < m) (h : a * c ≑ b * c [MOD m]) : a ≑ b [MOD m / gcd m c] := by apply cancel_left_div_gcd hm simpa [mul_comm] using h lemma cancel_left_div_gcd' (hm : 0 < m) (hcd : c ≑ d [MOD m]) (h : c * a ≑ d * b [MOD m]) : a ≑ b [MOD m / gcd m c] := (h.trans <| hcd.symm.mul_right b).cancel_left_div_gcd hm lemma cancel_right_div_gcd' (hm : 0 < m) (hcd : c ≑ d [MOD m]) (h : a * c ≑ b * d [MOD m]) : a ≑ b [MOD m / gcd m c] := (h.trans <| hcd.symm.mul_left b).cancel_right_div_gcd hm /-- A common factor that's coprime with the modulus can be cancelled from a `ModEq` -/ lemma cancel_left_of_coprime (hmc : gcd m c = 1) (h : c * a ≑ c * b [MOD m]) : a ≑ b [MOD m] := by rcases m.eq_zero_or_pos with (rfl | hm) Β· simp only [gcd_zero_left] at hmc simp only [hmc, one_mul, modEq_zero_iff] at h subst h rfl simpa [hmc] using h.cancel_left_div_gcd hm /-- A common factor that's coprime with the modulus can be cancelled from a `ModEq` -/ lemma cancel_right_of_coprime (hmc : gcd m c = 1) (h : a * c ≑ b * c [MOD m]) : a ≑ b [MOD m] := cancel_left_of_coprime hmc <| by simpa [mul_comm] using h end ModEq /-- The natural number less than `lcm n m` congruent to `a` mod `n` and `b` mod `m` -/ def chineseRemainder' (h : a ≑ b [MOD gcd n m]) : { k // k ≑ a [MOD n] ∧ k ≑ b [MOD m] } := if hn : n = 0 then ⟨a, by rw [hn, gcd_zero_left] at h; constructor Β· rfl Β· exact h⟩ else if hm : m = 0 then ⟨b, by rw [hm, gcd_zero_right] at h; constructor Β· exact h.symm Β· rfl⟩ else ⟨let (c, d) := xgcd n m; Int.toNat ((n * c * b + m * d * a) / gcd n m % lcm n m), by rw [xgcd_val] dsimp rw [modEq_iff_dvd, modEq_iff_dvd, Int.toNat_of_nonneg (Int.emod_nonneg _ (Int.natCast_ne_zero.2 (lcm_ne_zero hn hm)))] have hnonzero : (gcd n m : β„€) β‰  0 := by norm_cast rw [Nat.gcd_eq_zero_iff, not_and] exact fun _ => hm have hcoedvd : βˆ€ t, (gcd n m : β„€) ∣ t * (b - a) := fun t => h.dvd.mul_left _ have := gcd_eq_gcd_ab n m constructor <;> rw [Int.emod_def, ← sub_add] <;> refine Int.dvd_add ?_ (dvd_mul_of_dvd_left ?_ _) <;> try norm_cast Β· rw [← sub_eq_iff_eq_add'] at this rw [← this, Int.sub_mul, ← add_sub_assoc, add_comm, add_sub_assoc, ← Int.mul_sub, Int.add_ediv_of_dvd_left, Int.mul_ediv_cancel_left _ hnonzero, Int.mul_ediv_assoc _ h.dvd, ← sub_sub, sub_self, zero_sub, Int.dvd_neg, mul_assoc] Β· exact dvd_mul_right _ _ norm_cast exact dvd_mul_right _ _ Β· exact dvd_lcm_left n m Β· rw [← sub_eq_iff_eq_add] at this rw [← this, Int.sub_mul, sub_add, ← Int.mul_sub, Int.sub_ediv_of_dvd, Int.mul_ediv_cancel_left _ hnonzero, Int.mul_ediv_assoc _ h.dvd, ← sub_add, sub_self, zero_add, mul_assoc] Β· exact dvd_mul_right _ _ Β· exact hcoedvd _ Β· exact dvd_lcm_right n m⟩ /-- The natural number less than `n*m` congruent to `a` mod `n` and `b` mod `m` -/ def chineseRemainder (co : n.Coprime m) (a b : β„•) : { k // k ≑ a [MOD n] ∧ k ≑ b [MOD m] } := chineseRemainder' (by convert @modEq_one a b) theorem chineseRemainder'_lt_lcm (h : a ≑ b [MOD gcd n m]) (hn : n β‰  0) (hm : m β‰  0) : ↑(chineseRemainder' h) < lcm n m := by dsimp only [chineseRemainder'] rw [dif_neg hn, dif_neg hm, Subtype.coe_mk, xgcd_val, ← Int.toNat_natCast (lcm n m)] have lcm_pos := Int.natCast_pos.mpr (Nat.pos_of_ne_zero (lcm_ne_zero hn hm)) exact (Int.toNat_lt_toNat lcm_pos).mpr (Int.emod_lt_of_pos _ lcm_pos) theorem chineseRemainder_lt_mul (co : n.Coprime m) (a b : β„•) (hn : n β‰  0) (hm : m β‰  0) : ↑(chineseRemainder co a b) < n * m := lt_of_lt_of_le (chineseRemainder'_lt_lcm _ hn hm) (le_of_eq co.lcm_eq_mul) theorem mod_lcm (hn : a ≑ b [MOD n]) (hm : a ≑ b [MOD m]) : a ≑ b [MOD lcm n m] := Nat.modEq_iff_dvd.mpr <| Int.coe_lcm_dvd (Nat.modEq_iff_dvd.mp hn) (Nat.modEq_iff_dvd.mp hm) theorem chineseRemainder_modEq_unique (co : n.Coprime m) {a b z} (hzan : z ≑ a [MOD n]) (hzbm : z ≑ b [MOD m]) : z ≑ chineseRemainder co a b [MOD n*m] := by simpa [Nat.Coprime.lcm_eq_mul co] using mod_lcm (hzan.trans ((chineseRemainder co a b).prop.1).symm) (hzbm.trans ((chineseRemainder co a b).prop.2).symm) theorem modEq_and_modEq_iff_modEq_mul {a b m n : β„•} (hmn : m.Coprime n) : a ≑ b [MOD m] ∧ a ≑ b [MOD n] ↔ a ≑ b [MOD m * n] := ⟨fun h => by rw [Nat.modEq_iff_dvd, Nat.modEq_iff_dvd, ← Int.dvd_natAbs, Int.natCast_dvd_natCast, ← Int.dvd_natAbs, Int.natCast_dvd_natCast] at h rw [Nat.modEq_iff_dvd, ← Int.dvd_natAbs, Int.natCast_dvd_natCast] exact hmn.mul_dvd_of_dvd_of_dvd h.1 h.2, fun h => ⟨h.of_mul_right _, h.of_mul_left _⟩⟩ theorem coprime_of_mul_modEq_one (b : β„•) {a n : β„•} (h : a * b ≑ 1 [MOD n]) : a.Coprime n := by obtain ⟨g, hh⟩ := Nat.gcd_dvd_right a n rw [Nat.coprime_iff_gcd_eq_one, ← Nat.dvd_one, ← Nat.modEq_zero_iff_dvd] calc 1 ≑ a * b [MOD a.gcd n] := (hh β–Έ h).symm.of_mul_right g _ ≑ 0 * b [MOD a.gcd n] := (Nat.modEq_zero_iff_dvd.mpr (Nat.gcd_dvd_left _ _)).mul_right b _ = 0 := by rw [zero_mul] theorem add_mod_add_ite (a b c : β„•) : ((a + b) % c + if c ≀ a % c + b % c then c else 0) = a % c + b % c := have : (a + b) % c = (a % c + b % c) % c := ((mod_modEq _ _).add <| mod_modEq _ _).symm if hc0 : c = 0 then by simp [hc0, Nat.mod_zero] else by rw [this] split_ifs with h Β· have h2 : (a % c + b % c) / c < 2 := Nat.div_lt_of_lt_mul (by rw [mul_two] exact add_lt_add (Nat.mod_lt _ (Nat.pos_of_ne_zero hc0)) (Nat.mod_lt _ (Nat.pos_of_ne_zero hc0))) have h0 : 0 < (a % c + b % c) / c := Nat.div_pos h (Nat.pos_of_ne_zero hc0) rw [← @add_right_cancel_iff _ _ _ (c * ((a % c + b % c) / c)), add_comm _ c, add_assoc, mod_add_div, le_antisymm (le_of_lt_succ h2) h0, mul_one, add_comm] Β· rw [Nat.mod_eq_of_lt (lt_of_not_ge h), add_zero] theorem add_mod_of_add_mod_lt {a b c : β„•} (hc : a % c + b % c < c) : (a + b) % c = a % c + b % c := by rw [← add_mod_add_ite, if_neg (not_le_of_gt hc), add_zero] theorem add_mod_add_of_le_add_mod {a b c : β„•} (hc : c ≀ a % c + b % c) : (a + b) % c + c = a % c + b % c := by rw [← add_mod_add_ite, if_pos hc] theorem add_div_eq_of_add_mod_lt {a b c : β„•} (hc : a % c + b % c < c) : (a + b) / c = a / c + b / c := if hc0 : c = 0 then by simp [hc0] else by rw [Nat.add_div (Nat.pos_of_ne_zero hc0), if_neg (not_le_of_gt hc), add_zero] protected theorem add_div_of_dvd_right {a b c : β„•} (hca : c ∣ a) : (a + b) / c = a / c + b / c := if h : c = 0 then by simp [h] else add_div_eq_of_add_mod_lt (by rw [Nat.mod_eq_zero_of_dvd hca, zero_add] exact Nat.mod_lt _ (zero_lt_of_ne_zero h)) protected theorem add_div_of_dvd_left {a b c : β„•} (hca : c ∣ b) : (a + b) / c = a / c + b / c := by rwa [add_comm, Nat.add_div_of_dvd_right, add_comm] theorem add_div_eq_of_le_mod_add_mod {a b c : β„•} (hc : c ≀ a % c + b % c) (hc0 : 0 < c) : (a + b) / c = a / c + b / c + 1 := by rw [Nat.add_div hc0, if_pos hc] theorem add_div_le_add_div (a b c : β„•) : a / c + b / c ≀ (a + b) / c := if hc0 : c = 0 then by simp [hc0] else by rw [Nat.add_div (Nat.pos_of_ne_zero hc0)]; exact Nat.le_add_right _ _ theorem le_mod_add_mod_of_dvd_add_of_not_dvd {a b c : β„•} (h : c ∣ a + b) (ha : Β¬c ∣ a) : c ≀ a % c + b % c := by_contradiction fun hc => by have : (a + b) % c = a % c + b % c := add_mod_of_add_mod_lt (lt_of_not_ge hc) simp_all [dvd_iff_mod_eq_zero] lemma mod_sub_of_le {a b n : β„•} (h : b ≀ a % n) : a % n - b = (a - b) % n := by rcases n.eq_zero_or_pos with rfl | hn; Β· simp only [mod_zero] nth_rw 2 [← div_add_mod a n]; rw [Nat.add_sub_assoc h, mul_add_mod] exact (mod_eq_of_lt <| (sub_le ..).trans_lt (mod_lt a hn)).symm theorem odd_mul_odd {n m : β„•} : n % 2 = 1 β†’ m % 2 = 1 β†’ n * m % 2 = 1 := by simpa [Nat.ModEq] using @ModEq.mul 2 n 1 m 1 theorem odd_mul_odd_div_two {m n : β„•} (hm1 : m % 2 = 1) (hn1 : n % 2 = 1) : m * n / 2 = m * (n / 2) + m / 2 := have hn0 : 0 < n := Nat.pos_of_ne_zero fun h => by simp_all mul_right_injectiveβ‚€ two_ne_zero <| by dsimp rw [mul_add, two_mul_odd_div_two hm1, mul_left_comm, two_mul_odd_div_two hn1, two_mul_odd_div_two (Nat.odd_mul_odd hm1 hn1), Nat.mul_sub, mul_one, ← Nat.add_sub_assoc (by cutsat), Nat.sub_add_cancel (Nat.le_mul_of_pos_right m hn0)] theorem odd_of_mod_four_eq_one {n : β„•} : n % 4 = 1 β†’ n % 2 = 1 := by simpa [ModEq] using @ModEq.of_mul_left 2 n 1 2 theorem odd_of_mod_four_eq_three {n : β„•} : n % 4 = 3 β†’ n % 2 = 1 := by simpa [ModEq] using @ModEq.of_mul_left 2 n 3 2 /-- A natural number is odd iff it has residue `1` or `3` mod `4`. -/ theorem odd_mod_four_iff {n : β„•} : n % 2 = 1 ↔ n % 4 = 1 ∨ n % 4 = 3 := have help : βˆ€ m : β„•, m < 4 β†’ m % 2 = 1 β†’ m = 1 ∨ m = 3 := by decide ⟨fun hn => help (n % 4) (mod_lt n (by cutsat)) <| (mod_mod_of_dvd n (by decide : 2 ∣ 4)).trans hn, fun h => Or.elim h odd_of_mod_four_eq_one odd_of_mod_four_eq_three⟩ lemma mod_eq_of_modEq {a b n} (h : a ≑ b [MOD n]) (hb : b < n) : a % n = b := Eq.trans h (mod_eq_of_lt hb) end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Nth.lean
import Mathlib.Data.List.GetD import Mathlib.Data.Nat.Count import Mathlib.Data.Nat.SuccPred import Mathlib.Order.Interval.Set.Monotone import Mathlib.Order.OrderIsoNat import Mathlib.Order.WellFounded import Mathlib.Data.Finset.Sort /-! # The `n`th Number Satisfying a Predicate This file defines a function for "what is the `n`th number that satisfies a given predicate `p`", and provides lemmas that deal with this function and its connection to `Nat.count`. ## Main definitions * `Nat.nth p n`: The `n`-th natural `k` (zero-indexed) such that `p k`. If there is no such natural (that is, `p` is true for at most `n` naturals), then `Nat.nth p n = 0`. ## Main results * `Nat.nth_eq_orderEmbOfFin`: For a finitely-often true `p`, gives the cardinality of the set of numbers satisfying `p` above particular values of `nth p` * `Nat.gc_count_nth`: Establishes a Galois connection between `Nat.nth p` and `Nat.count p`. * `Nat.nth_eq_orderIsoOfNat`: For an infinitely-often true predicate, `nth` agrees with the order-isomorphism of the subtype to the natural numbers. ## Implementation details Much of the below was written before `Set.encard` existed and partly for this reason uses the pattern `βˆ€ hf : Set.Finite (setOf p), n < hf.toFinset.card` rather than `n < {x | p x}.encard`. We should consider changing this. There has been some discussion on the subject of whether both of `nth` and `Nat.Subtype.orderIsoOfNat` should exist. See discussion [here](https://github.com/leanprover-community/mathlib/pull/9457#pullrequestreview-767221180). Future work should address how lemmas that use these should be written. -/ open Finset namespace Nat variable (p : β„• β†’ Prop) /-- Find the `n`-th natural number satisfying `p` (indexed from `0`, so `nth p 0` is the first natural number satisfying `p`), or `0` if there is no such number. See also `Subtype.orderIsoOfNat` for the order isomorphism with β„• when `p` is infinitely often true. -/ noncomputable def nth (p : β„• β†’ Prop) (n : β„•) : β„• := by classical exact if h : Set.Finite (setOf p) then h.toFinset.sort.getD n 0 else @Nat.Subtype.orderIsoOfNat (setOf p) (Set.Infinite.to_subtype h) n variable {p} /-! ### Lemmas about `Nat.nth` on a finite set -/ theorem nth_of_card_le (hf : (setOf p).Finite) {n : β„•} (hn : #hf.toFinset ≀ n) : nth p n = 0 := by rw [nth, dif_pos hf, List.getD_eq_default]; rwa [Finset.length_sort] theorem nth_eq_getD_sort (h : (setOf p).Finite) (n : β„•) : nth p n = h.toFinset.sort.getD n 0 := dif_pos h theorem nth_eq_orderEmbOfFin (hf : (setOf p).Finite) {n : β„•} (hn : n < #hf.toFinset) : nth p n = hf.toFinset.orderEmbOfFin rfl ⟨n, hn⟩ := by rw [nth_eq_getD_sort hf, Finset.orderEmbOfFin_apply, List.getD_eq_getElem, Fin.getElem_fin] theorem nth_strictMonoOn (hf : (setOf p).Finite) : StrictMonoOn (nth p) (Set.Iio #hf.toFinset) := by rintro m (hm : m < _) n (hn : n < _) h simp only [nth_eq_orderEmbOfFin, *] exact OrderEmbedding.strictMono _ h theorem nth_lt_nth_of_lt_card (hf : (setOf p).Finite) {m n : β„•} (h : m < n) (hn : n < #hf.toFinset) : nth p m < nth p n := nth_strictMonoOn hf (h.trans hn) hn h theorem nth_le_nth_of_lt_card (hf : (setOf p).Finite) {m n : β„•} (h : m ≀ n) (hn : n < #hf.toFinset) : nth p m ≀ nth p n := (nth_strictMonoOn hf).monotoneOn (h.trans_lt hn) hn h theorem lt_of_nth_lt_nth_of_lt_card (hf : (setOf p).Finite) {m n : β„•} (h : nth p m < nth p n) (hm : m < #hf.toFinset) : m < n := not_le.1 fun hle => h.not_ge <| nth_le_nth_of_lt_card hf hle hm theorem le_of_nth_le_nth_of_lt_card (hf : (setOf p).Finite) {m n : β„•} (h : nth p m ≀ nth p n) (hm : m < #hf.toFinset) : m ≀ n := not_lt.1 fun hlt => h.not_gt <| nth_lt_nth_of_lt_card hf hlt hm theorem nth_injOn (hf : (setOf p).Finite) : (Set.Iio #hf.toFinset).InjOn (nth p) := (nth_strictMonoOn hf).injOn theorem range_nth_of_finite (hf : (setOf p).Finite) : Set.range (nth p) = insert 0 (setOf p) := by simpa only [← List.getD_eq_getElem?_getD, ← nth_eq_getD_sort hf, mem_sort, Set.Finite.mem_toFinset] using Set.range_list_getD (hf.toFinset.sort (Β· ≀ Β·)) 0 @[simp] theorem image_nth_Iio_card (hf : (setOf p).Finite) : nth p '' Set.Iio #hf.toFinset = setOf p := calc nth p '' Set.Iio #hf.toFinset = Set.range (hf.toFinset.orderEmbOfFin rfl) := by ext x simp only [Set.mem_image, Set.mem_range, Fin.exists_iff, ← nth_eq_orderEmbOfFin hf, Set.mem_Iio, exists_prop] _ = setOf p := by rw [range_orderEmbOfFin, Set.Finite.coe_toFinset] theorem nth_mem_of_lt_card {n : β„•} (hf : (setOf p).Finite) (hlt : n < #hf.toFinset) : p (nth p n) := (image_nth_Iio_card hf).subset <| Set.mem_image_of_mem _ hlt theorem exists_lt_card_finite_nth_eq (hf : (setOf p).Finite) {x} (h : p x) : βˆƒ n, n < #hf.toFinset ∧ nth p n = x := by rwa [← @Set.mem_setOf_eq _ _ p, ← image_nth_Iio_card hf] at h /-! ### Lemmas about `Nat.nth` on an infinite set -/ /-- When `s` is an infinite set, `nth` agrees with `Nat.Subtype.orderIsoOfNat`. -/ theorem nth_apply_eq_orderIsoOfNat (hf : (setOf p).Infinite) (n : β„•) : nth p n = @Nat.Subtype.orderIsoOfNat (setOf p) hf.to_subtype n := by rw [nth, dif_neg hf] /-- When `s` is an infinite set, `nth` agrees with `Nat.Subtype.orderIsoOfNat`. -/ theorem nth_eq_orderIsoOfNat (hf : (setOf p).Infinite) : nth p = (↑) ∘ @Nat.Subtype.orderIsoOfNat (setOf p) hf.to_subtype := funext <| nth_apply_eq_orderIsoOfNat hf theorem nth_strictMono (hf : (setOf p).Infinite) : StrictMono (nth p) := by rw [nth_eq_orderIsoOfNat hf] exact (Subtype.strictMono_coe _).comp (OrderIso.strictMono _) theorem nth_injective (hf : (setOf p).Infinite) : Function.Injective (nth p) := (nth_strictMono hf).injective theorem nth_monotone (hf : (setOf p).Infinite) : Monotone (nth p) := (nth_strictMono hf).monotone theorem nth_lt_nth (hf : (setOf p).Infinite) {k n} : nth p k < nth p n ↔ k < n := (nth_strictMono hf).lt_iff_lt theorem nth_le_nth (hf : (setOf p).Infinite) {k n} : nth p k ≀ nth p n ↔ k ≀ n := (nth_strictMono hf).le_iff_le theorem range_nth_of_infinite (hf : (setOf p).Infinite) : Set.range (nth p) = setOf p := by rw [nth_eq_orderIsoOfNat hf] haveI := hf.to_subtype classical exact Nat.Subtype.coe_comp_ofNat_range theorem nth_mem_of_infinite (hf : (setOf p).Infinite) (n : β„•) : p (nth p n) := Set.range_subset_iff.1 (range_nth_of_infinite hf).le n /-! ### Lemmas that work for finite and infinite sets -/ theorem exists_lt_card_nth_eq {x} (h : p x) : βˆƒ n, (βˆ€ hf : (setOf p).Finite, n < #hf.toFinset) ∧ nth p n = x := by refine (setOf p).finite_or_infinite.elim (fun hf => ?_) fun hf => ?_ Β· rcases exists_lt_card_finite_nth_eq hf h with ⟨n, hn, hx⟩ exact ⟨n, fun _ => hn, hx⟩ Β· rw [← @Set.mem_setOf_eq _ _ p, ← range_nth_of_infinite hf] at h rcases h with ⟨n, hx⟩ exact ⟨n, fun hf' => absurd hf' hf, hx⟩ theorem subset_range_nth : setOf p βŠ† Set.range (nth p) := fun x (hx : p x) => let ⟨n, _, hn⟩ := exists_lt_card_nth_eq hx ⟨n, hn⟩ theorem range_nth_subset : Set.range (nth p) βŠ† insert 0 (setOf p) := (setOf p).finite_or_infinite.elim (fun h => (range_nth_of_finite h).subset) fun h => (range_nth_of_infinite h).trans_subset (Set.subset_insert _ _) theorem nth_mem (n : β„•) (h : βˆ€ hf : (setOf p).Finite, n < #hf.toFinset) : p (nth p n) := (setOf p).finite_or_infinite.elim (fun hf => nth_mem_of_lt_card hf (h hf)) fun h => nth_mem_of_infinite h n theorem nth_lt_nth' {m n : β„•} (hlt : m < n) (h : βˆ€ hf : (setOf p).Finite, n < #hf.toFinset) : nth p m < nth p n := (setOf p).finite_or_infinite.elim (fun hf => nth_lt_nth_of_lt_card hf hlt (h _)) fun hf => (nth_lt_nth hf).2 hlt theorem nth_le_nth' {m n : β„•} (hle : m ≀ n) (h : βˆ€ hf : (setOf p).Finite, n < #hf.toFinset) : nth p m ≀ nth p n := (setOf p).finite_or_infinite.elim (fun hf => nth_le_nth_of_lt_card hf hle (h _)) fun hf => (nth_le_nth hf).2 hle theorem le_nth {n : β„•} (h : βˆ€ hf : (setOf p).Finite, n < #hf.toFinset) : n ≀ nth p n := (setOf p).finite_or_infinite.elim (fun hf => ((nth_strictMonoOn hf).mono <| Set.Iic_subset_Iio.2 (h _)).Iic_id_le _ le_rfl) fun hf => (nth_strictMono hf).id_le _ theorem isLeast_nth {n} (h : βˆ€ hf : (setOf p).Finite, n < #hf.toFinset) : IsLeast {i | p i ∧ βˆ€ k < n, nth p k < i} (nth p n) := ⟨⟨nth_mem n h, fun _k hk => nth_lt_nth' hk h⟩, fun _x hx => let ⟨k, hk, hkx⟩ := exists_lt_card_nth_eq hx.1 (lt_or_ge k n).elim (fun hlt => absurd hkx (hx.2 _ hlt).ne) fun hle => hkx β–Έ nth_le_nth' hle hk⟩ theorem isLeast_nth_of_lt_card {n : β„•} (hf : (setOf p).Finite) (hn : n < #hf.toFinset) : IsLeast {i | p i ∧ βˆ€ k < n, nth p k < i} (nth p n) := isLeast_nth fun _ => hn theorem isLeast_nth_of_infinite (hf : (setOf p).Infinite) (n : β„•) : IsLeast {i | p i ∧ βˆ€ k < n, nth p k < i} (nth p n) := isLeast_nth fun h => absurd h hf /-- An alternative recursive definition of `Nat.nth`: `Nat.nth s n` is the infimum of `x ∈ s` such that `Nat.nth s k < x` for all `k < n`, if this set is nonempty. We do not assume that the set is nonempty because we use the same "garbage value" `0` both for `sInf` on `β„•` and for `Nat.nth s n` for `n β‰₯ #s`. -/ theorem nth_eq_sInf (p : β„• β†’ Prop) (n : β„•) : nth p n = sInf {x | p x ∧ βˆ€ k < n, nth p k < x} := by by_cases! hn : βˆ€ hf : (setOf p).Finite, n < #hf.toFinset Β· exact (isLeast_nth hn).csInf_eq.symm Β· rcases hn with ⟨hf, hn⟩ rw [nth_of_card_le _ hn] refine ((congr_arg sInf <| Set.eq_empty_of_forall_notMem fun k hk => ?_).trans sInf_empty).symm rcases exists_lt_card_nth_eq hk.1 with ⟨k, hlt, rfl⟩ exact (hk.2 _ ((hlt hf).trans_le hn)).false theorem nth_zero : nth p 0 = sInf (setOf p) := by rw [nth_eq_sInf]; simp @[simp] theorem nth_zero_of_zero (h : p 0) : nth p 0 = 0 := by simp [nth_zero, h] theorem nth_zero_of_exists [DecidablePred p] (h : βˆƒ n, p n) : nth p 0 = Nat.find h := by rw [nth_zero]; convert Nat.sInf_def h theorem nth_eq_zero {n} : nth p n = 0 ↔ p 0 ∧ n = 0 ∨ βˆƒ hf : (setOf p).Finite, #hf.toFinset ≀ n := by refine ⟨fun h => ?_, ?_⟩ Β· simp only [or_iff_not_imp_right, not_exists, not_le] exact fun hn => ⟨h β–Έ nth_mem _ hn, nonpos_iff_eq_zero.1 <| h β–Έ le_nth hn⟩ Β· rintro (⟨hβ‚€, rfl⟩ | ⟨hf, hle⟩) exacts [nth_zero_of_zero hβ‚€, nth_of_card_le hf hle] lemma lt_card_toFinset_of_nth_ne_zero {n : β„•} (h : nth p n β‰  0) (hf : (setOf p).Finite) : n < #hf.toFinset := by simp only [ne_eq, nth_eq_zero, not_or, not_exists, not_le] at h exact h.2 hf lemma nth_mem_of_ne_zero {n : β„•} (h : nth p n β‰  0) : p (Nat.nth p n) := nth_mem n (lt_card_toFinset_of_nth_ne_zero h) theorem nth_eq_zero_mono (hβ‚€ : Β¬p 0) {a b : β„•} (hab : a ≀ b) (ha : nth p a = 0) : nth p b = 0 := by simp only [nth_eq_zero, hβ‚€, false_and, false_or] at ha ⊒ exact ha.imp fun hf hle => hle.trans hab lemma nth_ne_zero_anti (hβ‚€ : Β¬p 0) {a b : β„•} (hab : a ≀ b) (hb : nth p b β‰  0) : nth p a β‰  0 := mt (nth_eq_zero_mono hβ‚€ hab) hb theorem le_nth_of_lt_nth_succ {k a : β„•} (h : a < nth p (k + 1)) (ha : p a) : a ≀ nth p k := by rcases (setOf p).finite_or_infinite with hf | hf Β· rcases exists_lt_card_finite_nth_eq hf ha with ⟨n, hn, rfl⟩ rcases lt_or_ge (k + 1) #hf.toFinset with hk | hk Β· rwa [(nth_strictMonoOn hf).lt_iff_lt hn hk, Nat.lt_succ_iff, ← (nth_strictMonoOn hf).le_iff_le hn (k.lt_succ_self.trans hk)] at h Β· rw [nth_of_card_le _ hk] at h exact absurd h (zero_le _).not_gt Β· rcases subset_range_nth ha with ⟨n, rfl⟩ rwa [nth_lt_nth hf, Nat.lt_succ_iff, ← nth_le_nth hf] at h lemma nth_mem_anti {a b : β„•} (hab : a ≀ b) (h : p (nth p b)) : p (nth p a) := by by_cases h' : βˆ€ hf : (setOf p).Finite, a < #hf.toFinset Β· exact nth_mem a h' Β· simp only [not_forall, not_lt] at h' have h'b : βˆƒ hf : (setOf p).Finite, #hf.toFinset ≀ b := by rcases h' with ⟨hf, ha⟩ exact ⟨hf, ha.trans hab⟩ have ha0 : nth p a = 0 := by simp [nth_eq_zero, h'] have hb0 : nth p b = 0 := by simp [nth_eq_zero, h'b] rw [ha0] rwa [hb0] at h /-- `Nat.nth p` is the least strictly monotone function whose image is contained in `setOf p` -/ lemma nth_le_of_strictMonoOn_of_mapsTo {p : β„• β†’ Prop} (f : β„• β†’ β„•) (hmaps : Set.MapsTo f { n : β„• | βˆ€ hf : Set.Finite (setOf p), n < hf.toFinset.card } (setOf p)) (hmono : StrictMonoOn f { n : β„• | βˆ€ hf : Set.Finite (setOf p), n < hf.toFinset.card }) {n : β„•} : nth p n ≀ f n := by by_cases hn : (βˆ€ hf : Set.Finite (setOf p), n < hf.toFinset.card) Β· induction n using Nat.strong_induction_on with | _ n ih => rw [nth_eq_sInf] refine csInf_le (by simp) ⟨hmaps hn, fun k hk => ?_⟩ have : f k < f n := by apply hmono <;> grind grind Β· push_neg at hn rcases hn with ⟨hf, hn⟩ rw [nth, dif_pos hf, List.getD_eq_default _ _ (by simp [hn])] exact Nat.zero_le _ /-- `Nat.nth p` is the greatest monotone function whose image contains `setOf p`. -/ lemma le_nth_of_monotoneOn_of_surjOn {p : β„• β†’ Prop} (f : β„• β†’ β„•) (hsurj : Set.SurjOn f { n : β„• | βˆ€ hf : Set.Finite (setOf p), n < hf.toFinset.card } (setOf p)) (hmono : MonotoneOn f { n : β„• | βˆ€ hf : Set.Finite (setOf p), n < hf.toFinset.card }) {n : β„•} (hn : βˆ€ hf : Set.Finite (setOf p), n < hf.toFinset.card) : f n ≀ nth p n := by induction n with | zero => rw [Nat.nth_zero] refine le_csInf ⟨_, nth_mem _ hn⟩ fun b hb => ?_ rcases hsurj hb with ⟨k, hk, rfl⟩ exact hmono hn hk (Nat.zero_le _) | succ n ih => rw [nth_eq_sInf] refine le_csInf ?_ ?_ Β· use nth p (n + 1), nth_mem _ hn exact fun k hk => nth_lt_nth' hk hn rintro b ⟨hb, h⟩ rcases hsurj hb with ⟨m, hm, rfl⟩ apply hmono hn hm rw [Nat.succ_le] apply hmono.reflect_lt <;> grind /-- `Nat.nth p` is the unique strictly monotone function whose image is `setOf p`. -/ lemma eq_nth_of_strictMonoOn_of_mapsTo_of_surjOn {p : β„• β†’ Prop} (f : β„• β†’ β„•) (hsurj : Set.SurjOn f { n : β„• | βˆ€ hf : Set.Finite (setOf p), n < hf.toFinset.card } (setOf p)) (hmaps : Set.MapsTo f { n : β„• | βˆ€ hf : Set.Finite (setOf p), n < hf.toFinset.card } (setOf p)) (hmono : StrictMonoOn f { n : β„• | βˆ€ hf : Set.Finite (setOf p), n < hf.toFinset.card }) : Set.EqOn f (nth p) { n : β„• | βˆ€ hf : Set.Finite (setOf p), n < hf.toFinset.card } := fun _ hi => le_antisymm (Nat.le_nth_of_monotoneOn_of_surjOn _ hsurj hmono.monotoneOn hi) (Nat.nth_le_of_strictMonoOn_of_mapsTo _ hmaps hmono) lemma nth_comp_of_strictMono {n : β„•} {f : β„• β†’ β„•} (hf : StrictMono f) (h0 : βˆ€ k, p k β†’ k ∈ Set.range f) (h : βˆ€ hfi : (setOf p).Finite, n < hfi.toFinset.card) : f (nth (fun i ↦ p (f i)) n) = nth p n := by have hs {p' : β„• β†’ Prop} (h0p' : βˆ€ k, p' k β†’ k ∈ Set.range f) : f '' {i | p' (f i)} = setOf p' := by ext i refine ⟨fun ⟨_, hi, h⟩ ↦ h β–Έ hi, fun he ↦ ?_⟩ rcases h0p' _ he with ⟨t, rfl⟩ exact ⟨t, he, rfl⟩ induction n using Nat.case_strong_induction_on case _ => simp_rw [nth_zero] replace h := nth_mem _ h rw [← hs h0, ← hf.monotone.map_csInf] rcases h0 _ h with ⟨t, ht⟩ exact ⟨t, Set.mem_setOf_eq β–Έ ht β–Έ h⟩ case _ n ih => repeat nth_rw 1 [nth_eq_sInf] have h0' : βˆ€ k', (p k' ∧ βˆ€ k < n + 1, nth p k < k') β†’ k' ∈ Set.range f := fun _ h ↦ h0 _ h.1 rw [← hs h0', ← hf.monotone.map_csInf] Β· convert rfl using 8 with k m' hm nth_rw 2 [← hf.lt_iff_lt] convert Iff.rfl using 2 exact ih m' (Nat.lt_add_one_iff.mp hm) fun hfi ↦ hm.trans (h hfi) Β· rcases h0 _ (nth_mem _ h) with ⟨t, ht⟩ exact ⟨t, ht β–Έ (nth_mem _ h), fun _ hk ↦ ht β–Έ nth_lt_nth' hk h⟩ lemma nth_add {m n : β„•} (h0 : βˆ€ k < m, Β¬p k) (h : nth p n β‰  0) : nth (fun i ↦ p (i + m)) n + m = nth p n := by refine nth_comp_of_strictMono (strictMono_id.add_const m) (fun k hk ↦ ?_) (fun hf ↦ lt_card_toFinset_of_nth_ne_zero h hf) by_contra hn simp_rw [id_eq, Set.mem_range, eq_comm] at hn exact h0 _ (not_le.mp fun h ↦ hn (le_iff_exists_add'.mp h)) hk lemma nth_add_eq_sub {m n : β„•} (h0 : βˆ€ k < m, Β¬p k) (h : nth p n β‰  0) : nth (fun i ↦ p (i + m)) n = nth p n - m := by rw [← nth_add h0 h, Nat.add_sub_cancel] lemma nth_add_one {n : β„•} (h0 : Β¬p 0) (h : nth p n β‰  0) : nth (fun i ↦ p (i + 1)) n + 1 = nth p n := nth_add (fun _ hk ↦ (lt_one_iff.1 hk β–Έ h0)) h lemma nth_add_one_eq_sub {n : β„•} (h0 : Β¬p 0) (h : nth p n β‰  0) : nth (fun i ↦ p (i + 1)) n = nth p n - 1 := nth_add_eq_sub (fun _ hk ↦ (lt_one_iff.1 hk β–Έ h0)) h section Count variable (p) [DecidablePred p] @[simp] theorem count_nth_zero : count p (nth p 0) = 0 := by rw [count_eq_card_filter_range, card_eq_zero, filter_eq_empty_iff, nth_zero] exact fun n h₁ hβ‚‚ => (mem_range.1 h₁).not_ge (Nat.sInf_le hβ‚‚) theorem filter_range_nth_subset_insert (k : β„•) : {n ∈ range (nth p (k + 1)) | p n} βŠ† insert (nth p k) {n ∈ range (nth p k) | p n} := by intro a ha simp only [mem_insert, mem_filter, mem_range] at ha ⊒ exact (le_nth_of_lt_nth_succ ha.1 ha.2).eq_or_lt.imp_right fun h => ⟨h, ha.2⟩ variable {p} theorem filter_range_nth_eq_insert {k : β„•} (hlt : βˆ€ hf : (setOf p).Finite, k + 1 < #hf.toFinset) : {n ∈ range (nth p (k + 1)) | p n} = insert (nth p k) {n ∈ range (nth p k) | p n} := by refine (filter_range_nth_subset_insert p k).antisymm fun a ha => ?_ simp only [mem_insert, mem_filter, mem_range] at ha ⊒ have : nth p k < nth p (k + 1) := nth_lt_nth' k.lt_succ_self hlt rcases ha with (rfl | ⟨hlt, hpa⟩) Β· exact ⟨this, nth_mem _ fun hf => k.lt_succ_self.trans (hlt hf)⟩ Β· exact ⟨hlt.trans this, hpa⟩ theorem filter_range_nth_eq_insert_of_finite (hf : (setOf p).Finite) {k : β„•} (hlt : k + 1 < #hf.toFinset) : {n ∈ range (nth p (k + 1)) | p n} = insert (nth p k) {n ∈ range (nth p k) | p n} := filter_range_nth_eq_insert fun _ => hlt theorem filter_range_nth_eq_insert_of_infinite (hp : (setOf p).Infinite) (k : β„•) : {n ∈ range (nth p (k + 1)) | p n} = insert (nth p k) {n ∈ range (nth p k) | p n} := filter_range_nth_eq_insert fun hf => absurd hf hp theorem count_nth {n : β„•} (hn : βˆ€ hf : (setOf p).Finite, n < #hf.toFinset) : count p (nth p n) = n := by induction n with | zero => exact count_nth_zero _ | succ k ihk => rw [count_eq_card_filter_range, filter_range_nth_eq_insert hn, card_insert_of_notMem, ← count_eq_card_filter_range, ihk fun hf => lt_of_succ_lt (hn hf)] simp theorem count_nth_of_lt_card_finite {n : β„•} (hp : (setOf p).Finite) (hlt : n < #hp.toFinset) : count p (nth p n) = n := count_nth fun _ => hlt theorem count_nth_of_infinite (hp : (setOf p).Infinite) (n : β„•) : count p (nth p n) = n := count_nth fun hf => absurd hf hp theorem surjective_count_of_infinite_setOf (h : {n | p n}.Infinite) : Function.Surjective (Nat.count p) := fun n => ⟨nth p n, count_nth_of_infinite h n⟩ theorem count_nth_succ {n : β„•} (hn : βˆ€ hf : (setOf p).Finite, n < #hf.toFinset) : count p (nth p n + 1) = n + 1 := by rw [count_succ, count_nth hn, if_pos (nth_mem _ hn)] lemma count_nth_succ_of_infinite (hp : (setOf p).Infinite) (n : β„•) : count p (nth p n + 1) = n + 1 := by rw [count_succ, count_nth_of_infinite hp, if_pos (nth_mem_of_infinite hp _)] @[simp] theorem nth_count {n : β„•} (hpn : p n) : nth p (count p n) = n := have : βˆ€ hf : (setOf p).Finite, count p n < #hf.toFinset := fun hf => count_lt_card hf hpn count_injective (nth_mem _ this) hpn (count_nth this) theorem nth_lt_of_lt_count {n k : β„•} (h : k < count p n) : nth p k < n := by refine (count_monotone p).reflect_lt ?_ rwa [count_nth] exact fun hf => h.trans_le (count_le_card hf n) theorem le_nth_of_count_le {n k : β„•} (h : n ≀ nth p k) : count p n ≀ k := not_lt.1 fun hlt => h.not_gt <| nth_lt_of_lt_count hlt protected theorem count_eq_zero (h : βˆƒ n, p n) {n : β„•} : count p n = 0 ↔ n ≀ nth p 0 := by rw [nth_zero_of_exists h, le_find_iff h, Nat.count_iff_forall_not] variable (p) in theorem nth_count_eq_sInf (n : β„•) : nth p (count p n) = sInf {i : β„• | p i ∧ n ≀ i} := by refine (nth_eq_sInf _ _).trans (congr_arg sInf ?_) refine Set.ext fun a => and_congr_right fun hpa => ?_ refine ⟨fun h => not_lt.1 fun ha => ?_, fun hn k hk => lt_of_lt_of_le (nth_lt_of_lt_count hk) hn⟩ have hn : nth p (count p a) < a := h _ (count_strict_mono hpa ha) rwa [nth_count hpa, lt_self_iff_false] at hn theorem le_nth_count' {n : β„•} (hpn : βˆƒ k, p k ∧ n ≀ k) : n ≀ nth p (count p n) := (le_csInf hpn fun _ => And.right).trans (nth_count_eq_sInf p n).ge theorem le_nth_count (hp : (setOf p).Infinite) (n : β„•) : n ≀ nth p (count p n) := let ⟨m, hp, hn⟩ := hp.exists_gt n le_nth_count' ⟨m, hp, hn.le⟩ /-- If a predicate `p : β„• β†’ Prop` is true for infinitely many numbers, then `Nat.count p` and `Nat.nth p` form a Galois insertion. -/ noncomputable def giCountNth (hp : (setOf p).Infinite) : GaloisInsertion (count p) (nth p) := GaloisInsertion.monotoneIntro (nth_monotone hp) (count_monotone p) (le_nth_count hp) (count_nth_of_infinite hp) theorem gc_count_nth (hp : (setOf p).Infinite) : GaloisConnection (count p) (nth p) := (giCountNth hp).gc theorem count_le_iff_le_nth (hp : (setOf p).Infinite) {a b : β„•} : count p a ≀ b ↔ a ≀ nth p b := gc_count_nth hp _ _ theorem lt_nth_iff_count_lt (hp : (setOf p).Infinite) {a b : β„•} : a < count p b ↔ nth p a < b := (gc_count_nth hp).lt_iff_lt end Count theorem nth_of_forall {n : β„•} (hp : βˆ€ n' ≀ n, p n') : nth p n = n := by classical nth_rw 1 [← count_of_forall (hp Β· Β·.le), nth_count (hp n le_rfl)] @[simp] theorem nth_true (n : β„•) : nth (fun _ ↦ True) n = n := nth_of_forall fun _ _ ↦ trivial theorem nth_of_forall_not {n : β„•} (hp : βˆ€ n' β‰₯ n, Β¬p n') : nth p n = 0 := by have : setOf p βŠ† Finset.range n := by intro n' hn' contrapose! hp exact ⟨n', by simpa using hp, Set.mem_setOf.mp hn'⟩ rw [nth_of_card_le ((finite_toSet _).subset this)] Β· refine (Finset.card_le_card ?_).trans_eq (Finset.card_range n) exact Set.Finite.toFinset_subset.mpr this @[simp] theorem nth_false (n : β„•) : nth (fun _ ↦ False) n = 0 := nth_of_forall_not fun _ _ ↦ id end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Bitwise.lean
import Mathlib.Algebra.Group.Nat.Even import Mathlib.Algebra.NeZero import Mathlib.Algebra.Ring.Nat import Mathlib.Data.Bool.Basic import Mathlib.Data.List.GetD import Mathlib.Data.Nat.Bits import Mathlib.Order.Basic import Mathlib.Tactic.AdaptationNote import Mathlib.Tactic.Common import Batteries.Data.Nat.Bitwise /-! # Bitwise operations on natural numbers In the first half of this file, we provide theorems for reasoning about natural numbers from their bitwise properties. In the second half of this file, we show properties of the bitwise operations `lor`, `land` and `xor`, which are defined in core. ## Main results * `eq_of_testBit_eq`: two natural numbers are equal if they have equal bits at every position. * `exists_most_significant_bit`: if `n β‰  0`, then there is some position `i` that contains the most significant `1`-bit of `n`. * `lt_of_testBit`: if `n` and `m` are numbers and `i` is a position such that the `i`-th bit of of `n` is zero, the `i`-th bit of `m` is one, and all more significant bits are equal, then `n < m`. ## Future work There is another way to express bitwise properties of natural number: `digits 2`. The two ways should be connected. ## Keywords bitwise, and, or, xor -/ open Function namespace Nat section variable {f : Bool β†’ Bool β†’ Bool} @[simp] lemma bitwise_zero_left (m : Nat) : bitwise f 0 m = if f false true then m else 0 := by simp [bitwise] @[simp] lemma bitwise_zero_right (n : Nat) : bitwise f n 0 = if f true false then n else 0 := by unfold bitwise simp only [ite_self, Nat.zero_div, ite_true, ite_eq_right_iff] rintro ⟨⟩ split_ifs <;> rfl lemma bitwise_zero : bitwise f 0 0 = 0 := by simp only [bitwise_zero_right, ite_self] lemma bitwise_of_ne_zero {n m : Nat} (hn : n β‰  0) (hm : m β‰  0) : bitwise f n m = bit (f (bodd n) (bodd m)) (bitwise f (n / 2) (m / 2)) := by conv_lhs => unfold bitwise have mod_two_iff_bod x : (x % 2 = 1 : Bool) = bodd x := by simp only [mod_two_of_bodd]; cases bodd x <;> rfl simp only [hn, hm, mod_two_iff_bod, ite_false, bit, two_mul, Bool.cond_eq_ite] theorem binaryRec_of_ne_zero {C : Nat β†’ Sort*} (z : C 0) (f : βˆ€ b n, C n β†’ C (bit b n)) {n} (h : n β‰  0) : binaryRec z f n = bit_bodd_div2 n β–Έ f (bodd n) (div2 n) (binaryRec z f (div2 n)) := by cases n using bitCasesOn with | bit b n => rw [binaryRec_eq _ _ (by right; simpa [bit_eq_zero_iff] using h)] generalize_proofs h; revert h rw [bodd_bit, div2_bit] simp @[simp] lemma bitwise_bit {f : Bool β†’ Bool β†’ Bool} (h : f false false = false := by rfl) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := by conv_lhs => unfold bitwise simp only [bit, Bool.cond_eq_ite] have h4 x : (x + x + 1) / 2 = x := by rw [← two_mul, add_comm]; simp [add_mul_div_left] cases a <;> cases b <;> simp <;> split_ifs <;> simp_all +decide [two_mul] lemma bit_mod_two_eq_zero_iff (a x) : bit a x % 2 = 0 ↔ !a := by simp lemma bit_mod_two_eq_one_iff (a x) : bit a x % 2 = 1 ↔ a := by simp @[simp] theorem lor_bit : βˆ€ a m b n, bit a m ||| bit b n = bit (a || b) (m ||| n) := bitwise_bit @[simp] theorem land_bit : βˆ€ a m b n, bit a m &&& bit b n = bit (a && b) (m &&& n) := bitwise_bit @[simp] theorem ldiff_bit : βˆ€ a m b n, ldiff (bit a m) (bit b n) = bit (a && not b) (ldiff m n) := bitwise_bit @[simp] theorem xor_bit : βˆ€ a m b n, bit a m ^^^ bit b n = bit (bne a b) (m ^^^ n) := bitwise_bit attribute [simp] Nat.testBit_bitwise theorem testBit_lor : βˆ€ m n k, testBit (m ||| n) k = (testBit m k || testBit n k) := testBit_bitwise rfl theorem testBit_land : βˆ€ m n k, testBit (m &&& n) k = (testBit m k && testBit n k) := testBit_bitwise rfl @[simp] theorem testBit_ldiff : βˆ€ m n k, testBit (ldiff m n) k = (testBit m k && not (testBit n k)) := testBit_bitwise rfl attribute [simp] testBit_xor end @[simp] theorem bit_false : bit false = (2 * Β·) := rfl @[simp] theorem bit_true : bit true = (2 * Β· + 1) := rfl @[simp] theorem bit_false_apply (n) : bit false n = (2 * n) := rfl @[simp] theorem bit_true_apply (n) : bit true n = (2 * n + 1) := rfl theorem bit_ne_zero_iff {n : β„•} {b : Bool} : n.bit b β‰  0 ↔ n = 0 β†’ b = true := by simp /-- An alternative for `bitwise_bit` which replaces the `f false false = false` assumption with assumptions that neither `bit a m` nor `bit b n` are `0` (albeit, phrased as the implications `m = 0 β†’ a = true` and `n = 0 β†’ b = true`) -/ lemma bitwise_bit' {f : Bool β†’ Bool β†’ Bool} (a : Bool) (m : Nat) (b : Bool) (n : Nat) (ham : m = 0 β†’ a = true) (hbn : n = 0 β†’ b = true) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := by conv_lhs => unfold bitwise rw [← bit_ne_zero_iff] at ham hbn simp only [ham, hbn, bit_mod_two_eq_one_iff, Bool.decide_coe, ← div2_val, div2_bit, ite_false] conv_rhs => simp only [bit, two_mul, Bool.cond_eq_ite] lemma bitwise_eq_binaryRec (f : Bool β†’ Bool β†’ Bool) : bitwise f = binaryRec (fun n => cond (f false true) n 0) fun a m Ia => binaryRec (cond (f true false) (bit a m) 0) fun b n _ => bit (f a b) (Ia n) := by funext x y induction x using binaryRec' generalizing y with | zero => simp only [bitwise_zero_left, binaryRec_zero, Bool.cond_eq_ite] | bit xb x hxb ih => rw [← bit_ne_zero_iff] at hxb simp_rw [binaryRec_of_ne_zero _ _ hxb, bodd_bit, div2_bit, eq_rec_constant] induction y using binaryRec' with | zero => simp only [bitwise_zero_right, binaryRec_zero, Bool.cond_eq_ite] | bit yb y hyb => rw [← bit_ne_zero_iff] at hyb simp_rw [binaryRec_of_ne_zero _ _ hyb, bitwise_of_ne_zero hxb hyb, bodd_bit, ← div2_val, div2_bit, eq_rec_constant, ih] theorem zero_of_testBit_eq_false {n : β„•} (h : βˆ€ i, testBit n i = false) : n = 0 := by induction n using Nat.binaryRec with | zero => rfl | bit b n hn => ?_ have : b = false := by simpa using h 0 rw [this, bit_false, hn fun i => by rw [← h (i + 1), testBit_bit_succ]] theorem testBit_eq_false_of_lt {n i} (h : n < 2 ^ i) : n.testBit i = false := by simp [testBit, shiftRight_eq_div_pow, Nat.div_eq_of_lt h] /-- The ith bit is the ith element of `n.bits`. -/ theorem testBit_eq_inth (n i : β„•) : n.testBit i = n.bits.getI i := by induction i generalizing n with | zero => simp only [testBit, shiftRight_zero, one_and_eq_mod_two, mod_two_of_bodd, bodd_eq_bits_head, List.getI_zero_eq_headI] cases List.headI (bits n) <;> rfl | succ i ih => conv_lhs => rw [← bit_bodd_div2 n] rw [testBit_bit_succ, ih n.div2, div2_bits_eq_tail] cases n.bits <;> simp theorem exists_most_significant_bit {n : β„•} (h : n β‰  0) : βˆƒ i, testBit n i = true ∧ βˆ€ j, i < j β†’ testBit n j = false := by induction n using Nat.binaryRec with | zero => exact False.elim (h rfl) | bit b n hn => ?_ by_cases h' : n = 0 Β· subst h' rw [show b = true by revert h cases b <;> simp] refine ⟨0, ⟨by rw [testBit_bit_zero], fun j hj => ?_⟩⟩ obtain ⟨j', rfl⟩ := exists_eq_succ_of_ne_zero (ne_of_gt hj) rw [testBit_bit_succ, zero_testBit] Β· obtain ⟨k, ⟨hk, hk'⟩⟩ := hn h' refine ⟨k + 1, ⟨by rw [testBit_bit_succ, hk], fun j hj => ?_⟩⟩ obtain ⟨j', rfl⟩ := exists_eq_succ_of_ne_zero (show j β‰  0 by intro x; subst x; simp at hj) exact (testBit_bit_succ _ _ _).trans (hk' _ (lt_of_succ_lt_succ hj)) theorem lt_of_testBit {n m : β„•} (i : β„•) (hn : testBit n i = false) (hm : testBit m i = true) (hnm : βˆ€ j, i < j β†’ testBit n j = testBit m j) : n < m := by induction n using Nat.binaryRec generalizing i m with | zero => rw [Nat.pos_iff_ne_zero] rintro rfl simp at hm | bit b n hn' => induction m using Nat.binaryRec generalizing i with | zero => exact False.elim (Bool.false_ne_true ((zero_testBit i).symm.trans hm)) | bit b' m hm' => by_cases hi : i = 0 Β· subst hi simp only [testBit_bit_zero] at hn hm have : n = m := eq_of_testBit_eq fun i => by convert hnm (i + 1) (Nat.zero_lt_succ _) using 1 <;> rw [testBit_bit_succ] rw [hn, hm, this, bit_false, bit_true] exact Nat.lt_succ_self _ Β· obtain ⟨i', rfl⟩ := exists_eq_succ_of_ne_zero hi simp only [testBit_bit_succ] at hn hm have := hn' _ hn hm fun j hj => by convert hnm j.succ (succ_lt_succ hj) using 1 <;> rw [testBit_bit_succ] exact bit_lt_bit b b' this theorem bitwise_swap {f : Bool β†’ Bool β†’ Bool} : bitwise (Function.swap f) = Function.swap (bitwise f) := by funext m n simp only [Function.swap] induction m using Nat.strongRecOn generalizing n with | ind m ih => ?_ rcases m with - | m <;> rcases n with - | n <;> try rw [bitwise_zero_left, bitwise_zero_right] Β· specialize ih ((m + 1) / 2) (div_lt_self' ..) simp [bitwise_of_ne_zero, ih] /-- If `f` is a commutative operation on bools such that `f false false = false`, then `bitwise f` is also commutative. -/ theorem bitwise_comm {f : Bool β†’ Bool β†’ Bool} (hf : βˆ€ b b', f b b' = f b' b) (n m : β„•) : bitwise f n m = bitwise f m n := suffices bitwise f = swap (bitwise f) by conv_lhs => rw [this] calc bitwise f = bitwise (swap f) := congr_arg _ <| funext fun _ => funext <| hf _ _ = swap (bitwise f) := bitwise_swap theorem lor_comm (n m : β„•) : n ||| m = m ||| n := bitwise_comm Bool.or_comm n m theorem land_comm (n m : β„•) : n &&& m = m &&& n := bitwise_comm Bool.and_comm n m lemma and_two_pow (n i : β„•) : n &&& 2 ^ i = (n.testBit i).toNat * 2 ^ i := by refine eq_of_testBit_eq fun j => ?_ obtain rfl | hij := Decidable.eq_or_ne i j <;> cases h : n.testBit i Β· simp [h] Β· simp [h] Β· simp [testBit_two_pow_of_ne hij] Β· simp [testBit_two_pow_of_ne hij] lemma two_pow_and (n i : β„•) : 2 ^ i &&& n = 2 ^ i * (n.testBit i).toNat := by rw [mul_comm, land_comm, and_two_pow] /-- Proving associativity of bitwise operations in general essentially boils down to a huge case distinction, so it is shorter to use this tactic instead of proving it in the general case. -/ macro "bitwise_assoc_tac" : tactic => set_option hygiene false in `(tactic| ( induction n using Nat.binaryRec generalizing m k with | zero => simp | bit b n hn => ?_ induction m using Nat.binaryRec with | zero => simp | bit b' m hm => ?_ induction k using Nat.binaryRec <;> simp [hn, Bool.or_assoc, Bool.and_assoc, Bool.bne_eq_xor])) theorem land_assoc (n m k : β„•) : (n &&& m) &&& k = n &&& (m &&& k) := by bitwise_assoc_tac theorem lor_assoc (n m k : β„•) : (n ||| m) ||| k = n ||| (m ||| k) := by bitwise_assoc_tac @[deprecated Nat.xor_xor_cancel_right (since := "2025-10-02")] theorem xor_cancel_right (n m : β„•) : (m ^^^ n) ^^^ n = m := Nat.xor_xor_cancel_right .. @[deprecated Nat.xor_xor_cancel_left (since := "2025-10-02")] theorem xor_cancel_left (n m : β„•) : n ^^^ (n ^^^ m) = m := Nat.xor_xor_cancel_left .. @[deprecated Nat.xor_eq_zero_iff (since := "2025-10-02")] theorem xor_eq_zero {n m : β„•} : n ^^^ m = 0 ↔ n = m := Nat.xor_eq_zero_iff @[deprecated Nat.xor_ne_zero_iff (since := "2025-10-02")] theorem xor_ne_zero {n m : β„•} : n ^^^ m β‰  0 ↔ n β‰  m := Nat.xor_ne_zero_iff theorem xor_trichotomy {a b c : β„•} (h : a ^^^ b ^^^ c β‰  0) : b ^^^ c < a ∨ c ^^^ a < b ∨ a ^^^ b < c := by set v := a ^^^ b ^^^ c with hv -- The xor of any two of `a`, `b`, `c` is the xor of `v` and the third. have hab : a ^^^ b = c ^^^ v := by rw [Nat.xor_comm c, Nat.xor_xor_cancel_right] have hbc : b ^^^ c = a ^^^ v := by rw [← Nat.xor_assoc, Nat.xor_xor_cancel_left] have hca : c ^^^ a = b ^^^ v := by rw [hv, Nat.xor_assoc, Nat.xor_comm a, ← Nat.xor_assoc, Nat.xor_xor_cancel_left] -- If `i` is the position of the most significant bit of `v`, then at least one of `a`, `b`, `c` -- has a one bit at position `i`. obtain ⟨i, ⟨hi, hi'⟩⟩ := exists_most_significant_bit h have : testBit a i ∨ testBit b i ∨ testBit c i := by contrapose! hi simp_rw [Bool.eq_false_eq_not_eq_true] at hi ⊒ rw [testBit_xor, testBit_xor, hi.1, hi.2.1, hi.2.2] rfl -- If, say, `a` has a one bit at position `i`, then `a xor v` has a zero bit at position `i`, but -- the same bits as `a` in positions greater than `j`, so `a xor v < a`. obtain h | h | h := this on_goal 1 => left; rw [hbc] on_goal 2 => right; left; rw [hca] on_goal 3 => right; right; rw [hab] all_goals refine lt_of_testBit i ?_ h fun j hj => ?_ Β· rw [testBit_xor, h, hi] rfl Β· simp only [testBit_xor, hi' _ hj, Bool.bne_false] theorem lt_xor_cases {a b c : β„•} (h : a < b ^^^ c) : a ^^^ c < b ∨ a ^^^ b < c := by obtain ha | hb | hc := xor_trichotomy <| Nat.xor_assoc _ _ _ β–Έ xor_ne_zero_iff.2 h.ne exacts [(h.asymm ha).elim, Or.inl <| Nat.xor_comm _ _ β–Έ hb, Or.inr hc] @[simp] theorem xor_mod_two_eq {m n : β„•} : (m ^^^ n) % 2 = (m + n) % 2 := by by_cases h : (m + n) % 2 = 0 Β· simp only [h, mod_two_eq_zero_iff_testBit_zero, testBit_zero, xor_mod_two_eq_one, decide_not, Bool.decide_iff_dist, Bool.not_eq_false', beq_iff_eq, decide_eq_decide] cutsat Β· simp only [mod_two_ne_zero] at h simp only [h, xor_mod_two_eq_one] cutsat @[simp] theorem even_xor {m n : β„•} : Even (m ^^^ n) ↔ (Even m ↔ Even n) := by simp only [even_iff, xor_mod_two_eq] cutsat @[simp] theorem bit_lt_two_pow_succ_iff {b x n} : bit b x < 2 ^ (n + 1) ↔ x < 2 ^ n := by cases b <;> simp <;> omega lemma shiftLeft_lt {x n m : β„•} (h : x < 2 ^ n) : x <<< m < 2 ^ (n + m) := by simp only [Nat.pow_add, shiftLeft_eq, Nat.mul_lt_mul_right (Nat.two_pow_pos _), h] /-- Note that the LHS is the expression used within `Std.BitVec.append`, hence the name. -/ lemma append_lt {x y n m} (hx : x < 2 ^ n) (hy : y < 2 ^ m) : y <<< n ||| x < 2 ^ (n + m) := by apply bitwise_lt_two_pow Β· rw [add_comm]; apply shiftLeft_lt hy Β· apply lt_of_lt_of_le hx <| Nat.pow_le_pow_right (le_succ _) (le_add_right _ _) end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Count.lean
import Mathlib.Algebra.Group.Nat.Range import Mathlib.Data.Set.Finite.Basic /-! # Counting on β„• This file defines the `count` function, which gives, for any predicate on the natural numbers, "how many numbers under `k` satisfy this predicate?". We then prove several expected lemmas about `count`, relating it to the cardinality of other objects, and helping to evaluate it for specific `k`. -/ assert_not_imported Mathlib.Dynamics.FixedPoints.Basic assert_not_exists Ring open Finset namespace Nat variable (p : β„• β†’ Prop) section Count variable [DecidablePred p] /-- Count the number of naturals `k < n` satisfying `p k`. -/ def count (n : β„•) : β„• := (List.range n).countP p @[simp, grind =] theorem count_zero : count p 0 = 0 := by simp [count] /-- A fintype instance for the set relevant to `Nat.count`. Locally an instance in scope `count` -/ def CountSet.fintype (n : β„•) : Fintype { i // i < n ∧ p i } := Fintype.ofFinset {x ∈ range n | p x} <| by intro x rw [mem_filter, mem_range] rfl scoped[Count] attribute [instance] Nat.CountSet.fintype open Count theorem count_eq_card_filter_range (n : β„•) : count p n = #{x ∈ range n | p x} := by rw [count, List.countP_eq_length_filter] rfl /-- `count p n` can be expressed as the cardinality of `{k // k < n ∧ p k}`. -/ theorem count_eq_card_fintype (n : β„•) : count p n = Fintype.card { k : β„• // k < n ∧ p k } := by rw [count_eq_card_filter_range, Fintype.card_of_subtype] simp theorem count_le {n : β„•} : count p n ≀ n := by rw [count_eq_card_filter_range] exact (card_filter_le _ _).trans_eq (card_range _) @[grind =] theorem count_succ (n : β„•) : count p (n + 1) = count p n + if p n then 1 else 0 := by grind [count, List.range_succ] @[mono] theorem count_monotone : Monotone (count p) := monotone_nat_of_le_succ (by grind) theorem count_add (a b : β„•) : count p (a + b) = count p a + count (fun k ↦ p (a + k)) b := by have : Disjoint {x ∈ range a | p x} {x ∈ (range b).map <| addLeftEmbedding a | p x} := by grind [Finset.disjoint_left] simp_rw [count_eq_card_filter_range, range_add, filter_union, card_union_of_disjoint this, filter_map, addLeftEmbedding, card_map, Function.Embedding.coeFn_mk, Function.comp_def] theorem count_add' (a b : β„•) : count p (a + b) = count (fun k ↦ p (k + b)) a + count p b := by rw [add_comm, count_add, add_comm] simp_rw [add_comm b] theorem count_one : count p 1 = if p 0 then 1 else 0 := by simp [count_succ] theorem count_succ' (n : β„•) : count p (n + 1) = count (fun k ↦ p (k + 1)) n + if p 0 then 1 else 0 := by rw [count_add', count_one] variable {p} @[simp] theorem count_lt_count_succ_iff {n : β„•} : count p n < count p (n + 1) ↔ p n := by grind theorem count_succ_eq_succ_count_iff {n : β„•} : count p (n + 1) = count p n + 1 ↔ p n := by grind theorem count_succ_eq_count_iff {n : β„•} : count p (n + 1) = count p n ↔ Β¬p n := by grind alias ⟨_, count_succ_eq_succ_count⟩ := count_succ_eq_succ_count_iff alias ⟨_, count_succ_eq_count⟩ := count_succ_eq_count_iff theorem lt_of_count_lt_count {a b : β„•} (h : count p a < count p b) : a < b := (count_monotone p).reflect_lt h theorem count_strict_mono {m n : β„•} (hm : p m) (hmn : m < n) : count p m < count p n := (count_lt_count_succ_iff.2 hm).trans_le <| count_monotone _ (Nat.succ_le_iff.2 hmn) theorem count_injective {m n : β„•} (hm : p m) (hn : p n) (heq : count p m = count p n) : m = n := by by_contra! h : m β‰  n wlog hmn : m < n Β· exact this hn hm heq.symm h.symm (by grind) Β· simpa [heq] using count_strict_mono hm hmn theorem count_le_card (hp : (setOf p).Finite) (n : β„•) : count p n ≀ #hp.toFinset := by rw [count_eq_card_filter_range] exact Finset.card_mono fun x hx ↦ hp.mem_toFinset.2 (mem_filter.1 hx).2 theorem count_lt_card {n : β„•} (hp : (setOf p).Finite) (hpn : p n) : count p n < #hp.toFinset := (count_lt_count_succ_iff.2 hpn).trans_le (count_le_card hp _) theorem count_iff_forall {n : β„•} : count p n = n ↔ βˆ€ n' < n, p n' := by simpa [count_eq_card_filter_range, card_range, mem_range] using card_filter_eq_iff (p := p) (s := range n) alias ⟨_, count_of_forall⟩ := count_iff_forall @[simp] theorem count_true (n : β„•) : count (fun _ ↦ True) n = n := count_of_forall fun _ _ ↦ trivial theorem count_iff_forall_not {n : β„•} : count p n = 0 ↔ βˆ€ m < n, Β¬p m := by simp [count_eq_card_filter_range] alias ⟨_, count_of_forall_not⟩ := count_iff_forall_not theorem count_ne_iff_exists {n : β„•} : n.count p β‰  0 ↔ βˆƒ m < n, p m := by simp [Nat.count_iff_forall_not] @[simp] theorem count_false (n : β„•) : count (fun _ ↦ False) n = 0 := count_of_forall_not fun _ _ ↦ id lemma exists_of_count_lt_count {a b : β„•} (h : a.count p < b.count p) : βˆƒ x ∈ Set.Ico a b, p x := by obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_lt (lt_of_count_lt_count h) rw [add_assoc, count_add, Nat.lt_add_right_iff_pos] at h obtain ⟨t, ht, hp⟩ := count_ne_iff_exists.mp h.ne' simp_rw [Set.mem_Ico] exact ⟨a + t, by grind⟩ variable {q : β„• β†’ Prop} variable [DecidablePred q] @[gcongr] theorem count_mono_left {n : β„•} (hpq : βˆ€ k < n, p k β†’ q k) : count p n ≀ count q n := List.countP_mono_left <| by simpa end Count end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/PrimeFin.lean
import Mathlib.Data.Countable.Defs import Mathlib.Data.Nat.Factors import Mathlib.Data.Nat.Prime.Infinite import Mathlib.Data.Set.Finite.Lattice /-! # Prime numbers This file contains some results about prime numbers which depend on finiteness of sets. -/ open Finset namespace Nat variable {a b k m n p : β„•} /-- A version of `Nat.exists_infinite_primes` using the `Set.Infinite` predicate. -/ theorem infinite_setOf_prime : { p | Prime p }.Infinite := Set.infinite_of_not_bddAbove not_bddAbove_setOf_prime instance Primes.infinite : Infinite Primes := infinite_setOf_prime.to_subtype instance Primes.countable : Countable Primes := ⟨⟨coeNat.coe, coe_nat_injective⟩⟩ /-- The prime factors of a natural number as a finset. -/ def primeFactors (n : β„•) : Finset β„• := n.primeFactorsList.toFinset @[simp] lemma toFinset_factors (n : β„•) : n.primeFactorsList.toFinset = n.primeFactors := rfl @[simp] lemma mem_primeFactors : p ∈ n.primeFactors ↔ p.Prime ∧ p ∣ n ∧ n β‰  0 := by simp_rw [← toFinset_factors, List.mem_toFinset, mem_primeFactorsList'] lemma mem_primeFactors_of_ne_zero (hn : n β‰  0) : p ∈ n.primeFactors ↔ p.Prime ∧ p ∣ n := by simp [hn] lemma primeFactors_mono (hmn : m ∣ n) (hn : n β‰  0) : primeFactors m βŠ† primeFactors n := by simp only [subset_iff, mem_primeFactors, and_imp] exact fun p hp hpm _ ↦ ⟨hp, hpm.trans hmn, hn⟩ lemma mem_primeFactors_iff_mem_primeFactorsList : p ∈ n.primeFactors ↔ p ∈ n.primeFactorsList := by simp only [primeFactors, List.mem_toFinset] lemma prime_of_mem_primeFactors (hp : p ∈ n.primeFactors) : p.Prime := (mem_primeFactors.1 hp).1 lemma dvd_of_mem_primeFactors (hp : p ∈ n.primeFactors) : p ∣ n := (mem_primeFactors.1 hp).2.1 lemma pos_of_mem_primeFactors (hp : p ∈ n.primeFactors) : 0 < p := (prime_of_mem_primeFactors hp).pos lemma le_of_mem_primeFactors (h : p ∈ n.primeFactors) : p ≀ n := le_of_dvd (mem_primeFactors.1 h).2.2.bot_lt <| dvd_of_mem_primeFactors h @[simp] lemma primeFactors_zero : primeFactors 0 = βˆ… := by ext simp @[simp] lemma primeFactors_one : primeFactors 1 = βˆ… := by ext simpa using Prime.ne_one @[simp] lemma primeFactors_eq_empty : n.primeFactors = βˆ… ↔ n = 0 ∨ n = 1 := by constructor Β· contrapose! rintro hn obtain ⟨p, hp, hpn⟩ := exists_prime_and_dvd hn.2 exact Nonempty.ne_empty <| ⟨_, mem_primeFactors.2 ⟨hp, hpn, hn.1⟩⟩ Β· rintro (rfl | rfl) <;> simp @[simp] lemma nonempty_primeFactors {n : β„•} : n.primeFactors.Nonempty ↔ 1 < n := by rw [← not_iff_not, Finset.not_nonempty_iff_eq_empty, primeFactors_eq_empty, not_lt, Nat.le_one_iff_eq_zero_or_eq_one] @[simp] protected lemma Prime.primeFactors (hp : p.Prime) : p.primeFactors = {p} := by simp [Nat.primeFactors, primeFactorsList_prime hp] lemma primeFactors_mul (ha : a β‰  0) (hb : b β‰  0) : (a * b).primeFactors = a.primeFactors βˆͺ b.primeFactors := by ext; simp only [Finset.mem_union, mem_primeFactors_iff_mem_primeFactorsList, mem_primeFactorsList_mul ha hb] lemma Coprime.primeFactors_mul {a b : β„•} (hab : Coprime a b) : (a * b).primeFactors = a.primeFactors βˆͺ b.primeFactors := (List.toFinset.ext <| mem_primeFactorsList_mul_of_coprime hab).trans <| List.toFinset_union _ _ lemma primeFactors_gcd (ha : a β‰  0) (hb : b β‰  0) : (a.gcd b).primeFactors = a.primeFactors ∩ b.primeFactors := by ext; simp [dvd_gcd_iff, ha, hb, gcd_ne_zero_left ha]; aesop @[simp] lemma disjoint_primeFactors (ha : a β‰  0) (hb : b β‰  0) : Disjoint a.primeFactors b.primeFactors ↔ Coprime a b := by simp [disjoint_iff_inter_eq_empty, coprime_iff_gcd_eq_one, ← primeFactors_gcd, ha, hb] protected lemma Coprime.disjoint_primeFactors (hab : Coprime a b) : Disjoint a.primeFactors b.primeFactors := List.disjoint_toFinset_iff_disjoint.2 <| coprime_primeFactorsList_disjoint hab lemma primeFactors_pow_succ (n k : β„•) : (n ^ (k + 1)).primeFactors = n.primeFactors := by rcases eq_or_ne n 0 with (rfl | hn) Β· simp induction k with | zero => simp | succ k ih => rw [pow_succ', primeFactors_mul hn (pow_ne_zero _ hn), ih, Finset.union_idempotent] lemma primeFactors_pow (n : β„•) (hk : k β‰  0) : (n ^ k).primeFactors = n.primeFactors := by cases k Β· simp at hk rw [primeFactors_pow_succ] /-- The only prime divisor of positive prime power `p^k` is `p` itself -/ lemma primeFactors_prime_pow (hk : k β‰  0) (hp : Prime p) : (p ^ k).primeFactors = {p} := by simp [primeFactors_pow p hk, hp] end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Dist.lean
import Mathlib.Algebra.Order.Group.Nat import Mathlib.Algebra.Order.Ring.Canonical /-! # Distance function on β„• This file defines a simple distance function on naturals from truncated subtraction. -/ namespace Nat /-- Distance (absolute value of difference) between natural numbers. -/ def dist (n m : β„•) := n - m + (m - n) theorem dist_comm (n m : β„•) : dist n m = dist m n := by simp [dist, add_comm] @[simp] theorem dist_self (n : β„•) : dist n n = 0 := by simp [dist, tsub_self] theorem eq_of_dist_eq_zero {n m : β„•} (h : dist n m = 0) : n = m := by unfold Nat.dist at h; cutsat theorem dist_eq_zero {n m : β„•} (h : n = m) : dist n m = 0 := by unfold Nat.dist; cutsat theorem dist_eq_sub_of_le {n m : β„•} (h : n ≀ m) : dist n m = m - n := by unfold Nat.dist; cutsat theorem dist_eq_sub_of_le_right {n m : β„•} (h : m ≀ n) : dist n m = n - m := by unfold Nat.dist; cutsat theorem dist_tri_left (n m : β„•) : m ≀ dist n m + n := by unfold Nat.dist; cutsat theorem dist_tri_right (n m : β„•) : m ≀ n + dist n m := by unfold Nat.dist; cutsat theorem dist_tri_left' (n m : β„•) : n ≀ dist n m + m := by unfold Nat.dist; cutsat theorem dist_tri_right' (n m : β„•) : n ≀ m + dist n m := by unfold Nat.dist; cutsat theorem dist_zero_right (n : β„•) : dist n 0 = n := by unfold Nat.dist; cutsat theorem dist_zero_left (n : β„•) : dist 0 n = n := by unfold Nat.dist; cutsat theorem dist_add_add_right (n k m : β„•) : dist (n + k) (m + k) = dist n m := by unfold Nat.dist; cutsat theorem dist_add_add_left (k n m : β„•) : dist (k + n) (k + m) = dist n m := by unfold Nat.dist; cutsat theorem dist_eq_intro {n m k l : β„•} (h : n + m = k + l) : dist n k = dist l m := by unfold Nat.dist; cutsat theorem dist.triangle_inequality (n m k : β„•) : dist n k ≀ dist n m + dist m k := by unfold Nat.dist; cutsat theorem dist_mul_right (n k m : β„•) : dist (n * k) (m * k) = dist n m * k := by rw [dist, dist, right_distrib, tsub_mul n, tsub_mul m] theorem dist_mul_left (k n m : β„•) : dist (k * n) (k * m) = k * dist n m := by rw [mul_comm k n, mul_comm k m, dist_mul_right, mul_comm] theorem dist_eq_max_sub_min {i j : β„•} : dist i j = (max i j) - min i j := by cases le_total i j <;> simp [Nat.dist, *] theorem dist_succ_succ {i j : Nat} : dist (succ i) (succ j) = dist i j := by unfold Nat.dist; cutsat theorem dist_pos_of_ne {i j : Nat} (h : i β‰  j) : 0 < dist i j := by unfold Nat.dist; cutsat end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/SuccPred.lean
import Mathlib.Algebra.Order.Group.Nat import Mathlib.Algebra.Ring.Nat import Mathlib.Algebra.Order.Monoid.Unbundled.WithTop import Mathlib.Algebra.Order.Sub.Unbundled.Basic import Mathlib.Algebra.Order.SuccPred import Mathlib.Data.Fin.Basic import Mathlib.Order.Nat import Mathlib.Order.SuccPred.Archimedean import Mathlib.Order.SuccPred.WithBot /-! # Successors and predecessors of naturals In this file, we show that `β„•` is both an archimedean `succOrder` and an archimedean `predOrder`. -/ open Function Order namespace Nat variable {m n : β„•} -- so that Lean reads `Nat.succ` through `succ_order.succ` @[instance] abbrev instSuccOrder : SuccOrder β„• := SuccOrder.ofSuccLeIff succ Nat.succ_le instance instSuccAddOrder : SuccAddOrder β„• := ⟨fun _ => rfl⟩ -- so that Lean reads `Nat.pred` through `pred_order.pred` @[instance] abbrev instPredOrder : PredOrder β„• where pred := pred pred_le := pred_le min_of_le_pred {a} ha := by cases a Β· exact isMin_bot Β· exact (not_succ_le_self _ ha).elim le_pred_of_lt {a} {b} h := by cases b Β· exact (a.not_lt_zero h).elim Β· exact le_of_succ_le_succ h instance instPredSubOrder : PredSubOrder β„• := ⟨fun _ => rfl⟩ @[simp] theorem succ_eq_succ : Order.succ = succ := rfl @[simp] theorem pred_eq_pred : Order.pred = pred := rfl protected theorem succ_iterate (a : β„•) : βˆ€ n, succ^[n] a = a + n := Order.succ_iterate a protected theorem pred_iterate (a : β„•) : βˆ€ n, pred^[n] a = a - n | 0 => rfl | n + 1 => by rw [Function.iterate_succ', sub_succ] exact congr_arg _ (Nat.pred_iterate a n) lemma le_succ_iff_eq_or_le : m ≀ n.succ ↔ m = n.succ ∨ m ≀ n := Order.le_succ_iff_eq_or_le instance : IsSuccArchimedean β„• := ⟨fun {a} {b} h => ⟨b - a, by rw [succ_eq_succ, Nat.succ_iterate, add_tsub_cancel_of_le h]⟩⟩ instance : IsPredArchimedean β„• := ⟨fun {a} {b} h => ⟨b - a, by rw [pred_eq_pred, Nat.pred_iterate, tsub_tsub_cancel_of_le h]⟩⟩ lemma forall_ne_zero_iff (P : β„• β†’ Prop) : (βˆ€ i, i β‰  0 β†’ P i) ↔ (βˆ€ i, P (i + 1)) := SuccOrder.forall_ne_bot_iff P end Nat @[simp, norm_cast] theorem Fin.coe_covBy_iff {n : β„•} {a b : Fin n} : (a : β„•) β‹– b ↔ a β‹– b := and_congr_right' ⟨fun h _c hc => h hc, fun h c ha hb => @h ⟨c, hb.trans b.prop⟩ ha hb⟩ alias ⟨_, CovBy.coe_fin⟩ := Fin.coe_covBy_iff @[simp] theorem withBotSucc_zero : WithBot.succ 0 = 1 := rfl @[simp] theorem withBotSucc_one : WithBot.succ 1 = 2 := rfl
.lake/packages/mathlib/Mathlib/Data/Nat/Sqrt.lean
import Mathlib.Data.Nat.Basic import Batteries.Data.Nat.Basic /-! # Properties of the natural number square root function. -/ namespace Nat /- We don't want to import the algebraic hierarchy in this file. -/ assert_not_exists Monoid variable {m n a : β„•} /-! ### `sqrt` See [Wikipedia, *Methods of computing square roots*] (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2)). -/ private lemma iter_fp_bound (n k : β„•) : let iter_next (n guess : β„•) := (guess + n / guess) / 2; sqrt.iter n k ≀ iter_next n (sqrt.iter n k) := by intro iter_next unfold sqrt.iter if h : (k + n / k) / 2 < k then simpa [if_pos h] using iter_fp_bound _ _ else grind private lemma AM_GM : {a b : β„•} β†’ (4 * a * b ≀ (a + b) * (a + b)) | 0, _ => by rw [Nat.mul_zero, Nat.zero_mul]; exact zero_le _ | _, 0 => by rw [Nat.mul_zero]; exact zero_le _ | a + 1, b + 1 => by simpa only [Nat.mul_add, Nat.add_mul, show (4 : β„•) = 1 + 1 + 1 + 1 from rfl, Nat.one_mul, Nat.mul_one, Nat.add_assoc, Nat.add_left_comm, Nat.add_le_add_iff_left] using Nat.add_le_add_right (@AM_GM a b) 4 -- These two lemmas seem like they belong to `Batteries.Data.Nat.Basic`. lemma sqrt.iter_sq_le (n guess : β„•) : sqrt.iter n guess * sqrt.iter n guess ≀ n := by unfold sqrt.iter let next := (guess + n / guess) / 2 if h : next < guess then simpa only [next, dif_pos h] using sqrt.iter_sq_le n next else apply Nat.mul_le_of_le_div grind lemma sqrt.lt_iter_succ_sq (n guess : β„•) (hn : n < (guess + 1) * (guess + 1)) : n < (sqrt.iter n guess + 1) * (sqrt.iter n guess + 1) := by unfold sqrt.iter -- m was `next` let m := (guess + n / guess) / 2 dsimp split_ifs with h Β· suffices n < (m + 1) * (m + 1) by simpa only [dif_pos h] using sqrt.lt_iter_succ_sq n m this refine Nat.lt_of_mul_lt_mul_left ?_ (a := 4 * (guess * guess)) apply Nat.lt_of_le_of_lt AM_GM rw [show (4 : β„•) = 2 * 2 from rfl] rw [Nat.mul_mul_mul_comm 2, Nat.mul_mul_mul_comm (2 * guess)] refine Nat.mul_self_lt_mul_self (?_ : _ < _ * ((_ / 2) + 1)) rw [← add_div_right _ (by decide), Nat.mul_comm 2, Nat.mul_assoc, show guess + n / guess + 2 = (guess + n / guess + 1) + 1 from rfl] have aux_lemma {a : β„•} : a ≀ 2 * ((a + 1) / 2) := by omega refine lt_of_lt_of_le ?_ (Nat.mul_le_mul_left _ aux_lemma) rw [Nat.add_assoc, Nat.mul_add] exact Nat.add_lt_add_left (lt_mul_div_succ _ (lt_of_le_of_lt (Nat.zero_le m) h)) _ Β· exact hn private def IsSqrt (n q : β„•) : Prop := q * q ≀ n ∧ n < (q + 1) * (q + 1) /- Sketch of proof: Up to rounding, in terms of the definition of `sqrt.iter`, * By AM-GM inequality, `nextΒ² β‰₯ n` giving one of the bounds. * When we terminated, we have `guess β‰₯ next` from which we deduce the other bound `n β‰₯ nextΒ²`. To turn this into a lean proof we need to manipulate, use properties of natural number division etc. -/ private lemma sqrt_isSqrt (n : β„•) : IsSqrt n (sqrt n) := by match n with | 0 => simp [IsSqrt, sqrt] | 1 => simp [IsSqrt, sqrt] | n + 2 => have h : Β¬ (n + 2) ≀ 1 := by simp simp only [IsSqrt, sqrt, h, ite_false] refine ⟨sqrt.iter_sq_le _ _, sqrt.lt_iter_succ_sq _ _ ?_⟩ simp only [Nat.mul_add, Nat.add_mul, Nat.one_mul, Nat.mul_one, ← Nat.add_assoc] rw [Nat.lt_add_one_iff, Nat.add_assoc, ← Nat.mul_two] refine le_trans (Nat.le_of_eq (div_add_mod' (n + 2) 2).symm) ?_ rw [show (n + 2) / 2 * 2 + (n + 2) % 2 = n + 2 by grind] simp only [shiftLeft_eq, Nat.one_mul] refine Nat.le_of_lt (Nat.le_trans lt_log2_self (le_add_right_of_le ?_)) rw [← Nat.pow_add] apply Nat.pow_le_pow_right (by decide) grind lemma sqrt_le (n : β„•) : sqrt n * sqrt n ≀ n := (sqrt_isSqrt n).left lemma sqrt_le' (n : β„•) : sqrt n ^ 2 ≀ n := by simpa [Nat.pow_two] using sqrt_le n lemma lt_succ_sqrt (n : β„•) : n < succ (sqrt n) * succ (sqrt n) := (sqrt_isSqrt n).right lemma lt_succ_sqrt' (n : β„•) : n < succ (sqrt n) ^ 2 := by simpa [Nat.pow_two] using lt_succ_sqrt n lemma sqrt_le_add (n : β„•) : n ≀ sqrt n * sqrt n + sqrt n + sqrt n := by rw [← succ_mul]; exact le_of_lt_succ (lt_succ_sqrt n) lemma le_sqrt : m ≀ sqrt n ↔ m * m ≀ n := ⟨fun h ↦ le_trans (mul_self_le_mul_self h) (sqrt_le n), fun h ↦ le_of_lt_succ <| Nat.mul_self_lt_mul_self_iff.1 <| lt_of_le_of_lt h (lt_succ_sqrt n)⟩ lemma le_sqrt' : m ≀ sqrt n ↔ m ^ 2 ≀ n := by simpa only [Nat.pow_two] using le_sqrt lemma sqrt_lt : sqrt m < n ↔ m < n * n := by simp only [← not_le, le_sqrt] lemma sqrt_lt' : sqrt m < n ↔ m < n ^ 2 := by simp only [← not_le, le_sqrt'] lemma sqrt_le_self (n : β„•) : sqrt n ≀ n := le_trans (le_mul_self _) (sqrt_le n) @[gcongr] lemma sqrt_le_sqrt (h : m ≀ n) : sqrt m ≀ sqrt n := le_sqrt.2 (le_trans (sqrt_le _) h) @[simp, grind =] lemma sqrt_zero : sqrt 0 = 0 := rfl @[simp, grind =] lemma sqrt_one : sqrt 1 = 1 := rfl lemma sqrt_eq_zero : sqrt n = 0 ↔ n = 0 := ⟨fun h ↦ have := @sqrt_lt n 1; by grind, by grind⟩ lemma eq_sqrt : a = sqrt n ↔ a * a ≀ n ∧ n < (a + 1) * (a + 1) := ⟨fun e ↦ e.symm β–Έ sqrt_isSqrt n, fun ⟨h₁, hβ‚‚βŸ© ↦ le_antisymm (le_sqrt.2 h₁) (le_of_lt_succ <| sqrt_lt.2 hβ‚‚)⟩ lemma eq_sqrt' : a = sqrt n ↔ a ^ 2 ≀ n ∧ n < (a + 1) ^ 2 := by simpa only [Nat.pow_two] using eq_sqrt lemma le_three_of_sqrt_eq_one (h : sqrt n = 1) : n ≀ 3 := le_of_lt_succ <| (@sqrt_lt n 2).1 <| by grind lemma sqrt_lt_self (h : 1 < n) : sqrt n < n := sqrt_lt.2 <| by have := Nat.mul_lt_mul_of_pos_left h (lt_of_succ_lt h); grind @[grind =] lemma sqrt_pos : 0 < sqrt n ↔ 0 < n := le_sqrt lemma sqrt_add_eq (n : β„•) (h : a ≀ n + n) : sqrt (n * n + a) = n := le_antisymm (le_of_lt_succ <| sqrt_lt.2 <| by grind) (le_sqrt.2 <| by grind) lemma sqrt_add_eq' (n : β„•) (h : a ≀ n + n) : sqrt (n ^ 2 + a) = n := by simpa [Nat.pow_two] using sqrt_add_eq n h @[simp] lemma sqrt_eq (n : β„•) : sqrt (n * n) = n := sqrt_add_eq n (zero_le _) @[simp] lemma sqrt_eq' (n : β„•) : sqrt (n ^ 2) = n := sqrt_add_eq' n (zero_le _) lemma sqrt_succ_le_succ_sqrt (n : β„•) : sqrt n.succ ≀ n.sqrt.succ := le_of_lt_succ <| sqrt_lt.2 <| (have := sqrt_le_add n; by grind) @[simp] lemma log2_two : (2 : β„•).log2 = 1 := rfl @[simp] lemma sqrt_two : sqrt 2 = 1 := by simp [sqrt, sqrt.iter] lemma add_one_sqrt_le_of_ne_zero {n : β„•} (hn : n β‰  0) : (n + 1).sqrt ≀ n := le_induction (by simp) (fun n _ ih ↦ le_trans n.succ.sqrt_succ_le_succ_sqrt (succ_le_succ ih)) n (Nat.pos_of_ne_zero hn) lemma exists_mul_self (x : β„•) : (βˆƒ n, n * n = x) ↔ sqrt x * sqrt x = x := ⟨fun ⟨n, hn⟩ ↦ by rw [← hn, sqrt_eq], fun h ↦ ⟨sqrt x, h⟩⟩ lemma exists_mul_self' (x : β„•) : (βˆƒ n, n ^ 2 = x) ↔ sqrt x ^ 2 = x := by simpa only [Nat.pow_two] using exists_mul_self x lemma sqrt_mul_sqrt_lt_succ (n : β„•) : sqrt n * sqrt n < n + 1 := Nat.lt_succ_iff.mpr (sqrt_le _) lemma sqrt_mul_sqrt_lt_succ' (n : β„•) : sqrt n ^ 2 < n + 1 := Nat.lt_succ_iff.mpr (sqrt_le' _) lemma succ_le_succ_sqrt (n : β„•) : n + 1 ≀ (sqrt n + 1) * (sqrt n + 1) := le_of_pred_lt (lt_succ_sqrt _) lemma succ_le_succ_sqrt' (n : β„•) : n + 1 ≀ (sqrt n + 1) ^ 2 := le_of_pred_lt (lt_succ_sqrt' _) /-- There are no perfect squares strictly between mΒ² and (m+1)Β² -/ lemma not_exists_sq (hl : m * m < n) (hr : n < (m + 1) * (m + 1)) : Β¬βˆƒ t, t * t = n := by rintro ⟨t, rfl⟩ have h1 : m < t := Nat.mul_self_lt_mul_self_iff.1 hl have h2 : t < m + 1 := Nat.mul_self_lt_mul_self_iff.1 hr grind lemma not_exists_sq' : m ^ 2 < n β†’ n < (m + 1) ^ 2 β†’ Β¬βˆƒ t, t ^ 2 = n := by simpa only [Nat.pow_two] using not_exists_sq lemma le_sqrt_of_eq_mul {a b c : β„•} (h : a = b * c) : b ≀ a.sqrt ∨ c ≀ a.sqrt := by rcases le_total b c with bc | cb Β· exact Or.inl <| le_sqrt.mpr <| h β–Έ mul_le_mul_left b bc Β· exact Or.inr <| le_sqrt.mpr <| h β–Έ mul_le_mul_right c cb end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/BinaryRec.lean
import Batteries.Tactic.Alias import Mathlib.Init /-! # Binary recursion on `Nat` This file defines binary recursion on `Nat`. ## Main results * `Nat.binaryRec`: A recursion principle for `bit` representations of natural numbers. * `Nat.binaryRec'`: The same as `binaryRec`, but the induction step can assume that if `n=0`, the bit being appended is `true`. * `Nat.binaryRecFromOne`: The same as `binaryRec`, but special casing both 0 and 1 as base cases. -/ universe u namespace Nat /-- `bit b` appends the digit `b` to the little end of the binary representation of its natural number input. -/ def bit (b : Bool) (n : Nat) : Nat := cond b (2 * n + 1) (2 * n) theorem shiftRight_one (n) : n >>> 1 = n / 2 := rfl @[simp] theorem bit_decide_mod_two_eq_one_shiftRight_one (n : Nat) : bit (n % 2 = 1) (n >>> 1) = n := by simp only [bit, shiftRight_one] cases mod_two_eq_zero_or_one n with | _ h => simpa [h] using Nat.div_add_mod n 2 theorem bit_testBit_zero_shiftRight_one (n : Nat) : bit (n.testBit 0) (n >>> 1) = n := by simp @[simp] theorem bit_eq_zero_iff {n : Nat} {b : Bool} : bit b n = 0 ↔ n = 0 ∧ b = false := by cases n <;> cases b <;> simp [bit, Nat.two_mul, ← Nat.add_assoc] /-- For a predicate `motive : Nat β†’ Sort u`, if instances can be constructed for natural numbers of the form `bit b n`, they can be constructed for any given natural number. -/ @[inline] def bitCasesOn {motive : Nat β†’ Sort u} (n) (bit : βˆ€ b n, motive (bit b n)) : motive n := -- `1 &&& n != 0` is faster than `n.testBit 0`. This may change when we have faster `testBit`. let x := bit (1 &&& n != 0) (n >>> 1) -- `congrArg motive _ β–Έ x` is defeq to `x` in non-dependent case congrArg motive n.bit_testBit_zero_shiftRight_one β–Έ x /-- A recursion principle for `bit` representations of natural numbers. For a predicate `motive : Nat β†’ Sort u`, if instances can be constructed for natural numbers of the form `bit b n`, they can be constructed for all natural numbers. -/ @[elab_as_elim, specialize] def binaryRec {motive : Nat β†’ Sort u} (zero : motive 0) (bit : βˆ€ b n, motive n β†’ motive (bit b n)) (n : Nat) : motive n := if n0 : n = 0 then congrArg motive n0 β–Έ zero else let x := bit (1 &&& n != 0) (n >>> 1) (binaryRec zero bit (n >>> 1)) congrArg motive n.bit_testBit_zero_shiftRight_one β–Έ x decreasing_by exact bitwise_rec_lemma n0 /-- The same as `binaryRec`, but the induction step can assume that if `n=0`, the bit being appended is `true` -/ @[elab_as_elim, specialize] def binaryRec' {motive : Nat β†’ Sort u} (zero : motive 0) (bit : βˆ€ b n, (n = 0 β†’ b = true) β†’ motive n β†’ motive (bit b n)) : βˆ€ n, motive n := binaryRec zero fun b n ih => if h : n = 0 β†’ b = true then bit b n h ih else have : n.bit b = 0 := by rw [bit_eq_zero_iff] cases n <;> cases b <;> simp at h ⊒ congrArg motive this β–Έ zero /-- The same as `binaryRec`, but special casing both 0 and 1 as base cases -/ @[elab_as_elim, specialize] def binaryRecFromOne {motive : Nat β†’ Sort u} (zero : motive 0) (one : motive 1) (bit : βˆ€ b n, n β‰  0 β†’ motive n β†’ motive (bit b n)) : βˆ€ n, motive n := binaryRec' zero fun b n h ih => if h' : n = 0 then have : n.bit b = Nat.bit true 0 := by rw [h', h h'] congrArg motive this β–Έ one else bit b n h' ih theorem bit_val (b n) : bit b n = 2 * n + b.toNat := by cases b <;> rfl @[simp] theorem bit_div_two (b n) : bit b n / 2 = n := by rw [bit_val, Nat.add_comm, add_mul_div_left, div_eq_of_lt, Nat.zero_add] Β· cases b <;> decide Β· decide @[simp] theorem bit_mod_two (b n) : bit b n % 2 = b.toNat := by cases b <;> simp [bit_val] @[simp] theorem bit_shiftRight_one (b n) : bit b n >>> 1 = n := bit_div_two b n theorem testBit_bit_zero (b n) : (bit b n).testBit 0 = b := by simp variable {motive : Nat β†’ Sort u} @[simp] theorem bitCasesOn_bit (h : βˆ€ b n, motive (bit b n)) (b : Bool) (n : Nat) : bitCasesOn (bit b n) h = h b n := by change congrArg motive (bit b n).bit_testBit_zero_shiftRight_one β–Έ h _ _ = h b n generalize congrArg motive (bit b n).bit_testBit_zero_shiftRight_one = e; revert e rw [testBit_bit_zero, bit_shiftRight_one] intros; rfl @[simp] theorem binaryRec_zero (zero : motive 0) (bit : βˆ€ b n, motive n β†’ motive (bit b n)) : binaryRec zero bit 0 = zero := by rw [binaryRec] simp @[simp] theorem binaryRec_one (zero : motive 0) (bit : βˆ€ b n, motive n β†’ motive (bit b n)) : binaryRec (motive := motive) zero bit 1 = bit true 0 zero := by rw [binaryRec] simp only [add_one_ne_zero, ↓reduceDIte, Nat.reduceShiftRight, binaryRec_zero] rfl theorem binaryRec_eq {zero : motive 0} {bit : βˆ€ b n, motive n β†’ motive (bit b n)} (b n) (h : bit false 0 zero = zero ∨ (n = 0 β†’ b = true)) : binaryRec zero bit (n.bit b) = bit b n (binaryRec zero bit n) := by by_cases h' : n.bit b = 0 case pos => obtain ⟨rfl, rfl⟩ := bit_eq_zero_iff.mp h' simp only [Bool.false_eq_true, imp_false, not_true_eq_false, or_false] at h unfold binaryRec exact h.symm case neg => rw [binaryRec, dif_neg h'] change congrArg motive (n.bit b).bit_testBit_zero_shiftRight_one β–Έ bit _ _ _ = _ generalize congrArg motive (n.bit b).bit_testBit_zero_shiftRight_one = e; revert e rw [testBit_bit_zero, bit_shiftRight_one] intros; rfl @[simp] theorem binaryRec'_zero (zero : motive 0) (bit : (b : Bool) β†’ (n : Nat) β†’ (n = 0 β†’ b = true) β†’ motive n β†’ motive (n.bit b)) : binaryRec' zero bit 0 = zero := by rw [binaryRec', Nat.binaryRec_zero] @[simp] theorem binaryRec'_one (zero : motive 0) (bit : (b : Bool) β†’ (n : Nat) β†’ (n = 0 β†’ b = true) β†’ motive n β†’ motive (n.bit b)) : binaryRec' (motive := motive) zero bit 1 = bit true 0 (by simp) zero := by rw [binaryRec', Nat.binaryRec_one, dif_pos] theorem binaryRec'_eq {zero : motive 0} {bit : (b : Bool) β†’ (n : Nat) β†’ (n = 0 β†’ b = true) β†’ motive n β†’ motive (n.bit b)} (b n) (h : n = 0 β†’ b = true) : binaryRec' zero bit (n.bit b) = bit b n h (binaryRec' zero bit n) := by rw [binaryRec', binaryRec_eq _ _ (by simp), dif_pos h, binaryRec'] @[simp] theorem binaryRecFromOne_zero (zero : motive 0) (one : motive 1) (bit : (b : Bool) β†’ (n : Nat) β†’ n β‰  0 β†’ motive n β†’ motive (n.bit b)) : binaryRecFromOne zero one bit 0 = zero := binaryRec'_zero _ _ @[simp] theorem binaryRecFromOne_one {zero : motive 0} {one : motive 1} (bit : (b : Bool) β†’ (n : Nat) β†’ n β‰  0 β†’ motive n β†’ motive (n.bit b)) : binaryRecFromOne zero one bit 1 = one := by rw [binaryRecFromOne, binaryRec'_one, dif_pos rfl] theorem binaryRecFromOne_eq {zero : motive 0} {one : motive 1} {bit : (b : Bool) β†’ (n : Nat) β†’ n β‰  0 β†’ motive n β†’ motive (n.bit b)} (b n) (h) : binaryRecFromOne zero one bit (Nat.bit b n) = bit b n h (binaryRecFromOne zero one bit n) := by rw [binaryRecFromOne, binaryRec'_eq _ _ (by simp [h]), dif_neg h, binaryRecFromOne] end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/BitIndices.lean
import Mathlib.Algebra.BigOperators.Ring.List import Mathlib.Algebra.Order.BigOperators.Group.List import Mathlib.Algebra.Order.Group.Nat import Mathlib.Algebra.Order.Sub.Basic import Mathlib.Data.List.Sort import Mathlib.Data.Nat.Bitwise /-! # Bit Indices Given `n : β„•`, we define `Nat.bitIndices n`, which is the `List` of indices of `1`s in the binary expansion of `n`. If `s : Finset β„•` and `n = βˆ‘ i ∈ s, 2^i`, then `Nat.bitIndices n` is the sorted list of elements of `s`. The lemma `twoPowSum_bitIndices` proves that summing `2 ^ i` over this list gives `n`. This is used in `Combinatorics.colex` to construct a bijection `equivBitIndices : β„• ≃ Finset β„•`. ## TODO Relate the material in this file to `Nat.digits` and `Nat.bits`. -/ open List namespace Nat variable {a n : β„•} /-- The function which maps each natural number `βˆ‘ i ∈ s, 2^i` to the list of elements of `s` in increasing order. -/ def bitIndices (n : β„•) : List β„• := @binaryRec (fun _ ↦ List β„•) [] (fun b _ s ↦ b.casesOn (s.map (Β· + 1)) (0 :: s.map (Β· + 1))) n @[simp] theorem bitIndices_zero : bitIndices 0 = [] := by simp [bitIndices] @[simp] theorem bitIndices_one : bitIndices 1 = [0] := by simp [bitIndices] theorem bitIndices_bit_true (n : β„•) : bitIndices (bit true n) = 0 :: ((bitIndices n).map (Β· + 1)) := binaryRec_eq _ _ (.inl rfl) theorem bitIndices_bit_false (n : β„•) : bitIndices (bit false n) = (bitIndices n).map (Β· + 1) := binaryRec_eq _ _ (.inl rfl) @[simp] theorem bitIndices_two_mul_add_one (n : β„•) : bitIndices (2 * n + 1) = 0 :: (bitIndices n).map (Β· + 1) := by rw [← bitIndices_bit_true, bit_true] @[simp] theorem bitIndices_two_mul (n : β„•) : bitIndices (2 * n) = (bitIndices n).map (Β· + 1) := by rw [← bitIndices_bit_false, bit_false] @[simp] theorem bitIndices_sorted {n : β„•} : n.bitIndices.Sorted (Β· < Β·) := by induction n using binaryRec with | zero => simp | bit b n hs => suffices List.Pairwise (fun a b ↦ a < b) n.bitIndices by cases b <;> simpa [List.Sorted, bit_false, bit_true, List.pairwise_map] exact List.Pairwise.imp (by simp) hs @[simp] theorem bitIndices_two_pow_mul (k n : β„•) : bitIndices (2^k * n) = (bitIndices n).map (Β· + k) := by induction k with | zero => simp | succ k ih => rw [add_comm, pow_add, pow_one, mul_assoc, bitIndices_two_mul, ih, List.map_map, comp_add_right] simp [add_comm (a := 1)] @[simp] theorem bitIndices_two_pow (k : β„•) : bitIndices (2^k) = [k] := by rw [← mul_one (a := 2^k), bitIndices_two_pow_mul]; simp @[simp] theorem twoPowSum_bitIndices (n : β„•) : (n.bitIndices.map (fun i ↦ 2 ^ i)).sum = n := by induction n using binaryRec with | zero => simp | bit b n hs => have hrw : (fun i ↦ 2^i) ∘ (fun x ↦ x+1) = fun i ↦ 2 * 2 ^ i := by ext i; simp [pow_add, mul_comm] cases b Β· simpa [hrw, List.sum_map_mul_left] simp [hrw, List.sum_map_mul_left, hs, add_comm (a := 1)] /-- Together with `Nat.twoPowSum_bitIndices`, this implies a bijection between `β„•` and `Finset β„•`. See `Finset.equivBitIndices` for this bijection. -/ theorem bitIndices_twoPowsum {L : List β„•} (hL : List.Sorted (Β· < Β·) L) : (L.map (fun i ↦ 2^i)).sum.bitIndices = L := by cases L with | nil => simp | cons a L => obtain ⟨haL, hL⟩ := sorted_cons.1 hL simp_rw [Nat.lt_iff_add_one_le] at haL have h' : βˆƒ (Lβ‚€ : List β„•), Lβ‚€.Sorted (Β· < Β·) ∧ L = Lβ‚€.map (Β· + a + 1) := by refine ⟨L.map (Β· - (a+1)), ?_, ?_⟩ Β· rwa [Sorted, pairwise_map, Pairwise.and_mem, Pairwise.iff (S := fun x y ↦ x ∈ L ∧ y ∈ L ∧ x < y), ← Pairwise.and_mem] simp only [and_congr_right_iff] exact fun x y hx _ ↦ by rw [tsub_lt_tsub_iff_right (haL _ hx)] have h' : βˆ€ x ∈ L, ((fun x ↦ x + a + 1) ∘ (fun x ↦ x - (a + 1))) x = x := fun x hx ↦ by simp only [add_assoc, Function.comp_apply]; rw [tsub_add_cancel_of_le (haL _ hx)] simp [List.map_congr_left h'] obtain ⟨Lβ‚€, hLβ‚€, rfl⟩ := h' have hrw : (2^Β·) ∘ (Β· + a + 1) = fun i ↦ 2^a * (2 * 2^i) := by ext x; simp only [Function.comp_apply, pow_add, pow_one]; ac_rfl simp only [List.map_cons, List.map_map, List.sum_map_mul_left, List.sum_cons, hrw] nth_rw 1 [← mul_one (a := 2^a)] rw [← mul_add, bitIndices_two_pow_mul, add_comm, bitIndices_two_mul_add_one, bitIndices_twoPowsum hLβ‚€] simp [add_comm (a := 1), add_assoc] termination_by L.length theorem two_pow_le_of_mem_bitIndices (ha : a ∈ n.bitIndices) : 2^a ≀ n := by rw [← twoPowSum_bitIndices n] exact List.single_le_sum (by simp) _ <| mem_map_of_mem ha theorem notMem_bitIndices_self (n : β„•) : n βˆ‰ n.bitIndices := fun h ↦ (n.lt_two_pow_self).not_ge <| two_pow_le_of_mem_bitIndices h @[deprecated (since := "2025-05-23")] alias not_mem_bitIndices_self := notMem_bitIndices_self end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/EvenOddRec.lean
import Mathlib.Algebra.Ring.Parity import Mathlib.Data.Nat.BinaryRec /-! # A recursion principle based on even and odd numbers. -/ namespace Nat /-- Recursion principle on even and odd numbers: if we have `P 0`, and for all `i : β„•` we can extend from `P i` to both `P (2 * i)` and `P (2 * i + 1)`, then we have `P n` for all `n : β„•`. This is nothing more than a wrapper around `Nat.binaryRec`, to avoid having to switch to dealing with `bit0` and `bit1`. -/ @[elab_as_elim] def evenOddRec {P : β„• β†’ Sort*} (h0 : P 0) (h_even : βˆ€ n, P n β†’ P (2 * n)) (h_odd : βˆ€ n, P n β†’ P (2 * n + 1)) (n : β„•) : P n := binaryRec h0 (fun | false, i, hi => (h_even i hi : P (2 * i)) | true, i, hi => (h_odd i hi : P (2 * i + 1))) n @[simp] theorem evenOddRec_zero {P : β„• β†’ Sort*} (h0 : P 0) (h_even : βˆ€ i, P i β†’ P (2 * i)) (h_odd : βˆ€ i, P i β†’ P (2 * i + 1)) : evenOddRec h0 h_even h_odd 0 = h0 := binaryRec_zero _ _ @[simp] theorem evenOddRec_even {P : β„• β†’ Sort*} (h0 : P 0) (h_even : βˆ€ i, P i β†’ P (2 * i)) (h_odd : βˆ€ i, P i β†’ P (2 * i + 1)) (H : h_even 0 h0 = h0) (n : β„•) : (2 * n).evenOddRec h0 h_even h_odd = h_even n (evenOddRec h0 h_even h_odd n) := by apply binaryRec_eq false n simp [H] @[simp] theorem evenOddRec_odd {P : β„• β†’ Sort*} (h0 : P 0) (h_even : βˆ€ i, P i β†’ P (2 * i)) (h_odd : βˆ€ i, P i β†’ P (2 * i + 1)) (H : h_even 0 h0 = h0) (n : β„•) : (2 * n + 1).evenOddRec h0 h_even h_odd = h_odd n (evenOddRec h0 h_even h_odd n) := by apply binaryRec_eq true n simp [H] /-- Strong recursion principle on even and odd numbers: if for all `i : β„•` we can prove `P (2 * i)` from `P j` for all `j < 2 * i` and we can prove `P (2 * i + 1)` from `P j` for all `j < 2 * i + 1`, then we have `P n` for all `n : β„•`. -/ @[elab_as_elim] noncomputable def evenOddStrongRec {P : β„• β†’ Sort*} (h_even : βˆ€ n : β„•, (βˆ€ k < 2 * n, P k) β†’ P (2 * n)) (h_odd : βˆ€ n : β„•, (βˆ€ k < 2 * n + 1, P k) β†’ P (2 * n + 1)) (n : β„•) : P n := n.strongRecOn fun m ih => m.even_or_odd'.choose_spec.by_cases (fun h => h.symm β–Έ h_even m.even_or_odd'.choose <| h β–Έ ih) (fun h => h.symm β–Έ h_odd m.even_or_odd'.choose <| h β–Έ ih) end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Init.lean
import Batteries.Tactic.Alias import Batteries.Tactic.Init import Mathlib.Init import Mathlib.Data.Int.Notation import Mathlib.Data.Nat.Notation import Mathlib.Tactic.Basic import Mathlib.Tactic.Lemma import Mathlib.Tactic.TypeStar import Mathlib.Util.AssertExists /-! # Basic operations on the natural numbers This file contains: * some basic lemmas about natural numbers * extra recursors: * `leRecOn`, `le_induction`: recursion and induction principles starting at non-zero numbers * `decreasing_induction`: recursion growing downwards * `le_rec_on'`, `decreasing_induction'`: versions with slightly weaker assumptions * `strong_rec'`: recursion based on strong inequalities * decidability instances on predicates about the natural numbers This file should not depend on anything defined in Mathlib (except for notation), so that it can be upstreamed to Batteries or the Lean standard library easily. See note [foundational algebra order theory]. -/ library_note2 Β«foundational algebra order theoryΒ» /-- Batteries has a home-baked development of the algebraic and order-theoretic theory of `β„•` and `β„€` which, in particular, is not typeclass-mediated. This is useful to set up the algebra and finiteness libraries in mathlib (naturals and integers show up as indices/offsets in lists, cardinality in finsets, powers in groups, ...). Less basic uses of `β„•` and `β„€` should however use the typeclass-mediated development. The relevant files are: * `Mathlib/Data/Nat/Basic.lean` for the continuation of the home-baked development on `β„•` * `Mathlib/Data/Int/Init.lean` for the continuation of the home-baked development on `β„€` * `Mathlib/Algebra/Group/Nat.lean` for the monoid instances on `β„•` * `Mathlib/Algebra/Group/Int.lean` for the group instance on `β„€` * `Mathlib/Algebra/Ring/Nat.lean` for the semiring instance on `β„•` * `Mathlib/Algebra/Ring/Int.lean` for the ring instance on `β„€` * `Mathlib/Algebra/Order/Group/Nat.lean` for the ordered monoid instance on `β„•` * `Mathlib/Algebra/Order/Group/Int.lean` for the ordered group instance on `β„€` * `Mathlib/Algebra/Order/Ring/Nat.lean` for the ordered semiring instance on `β„•` * `Mathlib/Algebra/Order/Ring/Int.lean` for the ordered ring instance on `β„€` -/ /- We don't want to import the algebraic hierarchy in this file. -/ assert_not_exists Monoid open Function namespace Nat variable {a b c d e m n k : β„•} {p : β„• β†’ Prop} /-! ### `succ`, `pred` -/ lemma succ_pos' : 0 < succ n := succ_pos n alias _root_.LT.lt.nat_succ_le := succ_le_of_lt alias ⟨of_le_succ, _⟩ := le_succ_iff @[deprecated (since := "2025-08-21")] alias forall_lt_succ := forall_lt_succ_right @[deprecated (since := "2025-08-15")] alias exists_lt_succ := exists_lt_succ_right lemma two_lt_of_ne : βˆ€ {n}, n β‰  0 β†’ n β‰  1 β†’ n β‰  2 β†’ 2 < n | 0, h, _, _ => (h rfl).elim | 1, _, h, _ => (h rfl).elim | 2, _, _, h => (h rfl).elim | n + 3, _, _, _ => le_add_left 3 n lemma two_le_iff : βˆ€ n, 2 ≀ n ↔ n β‰  0 ∧ n β‰  1 | 0 => by simp | 1 => by simp | n + 2 => by simp /-! ### `add` -/ /-! ### `sub` -/ /-! ### `mul` -/ lemma mul_def : Nat.mul m n = m * n := mul_eq lemma two_mul_ne_two_mul_add_one : 2 * n β‰  2 * m + 1 := mt (congrArg (Β· % 2)) (by rw [Nat.add_comm, add_mul_mod_self_left, mul_mod_right, mod_eq_of_lt] <;> simp) @[deprecated (since := "2025-06-05")] alias mul_right_eq_self_iff := mul_eq_left @[deprecated (since := "2025-06-05")] alias mul_left_eq_self_iff := mul_eq_right @[deprecated (since := "2025-06-05")] alias eq_zero_of_double_le := eq_zero_of_two_mul_le /-! ### `div` -/ lemma le_div_two_iff_mul_two_le {n m : β„•} : m ≀ n / 2 ↔ (m : β„€) * 2 ≀ n := by rw [Nat.le_div_iff_mul_le Nat.zero_lt_two, ← Int.ofNat_le, Int.natCast_mul, Int.ofNat_two] /-- A version of `Nat.div_lt_self` using successors, rather than additional hypotheses. -/ lemma div_lt_self' (a b : β„•) : (a + 1) / (b + 2) < a + 1 := Nat.div_lt_self (Nat.succ_pos _) (Nat.succ_lt_succ (Nat.succ_pos _)) @[deprecated (since := "2025-06-05")] alias eq_zero_of_le_half := eq_zero_of_le_div_two @[deprecated (since := "2025-06-05")] alias le_half_of_half_lt_sub := le_div_two_of_div_two_lt_sub @[deprecated (since := "2025-06-05")] alias half_le_of_sub_le_half := div_two_le_of_sub_le_div_two @[deprecated (since := "2025-06-05")] protected alias div_le_of_le_mul' := Nat.div_le_of_le_mul @[deprecated (since := "2025-06-05")] protected alias div_le_self' := Nat.div_le_self lemma two_mul_odd_div_two (hn : n % 2 = 1) : 2 * (n / 2) = n - 1 := by cutsat /-! ### `pow` -/ lemma one_le_pow' (n m : β„•) : 1 ≀ (m + 1) ^ n := one_le_pow n (m + 1) (succ_pos m) alias sq_sub_sq := pow_two_sub_pow_two /-! ### Recursion and induction principles This section is here due to dependencies -- the lemmas here require some of the lemmas proved above, and some of the results in later sections depend on the definitions in this section. -/ @[simp] lemma rec_zero {C : β„• β†’ Sort*} (h0 : C 0) (h : βˆ€ n, C n β†’ C (n + 1)) : Nat.rec h0 h 0 = h0 := rfl -- Not `@[simp]` since `simp` can reduce the whole term. lemma rec_add_one {C : β„• β†’ Sort*} (h0 : C 0) (h : βˆ€ n, C n β†’ C (n + 1)) (n : β„•) : Nat.rec h0 h (n + 1) = h n (Nat.rec h0 h n) := rfl @[simp] lemma rec_one {C : β„• β†’ Sort*} (h0 : C 0) (h : βˆ€ n, C n β†’ C (n + 1)) : Nat.rec (motive := C) h0 h 1 = h 0 h0 := rfl /-- Recursion starting at a non-zero number: given a map `C k β†’ C (k+1)` for each `k β‰₯ n`, there is a map from `C n` to each `C m`, `n ≀ m`. This is a version of `Nat.le.rec` that works for `Sort u`. Similarly to `Nat.le.rec`, it can be used as ``` induction hle using Nat.leRec with | refl => sorry | le_succ_of_le hle ih => sorry ``` -/ @[elab_as_elim] def leRec {n} {motive : (m : β„•) β†’ n ≀ m β†’ Sort*} (refl : motive n (Nat.le_refl _)) (le_succ_of_le : βˆ€ ⦃k⦄ (h : n ≀ k), motive k h β†’ motive (k + 1) (le_succ_of_le h)) : βˆ€ {m} (h : n ≀ m), motive m h | 0, H => Nat.eq_zero_of_le_zero H β–Έ refl | m + 1, H => (le_succ_iff.1 H).by_cases (fun h : n ≀ m ↦ le_succ_of_le h <| leRec refl le_succ_of_le h) (fun h : n = m + 1 ↦ h β–Έ refl) -- This verifies the signatures of the recursor matches the builtin one, as promised in the -- above. theorem leRec_eq_leRec : @Nat.leRec.{0} = @Nat.le.rec := rfl @[simp] lemma leRec_self {n} {motive : (m : β„•) β†’ n ≀ m β†’ Sort*} (refl : motive n (Nat.le_refl _)) (le_succ_of_le : βˆ€ ⦃k⦄ (h : n ≀ k), motive k h β†’ motive (k + 1) (le_succ_of_le h)) : (leRec (motive := motive) refl le_succ_of_le (Nat.le_refl _) : motive n (Nat.le_refl _)) = refl := by cases n <;> simp [leRec, Or.by_cases, dif_neg] @[simp] lemma leRec_succ {n} {motive : (m : β„•) β†’ n ≀ m β†’ Sort*} (refl : motive n (Nat.le_refl _)) (le_succ_of_le : βˆ€ ⦃k⦄ (h : n ≀ k), motive k h β†’ motive (k + 1) (le_succ_of_le h)) (h1 : n ≀ m) {h2 : n ≀ m + 1} : (leRec (motive := motive) refl le_succ_of_le h2) = le_succ_of_le h1 (leRec (motive := motive) refl le_succ_of_le h1) := by conv => lhs rw [leRec, Or.by_cases, dif_pos h1] lemma leRec_succ' {n} {motive : (m : β„•) β†’ n ≀ m β†’ Sort*} (refl le_succ_of_le) : (leRec (motive := motive) refl le_succ_of_le (le_succ _)) = le_succ_of_le _ refl := by rw [leRec_succ, leRec_self] lemma leRec_trans {n m k} {motive : (m : β„•) β†’ n ≀ m β†’ Sort*} (refl le_succ_of_le) (hnm : n ≀ m) (hmk : m ≀ k) : leRec (motive := motive) refl le_succ_of_le (Nat.le_trans hnm hmk) = leRec (leRec refl (fun _ h => le_succ_of_le h) hnm) (fun _ h => le_succ_of_le <| Nat.le_trans hnm h) hmk := by induction hmk with | refl => rw [leRec_self] | step hmk ih => rw [leRec_succ _ _ (Nat.le_trans hnm hmk), ih, leRec_succ] lemma leRec_succ_left {motive : (m : β„•) β†’ n ≀ m β†’ Sort*} (refl le_succ_of_le) {m} (h1 : n ≀ m) (h2 : n + 1 ≀ m) : -- the `@` is needed for this to elaborate, even though we only provide explicit arguments! @leRec _ _ (le_succ_of_le (Nat.le_refl _) refl) (fun _ h ih => le_succ_of_le (le_of_succ_le h) ih) _ h2 = leRec (motive := motive) refl le_succ_of_le h1 := by rw [leRec_trans _ _ (le_succ n) h2, leRec_succ'] /-- Recursion starting at a non-zero number: given a map `C k β†’ C (k + 1)` for each `k`, there is a map from `C n` to each `C m`, `n ≀ m`. For a version where the assumption is only made when `k β‰₯ n`, see `Nat.leRec`. -/ @[elab_as_elim] def leRecOn {C : β„• β†’ Sort*} {n : β„•} : βˆ€ {m}, n ≀ m β†’ (βˆ€ {k}, C k β†’ C (k + 1)) β†’ C n β†’ C m := fun h of_succ self => Nat.leRec self (fun _ _ => @of_succ _) h lemma leRecOn_self {C : β„• β†’ Sort*} {n} {next : βˆ€ {k}, C k β†’ C (k + 1)} (x : C n) : (leRecOn n.le_refl next x : C n) = x := leRec_self _ _ lemma leRecOn_succ {C : β„• β†’ Sort*} {n m} (h1 : n ≀ m) {h2 : n ≀ m + 1} {next} (x : C n) : (leRecOn h2 next x : C (m + 1)) = next (leRecOn h1 next x : C m) := leRec_succ _ _ _ lemma leRecOn_succ' {C : β„• β†’ Sort*} {n} {h : n ≀ n + 1} {next : βˆ€ {k}, C k β†’ C (k + 1)} (x : C n) : (leRecOn h next x : C (n + 1)) = next x := leRec_succ' _ _ lemma leRecOn_trans {C : β„• β†’ Sort*} {n m k} (hnm : n ≀ m) (hmk : m ≀ k) {next} (x : C n) : (leRecOn (Nat.le_trans hnm hmk) (@next) x : C k) = leRecOn hmk (@next) (leRecOn hnm (@next) x) := leRec_trans _ _ _ _ lemma leRecOn_succ_left {C : β„• β†’ Sort*} {n m} {next : βˆ€ {k}, C k β†’ C (k + 1)} (x : C n) (h1 : n ≀ m) (h2 : n + 1 ≀ m) : (leRecOn h2 next (next x) : C m) = (leRecOn h1 next x : C m) := leRec_succ_left (motive := fun n _ => C n) _ (fun _ _ => @next _) _ _ /-- Recursion principle based on `<`. -/ @[elab_as_elim] protected def strongRec' {p : β„• β†’ Sort*} (H : βˆ€ n, (βˆ€ m, m < n β†’ p m) β†’ p n) : βˆ€ n : β„•, p n | n => H n fun m _ ↦ Nat.strongRec' H m /-- Recursion principle based on `<` applied to some natural number. -/ @[elab_as_elim] def strongRecOn' {P : β„• β†’ Sort*} (n : β„•) (h : βˆ€ n, (βˆ€ m, m < n β†’ P m) β†’ P n) : P n := Nat.strongRec' h n lemma strongRecOn'_beta {P : β„• β†’ Sort*} {h} : (strongRecOn' n h : P n) = h n fun m _ ↦ (strongRecOn' m h : P m) := by simp only [strongRecOn']; rw [Nat.strongRec'] /-- Induction principle starting at a non-zero number. To use in an induction proof, the syntax is `induction n, hn using Nat.le_induction` (or the same for `induction'`). This is an alias of `Nat.leRec`, specialized to `Prop`. -/ @[elab_as_elim] lemma le_induction {m : β„•} {P : βˆ€ n, m ≀ n β†’ Prop} (base : P m m.le_refl) (succ : βˆ€ n hmn, P n hmn β†’ P (n + 1) (le_succ_of_le hmn)) : βˆ€ n hmn, P n hmn := @Nat.leRec (motive := P) _ base succ /-- Induction principle deriving the next case from the two previous ones. -/ def twoStepInduction {P : β„• β†’ Sort*} (zero : P 0) (one : P 1) (more : βˆ€ n, P n β†’ P (n + 1) β†’ P (n + 2)) : βˆ€ a, P a | 0 => zero | 1 => one | _ + 2 => more _ (twoStepInduction zero one more _) (twoStepInduction zero one more _) @[elab_as_elim] protected theorem strong_induction_on {p : β„• β†’ Prop} (n : β„•) (h : βˆ€ n, (βˆ€ m, m < n β†’ p m) β†’ p n) : p n := Nat.strongRecOn n h protected theorem case_strong_induction_on {p : β„• β†’ Prop} (a : β„•) (hz : p 0) (hi : βˆ€ n, (βˆ€ m, m ≀ n β†’ p m) β†’ p (n + 1)) : p a := Nat.caseStrongRecOn a hz hi /-- Decreasing induction: if `P (k+1)` implies `P k` for all `k < n`, then `P n` implies `P m` for all `m ≀ n`. Also works for functions to `Sort*`. For a version also assuming `m ≀ k`, see `Nat.decreasingInduction'`. -/ @[elab_as_elim] def decreasingInduction {n} {motive : (m : β„•) β†’ m ≀ n β†’ Sort*} (of_succ : βˆ€ k (h : k < n), motive (k + 1) h β†’ motive k (le_of_succ_le h)) (self : motive n (Nat.le_refl _)) {m} (mn : m ≀ n) : motive m mn := by induction mn using leRec with | refl => exact self | @le_succ_of_le k _ ih => apply ih (fun i hi => of_succ i (le_succ_of_le hi)) (of_succ k (lt_succ_self _) self) @[simp] lemma decreasingInduction_self {n} {motive : (m : β„•) β†’ m ≀ n β†’ Sort*} (of_succ self) : (decreasingInduction (motive := motive) of_succ self (Nat.le_refl _)) = self := by dsimp only [decreasingInduction] rw [leRec_self] lemma decreasingInduction_succ {n} {motive : (m : β„•) β†’ m ≀ n + 1 β†’ Sort*} (of_succ self) (mn : m ≀ n) (msn : m ≀ n + 1) : (decreasingInduction (motive := motive) of_succ self msn : motive m msn) = decreasingInduction (motive := fun m h => motive m (le_succ_of_le h)) (fun _ _ => of_succ _ _) (of_succ _ _ self) mn := by dsimp only [decreasingInduction]; rw [leRec_succ] @[simp] lemma decreasingInduction_succ' {n} {motive : (m : β„•) β†’ m ≀ n + 1 β†’ Sort*} (of_succ self) : decreasingInduction (motive := motive) of_succ self n.le_succ = of_succ _ _ self := by dsimp only [decreasingInduction]; rw [leRec_succ'] lemma decreasingInduction_trans {motive : (m : β„•) β†’ m ≀ k β†’ Sort*} (hmn : m ≀ n) (hnk : n ≀ k) (of_succ self) : (decreasingInduction (motive := motive) of_succ self (Nat.le_trans hmn hnk) : motive m _) = decreasingInduction (fun _ _ => of_succ _ _) (decreasingInduction of_succ self hnk) hmn := by induction hnk with | refl => rw [decreasingInduction_self] | step hnk ih => rw [decreasingInduction_succ _ _ (Nat.le_trans hmn hnk), ih, decreasingInduction_succ] lemma decreasingInduction_succ_left {motive : (m : β„•) β†’ m ≀ n β†’ Sort*} (of_succ self) (smn : m + 1 ≀ n) (mn : m ≀ n) : decreasingInduction (motive := motive) of_succ self mn = of_succ m smn (decreasingInduction of_succ self smn) := by rw [Subsingleton.elim mn (Nat.le_trans (le_succ m) smn), decreasingInduction_trans (n := m + 1) (Nat.le_succ m), decreasingInduction_succ'] /-- Given `P : β„• β†’ β„• β†’ Sort*`, if for all `m n : β„•` we can extend `P` from the rectangle strictly below `(m, n)` to `P m n`, then we have `P n m` for all `n m : β„•`. Note that for non-`Prop` output it is preferable to use the equation compiler directly if possible, since this produces equation lemmas. -/ @[elab_as_elim] def strongSubRecursion {P : β„• β†’ β„• β†’ Sort*} (H : βˆ€ m n, (βˆ€ x y, x < m β†’ y < n β†’ P x y) β†’ P m n) : βˆ€ n m : β„•, P n m | n, m => H n m fun x y _ _ ↦ strongSubRecursion H x y /-- Given `P : β„• β†’ β„• β†’ Sort*`, if we have `P m 0` and `P 0 n` for all `m n : β„•`, and for any `m n : β„•` we can extend `P` from `(m, n + 1)` and `(m + 1, n)` to `(m + 1, n + 1)` then we have `P m n` for all `m n : β„•`. Note that for non-`Prop` output it is preferable to use the equation compiler directly if possible, since this produces equation lemmas. -/ @[elab_as_elim] def pincerRecursion {P : β„• β†’ β„• β†’ Sort*} (Ha0 : βˆ€ m : β„•, P m 0) (H0b : βˆ€ n : β„•, P 0 n) (H : βˆ€ x y : β„•, P x y.succ β†’ P x.succ y β†’ P x.succ y.succ) : βˆ€ n m : β„•, P n m | m, 0 => Ha0 m | 0, n => H0b n | Nat.succ _, Nat.succ _ => H _ _ (pincerRecursion Ha0 H0b H _ _) (pincerRecursion Ha0 H0b H _ _) /-- Decreasing induction: if `P (k+1)` implies `P k` for all `m ≀ k < n`, then `P n` implies `P m`. Also works for functions to `Sort*`. Weakens the assumptions of `Nat.decreasingInduction`. -/ @[elab_as_elim] def decreasingInduction' {P : β„• β†’ Sort*} (h : βˆ€ k < n, m ≀ k β†’ P (k + 1) β†’ P k) (mn : m ≀ n) (hP : P n) : P m := by induction mn using decreasingInduction with | self => exact hP | of_succ k hk ih => exact h _ (lt_of_succ_le hk) (Nat.le_refl _) (ih fun k' hk' h'' => h k' hk' <| le_of_succ_le h'') /-- Given a predicate on two naturals `P : β„• β†’ β„• β†’ Prop`, `P a b` is true for all `a < b` if `P (a + 1) (a + 1)` is true for all `a`, `P 0 (b + 1)` is true for all `b` and for all `a < b`, `P (a + 1) b` is true and `P a (b + 1)` is true implies `P (a + 1) (b + 1)` is true. -/ @[elab_as_elim] theorem diag_induction (P : β„• β†’ β„• β†’ Prop) (ha : βˆ€ a, P (a + 1) (a + 1)) (hb : βˆ€ b, P 0 (b + 1)) (hd : βˆ€ a b, a < b β†’ P (a + 1) b β†’ P a (b + 1) β†’ P (a + 1) (b + 1)) : βˆ€ a b, a < b β†’ P a b | 0, _ + 1, _ => hb _ | a + 1, b + 1, h => by apply hd _ _ (Nat.add_lt_add_iff_right.1 h) Β· have this : a + 1 = b ∨ a + 1 < b := by omega rcases this with (rfl | h) Β· exact ha _ apply diag_induction P ha hb hd (a + 1) b h apply diag_induction P ha hb hd a (b + 1) apply Nat.lt_of_le_of_lt (Nat.le_succ _) h /-! ### `mod`, `dvd` -/ lemma not_pos_pow_dvd {a n : β„•} (ha : 1 < a) (hn : 1 < n) : Β¬ a ^ n ∣ a := not_dvd_of_pos_of_lt (Nat.lt_trans Nat.zero_lt_one ha) (lt_of_eq_of_lt (Nat.pow_one a).symm ((Nat.pow_lt_pow_iff_right ha).2 hn)) /-- `m` is not divisible by `n` if it is between `n * k` and `n * (k + 1)` for some `k`. -/ @[deprecated (since := "2025-06-05")] alias not_dvd_of_between_consec_multiples := not_dvd_of_lt_of_lt_mul_succ @[simp] protected theorem not_two_dvd_bit1 (n : β„•) : Β¬2 ∣ 2 * n + 1 := by cutsat /-- A natural number `m` divides the sum `m + n` if and only if `m` divides `n`. -/ @[simp] protected lemma dvd_add_self_left : m ∣ m + n ↔ m ∣ n := Nat.dvd_add_right (Nat.dvd_refl m) /-- A natural number `m` divides the sum `n + m` if and only if `m` divides `n`. -/ @[simp] protected lemma dvd_add_self_right : m ∣ n + m ↔ m ∣ n := Nat.dvd_add_left (Nat.dvd_refl m) /-- `n` is not divisible by `a` iff it is between `a * k` and `a * (k + 1)` for some `k`. -/ @[deprecated (since := "2025-06-05")] alias not_dvd_iff_between_consec_multiples := not_dvd_iff_lt_mul_succ /-- Two natural numbers are equal if and only if they have the same multiples. -/ lemma dvd_right_iff_eq : (βˆ€ a : β„•, m ∣ a ↔ n ∣ a) ↔ m = n := ⟨fun h => Nat.dvd_antisymm ((h _).mpr (Nat.dvd_refl _)) ((h _).mp (Nat.dvd_refl _)), fun h n => by rw [h]⟩ /-- Two natural numbers are equal if and only if they have the same divisors. -/ lemma dvd_left_iff_eq : (βˆ€ a : β„•, a ∣ m ↔ a ∣ n) ↔ m = n := ⟨fun h => Nat.dvd_antisymm ((h _).mp (Nat.dvd_refl _)) ((h _).mpr (Nat.dvd_refl _)), fun h n => by rw [h]⟩ /-! ### Decidability of predicates -/ instance decidableLoHi (lo hi : β„•) (P : β„• β†’ Prop) [DecidablePred P] : Decidable (βˆ€ x, lo ≀ x β†’ x < hi β†’ P x) := decidable_of_iff (βˆ€ x < hi - lo, P (lo + x)) <| by refine ⟨fun al x hl hh ↦ ?_, fun al x h ↦ al _ (Nat.le_add_right _ _) (Nat.lt_sub_iff_add_lt'.1 h)⟩ have := al (x - lo) ((Nat.sub_lt_sub_iff_right hl).2 hh) rwa [Nat.add_sub_cancel' hl] at this instance decidableLoHiLe (lo hi : β„•) (P : β„• β†’ Prop) [DecidablePred P] : Decidable (βˆ€ x, lo ≀ x β†’ x ≀ hi β†’ P x) := decidable_of_iff (βˆ€ x, lo ≀ x β†’ x < hi + 1 β†’ P x) <| forallβ‚‚_congr fun _ _ ↦ imp_congr Nat.lt_succ_iff Iff.rfl /-! ### `Nat.AtLeastTwo` -/ /-- A type class for natural numbers which are greater than or equal to `2`. `NeZero` and `AtLeastTwo` are used for numeric literals, and also for groups of related lemmas sharing a common value of `n` that needs to be nonzero, or at least `2`, and where it is convenient to pass this information implicitly. Instances for these classes cover some of the cases where it is most structurally obvious from the syntactic form of `n` that it satisfies the required conditions, such as `m + 1`. Less widely used cases may be defined as lemmas rather than global instances and then made into instances locally where needed. If implicit arguments, appearing before other explicit arguments, are allowed to be `autoParam`s in a future version of Lean, such an `autoParam` that is proved `by cutsat` might be a more general replacement for the use of typeclass inference for this purpose. -/ class AtLeastTwo (n : β„•) : Prop where prop : 2 ≀ n instance (n : β„•) [NeZero n] : (n + 1).AtLeastTwo := ⟨by have := NeZero.ne n; cutsat⟩ namespace AtLeastTwo variable {n : β„•} [n.AtLeastTwo] lemma one_lt : 1 < n := prop lemma ne_one : n β‰  1 := Nat.ne_of_gt one_lt instance (priority := 100) toNeZero (n : β„•) [n.AtLeastTwo] : NeZero n := ⟨Nat.ne_of_gt (Nat.le_of_lt one_lt)⟩ variable (n) in lemma neZero_sub_one : NeZero (n - 1) := ⟨by have := prop (n := n); cutsat⟩ end AtLeastTwo end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Factors.lean
import Mathlib.Algebra.BigOperators.Ring.List import Mathlib.Data.Nat.GCD.Basic import Mathlib.Data.Nat.Prime.Basic import Mathlib.Data.List.Prime import Mathlib.Data.List.Sort import Mathlib.Data.List.Perm.Subperm /-! # Prime numbers This file deals with the factors of natural numbers. ## Important declarations - `Nat.primeFactorsList n`: the prime factorization of `n` - `Nat.primeFactorsList_unique`: uniqueness of the prime factorisation -/ assert_not_exists Multiset open Bool Subtype open Nat namespace Nat /-- `primeFactorsList n` is the prime factorization of `n`, listed in increasing order. -/ def primeFactorsList : β„• β†’ List β„• | 0 => [] | 1 => [] | k + 2 => let m := minFac (k + 2) m :: primeFactorsList ((k + 2) / m) decreasing_by exact factors_lemma @[simp] theorem primeFactorsList_zero : primeFactorsList 0 = [] := by rw [primeFactorsList] @[simp] theorem primeFactorsList_one : primeFactorsList 1 = [] := by rw [primeFactorsList] @[simp] theorem primeFactorsList_two : primeFactorsList 2 = [2] := by simp [primeFactorsList] theorem prime_of_mem_primeFactorsList {n : β„•} : βˆ€ {p : β„•}, p ∈ primeFactorsList n β†’ Prime p := by match n with | 0 => simp | 1 => simp | k + 2 => intro p h let m := minFac (k + 2) have : (k + 2) / m < (k + 2) := factors_lemma have h₁ : p = m ∨ p ∈ primeFactorsList ((k + 2) / m) := List.mem_cons.1 (by rwa [primeFactorsList] at h) exact Or.casesOn h₁ (fun hβ‚‚ => hβ‚‚.symm β–Έ minFac_prime (by simp)) prime_of_mem_primeFactorsList theorem pos_of_mem_primeFactorsList {n p : β„•} (h : p ∈ primeFactorsList n) : 0 < p := Prime.pos (prime_of_mem_primeFactorsList h) theorem prod_primeFactorsList : βˆ€ {n}, n β‰  0 β†’ List.prod (primeFactorsList n) = n | 0 => by simp | 1 => by simp | k + 2 => fun _ => let m := minFac (k + 2) have : (k + 2) / m < (k + 2) := factors_lemma show (primeFactorsList (k + 2)).prod = (k + 2) by have h₁ : (k + 2) / m β‰  0 := fun h => by have : (k + 2) = 0 * m := (Nat.div_eq_iff_eq_mul_left (minFac_pos _) (minFac_dvd _)).1 h rw [zero_mul] at this; exact (show k + 2 β‰  0 by simp) this rw [primeFactorsList, List.prod_cons, prod_primeFactorsList h₁, Nat.mul_div_cancel' (minFac_dvd _)] theorem primeFactorsList_prime {p : β„•} (hp : Nat.Prime p) : p.primeFactorsList = [p] := by have : p = p - 2 + 2 := Nat.eq_add_of_sub_eq hp.two_le rfl rw [this, primeFactorsList] simp only [Eq.symm this] have : Nat.minFac p = p := (Nat.prime_def_minFac.mp hp).2 simp only [this, primeFactorsList, Nat.div_self (Nat.Prime.pos hp)] theorem isChain_cons_primeFactorsList {n : β„•} : βˆ€ {a}, (βˆ€ p, Prime p β†’ p ∣ n β†’ a ≀ p) β†’ List.IsChain (Β· ≀ Β·) (a :: primeFactorsList n) := by match n with | 0 => simp | 1 => simp | k + 2 => intro a h let m := minFac (k + 2) have : (k + 2) / m < (k + 2) := factors_lemma rw [primeFactorsList] refine List.IsChain.cons_cons ((le_minFac.2 h).resolve_left (by simp)) (isChain_cons_primeFactorsList ?_) exact fun p pp d => minFac_le_of_dvd pp.two_le (d.trans <| div_dvd_of_dvd <| minFac_dvd _) @[deprecated (since := "2025-09-21")] alias primeFactorsList_chain := isChain_cons_primeFactorsList theorem isChain_two_cons_primeFactorsList (n) : List.IsChain (Β· ≀ Β·) (2 :: primeFactorsList n) := isChain_cons_primeFactorsList fun _ pp _ => pp.two_le theorem isChain_primeFactorsList (n) : List.IsChain (Β· ≀ Β·) (primeFactorsList n) := (isChain_two_cons_primeFactorsList _).tail @[deprecated (since := "2025-09-24")] alias primeFactorsList_chain_2 := isChain_two_cons_primeFactorsList @[deprecated (since := "2025-09-24")] alias primeFactorsList_chain' := isChain_primeFactorsList theorem primeFactorsList_sorted (n : β„•) : List.Sorted (Β· ≀ Β·) (primeFactorsList n) := (isChain_primeFactorsList _).pairwise /-- `primeFactorsList` can be constructed inductively by extracting `minFac`, for sufficiently large `n`. -/ theorem primeFactorsList_add_two (n : β„•) : primeFactorsList (n + 2) = minFac (n + 2) :: primeFactorsList ((n + 2) / minFac (n + 2)) := by rw [primeFactorsList] @[simp] theorem primeFactorsList_eq_nil (n : β„•) : n.primeFactorsList = [] ↔ n = 0 ∨ n = 1 := by constructor <;> intro h Β· rcases n with (_ | _ | n) Β· exact Or.inl rfl Β· exact Or.inr rfl Β· rw [primeFactorsList] at h injection h Β· rcases h with (rfl | rfl) Β· exact primeFactorsList_zero Β· exact primeFactorsList_one theorem primeFactorsList_ne_nil (n : β„•) : n.primeFactorsList β‰  [] ↔ 1 < n := by simp [primeFactorsList_eq_nil n, one_lt_iff_ne_zero_and_ne_one] open scoped List in theorem eq_of_perm_primeFactorsList {a b : β„•} (ha : a β‰  0) (hb : b β‰  0) (h : a.primeFactorsList ~ b.primeFactorsList) : a = b := by simpa [prod_primeFactorsList ha, prod_primeFactorsList hb] using List.Perm.prod_eq h section open List theorem mem_primeFactorsList_iff_dvd {n p : β„•} (hn : n β‰  0) (hp : Prime p) : p ∈ primeFactorsList n ↔ p ∣ n where mp h := prod_primeFactorsList hn β–Έ List.dvd_prod h mpr h := mem_list_primes_of_dvd_prod (prime_iff.mp hp) (fun _ h ↦ prime_iff.mp (prime_of_mem_primeFactorsList h)) ((prod_primeFactorsList hn).symm β–Έ h) theorem dvd_of_mem_primeFactorsList {n p : β„•} (h : p ∈ n.primeFactorsList) : p ∣ n := by rcases n.eq_zero_or_pos with (rfl | hn) Β· exact dvd_zero p Β· rwa [← mem_primeFactorsList_iff_dvd hn.ne' (prime_of_mem_primeFactorsList h)] theorem mem_primeFactorsList {n p} (hn : n β‰  0) : p ∈ primeFactorsList n ↔ Prime p ∧ p ∣ n := ⟨fun h => ⟨prime_of_mem_primeFactorsList h, dvd_of_mem_primeFactorsList h⟩, fun ⟨hprime, hdvd⟩ => (mem_primeFactorsList_iff_dvd hn hprime).mpr hdvd⟩ @[simp] lemma mem_primeFactorsList' {n p} : p ∈ n.primeFactorsList ↔ p.Prime ∧ p ∣ n ∧ n β‰  0 := by cases n <;> simp [mem_primeFactorsList, *] theorem le_of_mem_primeFactorsList {n p : β„•} (h : p ∈ n.primeFactorsList) : p ≀ n := by rcases n.eq_zero_or_pos with (rfl | hn) Β· rw [primeFactorsList_zero] at h cases h Β· exact le_of_dvd hn (dvd_of_mem_primeFactorsList h) /-- **Fundamental theorem of arithmetic** -/ theorem primeFactorsList_unique {n : β„•} {l : List β„•} (h₁ : prod l = n) (hβ‚‚ : βˆ€ p ∈ l, Prime p) : l ~ primeFactorsList n := by refine perm_of_prod_eq_prod ?_ ?_ ?_ Β· rw [h₁] refine (prod_primeFactorsList ?_).symm rintro rfl rw [prod_eq_zero_iff] at h₁ exact Prime.ne_zero (hβ‚‚ 0 h₁) rfl Β· simp_rw [← prime_iff] exact hβ‚‚ Β· simp_rw [← prime_iff] exact fun p => prime_of_mem_primeFactorsList theorem Prime.primeFactorsList_pow {p : β„•} (hp : p.Prime) (n : β„•) : (p ^ n).primeFactorsList = List.replicate n p := by symm rw [← List.replicate_perm] apply Nat.primeFactorsList_unique (List.prod_replicate n p) intro q hq rwa [eq_of_mem_replicate hq] theorem eq_prime_pow_of_unique_prime_dvd {n p : β„•} (hpos : n β‰  0) (h : βˆ€ {d}, Nat.Prime d β†’ d ∣ n β†’ d = p) : n = p ^ n.primeFactorsList.length := by set k := n.primeFactorsList.length rw [← prod_primeFactorsList hpos, ← prod_replicate k p, eq_replicate_of_mem fun d hd => h (prime_of_mem_primeFactorsList hd) (dvd_of_mem_primeFactorsList hd)] /-- For positive `a` and `b`, the prime factors of `a * b` are the union of those of `a` and `b` -/ theorem perm_primeFactorsList_mul {a b : β„•} (ha : a β‰  0) (hb : b β‰  0) : (a * b).primeFactorsList ~ a.primeFactorsList ++ b.primeFactorsList := by refine (primeFactorsList_unique ?_ ?_).symm Β· rw [List.prod_append, prod_primeFactorsList ha, prod_primeFactorsList hb] Β· intro p hp rw [List.mem_append] at hp rcases hp with hp' | hp' <;> exact prime_of_mem_primeFactorsList hp' /-- For coprime `a` and `b`, the prime factors of `a * b` are the union of those of `a` and `b` -/ theorem perm_primeFactorsList_mul_of_coprime {a b : β„•} (hab : Coprime a b) : (a * b).primeFactorsList ~ a.primeFactorsList ++ b.primeFactorsList := by rcases a.eq_zero_or_pos with (rfl | ha) Β· simp [(coprime_zero_left _).mp hab] rcases b.eq_zero_or_pos with (rfl | hb) Β· simp [(coprime_zero_right _).mp hab] exact perm_primeFactorsList_mul ha.ne' hb.ne' theorem primeFactorsList_sublist_right {n k : β„•} (h : k β‰  0) : n.primeFactorsList <+ (n * k).primeFactorsList := by rcases n with - | hn Β· simp [zero_mul] apply sublist_of_subperm_of_sorted _ (primeFactorsList_sorted _) (primeFactorsList_sorted _) simp only [(perm_primeFactorsList_mul (Nat.succ_ne_zero _) h).subperm_left] exact (sublist_append_left _ _).subperm theorem primeFactorsList_sublist_of_dvd {n k : β„•} (h : n ∣ k) (h' : k β‰  0) : n.primeFactorsList <+ k.primeFactorsList := by obtain ⟨a, rfl⟩ := h exact primeFactorsList_sublist_right (right_ne_zero_of_mul h') theorem primeFactorsList_subset_right {n k : β„•} (h : k β‰  0) : n.primeFactorsList βŠ† (n * k).primeFactorsList := (primeFactorsList_sublist_right h).subset theorem primeFactorsList_subset_of_dvd {n k : β„•} (h : n ∣ k) (h' : k β‰  0) : n.primeFactorsList βŠ† k.primeFactorsList := (primeFactorsList_sublist_of_dvd h h').subset theorem dvd_of_primeFactorsList_subperm {a b : β„•} (ha : a β‰  0) (h : a.primeFactorsList <+~ b.primeFactorsList) : a ∣ b := by rcases b.eq_zero_or_pos with (rfl | hb) Β· exact dvd_zero _ rcases a with (_ | _ | a) Β· exact (ha rfl).elim Β· exact one_dvd _ use (b.primeFactorsList.diff a.succ.succ.primeFactorsList).prod nth_rw 1 [← Nat.prod_primeFactorsList ha] rw [← List.prod_append, List.Perm.prod_eq <| List.subperm_append_diff_self_of_count_le <| List.subperm_ext_iff.mp h, Nat.prod_primeFactorsList hb.ne'] theorem replicate_subperm_primeFactorsList_iff {a b n : β„•} (ha : Prime a) (hb : b β‰  0) : replicate n a <+~ primeFactorsList b ↔ a ^ n ∣ b := by induction n generalizing b with | zero => simp | succ n ih => constructor Β· rw [List.subperm_iff] rintro ⟨u, hu1, hu2⟩ rw [← Nat.prod_primeFactorsList hb, ← hu1.prod_eq, ← prod_replicate] exact hu2.prod_dvd_prod Β· rintro ⟨c, rfl⟩ rw [Ne, pow_succ', mul_assoc, mul_eq_zero, _root_.not_or] at hb rw [pow_succ', mul_assoc, replicate_succ, (Nat.perm_primeFactorsList_mul hb.1 hb.2).subperm_left, primeFactorsList_prime ha, singleton_append, subperm_cons, ih hb.2] exact dvd_mul_right _ _ end theorem mem_primeFactorsList_mul {a b : β„•} (ha : a β‰  0) (hb : b β‰  0) {p : β„•} : p ∈ (a * b).primeFactorsList ↔ p ∈ a.primeFactorsList ∨ p ∈ b.primeFactorsList := by rw [mem_primeFactorsList (mul_ne_zero ha hb), mem_primeFactorsList ha, mem_primeFactorsList hb, ← and_or_left] simpa only [and_congr_right_iff] using Prime.dvd_mul /-- The sets of factors of coprime `a` and `b` are disjoint -/ theorem coprime_primeFactorsList_disjoint {a b : β„•} (hab : a.Coprime b) : List.Disjoint a.primeFactorsList b.primeFactorsList := by intro q hqa hqb apply not_prime_one rw [← eq_one_of_dvd_coprimes hab (dvd_of_mem_primeFactorsList hqa) (dvd_of_mem_primeFactorsList hqb)] exact prime_of_mem_primeFactorsList hqa theorem mem_primeFactorsList_mul_of_coprime {a b : β„•} (hab : Coprime a b) (p : β„•) : p ∈ (a * b).primeFactorsList ↔ p ∈ a.primeFactorsList βˆͺ b.primeFactorsList := by rcases a.eq_zero_or_pos with (rfl | ha) Β· simp [(coprime_zero_left _).mp hab] rcases b.eq_zero_or_pos with (rfl | hb) Β· simp [(coprime_zero_right _).mp hab] rw [mem_primeFactorsList_mul ha.ne' hb.ne', List.mem_union_iff] open List /-- If `p` is a prime factor of `a` then `p` is also a prime factor of `a * b` for any `b > 0` -/ theorem mem_primeFactorsList_mul_left {p a b : β„•} (hpa : p ∈ a.primeFactorsList) (hb : b β‰  0) : p ∈ (a * b).primeFactorsList := by rcases eq_or_ne a 0 with (rfl | ha) Β· simp at hpa apply (mem_primeFactorsList_mul ha hb).2 (Or.inl hpa) /-- If `p` is a prime factor of `b` then `p` is also a prime factor of `a * b` for any `a > 0` -/ theorem mem_primeFactorsList_mul_right {p a b : β„•} (hpb : p ∈ b.primeFactorsList) (ha : a β‰  0) : p ∈ (a * b).primeFactorsList := by rw [mul_comm] exact mem_primeFactorsList_mul_left hpb ha theorem eq_two_pow_or_exists_odd_prime_and_dvd (n : β„•) : (βˆƒ k : β„•, n = 2 ^ k) ∨ βˆƒ p, Nat.Prime p ∧ p ∣ n ∧ Odd p := (eq_or_ne n 0).elim (fun hn => Or.inr ⟨3, prime_three, hn.symm β–Έ dvd_zero 3, ⟨1, rfl⟩⟩) fun hn => or_iff_not_imp_right.mpr fun H => ⟨n.primeFactorsList.length, eq_prime_pow_of_unique_prime_dvd hn fun {_} hprime hdvd => hprime.eq_two_or_odd'.resolve_right fun hodd => H ⟨_, hprime, hdvd, hodd⟩⟩ theorem four_dvd_or_exists_odd_prime_and_dvd_of_two_lt {n : β„•} (n2 : 2 < n) : 4 ∣ n ∨ βˆƒ p, Prime p ∧ p ∣ n ∧ Odd p := by obtain ⟨_ | _ | k, rfl⟩ | ⟨p, hp, hdvd, hodd⟩ := n.eq_two_pow_or_exists_odd_prime_and_dvd Β· contradiction Β· contradiction Β· simp [Nat.pow_succ, mul_assoc] Β· exact Or.inr ⟨p, hp, hdvd, hodd⟩ end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Multiplicity.lean
import Mathlib.Data.Nat.Choose.Factorization /-! # Natural number multiplicity This file contains lemmas about the multiplicity function (the maximum prime power dividing a number) when applied to naturals, in particular calculating it for factorials and binomial coefficients. ## Multiplicity calculations * `Nat.Prime.multiplicity_factorial`: Legendre's Theorem. The multiplicity of `p` in `n!` is `n / p + ... + n / p ^ b` for any `b` such that `n / p ^ (b + 1) = 0`. See `padicValNat_factorial` for this result stated in the language of `p`-adic valuations and `sub_one_mul_padicValNat_factorial` for a related result. * `Nat.Prime.multiplicity_factorial_mul`: The multiplicity of `p` in `(p * n)!` is `n` more than that of `n!`. * `Nat.Prime.multiplicity_choose`: Kummer's Theorem. The multiplicity of `p` in `n.choose k` is the number of carries when `k` and `n - k` are added in base `p`. See `padicValNat_choose` for the same result but stated in the language of `p`-adic valuations and `sub_one_mul_padicValNat_choose_eq_sub_sum_digits` for a related result. ## Other declarations * `Nat.multiplicity_eq_card_pow_dvd`: The multiplicity of `m` in `n` is the number of positive natural numbers `i` such that `m ^ i` divides `n`. * `Nat.multiplicity_two_factorial_lt`: The multiplicity of `2` in `n!` is strictly less than `n`. * `Nat.Prime.multiplicity_something`: Specialization of `multiplicity.something` to a prime in the naturals. Avoids having to provide `p β‰  1` and other trivialities, along with translating between `Prime` and `Nat.Prime`. ## TODO Derive results from the corresponding ones `Mathlib.Data.Nat.Factorization.Multiplicity` ## Tags Legendre, p-adic -/ open Finset namespace Nat /-- The multiplicity of `m` in `n` is the number of positive natural numbers `i` such that `m ^ i` divides `n`. This set is expressed by filtering `Ico 1 b` where `b` is any bound greater than `log m n`. -/ theorem emultiplicity_eq_card_pow_dvd {m n b : β„•} (hm : m β‰  1) (hn : 0 < n) (hb : log m n < b) : emultiplicity m n = #{i ∈ Ico 1 b | m ^ i ∣ n} := have fin := Nat.finiteMultiplicity_iff.2 ⟨hm, hn⟩ calc emultiplicity m n = #(Ico 1 <| multiplicity m n + 1) := by simp [fin.emultiplicity_eq_multiplicity] _ = #{i ∈ Ico 1 b | m ^ i ∣ n} := congr_arg _ <| congr_arg card <| Finset.ext fun i => by simp only [mem_Ico, Nat.lt_succ_iff, fin.pow_dvd_iff_le_multiplicity, mem_filter, and_assoc, and_congr_right_iff, iff_and_self] intro hi h rw [← fin.pow_dvd_iff_le_multiplicity] at h rcases m with - | m Β· rw [zero_pow, zero_dvd_iff] at h exacts [(hn.ne' h).elim, one_le_iff_ne_zero.1 hi] refine LE.le.trans_lt ?_ hb exact le_log_of_pow_le (one_lt_iff_ne_zero_and_ne_one.2 ⟨m.succ_ne_zero, hm⟩) (le_of_dvd hn h) namespace Prime theorem emultiplicity_one {p : β„•} (hp : p.Prime) : emultiplicity p 1 = 0 := emultiplicity_of_one_right hp.prime.not_unit theorem emultiplicity_mul {p m n : β„•} (hp : p.Prime) : emultiplicity p (m * n) = emultiplicity p m + emultiplicity p n := _root_.emultiplicity_mul hp.prime theorem emultiplicity_pow {p m n : β„•} (hp : p.Prime) : emultiplicity p (m ^ n) = n * emultiplicity p m := _root_.emultiplicity_pow hp.prime theorem emultiplicity_self {p : β„•} (hp : p.Prime) : emultiplicity p p = 1 := (Nat.finiteMultiplicity_iff.2 ⟨hp.ne_one, hp.pos⟩).emultiplicity_self theorem emultiplicity_pow_self {p n : β„•} (hp : p.Prime) : emultiplicity p (p ^ n) = n := _root_.emultiplicity_pow_self hp.ne_zero hp.prime.not_unit n /-- **Legendre's Theorem** The multiplicity of a prime in `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 emultiplicity_factorial {p : β„•} (hp : p.Prime) : βˆ€ {n b : β„•}, log p n < b β†’ emultiplicity p n ! = (βˆ‘ i ∈ Ico 1 b, n / p ^ i : β„•) | 0, b, _ => by simp [Ico, hp.emultiplicity_one] | n + 1, b, hb => calc emultiplicity p (n + 1)! = emultiplicity p n ! + emultiplicity p (n + 1) := by rw [factorial_succ, hp.emultiplicity_mul, add_comm] _ = (βˆ‘ i ∈ Ico 1 b, n / p ^ i : β„•) + #{i ∈ Ico 1 b | p ^ i ∣ n + 1} := by rw [emultiplicity_factorial hp ((log_mono_right <| le_succ _).trans_lt hb), ← emultiplicity_eq_card_pow_dvd hp.ne_one (succ_pos _) hb] _ = (βˆ‘ i ∈ Ico 1 b, (n / p ^ i + if p ^ i ∣ n + 1 then 1 else 0) : β„•) := by rw [sum_add_distrib, sum_boole] simp _ = (βˆ‘ i ∈ Ico 1 b, (n + 1) / p ^ i : β„•) := congr_arg _ <| Finset.sum_congr rfl fun _ _ => Nat.succ_div.symm /-- For a prime number `p`, taking `(p - 1)` times the multiplicity of `p` in `n!` equals `n` minus the sum of base `p` digits of `n`. -/ theorem sub_one_mul_multiplicity_factorial {n p : β„•} (hp : p.Prime) : (p - 1) * multiplicity p n ! = n - (p.digits n).sum := by simp only [multiplicity_eq_of_emultiplicity_eq_some <| emultiplicity_factorial hp <| lt_succ_of_lt <| lt.base (log p n), ← Finset.sum_Ico_add' _ 0 _ 1, Ico_zero_eq_range, ← sub_one_mul_sum_log_div_pow_eq_sub_sum_digits] /-- The multiplicity of `p` in `(p * (n + 1))!` is one more than the sum of the multiplicities of `p` in `(p * n)!` and `n + 1`. -/ theorem emultiplicity_factorial_mul_succ {n p : β„•} (hp : p.Prime) : emultiplicity p (p * (n + 1))! = emultiplicity p (p * n)! + emultiplicity p (n + 1) + 1 := by have hp' := hp.prime have h0 : 2 ≀ p := hp.two_le have h1 : 1 ≀ p * n + 1 := Nat.le_add_left _ _ have h2 : p * n + 1 ≀ p * (n + 1) := by linarith have h3 : p * n + 1 ≀ p * (n + 1) + 1 := by omega have hm : emultiplicity p (p * n)! β‰  ⊀ := by rw [Ne, emultiplicity_eq_top, Classical.not_not, Nat.finiteMultiplicity_iff] exact ⟨hp.ne_one, factorial_pos _⟩ revert hm have h4 : βˆ€ m ∈ Ico (p * n + 1) (p * (n + 1)), emultiplicity p m = 0 := by intro m hm rw [emultiplicity_eq_zero, not_dvd_iff_lt_mul_succ _ hp.pos] rw [mem_Ico] at hm exact ⟨n, lt_of_succ_le hm.1, hm.2⟩ simp_rw [← prod_Ico_id_eq_factorial, Finset.emultiplicity_prod hp', ← sum_Ico_consecutive _ h1 h3, add_assoc] intro h rw [WithTop.add_left_inj h, sum_Ico_succ_top h2, hp.emultiplicity_mul, hp.emultiplicity_self, sum_congr rfl h4, sum_const_zero, zero_add, add_comm 1] /-- The multiplicity of `p` in `(p * n)!` is `n` more than that of `n!`. -/ theorem emultiplicity_factorial_mul {n p : β„•} (hp : p.Prime) : emultiplicity p (p * n)! = emultiplicity p n ! + n := by induction n with | zero => simp | succ n ih => simp only [hp, emultiplicity_factorial_mul_succ, ih, factorial_succ, emultiplicity_mul, cast_add, cast_one, ← add_assoc] congr 1 rw [add_comm, add_assoc] /- The multiplicity of a prime `p` in `p ^ n` is the sum of `p ^ i`, where `i` ranges between `0` and `n - 1`. -/ theorem multiplicity_factorial_pow {n p : β„•} (hp : p.Prime) : multiplicity p (p ^ n).factorial = βˆ‘ i ∈ Finset.range n, p ^ i := by rw [← ENat.coe_inj, ← (Nat.finiteMultiplicity_iff.2 ⟨hp.ne_one, (p ^ n).factorial_pos⟩).emultiplicity_eq_multiplicity] induction n with | zero => simp [hp.emultiplicity_one] | succ n h => rw [pow_succ', hp.emultiplicity_factorial_mul, h, Finset.sum_range_succ, ENat.coe_add] /-- A prime power divides `n!` iff it is at most the sum of the quotients `n / p ^ i`. This sum is expressed over the set `Ico 1 b` where `b` is any bound greater than `log p n` -/ theorem pow_dvd_factorial_iff {p : β„•} {n r b : β„•} (hp : p.Prime) (hbn : log p n < b) : p ^ r ∣ n ! ↔ r ≀ βˆ‘ i ∈ Ico 1 b, n / p ^ i := by rw [← WithTop.coe_le_coe, ENat.some_eq_coe, ← hp.emultiplicity_factorial hbn, pow_dvd_iff_le_emultiplicity] theorem emultiplicity_factorial_le_div_pred {p : β„•} (hp : p.Prime) (n : β„•) : emultiplicity p n ! ≀ (n / (p - 1) : β„•) := by rw [hp.emultiplicity_factorial (lt_succ_self _)] apply WithTop.coe_mono exact Nat.geom_sum_Ico_le hp.two_le _ _ /-- The multiplicity of `p` in `choose (n + k) k` is the number of carries when `k` and `n` are added in base `p`. The set is expressed by filtering `Ico 1 b` where `b` is any bound greater than `log p (n + k)`. -/ theorem emultiplicity_choose' {p n k b : β„•} (hp : p.Prime) (hnb : log p (n + k) < b) : emultiplicity p (choose (n + k) k) = #{i ∈ Ico 1 b | p ^ i ≀ k % p ^ i + n % p ^ i} := by have h₁ : emultiplicity p (choose (n + k) k) + emultiplicity p (k ! * n !) = #{i ∈ Ico 1 b | p ^ i ≀ k % p ^ i + n % p ^ i} + emultiplicity p (k ! * n !) := by rw [← hp.emultiplicity_mul, ← mul_assoc] have := (add_tsub_cancel_right n k) β–Έ choose_mul_factorial_mul_factorial (le_add_left k n) rw [this, hp.emultiplicity_factorial hnb, hp.emultiplicity_mul, hp.emultiplicity_factorial ((log_mono_right (le_add_left k n)).trans_lt hnb), hp.emultiplicity_factorial ((log_mono_right (le_add_left n k)).trans_lt (add_comm n k β–Έ hnb)), multiplicity_choose_aux hp (le_add_left k n)] simp [add_comm] refine WithTop.add_right_cancel ?_ h₁ apply finiteMultiplicity_iff_emultiplicity_ne_top.1 exact Nat.finiteMultiplicity_iff.2 ⟨hp.ne_one, mul_pos (factorial_pos k) (factorial_pos n)⟩ /-- The multiplicity of `p` in `choose n k` is the number of carries when `k` and `n - k` are added in base `p`. The set is expressed by filtering `Ico 1 b` where `b` is any bound greater than `log p n`. -/ theorem emultiplicity_choose {p n k b : β„•} (hp : p.Prime) (hkn : k ≀ n) (hnb : log p n < b) : emultiplicity p (choose n k) = #{i ∈ Ico 1 b | p ^ i ≀ k % p ^ i + (n - k) % p ^ i} := by have := Nat.sub_add_cancel hkn convert @emultiplicity_choose' p (n - k) k b hp _ Β· rw [this] exact this.symm β–Έ hnb /-- A lower bound on the multiplicity of `p` in `choose n k`. -/ theorem emultiplicity_le_emultiplicity_choose_add {p : β„•} (hp : p.Prime) : βˆ€ n k : β„•, emultiplicity p n ≀ emultiplicity p (choose n k) + emultiplicity p k | _, 0 => by simp | 0, _ + 1 => by simp | n + 1, k + 1 => by rw [← hp.emultiplicity_mul] refine emultiplicity_le_emultiplicity_of_dvd_right ?_ rw [← succ_mul_choose_eq] exact dvd_mul_right _ _ variable {p n k : β„•} theorem emultiplicity_choose_prime_pow_add_emultiplicity (hp : p.Prime) (hkn : k ≀ p ^ n) (hk0 : k β‰  0) : emultiplicity p (choose (p ^ n) k) + emultiplicity p k = n := le_antisymm (by have hdisj : Disjoint {i ∈ Ico 1 n.succ | p ^ i ≀ k % p ^ i + (p ^ n - k) % p ^ i} {i ∈ Ico 1 n.succ | p ^ i ∣ k} := by simp +contextual [disjoint_right, *, dvd_iff_mod_eq_zero, Nat.mod_lt _ (pow_pos hp.pos _)] rw [emultiplicity_choose hp hkn (lt_succ_self _), emultiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) hk0.bot_lt (lt_succ_of_le (log_mono_right hkn)), ← Nat.cast_add] apply WithTop.coe_mono rw [log_pow hp.one_lt, ← card_union_of_disjoint hdisj, filter_union_right] have filter_le_Ico := (Ico 1 n.succ).card_filter_le fun x => p ^ x ≀ k % p ^ x + (p ^ n - k) % p ^ x ∨ p ^ x ∣ k rwa [card_Ico 1 n.succ] at filter_le_Ico) (by rw [← hp.emultiplicity_pow_self]; exact emultiplicity_le_emultiplicity_choose_add hp _ _) theorem emultiplicity_choose_prime_pow {p n k : β„•} (hp : p.Prime) (hkn : k ≀ p ^ n) (hk0 : k β‰  0) : emultiplicity p (choose (p ^ n) k) = ↑(n - multiplicity p k) := by push_cast rw [← emultiplicity_choose_prime_pow_add_emultiplicity hp hkn hk0, (finiteMultiplicity_iff.2 ⟨hp.ne_one, Nat.pos_of_ne_zero hk0⟩).emultiplicity_eq_multiplicity, (finiteMultiplicity_iff.2 ⟨hp.ne_one, choose_pos hkn⟩).emultiplicity_eq_multiplicity] norm_cast rw [Nat.add_sub_cancel_right] theorem dvd_choose_pow (hp : Prime p) (hk : k β‰  0) (hkp : k β‰  p ^ n) : p ∣ (p ^ n).choose k := by obtain hkp | hkp := hkp.symm.lt_or_gt Β· simp [choose_eq_zero_of_lt hkp] refine emultiplicity_ne_zero.1 fun h => hkp.not_ge <| Nat.le_of_dvd hk.bot_lt ?_ have H := hp.emultiplicity_choose_prime_pow_add_emultiplicity hkp.le hk rw [h, zero_add, emultiplicity_eq_coe] at H exact H.1 theorem dvd_choose_pow_iff (hp : Prime p) : p ∣ (p ^ n).choose k ↔ k β‰  0 ∧ k β‰  p ^ n := by refine ⟨fun h => ⟨?_, ?_⟩, fun h => dvd_choose_pow hp h.1 h.2⟩ <;> rintro rfl <;> simp [hp.ne_one] at h end Prime theorem emultiplicity_two_factorial_lt : βˆ€ {n : β„•} (_ : n β‰  0), emultiplicity 2 n ! < n := by have h2 := prime_two.prime refine binaryRec ?_ ?_ Β· exact fun h => False.elim <| h rfl Β· intro b n ih h by_cases hn : n = 0 Β· subst hn simp only [ne_eq, bit_eq_zero_iff, true_and, Bool.not_eq_false] at h simp only [bit, h, cond_true, mul_zero, zero_add, factorial_one] rw [Prime.emultiplicity_one] Β· exact zero_lt_one Β· decide have : emultiplicity 2 (2 * n)! < (2 * n : β„•) := by rw [prime_two.emultiplicity_factorial_mul] rw [two_mul] push_cast apply WithTop.add_lt_add_right _ (ih hn) exact Ne.symm nofun cases b Β· simpa Β· suffices emultiplicity 2 (2 * n + 1) + emultiplicity 2 (2 * n)! < ↑(2 * n) + 1 by simpa [emultiplicity_mul, h2, prime_two, bit, factorial] rw [emultiplicity_eq_zero.2 (two_not_dvd_two_mul_add_one n), zero_add] refine this.trans ?_ exact mod_cast lt_succ_self _ end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/MaxPowDiv.lean
import Mathlib.Algebra.Divisibility.Units import Mathlib.Algebra.Order.Ring.Nat import Mathlib.Tactic.Common /-! # The maximal power of one natural number dividing another Here we introduce `p.maxPowDiv n` which returns the maximal `k : β„•` for which `p ^ k ∣ n` with the convention that `maxPowDiv 1 n = 0` for all `n`. We prove enough about `maxPowDiv` in this file to show equality with `Nat.padicValNat` in `padicValNat.padicValNat_eq_maxPowDiv`. The implementation of `maxPowDiv` improves on the speed of `padicValNat`. -/ namespace Nat /-- Tail recursive function which returns the largest `k : β„•` such that `p ^ k ∣ n` for any `p : β„•`. `padicValNat_eq_maxPowDiv` allows the code generator to use this definition for `padicValNat` -/ def maxPowDiv (p n : β„•) : β„• := go 0 p n where go (k p n : β„•) : β„• := if 1 < p ∧ 0 < n ∧ n % p = 0 then go (k+1) p (n / p) else k termination_by n decreasing_by apply Nat.div_lt_self <;> tauto attribute [inherit_doc maxPowDiv] maxPowDiv.go end Nat namespace Nat.maxPowDiv theorem go_succ {k p n : β„•} : go (k+1) p n = go k p n + 1 := by fun_induction go case case1 h ih => conv_lhs => unfold go simpa [if_pos h] using ih case case2 h => conv_lhs => unfold go simp [if_neg h] @[simp] theorem zero_base {n : β„•} : maxPowDiv 0 n = 0 := by dsimp [maxPowDiv] rw [maxPowDiv.go] simp @[simp] theorem zero {p : β„•} : maxPowDiv p 0 = 0 := by dsimp [maxPowDiv] rw [maxPowDiv.go] simp theorem base_mul_eq_succ {p n : β„•} (hp : 1 < p) (hn : 0 < n) : p.maxPowDiv (p*n) = p.maxPowDiv n + 1 := by have : 0 < p := lt_trans (b := 1) (by simp) hp dsimp [maxPowDiv] rw [maxPowDiv.go, if_pos, mul_div_right _ this] Β· apply go_succ Β· refine ⟨hp, ?_, by simp⟩ apply Nat.mul_pos this hn theorem base_pow_mul {p n exp : β„•} (hp : 1 < p) (hn : 0 < n) : p.maxPowDiv (p ^ exp * n) = p.maxPowDiv n + exp := by match exp with | 0 => simp | e + 1 => rw [Nat.pow_succ, mul_assoc, mul_comm, mul_assoc, base_mul_eq_succ hp, mul_comm, base_pow_mul hp hn] Β· ac_rfl Β· apply Nat.mul_pos hn <| pow_pos (pos_of_gt hp) e theorem pow_dvd (p n : β„•) : p ^ (p.maxPowDiv n) ∣ n := by dsimp [maxPowDiv] rw [go] by_cases h : (1 < p ∧ 0 < n ∧ n % p = 0) Β· have : n / p < n := by apply Nat.div_lt_self <;> aesop rw [if_pos h] have ⟨c,hc⟩ := pow_dvd p (n / p) rw [go_succ, pow_succ] nth_rw 2 [← mod_add_div' n p] rw [h.right.right, zero_add] exact ⟨c,by nth_rw 1 [hc]; ac_rfl⟩ Β· rw [if_neg h] simp theorem le_of_dvd {p n pow : β„•} (hp : 1 < p) (hn : n β‰  0) (h : p ^ pow ∣ n) : pow ≀ p.maxPowDiv n := by have ⟨c, hc⟩ := h have : 0 < c := by apply Nat.pos_of_ne_zero intro h' rw [h',mul_zero] at hc omega simp [hc, base_pow_mul hp this] end maxPowDiv end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/PowModTotient.lean
import Mathlib.NumberTheory.PowModTotient deprecated_module (since := "2025-09-19")
.lake/packages/mathlib/Mathlib/Data/Nat/Basic.lean
import Mathlib.Data.Nat.Init import Mathlib.Logic.Basic import Mathlib.Logic.Nontrivial.Defs import Mathlib.Order.Defs.LinearOrder import Mathlib.Tactic.GCongr.Core import Mathlib.Util.AssertExists /-! # Basic operations on the natural numbers This file builds on `Mathlib/Data/Nat/Init.lean` by adding basic lemmas on natural numbers depending on Mathlib definitions. See note [foundational algebra order theory]. -/ /- We don't want to import the algebraic hierarchy in this file. -/ assert_not_exists Monoid open Function namespace Nat variable {a b c d m n k : β„•} {p : β„• β†’ Prop} -- TODO: Move the `LinearOrder β„•` instance to `Order.Nat` (https://github.com/leanprover-community/mathlib4/pull/13092). instance instLinearOrder : LinearOrder β„• where le := Nat.le le_refl := @Nat.le_refl le_trans := @Nat.le_trans le_antisymm := @Nat.le_antisymm le_total := @Nat.le_total lt := Nat.lt lt_iff_le_not_ge := @Nat.lt_iff_le_not_le toDecidableLT := inferInstance toDecidableLE := inferInstance toDecidableEq := inferInstance -- Shortcut instances instance : Preorder β„• := inferInstance instance : PartialOrder β„• := inferInstance instance instNontrivial : Nontrivial β„• := ⟨⟨0, 1, Nat.zero_ne_one⟩⟩ attribute [gcongr] Nat.succ_le_succ Nat.div_le_div_right Nat.div_le_div /-! ### `succ`, `pred` -/ lemma succ_injective : Injective Nat.succ := @succ.inj /-! ### `div` -/ /-! ### `pow` -/ lemma pow_left_injective (hn : n β‰  0) : Injective (fun a : β„• ↦ a ^ n) := by simp [Injective, le_antisymm_iff, Nat.pow_le_pow_iff_left hn] protected lemma pow_right_injective (ha : 2 ≀ a) : Injective (a ^ Β·) := by simp [Injective, le_antisymm_iff, Nat.pow_le_pow_iff_right ha] /-! ### Recursion and induction principles This section is here due to dependencies -- the lemmas here require some of the lemmas proved above, and some of the results in later sections depend on the definitions in this section. -/ lemma leRecOn_injective {C : β„• β†’ Sort*} {n m} (hnm : n ≀ m) (next : βˆ€ {k}, C k β†’ C (k + 1)) (Hnext : βˆ€ n, Injective (@next n)) : Injective (@leRecOn C n m hnm next) := by induction hnm with | refl => intro x y H rwa [leRecOn_self, leRecOn_self] at H | step hnm ih => intro x y H rw [leRecOn_succ hnm, leRecOn_succ hnm] at H exact ih (Hnext _ H) lemma leRecOn_surjective {C : β„• β†’ Sort*} {n m} (hnm : n ≀ m) (next : βˆ€ {k}, C k β†’ C (k + 1)) (Hnext : βˆ€ n, Surjective (@next n)) : Surjective (@leRecOn C n m hnm next) := by induction hnm with | refl => intro x refine ⟨x, ?_⟩ rw [leRecOn_self] | step hnm ih => intro x obtain ⟨w, rfl⟩ := Hnext _ x obtain ⟨x, rfl⟩ := ih w refine ⟨x, ?_⟩ rw [leRecOn_succ] /-- A subset of `β„•` containing `k : β„•` and closed under `Nat.succ` contains every `n β‰₯ k`. -/ lemma set_induction_bounded {S : Set β„•} (hk : k ∈ S) (h_ind : βˆ€ k : β„•, k ∈ S β†’ k + 1 ∈ S) (hnk : k ≀ n) : n ∈ S := @leRecOn (fun n => n ∈ S) k n hnk @h_ind hk /-- A subset of `β„•` containing zero and closed under `Nat.succ` contains all of `β„•`. -/ lemma set_induction {S : Set β„•} (hb : 0 ∈ S) (h_ind : βˆ€ k : β„•, k ∈ S β†’ k + 1 ∈ S) (n : β„•) : n ∈ S := set_induction_bounded hb h_ind (zero_le n) /-! ### `mod`, `dvd` -/ /-- `dvd` is injective in the left argument -/ lemma dvd_left_injective : Function.Injective ((Β· ∣ Β·) : β„• β†’ β„• β†’ Prop) := fun _ _ h => dvd_right_iff_eq.mp fun a => iff_of_eq (congr_fun h a) @[simp] protected lemma dvd_sub_self_left {n m : β„•} : n ∣ n - m ↔ m = 0 ∨ n ≀ m := by rcases le_or_gt n m with h | h Β· simp [h] Β· rcases eq_or_ne m 0 with rfl | hm Β· simp Β· simp only [hm, h.not_ge, or_self, iff_false] refine not_dvd_of_pos_of_lt ?_ ?_ <;> grind @[simp] protected lemma dvd_sub_self_right {n m : β„•} : n ∣ m - n ↔ n ∣ m ∨ m ≀ n := by rcases le_or_gt m n with h | h Β· simp [h] Β· simp [dvd_sub_iff_left (le_of_lt h) (Nat.dvd_refl _), h.not_ge] end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Size.lean
import Mathlib.Algebra.Group.Nat.Defs import Mathlib.Algebra.Group.Basic import Mathlib.Data.Nat.Bits import Mathlib.Data.Nat.Basic /-! Lemmas about `size`. -/ namespace Nat /-! ### `shiftLeft` and `shiftRight` -/ section theorem shiftLeft_eq_mul_pow (m) : βˆ€ n, m <<< n = m * 2 ^ n := shiftLeft_eq _ theorem shiftLeft'_tt_eq_mul_pow (m) : βˆ€ n, shiftLeft' true m n + 1 = (m + 1) * 2 ^ n | 0 => by simp [shiftLeft', pow_zero] | k + 1 => by rw [shiftLeft', bit_val, Bool.toNat_true, add_assoc, ← Nat.mul_add_one, shiftLeft'_tt_eq_mul_pow m k, mul_left_comm, mul_comm 2, pow_succ] end theorem shiftLeft'_ne_zero_left (b) {m} (h : m β‰  0) (n) : shiftLeft' b m n β‰  0 := by induction n <;> simp [shiftLeft', *] theorem shiftLeft'_tt_ne_zero (m) : βˆ€ {n}, (n β‰  0) β†’ shiftLeft' true m n β‰  0 | 0, h => absurd rfl h | succ _, _ => by dsimp [shiftLeft', bit]; cutsat /-! ### `size` -/ @[simp] theorem size_zero : size 0 = 0 := by simp [size] @[simp] theorem size_bit {b n} (h : bit b n β‰  0) : size (bit b n) = succ (size n) := by unfold size conv => lhs rw [binaryRec] simp [h] section @[simp] theorem size_one : size 1 = 1 := show size (bit true 0) = 1 by rw [size_bit, size_zero]; exact Nat.one_ne_zero end @[simp] theorem size_shiftLeft' {b m n} (h : shiftLeft' b m n β‰  0) : size (shiftLeft' b m n) = size m + n := by induction n with | zero => simp [shiftLeft'] | succ n IH => simp only [shiftLeft', ne_eq] at h ⊒ rw [size_bit h, Nat.add_succ] by_cases s0 : shiftLeft' b m n = 0 case neg => rw [IH s0] rw [s0] at h ⊒ cases b; Β· exact absurd rfl h have : shiftLeft' true m n + 1 = 1 := congr_arg (Β· + 1) s0 rw [shiftLeft'_tt_eq_mul_pow] at this obtain rfl := succ.inj (eq_one_of_dvd_one ⟨_, this.symm⟩) simp only [zero_add, one_mul] at this obtain rfl : n = 0 := not_ne_iff.1 fun hn ↦ ne_of_gt (Nat.one_lt_pow hn (by decide)) this rw [add_zero] @[simp] theorem size_shiftLeft {m} (h : m β‰  0) (n) : size (m <<< n) = size m + n := by simp only [size_shiftLeft' (shiftLeft'_ne_zero_left _ h _), ← shiftLeft'_false] theorem lt_size_self (n : β„•) : n < 2 ^ size n := by rw [← one_shiftLeft] have : βˆ€ {n}, n = 0 β†’ n < 1 <<< (size n) := by simp refine binaryRec ?_ ?_ n Β· apply this rfl intro b n IH by_cases h : bit b n = 0 Β· apply this h rw [size_bit h, shiftLeft_succ, shiftLeft_eq, one_mul] cases b <;> dsimp [bit] <;> omega theorem size_le {m n : β„•} : size m ≀ n ↔ m < 2 ^ n := ⟨fun h => lt_of_lt_of_le (lt_size_self _) (Nat.pow_le_pow_right (by decide) h), by rw [← one_shiftLeft] induction m using binaryRec generalizing n with | zero => simp | bit b m IH => intro h by_cases e : bit b m = 0 Β· simp [e] rw [size_bit e] cases n with | zero => exact e.elim (Nat.eq_zero_of_le_zero (le_of_lt_succ h)) | succ n => apply succ_le_succ (IH _) apply Nat.lt_of_mul_lt_mul_left (a := 2) simp only [shiftLeft_succ] at * refine lt_of_le_of_lt ?_ h cases b <;> dsimp [bit] <;> omega⟩ theorem lt_size {m n : β„•} : m < size n ↔ 2 ^ m ≀ n := by rw [← not_lt, Decidable.iff_not_comm, not_lt, size_le] theorem size_pos {n : β„•} : 0 < size n ↔ 0 < n := by rw [lt_size]; rfl theorem size_eq_zero {n : β„•} : size n = 0 ↔ n = 0 := by simpa [Nat.pos_iff_ne_zero, not_iff_not] using size_pos theorem size_pow {n : β„•} : size (2 ^ n) = n + 1 := le_antisymm (size_le.2 <| Nat.pow_lt_pow_right (by decide) (lt_succ_self _)) (lt_size.2 <| le_rfl) theorem size_le_size {m n : β„•} (h : m ≀ n) : size m ≀ size n := size_le.2 <| lt_of_le_of_lt h (lt_size_self _) theorem size_eq_bits_len (n : β„•) : n.bits.length = n.size := by induction n using Nat.binaryRec' with | zero => simp | bit _ _ h ih => rw [size_bit, bits_append_bit _ _ h] Β· simp [ih] Β· simpa [bit_eq_zero_iff] end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Hyperoperation.lean
import Mathlib.Tactic.Ring /-! # Hyperoperation sequence This file defines the Hyperoperation sequence. `hyperoperation 0 m k = k + 1` `hyperoperation 1 m k = m + k` `hyperoperation 2 m k = m * k` `hyperoperation 3 m k = m ^ k` `hyperoperation (n + 3) m 0 = 1` `hyperoperation (n + 1) m (k + 1) = hyperoperation n m (hyperoperation (n + 1) m k)` ## References * <https://en.wikipedia.org/wiki/Hyperoperation> ## Tags hyperoperation -/ /-- Implementation of the hyperoperation sequence where `hyperoperation n m k` is the `n`th hyperoperation between `m` and `k`. -/ def hyperoperation : β„• β†’ β„• β†’ β„• β†’ β„• | 0, _, k => k + 1 | 1, m, 0 => m | 2, _, 0 => 0 | _ + 3, _, 0 => 1 | n + 1, m, k + 1 => hyperoperation n m (hyperoperation (n + 1) m k) attribute [local grind] hyperoperation -- Basic hyperoperation lemmas @[simp, grind =] theorem hyperoperation_zero (m k : β„•) : hyperoperation 0 m k = k + 1 := by grind @[grind =] theorem hyperoperation_ge_three_eq_one (n m : β„•) : hyperoperation (n + 3) m 0 = 1 := by grind @[grind =] theorem hyperoperation_recursion (n m k : β„•) : hyperoperation (n + 1) m (k + 1) = hyperoperation n m (hyperoperation (n + 1) m k) := by grind -- Interesting hyperoperation lemmas @[simp, grind =] theorem hyperoperation_one (m k : β„•) : hyperoperation 1 m k = m + k := by induction k with grind @[simp, grind =] theorem hyperoperation_two (m k : β„•) : hyperoperation 2 m k = m * k := by induction k with grind @[simp, grind =] theorem hyperoperation_three (m k : β„•) : hyperoperation 3 m k = m ^ k := by induction k with grind @[grind =] theorem hyperoperation_ge_two_eq_self (n m : β„•) : hyperoperation (n + 2) m 1 = m := by induction n with grind @[grind =] theorem hyperoperation_two_two_eq_four (n : β„•) : hyperoperation (n + 1) 2 2 = 4 := by induction n with grind @[grind =] theorem hyperoperation_ge_three_one (n k : β„•) : hyperoperation (n + 3) 1 k = 1 := by induction n generalizing k with grind [cases Nat] @[grind =] theorem hyperoperation_ge_four_zero (n k : β„•) : hyperoperation (n + 4) 0 k = if Even k then 1 else 0 := by induction k with grind
.lake/packages/mathlib/Mathlib/Data/Nat/Notation.lean
import Mathlib.Init /-! # Notation `β„•` for the natural numbers. -/ @[inherit_doc] notation "β„•" => Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Set.lean
import Mathlib.Data.Set.Image /-! ### Recursion on the natural numbers and `Set.range` -/ namespace Nat section Set open Set theorem zero_union_range_succ : {0} βˆͺ range succ = univ := by ext n cases n <;> simp @[simp] protected theorem range_succ : range succ = { i | 0 < i } := by ext (_ | i) <;> simp variable {Ξ± : Type*} theorem range_of_succ (f : β„• β†’ Ξ±) : {f 0} βˆͺ range (f ∘ succ) = range f := by rw [← image_singleton, range_comp, ← image_union, zero_union_range_succ, image_univ] theorem range_rec {Ξ± : Type*} (x : Ξ±) (f : β„• β†’ Ξ± β†’ Ξ±) : (Set.range fun n => Nat.rec x f n : Set Ξ±) = {x} βˆͺ Set.range fun n => Nat.rec (f 0 x) (f ∘ succ) n := by convert (range_of_succ (fun n => Nat.rec x f n : β„• β†’ Ξ±)).symm using 4 dsimp rename_i n induction n with | zero => rfl | succ n ihn => dsimp at ihn ⊒; rw [ihn] theorem range_casesOn {Ξ± : Type*} (x : Ξ±) (f : β„• β†’ Ξ±) : (Set.range fun n => Nat.casesOn n x f : Set Ξ±) = {x} βˆͺ Set.range f := (range_of_succ _).symm end Set end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/ChineseRemainder.lean
import Mathlib.Algebra.BigOperators.Ring.List import Mathlib.Data.Nat.ModEq import Mathlib.Data.Nat.GCD.BigOperators /-! # Chinese Remainder Theorem This file provides definitions and theorems for the Chinese Remainder Theorem. These are used in GΓΆdel's Beta function, which is used in proving GΓΆdel's incompleteness theorems. ## Main result - `chineseRemainderOfList`: Definition of the Chinese remainder of a list ## Tags Chinese Remainder Theorem, GΓΆdel, beta function -/ open scoped Function -- required for scoped `on` notation namespace Nat variable {ΞΉ : Type*} lemma modEq_list_prod_iff {a b} {l : List β„•} (co : l.Pairwise Coprime) : a ≑ b [MOD l.prod] ↔ βˆ€ i, a ≑ b [MOD l.get i] := by induction l with | nil => simp [modEq_one] | cons m l ih => have : Coprime m l.prod := coprime_list_prod_right_iff.mpr (List.pairwise_cons.mp co).1 simp only [List.prod_cons, ← modEq_and_modEq_iff_modEq_mul this, ih (List.Pairwise.of_cons co), List.length_cons] constructor Β· rintro ⟨h0, hs⟩ i cases i using Fin.cases <;> simp_all Β· intro h; exact ⟨h 0, fun i => h i.succ⟩ lemma modEq_list_map_prod_iff {a b} {s : ΞΉ β†’ β„•} {l : List ΞΉ} (co : l.Pairwise (Coprime on s)) : a ≑ b [MOD (l.map s).prod] ↔ βˆ€ i ∈ l, a ≑ b [MOD s i] := by induction l with | nil => simp [modEq_one] | cons i l ih => have : Coprime (s i) (l.map s).prod := by simp only [coprime_list_prod_right_iff, List.mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iffβ‚‚] intro j hj exact (List.pairwise_cons.mp co).1 j hj simp [← modEq_and_modEq_iff_modEq_mul this, ih (List.Pairwise.of_cons co)] @[deprecated (since := "2025-05-24")] alias modEq_list_prod_iff' := modEq_list_map_prod_iff variable (a s : ΞΉ β†’ β„•) /-- The natural number less than `(l.map s).prod` congruent to `a i` mod `s i` for all `i ∈ l`. -/ def chineseRemainderOfList : (l : List ΞΉ) β†’ l.Pairwise (Coprime on s) β†’ { k // βˆ€ i ∈ l, k ≑ a i [MOD s i] } | [], _ => ⟨0, by simp⟩ | i :: l, co => by have : Coprime (s i) (l.map s).prod := by simp only [coprime_list_prod_right_iff, List.mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iffβ‚‚] intro j hj exact (List.pairwise_cons.mp co).1 j hj have ih := chineseRemainderOfList l co.of_cons have k := chineseRemainder this (a i) ih use k simp only [List.mem_cons, forall_eq_or_imp, k.prop.1, true_and] intro j hj exact ((modEq_list_map_prod_iff co.of_cons).mp k.prop.2 j hj).trans (ih.prop j hj) @[simp] theorem chineseRemainderOfList_nil : (chineseRemainderOfList a s [] List.Pairwise.nil : β„•) = 0 := rfl theorem chineseRemainderOfList_lt_prod (l : List ΞΉ) (co : l.Pairwise (Coprime on s)) (hs : βˆ€ i ∈ l, s i β‰  0) : chineseRemainderOfList a s l co < (l.map s).prod := by cases l with | nil => simp | cons i l => simp only [chineseRemainderOfList, List.map_cons, List.prod_cons] have : Coprime (s i) (l.map s).prod := by simp only [coprime_list_prod_right_iff, List.mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iffβ‚‚] intro j hj exact (List.pairwise_cons.mp co).1 j hj refine chineseRemainder_lt_mul this (a i) (chineseRemainderOfList a s l co.of_cons) (hs i List.mem_cons_self) ?_ simp only [ne_eq, List.prod_eq_zero_iff, List.mem_map, not_exists, not_and] intro j hj exact hs j (List.mem_cons_of_mem _ hj) theorem chineseRemainderOfList_modEq_unique (l : List ΞΉ) (co : l.Pairwise (Coprime on s)) {z} (hz : βˆ€ i ∈ l, z ≑ a i [MOD s i]) : z ≑ chineseRemainderOfList a s l co [MOD (l.map s).prod] := by induction l with | nil => simp [modEq_one] | cons i l ih => simp only [List.map_cons, List.prod_cons, chineseRemainderOfList] have : Coprime (s i) (l.map s).prod := by simp only [coprime_list_prod_right_iff, List.mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iffβ‚‚] intro j hj exact (List.pairwise_cons.mp co).1 j hj exact chineseRemainder_modEq_unique this (hz i List.mem_cons_self) (ih co.of_cons (fun j hj => hz j (List.mem_cons_of_mem _ hj))) theorem chineseRemainderOfList_perm {l l' : List ΞΉ} (hl : l.Perm l') (hs : βˆ€ i ∈ l, s i β‰  0) (co : l.Pairwise (Coprime on s)) : (chineseRemainderOfList a s l co : β„•) = chineseRemainderOfList a s l' (co.perm hl coprime_comm.mpr) := by let z := chineseRemainderOfList a s l' (co.perm hl coprime_comm.mpr) have hlp : (l.map s).prod = (l'.map s).prod := List.Perm.prod_eq (List.Perm.map s hl) exact (chineseRemainderOfList_modEq_unique a s l co (z := z) (fun i hi => z.prop i (hl.symm.mem_iff.mpr hi))).symm.eq_of_lt_of_lt (chineseRemainderOfList_lt_prod _ _ _ _ hs) (by rw [hlp] exact chineseRemainderOfList_lt_prod _ _ _ _ (by simpa [List.Perm.mem_iff hl.symm] using hs)) /-- The natural number less than `(m.map s).prod` congruent to `a i` mod `s i` for all `i ∈ m`. -/ def chineseRemainderOfMultiset {m : Multiset ΞΉ} : m.Nodup β†’ (βˆ€ i ∈ m, s i β‰  0) β†’ Set.Pairwise {x | x ∈ m} (Coprime on s) β†’ { k // βˆ€ i ∈ m, k ≑ a i [MOD s i] } := Quotient.recOn m (fun l nod _ co => chineseRemainderOfList a s l (List.Nodup.pairwise_of_forall_ne nod co)) (fun l l' (pp : l.Perm l') ↦ funext fun nod' : l'.Nodup => have nod : l.Nodup := pp.symm.nodup_iff.mp nod' funext fun hs' : βˆ€ i ∈ l', s i β‰  0 => have hs : βˆ€ i ∈ l, s i β‰  0 := by simpa [List.Perm.mem_iff pp] using hs' funext fun co' : Set.Pairwise {x | x ∈ l'} (Coprime on s) => have co : Set.Pairwise {x | x ∈ l} (Coprime on s) := by simpa [List.Perm.mem_iff pp] using co' have lco : l.Pairwise (Coprime on s) := List.Nodup.pairwise_of_forall_ne nod co have : βˆ€ {m' e nod'' hs'' co''}, @Eq.ndrec (Multiset ΞΉ) l (fun m ↦ m.Nodup β†’ (βˆ€ i ∈ m, s i β‰  0) β†’ Set.Pairwise {x | x ∈ m} (Coprime on s) β†’ { k // βˆ€ i ∈ m, k ≑ a i [MOD s i] }) (fun nod _ co ↦ chineseRemainderOfList a s l (List.Nodup.pairwise_of_forall_ne nod co)) m' e nod'' hs'' co'' = (chineseRemainderOfList a s l lco : β„•) := by rintro _ rfl _ _ _; rfl by ext; exact this.trans <| chineseRemainderOfList_perm a s pp hs lco) theorem chineseRemainderOfMultiset_lt_prod {m : Multiset ΞΉ} (nod : m.Nodup) (hs : βˆ€ i ∈ m, s i β‰  0) (pp : Set.Pairwise {x | x ∈ m} (Coprime on s)) : chineseRemainderOfMultiset a s nod hs pp < (m.map s).prod := by induction m using Quot.ind with | _ l unfold chineseRemainderOfMultiset simpa using chineseRemainderOfList_lt_prod a s l (List.Nodup.pairwise_of_forall_ne nod pp) (by simpa using hs) /-- The natural number less than `∏ i ∈ t, s i` congruent to `a i` mod `s i` for all `i ∈ t`. -/ def chineseRemainderOfFinset (t : Finset ΞΉ) (hs : βˆ€ i ∈ t, s i β‰  0) (pp : Set.Pairwise t (Coprime on s)) : { k // βˆ€ i ∈ t, k ≑ a i [MOD s i] } := by simpa using chineseRemainderOfMultiset a s t.nodup (by simpa using hs) (by simpa using pp) theorem chineseRemainderOfFinset_lt_prod {t : Finset ΞΉ} (hs : βˆ€ i ∈ t, s i β‰  0) (pp : Set.Pairwise t (Coprime on s)) : chineseRemainderOfFinset a s t hs pp < ∏ i ∈ t, s i := by simpa [chineseRemainderOfFinset] using chineseRemainderOfMultiset_lt_prod a s t.nodup (by simpa using hs) (by simpa using pp) end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Squarefree.lean
import Mathlib.Algebra.Order.BigOperators.Ring.Finset import Mathlib.Algebra.Squarefree.Basic import Mathlib.Data.Nat.Factorization.Basic import Mathlib.NumberTheory.Divisors import Mathlib.RingTheory.UniqueFactorizationDomain.Nat /-! # Lemmas about squarefreeness of natural numbers A number is squarefree when it is not divisible by any squares except the squares of units. ## Main Results - `Nat.squarefree_iff_nodup_primeFactorsList`: A positive natural number `x` is squarefree iff the list `factors x` has no duplicate factors. ## Tags squarefree, multiplicity -/ open Finset namespace Nat theorem squarefree_iff_nodup_primeFactorsList {n : β„•} (h0 : n β‰  0) : Squarefree n ↔ n.primeFactorsList.Nodup := by rw [UniqueFactorizationMonoid.squarefree_iff_nodup_normalizedFactors h0, Nat.factors_eq] simp end Nat theorem Squarefree.nodup_primeFactorsList {n : β„•} (hn : Squarefree n) : n.primeFactorsList.Nodup := (Nat.squarefree_iff_nodup_primeFactorsList hn.ne_zero).mp hn namespace Nat variable {s : Finset β„•} {m n p : β„•} theorem squarefree_iff_prime_squarefree {n : β„•} : Squarefree n ↔ βˆ€ x, Prime x β†’ Β¬x * x ∣ n := squarefree_iff_irreducible_sq_not_dvd_of_exists_irreducible ⟨_, prime_two⟩ theorem _root_.Squarefree.natFactorization_le_one {n : β„•} (p : β„•) (hn : Squarefree n) : n.factorization p ≀ 1 := by rcases eq_or_ne n 0 with (rfl | hn') Β· simp rw [squarefree_iff_emultiplicity_le_one] at hn by_cases hp : p.Prime Β· have := hn p rw [← multiplicity_eq_factorization hp hn'] simp only [Nat.isUnit_iff, hp.ne_one, or_false] at this exact multiplicity_le_of_emultiplicity_le this Β· rw [factorization_eq_zero_of_not_prime _ hp] exact zero_le_one lemma factorization_eq_one_of_squarefree (hn : Squarefree n) (hp : p.Prime) (hpn : p ∣ n) : factorization n p = 1 := (hn.natFactorization_le_one _).antisymm <| (hp.dvd_iff_one_le_factorization hn.ne_zero).1 hpn theorem squarefree_of_factorization_le_one {n : β„•} (hn : n β‰  0) (hn' : βˆ€ p, n.factorization p ≀ 1) : Squarefree n := by rw [squarefree_iff_nodup_primeFactorsList hn, List.nodup_iff_count_le_one] intro a rw [primeFactorsList_count_eq] apply hn' theorem squarefree_iff_factorization_le_one {n : β„•} (hn : n β‰  0) : Squarefree n ↔ βˆ€ p, n.factorization p ≀ 1 := ⟨fun hn => hn.natFactorization_le_one, squarefree_of_factorization_le_one hn⟩ theorem Squarefree.ext_iff {n m : β„•} (hn : Squarefree n) (hm : Squarefree m) : n = m ↔ βˆ€ p, Prime p β†’ (p ∣ n ↔ p ∣ m) := by refine ⟨by rintro rfl; simp, fun h => eq_of_factorization_eq hn.ne_zero hm.ne_zero fun p => ?_⟩ by_cases hp : p.Prime Β· have h₁ := h _ hp rw [← not_iff_not, hp.dvd_iff_one_le_factorization hn.ne_zero, not_le, lt_one_iff, hp.dvd_iff_one_le_factorization hm.ne_zero, not_le, lt_one_iff] at h₁ have hβ‚‚ := hn.natFactorization_le_one p have h₃ := hm.natFactorization_le_one p cutsat rw [factorization_eq_zero_of_not_prime _ hp, factorization_eq_zero_of_not_prime _ hp] theorem squarefree_pow_iff {n k : β„•} (hn : n β‰  1) (hk : k β‰  0) : Squarefree (n ^ k) ↔ Squarefree n ∧ k = 1 := by refine ⟨fun h => ?_, by rintro ⟨hn, rfl⟩; simpa⟩ rcases eq_or_ne n 0 with (rfl | -) Β· simp [zero_pow hk] at h refine ⟨h.squarefree_of_dvd (dvd_pow_self _ hk), by_contradiction fun h₁ => ?_⟩ have : 2 ≀ k := k.two_le_iff.mpr ⟨hk, hβ‚βŸ© apply hn (Nat.isUnit_iff.1 (h _ _)) rw [← sq] exact pow_dvd_pow _ this theorem squarefree_and_prime_pow_iff_prime {n : β„•} : Squarefree n ∧ IsPrimePow n ↔ Prime n := by refine ⟨?_, fun hn => ⟨hn.squarefree, hn.isPrimePow⟩⟩ rw [isPrimePow_nat_iff] rintro ⟨h, p, k, hp, hk, rfl⟩ rw [squarefree_pow_iff hp.ne_one hk.ne'] at h rwa [h.2, pow_one] /-- Assuming that `n` has no factors less than `k`, returns the smallest prime `p` such that `p^2 ∣ n`. -/ def minSqFacAux : β„• β†’ β„• β†’ Option β„• | n, k => if h : n < k * k then none else have : Nat.sqrt n - k < Nat.sqrt n + 2 - k := by exact Nat.minFac_lemma n k h if k ∣ n then let n' := n / k have : Nat.sqrt n' - k < Nat.sqrt n + 2 - k := lt_of_le_of_lt (by gcongr; apply div_le_self) this if k ∣ n' then some k else minSqFacAux n' (k + 2) else minSqFacAux n (k + 2) termination_by n k => sqrt n + 2 - k /-- Returns the smallest prime factor `p` of `n` such that `p^2 ∣ n`, or `none` if there is no such `p` (that is, `n` is squarefree). See also `Nat.squarefree_iff_minSqFac`. -/ def minSqFac (n : β„•) : Option β„• := if 2 ∣ n then let n' := n / 2 if 2 ∣ n' then some 2 else minSqFacAux n' 3 else minSqFacAux n 3 /-- The correctness property of the return value of `minSqFac`. * If `none`, then `n` is squarefree; * If `some d`, then `d` is a minimal square factor of `n` -/ def MinSqFacProp (n : β„•) : Option β„• β†’ Prop | none => Squarefree n | some d => Prime d ∧ d * d ∣ n ∧ βˆ€ p, Prime p β†’ p * p ∣ n β†’ d ≀ p theorem minSqFacProp_div (n) {k} (pk : Prime k) (dk : k ∣ n) (dkk : Β¬k * k ∣ n) {o} (H : MinSqFacProp (n / k) o) : MinSqFacProp n o := by have : βˆ€ p, Prime p β†’ p * p ∣ n β†’ k * (p * p) ∣ n := fun p pp dp => have := (coprime_primes pk pp).2 fun e => by subst e contradiction (coprime_mul_iff_right.2 ⟨this, this⟩).mul_dvd_of_dvd_of_dvd dk dp rcases o with - | d Β· rw [MinSqFacProp, squarefree_iff_prime_squarefree] at H ⊒ exact fun p pp dp => H p pp ((dvd_div_iff_mul_dvd dk).2 (this _ pp dp)) Β· obtain ⟨H1, H2, H3⟩ := H simp only [dvd_div_iff_mul_dvd dk] at H2 H3 exact ⟨H1, dvd_trans (dvd_mul_left _ _) H2, fun p pp dp => H3 _ pp (this _ pp dp)⟩ theorem minSqFacAux_has_prop {n : β„•} (k) (n0 : 0 < n) (i) (e : k = 2 * i + 3) (ih : βˆ€ m, Prime m β†’ m ∣ n β†’ k ≀ m) : MinSqFacProp n (minSqFacAux n k) := by rw [minSqFacAux] by_cases h : n < k * k <;> simp only [h, ↓reduceDIte] Β· refine squarefree_iff_prime_squarefree.2 fun p pp d => ?_ have := ih p pp (dvd_trans ⟨_, rfl⟩ d) have := Nat.mul_le_mul this this exact not_le_of_gt h (le_trans this (le_of_dvd n0 d)) have k2 : 2 ≀ k := by omega have k0 : 0 < k := lt_of_lt_of_le (by decide) k2 have IH : βˆ€ n', n' ∣ n β†’ Β¬k ∣ n' β†’ MinSqFacProp n' (n'.minSqFacAux (k + 2)) := by intro n' nd' nk have hn' := le_of_dvd n0 nd' refine have : Nat.sqrt n' - k < Nat.sqrt n + 2 - k := lt_of_le_of_lt (by gcongr) (Nat.minFac_lemma n k h) @minSqFacAux_has_prop n' (k + 2) (pos_of_dvd_of_pos nd' n0) (i + 1) (by simp [e, left_distrib]) fun m m2 d => ?_ rcases Nat.eq_or_lt_of_le (ih m m2 (dvd_trans d nd')) with me | ml Β· subst me contradiction apply (Nat.eq_or_lt_of_le ml).resolve_left intro me rw [← me, e] at d change 2 * (i + 2) ∣ n' at d have := ih _ prime_two (dvd_trans (dvd_of_mul_right_dvd d) nd') rw [e] at this exact absurd this (by cutsat) have pk : k ∣ n β†’ Prime k := by refine fun dk => prime_def_minFac.2 ⟨k2, le_antisymm (minFac_le k0) ?_⟩ exact ih _ (minFac_prime (ne_of_gt k2)) (dvd_trans (minFac_dvd _) dk) split_ifs with dk dkk Β· exact ⟨pk dk, (Nat.dvd_div_iff_mul_dvd dk).1 dkk, fun p pp d => ih p pp (dvd_trans ⟨_, rfl⟩ d)⟩ Β· specialize IH (n / k) (div_dvd_of_dvd dk) dkk exact minSqFacProp_div _ (pk dk) dk (mt (Nat.dvd_div_iff_mul_dvd dk).2 dkk) IH Β· exact IH n (dvd_refl _) dk termination_by n.sqrt + 2 - k theorem minSqFac_has_prop (n : β„•) : MinSqFacProp n (minSqFac n) := by dsimp only [minSqFac]; split_ifs with d2 d4 Β· exact ⟨prime_two, (dvd_div_iff_mul_dvd d2).1 d4, fun p pp _ => pp.two_le⟩ Β· rcases Nat.eq_zero_or_pos n with n0 | n0 Β· subst n0 cases d4 (by decide) refine minSqFacProp_div _ prime_two d2 (mt (dvd_div_iff_mul_dvd d2).2 d4) ?_ refine minSqFacAux_has_prop 3 (Nat.div_pos (le_of_dvd n0 d2) (by decide)) 0 rfl ?_ refine fun p pp dp => succ_le_of_lt (lt_of_le_of_ne pp.two_le ?_) rintro rfl contradiction Β· rcases Nat.eq_zero_or_pos n with n0 | n0 Β· subst n0 cases d2 (by decide) refine minSqFacAux_has_prop _ n0 0 rfl ?_ refine fun p pp dp => succ_le_of_lt (lt_of_le_of_ne pp.two_le ?_) rintro rfl contradiction theorem minSqFac_prime {n d : β„•} (h : n.minSqFac = some d) : Prime d := by have := minSqFac_has_prop n rw [h] at this exact this.1 theorem minSqFac_dvd {n d : β„•} (h : n.minSqFac = some d) : d * d ∣ n := by have := minSqFac_has_prop n rw [h] at this exact this.2.1 theorem minSqFac_le_of_dvd {n d : β„•} (h : n.minSqFac = some d) {m} (m2 : 2 ≀ m) (md : m * m ∣ n) : d ≀ m := by have := minSqFac_has_prop n; rw [h] at this have fd := minFac_dvd m exact le_trans (this.2.2 _ (minFac_prime <| ne_of_gt m2) (dvd_trans (mul_dvd_mul fd fd) md)) (minFac_le <| lt_of_lt_of_le (by decide) m2) theorem squarefree_iff_minSqFac {n : β„•} : Squarefree n ↔ n.minSqFac = none := by have := minSqFac_has_prop n constructor <;> intro H Β· rcases e : n.minSqFac with - | d Β· rfl rw [e] at this cases squarefree_iff_prime_squarefree.1 H _ this.1 this.2.1 Β· rwa [H] at this instance : DecidablePred (Squarefree : β„• β†’ Prop) := fun _ => decidable_of_iff' _ squarefree_iff_minSqFac theorem squarefree_two : Squarefree 2 := by rw [squarefree_iff_nodup_primeFactorsList] <;> simp theorem divisors_filter_squarefree_of_squarefree {n : β„•} (hn : Squarefree n) : {d ∈ n.divisors | Squarefree d} = n.divisors := Finset.ext fun d => ⟨@Finset.filter_subset _ _ _ _ d, fun hd => Finset.mem_filter.mpr ⟨hd, hn.squarefree_of_dvd (Nat.dvd_of_mem_divisors hd) ⟩⟩ open UniqueFactorizationMonoid theorem divisors_filter_squarefree {n : β„•} (h0 : n β‰  0) : {d ∈ n.divisors | Squarefree d}.val = (UniqueFactorizationMonoid.normalizedFactors n).toFinset.powerset.val.map fun x => x.val.prod := by rw [(Finset.nodup _).ext ((Finset.nodup _).map_on _)] Β· intro a simp only [Multiset.mem_filter, Multiset.mem_map, Finset.filter_val, ← Finset.mem_def, mem_divisors] constructor Β· rintro ⟨⟨an, h0⟩, hsq⟩ use (UniqueFactorizationMonoid.normalizedFactors a).toFinset simp only [Finset.mem_powerset] rcases an with ⟨b, rfl⟩ rw [mul_ne_zero_iff] at h0 rw [UniqueFactorizationMonoid.squarefree_iff_nodup_normalizedFactors h0.1] at hsq rw [Multiset.toFinset_subset, Multiset.toFinset_val, hsq.dedup, ← associated_iff_eq, normalizedFactors_mul h0.1 h0.2] exact ⟨Multiset.subset_of_le (Multiset.le_add_right _ _), prod_normalizedFactors h0.1⟩ Β· rintro ⟨s, hs, rfl⟩ rw [Finset.mem_powerset, ← Finset.val_le_iff, Multiset.toFinset_val] at hs have hs0 : s.val.prod β‰  0 := by rw [Ne, Multiset.prod_eq_zero_iff] intro con apply not_irreducible_zero (irreducible_of_normalized_factor 0 (Multiset.mem_dedup.1 (Multiset.mem_of_le hs con))) rw [(prod_normalizedFactors h0).symm.dvd_iff_dvd_right] refine ⟨⟨Multiset.prod_dvd_prod_of_le (le_trans hs (Multiset.dedup_le _)), h0⟩, ?_⟩ have h := UniqueFactorizationMonoid.factors_unique irreducible_of_normalized_factor (fun x hx => irreducible_of_normalized_factor x (Multiset.mem_of_le (le_trans hs (Multiset.dedup_le _)) hx)) (prod_normalizedFactors hs0) rw [associated_eq_eq, Multiset.rel_eq] at h rw [UniqueFactorizationMonoid.squarefree_iff_nodup_normalizedFactors hs0, h] apply s.nodup Β· intro x hx y hy h rw [← Finset.val_inj, ← Multiset.rel_eq, ← associated_eq_eq] rw [← Finset.mem_def, Finset.mem_powerset] at hx hy apply UniqueFactorizationMonoid.factors_unique _ _ (associated_iff_eq.2 h) Β· intro z hz apply irreducible_of_normalized_factor z Β· rw [← Multiset.mem_toFinset] apply hx hz Β· intro z hz apply irreducible_of_normalized_factor z Β· rw [← Multiset.mem_toFinset] apply hy hz theorem sum_divisors_filter_squarefree {n : β„•} (h0 : n β‰  0) {Ξ± : Type*} [AddCommMonoid Ξ±] {f : β„• β†’ Ξ±} : βˆ‘ d ∈ n.divisors with Squarefree d, f d = βˆ‘ i ∈ (UniqueFactorizationMonoid.normalizedFactors n).toFinset.powerset, f i.val.prod := by rw [Finset.sum_eq_multiset_sum, divisors_filter_squarefree h0, Multiset.map_map, Finset.sum_eq_multiset_sum] rfl theorem sq_mul_squarefree_of_pos {n : β„•} (hn : 0 < n) : βˆƒ a b : β„•, 0 < a ∧ 0 < b ∧ b ^ 2 * a = n ∧ Squarefree a := by classical set S := {s ∈ range (n + 1) | s ∣ n ∧ βˆƒ x, s = x ^ 2} have hSne : S.Nonempty := by use 1 have h1 : 0 < n ∧ βˆƒ x : β„•, 1 = x ^ 2 := ⟨hn, ⟨1, (one_pow 2).symm⟩⟩ simp [S, h1] let s := Finset.max' S hSne have hs : s ∈ S := Finset.max'_mem S hSne simp only [S, Finset.mem_filter, Finset.mem_range] at hs obtain ⟨-, ⟨a, hsa⟩, ⟨b, hsb⟩⟩ := hs rw [hsa] at hn obtain ⟨hlts, hlta⟩ := CanonicallyOrderedAdd.mul_pos.mp hn rw [hsb] at hsa hn hlts refine ⟨a, b, hlta, (pow_pos_iff two_ne_zero).mp hlts, hsa.symm, ?_⟩ rintro x ⟨y, hy⟩ rw [Nat.isUnit_iff] by_contra hx refine Nat.lt_le_asymm ?_ (Finset.le_max' S ((b * x) ^ 2) ?_) Β· convert lt_mul_of_one_lt_right hlts (one_lt_pow two_ne_zero (one_lt_iff_ne_zero_and_ne_one.mpr ⟨fun h => by simp_all, hx⟩)) using 1 rw [mul_pow] Β· simp_rw [S, hsa, Finset.mem_filter, Finset.mem_range] refine ⟨Nat.lt_succ_iff.mpr (le_of_dvd hn ?_), ?_, ⟨b * x, rfl⟩⟩ <;> use y <;> rw [hy] <;> ring theorem sq_mul_squarefree_of_pos' {n : β„•} (h : 0 < n) : βˆƒ a b : β„•, (b + 1) ^ 2 * (a + 1) = n ∧ Squarefree (a + 1) := by obtain ⟨a₁, b₁, ha₁, hb₁, hab₁, habβ‚‚βŸ© := sq_mul_squarefree_of_pos h refine ⟨a₁.pred, b₁.pred, ?_, ?_⟩ <;> simpa only [add_one, succ_pred_eq_of_pos, ha₁, hb₁] theorem sq_mul_squarefree (n : β„•) : βˆƒ a b : β„•, b ^ 2 * a = n ∧ Squarefree a := by rcases n with - | n Β· exact ⟨1, 0, by simp, squarefree_one⟩ Β· obtain ⟨a, b, -, -, h₁, hβ‚‚βŸ© := sq_mul_squarefree_of_pos (succ_pos n) exact ⟨a, b, h₁, hβ‚‚βŸ© /-- `Squarefree` is multiplicative. Note that the β†’ direction does not require `hmn` and generalizes to arbitrary commutative monoids. See `Squarefree.of_mul_left` and `Squarefree.of_mul_right` above for auxiliary lemmas. -/ theorem squarefree_mul {m n : β„•} (hmn : m.Coprime n) : Squarefree (m * n) ↔ Squarefree m ∧ Squarefree n := by simp [squarefree_mul_iff, Nat.coprime_iff_isRelPrime.mp hmn] theorem coprime_of_squarefree_mul {m n : β„•} (h : Squarefree (m * n)) : m.Coprime n := coprime_of_dvd fun p hp hm hn => squarefree_iff_prime_squarefree.mp h p hp (mul_dvd_mul hm hn) theorem squarefree_mul_iff {m n : β„•} : Squarefree (m * n) ↔ m.Coprime n ∧ Squarefree m ∧ Squarefree n := by rw [_root_.squarefree_mul_iff, Nat.coprime_iff_isRelPrime] lemma coprime_div_gcd_of_squarefree (hm : Squarefree m) (hn : n β‰  0) : Coprime (m / gcd m n) n := by have : Coprime (m / gcd m n) (gcd m n) := coprime_of_squarefree_mul <| by simpa [Nat.div_mul_cancel, gcd_dvd_left] simpa [Nat.div_mul_cancel, gcd_dvd_right] using (coprime_div_gcd_div_gcd (m := m) (gcd_ne_zero_right hn).bot_lt).mul_right this lemma prod_primeFactors_of_squarefree (hn : Squarefree n) : ∏ p ∈ n.primeFactors, p = n := by rw [← toFinset_factors, List.prod_toFinset _ hn.nodup_primeFactorsList, List.map_id', Nat.prod_primeFactorsList hn.ne_zero] lemma primeFactors_prod (hs : βˆ€ p ∈ s, p.Prime) : primeFactors (∏ p ∈ s, p) = s := by have hn : ∏ p ∈ s, p β‰  0 := prod_ne_zero_iff.2 fun p hp ↦ (hs _ hp).ne_zero ext p rw [mem_primeFactors_of_ne_zero hn, and_congr_right (fun hp ↦ hp.prime.dvd_finset_prod_iff _)] refine ⟨?_, fun hp ↦ ⟨hs _ hp, _, hp, dvd_rfl⟩⟩ rintro ⟨hp, q, hq, hpq⟩ rwa [← ((hs _ hq).dvd_iff_eq hp.ne_one).1 hpq] lemma primeFactors_div_gcd (hm : Squarefree m) (hn : n β‰  0) : primeFactors (m / m.gcd n) = primeFactors m \ primeFactors n := by ext p have : m / m.gcd n β‰  0 := by simp [gcd_ne_zero_right hn, gcd_le_left _ hm.ne_zero.bot_lt] simp only [mem_primeFactors, ne_eq, this, not_false_eq_true, and_true, not_and, mem_sdiff, hm.ne_zero, hn, dvd_div_iff_mul_dvd (gcd_dvd_left _ _)] refine ⟨fun hp ↦ ⟨⟨hp.1, dvd_of_mul_left_dvd hp.2⟩, fun _ hpn ↦ hp.1.not_isUnit <| hm _ <| (mul_dvd_mul_right (dvd_gcd (dvd_of_mul_left_dvd hp.2) hpn) _).trans hp.2⟩, fun hp ↦ ⟨hp.1.1, Coprime.mul_dvd_of_dvd_of_dvd ?_ (gcd_dvd_left _ _) hp.1.2⟩⟩ rw [coprime_comm, hp.1.1.coprime_iff_not_dvd] exact fun hpn ↦ hp.2 hp.1.1 <| hpn.trans <| gcd_dvd_right _ _ lemma prod_primeFactors_invOn_squarefree : Set.InvOn (fun n : β„• ↦ (factorization n).support) (fun s ↦ ∏ p ∈ s, p) {s | βˆ€ p ∈ s, p.Prime} {n | Squarefree n} := ⟨fun _s ↦ primeFactors_prod, fun _n ↦ prod_primeFactors_of_squarefree⟩ theorem prod_primeFactors_sdiff_of_squarefree {n : β„•} (hn : Squarefree n) {t : Finset β„•} (ht : t βŠ† n.primeFactors) : ∏ a ∈ (n.primeFactors \ t), a = n / ∏ a ∈ t, a := by refine symm <| Nat.div_eq_of_eq_mul_left (Finset.prod_pos fun p hp => (prime_of_mem_primeFactorsList (List.mem_toFinset.mp (ht hp))).pos) ?_ rw [Finset.prod_sdiff ht, prod_primeFactors_of_squarefree hn] end Nat -- Porting note: comment out NormNum tactic, to be moved to another file. /- /-! ### Square-free prover -/ open NormNum namespace Tactic namespace NormNum /-- A predicate representing partial progress in a proof of `Squarefree`. -/ def SquarefreeHelper (n k : β„•) : Prop := 0 < k β†’ (βˆ€ m, Nat.Prime m β†’ m ∣ bit1 n β†’ bit1 k ≀ m) β†’ Squarefree (bit1 n) theorem squarefree_bit10 (n : β„•) (h : SquarefreeHelper n 1) : Squarefree (bit0 (bit1 n)) := by refine' @Nat.minSqFacProp_div _ _ Nat.prime_two two_dvd_bit0 _ none _ Β· rw [bit0_eq_two_mul (bit1 n), mul_dvd_mul_iff_left (two_ne_zero' β„•)] exact Nat.not_two_dvd_bit1 _ Β· rw [bit0_eq_two_mul, Nat.mul_div_right _ (by decide : 0 < 2)] refine' h (by decide) fun p pp dp => Nat.succ_le_of_lt (lt_of_le_of_ne pp.two_le _) rintro rfl exact Nat.not_two_dvd_bit1 _ dp theorem squarefree_bit1 (n : β„•) (h : SquarefreeHelper n 1) : Squarefree (bit1 n) := by refine' h (by decide) fun p pp dp => Nat.succ_le_of_lt (lt_of_le_of_ne pp.two_le _) rintro rfl; exact Nat.not_two_dvd_bit1 _ dp theorem squarefree_helper_0 {k} (k0 : 0 < k) {p : β„•} (pp : Nat.Prime p) (h : bit1 k ≀ p) : bit1 (k + 1) ≀ p ∨ bit1 k = p := by rcases lt_or_eq_of_le h with ((hp : _ + 1 ≀ _) | hp) Β· rw [bit1, bit0_eq_two_mul] at hp change 2 * (_ + 1) ≀ _ at hp rw [bit1, bit0_eq_two_mul] refine' Or.inl (lt_of_le_of_ne hp _) rintro rfl exact Nat.not_prime_mul (by decide) (lt_add_of_pos_left _ k0) pp Β· exact Or.inr hp theorem squarefreeHelper_1 (n k k' : β„•) (e : k + 1 = k') (hk : Nat.Prime (bit1 k) β†’ Β¬bit1 k ∣ bit1 n) (H : SquarefreeHelper n k') : SquarefreeHelper n k := fun k0 ih => by subst e refine' H (Nat.succ_pos _) fun p pp dp => _ refine' (squarefree_helper_0 k0 pp (ih p pp dp)).resolve_right fun hp => _ subst hp; cases hk pp dp theorem squarefreeHelper_2 (n k k' c : β„•) (e : k + 1 = k') (hc : bit1 n % bit1 k = c) (c0 : 0 < c) (h : SquarefreeHelper n k') : SquarefreeHelper n k := by refine' squarefree_helper_1 _ _ _ e (fun _ => _) h refine' mt _ (ne_of_gt c0); intro e₁ rwa [← hc, ← Nat.dvd_iff_mod_eq_zero] theorem squarefreeHelper_3 (n n' k k' c : β„•) (e : k + 1 = k') (hn' : bit1 n' * bit1 k = bit1 n) (hc : bit1 n' % bit1 k = c) (c0 : 0 < c) (H : SquarefreeHelper n' k') : SquarefreeHelper n k := fun k0 ih => by subst e have k0' : 0 < bit1 k := bit1_pos (Nat.zero_le _) have dn' : bit1 n' ∣ bit1 n := ⟨_, hn'.symm⟩ have dk : bit1 k ∣ bit1 n := ⟨_, ((mul_comm _ _).trans hn').symm⟩ have : bit1 n / bit1 k = bit1 n' := by rw [← hn', Nat.mul_div_cancel _ k0'] have k2 : 2 ≀ bit1 k := Nat.succ_le_succ (bit0_pos k0) have pk : (bit1 k).Prime := by refine' Nat.prime_def_minFac.2 ⟨k2, le_antisymm (Nat.minFac_le k0') _⟩ exact ih _ (Nat.minFac_prime (ne_of_gt k2)) (dvd_trans (Nat.minFac_dvd _) dk) have dkk' : Β¬bit1 k ∣ bit1 n' := by rw [Nat.dvd_iff_mod_eq_zero, hc] exact ne_of_gt c0 have dkk : Β¬bit1 k * bit1 k ∣ bit1 n := by rwa [← Nat.dvd_div_iff_mul_dvd dk, this] refine' @Nat.minSqFacProp_div _ _ pk dk dkk none _ rw [this] refine' H (Nat.succ_pos _) fun p pp dp => _ refine' (squarefree_helper_0 k0 pp (ih p pp <| dvd_trans dp dn')).resolve_right fun e => _ subst e contradiction theorem squarefreeHelper_4 (n k k' : β„•) (e : bit1 k * bit1 k = k') (hd : bit1 n < k') : SquarefreeHelper n k := by rcases Nat.eq_zero_or_pos n with h | h Β· subst n exact fun _ _ => squarefree_one subst e refine' fun k0 ih => Irreducible.squarefree (Nat.prime_def_le_sqrt.2 ⟨bit1_lt_bit1.2 h, _⟩) intro m m2 hm md obtain ⟨p, pp, hp⟩ := Nat.exists_prime_and_dvd (ne_of_gt m2) have := (ih p pp (dvd_trans hp md)).trans (le_trans (Nat.le_of_dvd (lt_of_lt_of_le (by decide) m2) hp) hm) rw [Nat.le_sqrt] at this exact not_le_of_gt hd this theorem not_squarefree_mul (a aa b n : β„•) (ha : a * a = aa) (hb : aa * b = n) (h₁ : 1 < a) : Β¬Squarefree n := by rw [← hb, ← ha] exact fun H => ne_of_gt h₁ (Nat.isUnit_iff.1 <| H _ ⟨_, rfl⟩) /-- Given `e` a natural numeral and `a : β„•` with `a^2 ∣ n`, return `⊒ Β¬ Squarefree e`. -/ unsafe def prove_non_squarefree (e : expr) (n a : β„•) : tactic expr := do let ea := reflect a let eaa := reflect (a * a) let c ← mk_instance_cache q(Nat) let (c, p₁) ← prove_lt_nat c q(1) ea let b := n / (a * a) let eb := reflect b let (c, eaa, pa) ← prove_mul_nat c ea ea let (c, e', pb) ← prove_mul_nat c eaa eb guard (e' == e) return <| q(@not_squarefree_mul).mk_app [ea, eaa, eb, e, pa, pb, p₁] /-- Given `en`,`en1 := bit1 en`, `n1` the value of `en1`, `ek`, returns `⊒ squarefree_helper en ek`. -/ unsafe def prove_squarefree_aux : βˆ€ (ic : instance_cache) (en en1 : expr) (n1 : β„•) (ek : expr) (k : β„•), tactic expr | ic, en, en1, n1, ek, k => do let k1 := bit1 k let ek1 := q((bit1 : β„• β†’ β„•)).mk_app [ek] if n1 < k1 * k1 then do let (ic, ek', p₁) ← prove_mul_nat ic ek1 ek1 let (ic, pβ‚‚) ← prove_lt_nat ic en1 ek' pure <| q(squarefreeHelper_4).mk_app [en, ek, ek', p₁, pβ‚‚] else do let c := n1 % k1 let k' := k + 1 let ek' := reflect k' let (ic, p₁) ← prove_succ ic ek ek' if c = 0 then do let n1' := n1 / k1 let n' := n1' / 2 let en' := reflect n' let en1' := q((bit1 : β„• β†’ β„•)).mk_app [en'] let (ic, _, pn') ← prove_mul_nat ic en1' ek1 let c := n1' % k1 guard (c β‰  0) let (ic, ec, pc) ← prove_div_mod ic en1' ek1 tt let (ic, pβ‚€) ← prove_pos ic ec let pβ‚‚ ← prove_squarefree_aux ic en' en1' n1' ek' k' pure <| q(squarefreeHelper_3).mk_app [en, en', ek, ek', ec, p₁, pn', pc, pβ‚€, pβ‚‚] else do let (ic, ec, pc) ← prove_div_mod ic en1 ek1 tt let (ic, pβ‚€) ← prove_pos ic ec let pβ‚‚ ← prove_squarefree_aux ic en en1 n1 ek' k' pure <| q(squarefreeHelper_2).mk_app [en, ek, ek', ec, p₁, pc, pβ‚€, pβ‚‚] /-- Given `n > 0` a squarefree natural numeral, returns `⊒ Squarefree n`. -/ unsafe def prove_squarefree (en : expr) (n : β„•) : tactic expr := match match_numeral en with | match_numeral_result.one => pure q(@squarefree_one β„• _) | match_numeral_result.bit0 en1 => match match_numeral en1 with | match_numeral_result.one => pure q(Nat.squarefree_two) | match_numeral_result.bit1 en => do let ic ← mk_instance_cache q(β„•) let p ← prove_squarefree_aux ic en en1 (n / 2) q((1 : β„•)) 1 pure <| q(squarefree_bit10).mk_app [en, p] | _ => failed | match_numeral_result.bit1 en' => do let ic ← mk_instance_cache q(β„•) let p ← prove_squarefree_aux ic en' en n q((1 : β„•)) 1 pure <| q(squarefree_bit1).mk_app [en', p] | _ => failed /-- Evaluates the `Squarefree` predicate on naturals. -/ @[norm_num] unsafe def eval_squarefree : expr β†’ tactic (expr Γ— expr) | q(@Squarefree β„• $(inst) $(e)) => do is_def_eq inst q(Nat.monoid) let n ← e.toNat match n with | 0 => false_intro q(@not_squarefree_zero β„• _ _) | 1 => true_intro q(@squarefree_one β„• _) | _ => match n with | some d => prove_non_squarefree e n d >>= false_intro | none => prove_squarefree e n >>= true_intro | _ => failed end NormNum end Tactic -/
.lake/packages/mathlib/Mathlib/Data/Nat/WithBot.lean
import Mathlib.Data.Nat.Cast.WithTop import Mathlib.Order.Nat /-! # `WithBot β„•` Lemmas about the type of natural numbers with a bottom element adjoined. -/ namespace Nat namespace WithBot instance : WellFoundedRelation (WithBot β„•) where rel := (Β· < Β·) wf := IsWellFounded.wf theorem add_eq_zero_iff {n m : WithBot β„•} : n + m = 0 ↔ n = 0 ∧ m = 0 := by cases n Β· simp [WithBot.bot_add] cases m Β· simp [WithBot.add_bot] simp [← WithBot.coe_add] theorem add_eq_one_iff {n m : WithBot β„•} : n + m = 1 ↔ n = 0 ∧ m = 1 ∨ n = 1 ∧ m = 0 := by cases n Β· simp only [WithBot.bot_add, WithBot.bot_ne_one, WithBot.bot_ne_zero, false_and, or_self] cases m Β· simp [WithBot.add_bot] simp [← WithBot.coe_add, Nat.add_eq_one_iff] theorem add_eq_two_iff {n m : WithBot β„•} : n + m = 2 ↔ n = 0 ∧ m = 2 ∨ n = 1 ∧ m = 1 ∨ n = 2 ∧ m = 0 := by cases n Β· simp [WithBot.bot_add] cases m Β· simp [WithBot.add_bot] simp [← WithBot.coe_add, Nat.add_eq_two_iff] theorem add_eq_three_iff {n m : WithBot β„•} : n + m = 3 ↔ n = 0 ∧ m = 3 ∨ n = 1 ∧ m = 2 ∨ n = 2 ∧ m = 1 ∨ n = 3 ∧ m = 0 := by cases n Β· simp [WithBot.bot_add] cases m Β· simp [WithBot.add_bot] simp [← WithBot.coe_add, Nat.add_eq_three_iff] theorem coe_nonneg {n : β„•} : 0 ≀ (n : WithBot β„•) := by rw [← WithBot.coe_zero, cast_withBot, WithBot.coe_le_coe] exact n.zero_le @[simp] theorem lt_zero_iff {n : WithBot β„•} : n < 0 ↔ n = βŠ₯ := WithBot.lt_coe_bot theorem one_le_iff_zero_lt {x : WithBot β„•} : 1 ≀ x ↔ 0 < x := by refine ⟨zero_lt_one.trans_le, fun h => ?_⟩ cases x Β· exact (not_lt_bot h).elim Β· rwa [← WithBot.coe_zero, WithBot.coe_lt_coe, ← Nat.add_one_le_iff, zero_add, ← WithBot.coe_le_coe, WithBot.coe_one] at h theorem lt_one_iff_le_zero {x : WithBot β„•} : x < 1 ↔ x ≀ 0 := not_iff_not.mp (by simpa using one_le_iff_zero_lt) theorem add_one_le_of_lt {n m : WithBot β„•} (h : n < m) : n + 1 ≀ m := by cases n Β· simp only [WithBot.bot_add, bot_le] cases m Β· exact (not_lt_bot h).elim Β· rwa [WithBot.coe_lt_coe, ← Nat.add_one_le_iff, ← WithBot.coe_le_coe, WithBot.coe_add, WithBot.coe_one] at h end WithBot end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Bits.lean
import Batteries.Tactic.GeneralizeProofs import Mathlib.Data.Nat.BinaryRec import Mathlib.Data.List.Defs import Mathlib.Tactic.Convert import Mathlib.Tactic.Says import Mathlib.Util.AssertExists /-! # Additional properties of binary recursion on `Nat` This file documents additional properties of binary recursion, which allows us to more easily work with operations which do depend on the number of leading zeros in the binary representation of `n`. For example, we can more easily work with `Nat.bits` and `Nat.size`. See also: `Nat.bitwise`, `Nat.pow` (for various lemmas about `size` and `shiftLeft`/`shiftRight`), and `Nat.digits`. -/ assert_not_exists Monoid -- Once we're in the `Nat` namespace, `xor` will inconveniently resolve to `Nat.xor`. /-- `bxor` denotes the `xor` function i.e. the exclusive-or function on type `Bool`. -/ local notation "bxor" => xor namespace Nat universe u variable {m n : β„•} /-- `boddDiv2 n` returns a 2-tuple of type `(Bool, Nat)` where the `Bool` value indicates whether `n` is odd or not and the `Nat` value returns `⌊n/2βŒ‹` -/ def boddDiv2 : β„• β†’ Bool Γ— β„• | 0 => (false, 0) | succ n => match boddDiv2 n with | (false, m) => (true, m) | (true, m) => (false, succ m) /-- `div2 n = ⌊n/2βŒ‹` the greatest integer smaller than `n/2` -/ def div2 (n : β„•) : β„• := (boddDiv2 n).2 /-- `bodd n` returns `true` if `n` is odd -/ def bodd (n : β„•) : Bool := (boddDiv2 n).1 @[simp] lemma bodd_zero : bodd 0 = false := rfl @[simp] lemma bodd_one : bodd 1 = true := rfl lemma bodd_two : bodd 2 = false := rfl @[simp] lemma bodd_succ (n : β„•) : bodd (succ n) = not (bodd n) := by simp only [bodd, boddDiv2] let ⟨b, m⟩ := boddDiv2 n cases b <;> rfl @[simp] lemma bodd_add (m n : β„•) : bodd (m + n) = bxor (bodd m) (bodd n) := by induction n case zero => simp case succ n ih => simp [← Nat.add_assoc, ih] @[simp] lemma bodd_mul (m n : β„•) : bodd (m * n) = (bodd m && bodd n) := by induction n with | zero => simp | succ n IH => simp only [mul_succ, bodd_add, IH, bodd_succ] cases bodd m <;> cases bodd n <;> rfl lemma mod_two_of_bodd (n : β„•) : n % 2 = (bodd n).toNat := by have : (n % 2).bodd = n.bodd := by simpa using congr_arg bodd (mod_add_div n 2) rw [← this] rcases mod_two_eq_zero_or_one n with h | h <;> rw [h] <;> rfl @[simp] lemma div2_zero : div2 0 = 0 := rfl @[simp] lemma div2_one : div2 1 = 0 := rfl lemma div2_two : div2 2 = 1 := rfl @[simp] lemma div2_succ (n : β„•) : div2 (n + 1) = cond (bodd n) (succ (div2 n)) (div2 n) := by simp only [bodd, boddDiv2, div2] rcases boddDiv2 n with ⟨_ | _, _⟩ <;> simp attribute [local simp] Nat.add_comm Nat.mul_comm lemma bodd_add_div2 : βˆ€ n, (bodd n).toNat + 2 * div2 n = n | 0 => rfl | succ n => by simp only [bodd_succ, div2_succ, Nat.mul_comm] refine Eq.trans ?_ (congr_arg succ (bodd_add_div2 n)) cases bodd n Β· simp Β· simp; cutsat @[grind =] lemma div2_val (n) : div2 n = n / 2 := by refine Nat.eq_of_mul_eq_mul_left (by decide) (Nat.add_left_cancel (Eq.trans ?_ (Nat.mod_add_div n 2).symm)) rw [mod_two_of_bodd, bodd_add_div2] @[simp, grind =] lemma bit_bodd_div2 (n : Nat) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans <| (Nat.add_comm _ _).trans <| bodd_add_div2 _ @[deprecated (since := "2025-09-24")] alias bit_decomp := bit_bodd_div2 lemma bit_false_zero : bit false 0 = 0 := rfl @[deprecated (since := "2025-09-24")] alias bit_zero := bit_false_zero /-- `shiftLeft' b m n` performs a left shift of `m` `n` times and adds the bit `b` as the least significant bit each time. Returns the corresponding natural number -/ def shiftLeft' (b : Bool) (m : β„•) : β„• β†’ β„• | 0 => m | n + 1 => bit b (shiftLeft' b m n) @[simp] lemma shiftLeft'_false : βˆ€ n, shiftLeft' false m n = m <<< n | 0 => rfl | n + 1 => by have : 2 * (m * 2 ^ n) = 2 ^ (n + 1) * m := by rw [Nat.mul_comm, Nat.mul_assoc, ← Nat.pow_succ]; simp simp [shiftLeft_eq, shiftLeft', bit_val, shiftLeft'_false, this] /-- Lean takes the unprimed name for `Nat.shiftLeft_eq m n : m <<< n = m * 2 ^ n`. -/ @[simp] lemma shiftLeft_eq' (m n : Nat) : shiftLeft m n = m <<< n := rfl @[simp] lemma shiftRight_eq (m n : Nat) : shiftRight m n = m >>> n := rfl lemma binaryRec_decreasing (h : n β‰  0) : div2 n < n := by grind /-- `size n` : Returns the size of a natural number in bits i.e. the length of its binary representation -/ def size : β„• β†’ β„• := binaryRec 0 fun _ _ => succ /-- `bits n` returns a list of Bools which correspond to the binary representation of n, where the head of the list represents the least significant bit -/ def bits : β„• β†’ List Bool := binaryRec [] fun b _ IH => b :: IH /-- `ldiff a b` performs bitwise set difference. For each corresponding pair of bits taken as Booleans, say `aα΅’` and `bα΅’`, it applies the Boolean operation `aα΅’ ∧ Β¬bα΅’` to obtain the `iα΅—Κ°` bit of the result. -/ def ldiff : β„• β†’ β„• β†’ β„• := bitwise fun a b => a && not b /-! bitwise ops -/ @[simp, grind =] lemma bodd_bit (b n) : bodd (bit b n) = b := by rw [bit_val] simp only [Nat.mul_comm, Nat.add_comm, bodd_add, bodd_mul, bodd_succ, bodd_zero, Bool.not_false, Bool.not_true, Bool.and_false, Bool.xor_false] cases b <;> cases bodd n <;> rfl @[simp, grind =] lemma div2_bit (b n) : div2 (bit b n) = n := by rw [bit_val, div2_val, Nat.add_comm, add_mul_div_left, div_eq_of_lt, Nat.zero_add] <;> cases b <;> decide lemma shiftLeft'_add (b m n) : βˆ€ k, shiftLeft' b m (n + k) = shiftLeft' b (shiftLeft' b m n) k | 0 => rfl | k + 1 => congr_arg (bit b) (shiftLeft'_add b m n k) lemma shiftLeft'_sub (b m) : βˆ€ {n k}, k ≀ n β†’ shiftLeft' b m (n - k) = (shiftLeft' b m n) >>> k | _, 0, _ => rfl | n + 1, k + 1, h => by rw [succ_sub_succ_eq_sub, shiftLeft', Nat.add_comm, shiftRight_add] simp only [shiftLeft'_sub, Nat.le_of_succ_le_succ h, shiftRight_succ, shiftRight_zero] simp [← div2_val, div2_bit] lemma shiftLeft_sub : βˆ€ (m : Nat) {n k}, k ≀ n β†’ m <<< (n - k) = (m <<< n) >>> k := fun _ _ _ hk => by simp only [← shiftLeft'_false, shiftLeft'_sub false _ hk] lemma bodd_eq_one_and_ne_zero : βˆ€ n, bodd n = (1 &&& n != 0) | 0 => rfl | 1 => rfl | n + 2 => by simpa using bodd_eq_one_and_ne_zero n lemma testBit_bit_succ (m b n) : testBit (bit b n) (succ m) = testBit n m := by have : bodd (((bit b n) >>> 1) >>> m) = bodd (n >>> m) := by simp only [shiftRight_eq_div_pow] simp [← div2_val, div2_bit] rw [← shiftRight_add, Nat.add_comm] at this simp only [bodd_eq_one_and_ne_zero] at this exact this /-! ### `boddDiv2_eq` and `bodd` -/ @[simp, grind =] theorem boddDiv2_eq (n : β„•) : boddDiv2 n = (bodd n, div2 n) := rfl @[simp] theorem div2_bit0 (n) : div2 (2 * n) = n := div2_bit false n -- simp can prove this theorem div2_bit1 (n) : div2 (2 * n + 1) = n := div2_bit true n /-! ### `bit0` and `bit1` -/ theorem bit_add : βˆ€ (b : Bool) (n m : β„•), bit b (n + m) = bit false n + bit b m | true, _, _ => by dsimp [bit]; cutsat | false, _, _ => by dsimp [bit]; cutsat theorem bit_add' : βˆ€ (b : Bool) (n m : β„•), bit b (n + m) = bit b n + bit false m | true, _, _ => by dsimp [bit]; cutsat | false, _, _ => by dsimp [bit]; cutsat theorem bit_ne_zero (b) {n} (h : n β‰  0) : bit b n β‰  0 := by cases b <;> dsimp [bit] <;> omega @[simp] theorem bitCasesOn_bit0 {motive : β„• β†’ Sort u} (H : βˆ€ b n, motive (bit b n)) (n : β„•) : bitCasesOn (2 * n) H = H false n := bitCasesOn_bit H false n @[simp] theorem bitCasesOn_bit1 {motive : β„• β†’ Sort u} (H : βˆ€ b n, motive (bit b n)) (n : β„•) : bitCasesOn (2 * n + 1) H = H true n := bitCasesOn_bit H true n theorem bit_cases_on_injective {motive : β„• β†’ Sort u} : Function.Injective fun H : βˆ€ b n, motive (bit b n) => fun n => bitCasesOn n H := by intro H₁ Hβ‚‚ h ext b n simpa only [bitCasesOn_bit] using congr_fun h (bit b n) @[simp] theorem bit_cases_on_inj {motive : β„• β†’ Sort u} (H₁ Hβ‚‚ : βˆ€ b n, motive (bit b n)) : ((fun n => bitCasesOn n H₁) = fun n => bitCasesOn n Hβ‚‚) ↔ H₁ = Hβ‚‚ := bit_cases_on_injective.eq_iff lemma bit_le : βˆ€ (b : Bool) {m n : β„•}, m ≀ n β†’ bit b m ≀ bit b n | true, _, _, h => by dsimp [bit]; cutsat | false, _, _, h => by dsimp [bit]; cutsat lemma bit_lt_bit (a b) (h : m < n) : bit a m < bit b n := calc bit a m < 2 * n := by cases a <;> dsimp [bit] <;> omega _ ≀ bit b n := by cases b <;> dsimp [bit] <;> omega @[simp] theorem zero_bits : bits 0 = [] := by simp [Nat.bits] @[simp] theorem bits_append_bit (n : β„•) (b : Bool) (hn : n = 0 β†’ b = true) : (bit b n).bits = b :: n.bits := by rw [Nat.bits, Nat.bits, binaryRec_eq] simpa @[simp] theorem bit0_bits (n : β„•) (hn : n β‰  0) : (2 * n).bits = false :: n.bits := bits_append_bit n false fun hn' => absurd hn' hn @[simp] theorem bit1_bits (n : β„•) : (2 * n + 1).bits = true :: n.bits := bits_append_bit n true fun _ => rfl @[simp] theorem one_bits : Nat.bits 1 = [true] := by convert bit1_bits 0 simp -- TODO Find somewhere this can live. -- example : bits 3423 = [true, true, true, true, true, false, true, false, true, false, true, true] -- := by norm_num theorem bodd_eq_bits_head (n : β„•) : n.bodd = n.bits.headI := by induction n using Nat.binaryRec' with | zero => simp | bit _ _ h => simp [bodd_bit, bits_append_bit _ _ h] theorem div2_bits_eq_tail (n : β„•) : n.div2.bits = n.bits.tail := by induction n using Nat.binaryRec' with | zero => simp | bit _ _ h => simp [div2_bit, bits_append_bit _ _ h] end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Periodic.lean
import Mathlib.Algebra.Ring.Periodic import Mathlib.Data.Nat.Count /-! # Periodic Functions on β„• This file identifies a few functions on `β„•` which are periodic, and also proves a lemma about periodic predicates which helps determine their cardinality when filtering intervals over them. -/ assert_not_exists TwoSidedIdeal namespace Nat open Function theorem periodic_gcd (a : β„•) : Periodic (gcd a) a := a.gcd_add_self_right theorem periodic_coprime (a : β„•) : Periodic (Coprime a) a := fun _ ↦ eq_iff_iff.mpr coprime_add_self_right theorem periodic_mod (a : β„•) : Periodic (fun n => n % a) a := (add_mod_right Β· a) theorem _root_.Function.Periodic.map_mod_nat {Ξ± : Type*} {f : β„• β†’ Ξ±} {a : β„•} (hf : Periodic f a) : βˆ€ n, f (n % a) = f n := fun n => by conv_rhs => rw [← n.mod_add_div a, mul_comm, ← Nat.nsmul_eq_mul, hf.nsmul] section Multiset open Multiset /-- An interval of length `a` filtered over a periodic predicate of period `a` has cardinality equal to the number naturals below `a` for which `p a` is true. -/ theorem filter_multiset_Ico_card_eq_of_periodic (n a : β„•) (p : β„• β†’ Prop) [DecidablePred p] (pp : Periodic p a) : card (filter p (Ico n (n + a))) = a.count p := by rw [count_eq_card_filter_range, Finset.card, Finset.filter_val, Finset.range_val, ← multiset_Ico_map_mod n, ← map_count_True_eq_filter_card, ← map_count_True_eq_filter_card, map_map] congr; funext n exact (pp.map_mod_nat n).symm end Multiset section Finset open Finset /-- An interval of length `a` filtered over a periodic predicate of period `a` has cardinality equal to the number naturals below `a` for which `p a` is true. -/ theorem filter_Ico_card_eq_of_periodic (n a : β„•) (p : β„• β†’ Prop) [DecidablePred p] (pp : Periodic p a) : ((Ico n (n + a)).filter p).card = a.count p := n.filter_multiset_Ico_card_eq_of_periodic a p pp end Finset end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/PartENat.lean
import Mathlib.Algebra.Group.Equiv.Basic import Mathlib.Data.ENat.Lattice import Mathlib.Data.Part import Mathlib.Tactic.NormNum /-! # Natural numbers with infinity The natural numbers and an extra `top` element `⊀`. This implementation uses `Part β„•` as an implementation. This version is deprecated, use `β„•βˆž` instead. ## Main definitions The following instances are defined: * `OrderedAddCommMonoid PartENat` * `CanonicallyOrderedAdd PartENat` * `CompleteLinearOrder PartENat` There is no additive analogue of `MonoidWithZero`; if there were then `PartENat` could be an `AddMonoidWithTop`. * `toWithTop` : the map from `PartENat` to `β„•βˆž`, with theorems that it plays well with `+` and `≀`. * `withTopAddEquiv : PartENat ≃+ β„•βˆž` * `withTopOrderIso : PartENat ≃o β„•βˆž` ## Implementation details `PartENat` is defined to be `Part β„•`. `+` and `≀` are defined on `PartENat`, but there is an issue with `*` because it's not clear what `0 * ⊀` should be. `mul` is hence left undefined. Similarly `⊀ - ⊀` is ambiguous so there is no `-` defined on `PartENat`. Before the `open scoped Classical` line, various proofs are made with decidability assumptions. This can cause issues -- see for example the non-simp lemma `toWithTopZero` proved by `rfl`, followed by `@[simp] lemma toWithTopZero'` whose proof uses `convert`. ## Deprecation As it appears this has been unused since 2018, we are now deprecating it. If `ENat` does not serve your purposes, please raise this on the community Zulip. ## Tags PartENat, β„•βˆž -/ open Part hiding some /-- Type of natural numbers with infinity (`⊀`) -/ @[deprecated ENat (since := "2025-09-01")] def PartENat : Type := Part β„• set_option linter.deprecated false namespace PartENat /-- The computable embedding `β„• β†’ PartENat`. This coincides with the coercion `coe : β„• β†’ PartENat`, see `PartENat.some_eq_natCast`. -/ @[coe] def some : β„• β†’ PartENat := Part.some instance : Zero PartENat := ⟨some 0⟩ instance : Inhabited PartENat := ⟨0⟩ instance : One PartENat := ⟨some 1⟩ instance : Add PartENat := ⟨fun x y => ⟨x.Dom ∧ y.Dom, fun h => get x h.1 + get y h.2⟩⟩ instance (n : β„•) : Decidable (some n).Dom := isTrue trivial @[simp] theorem dom_some (x : β„•) : (some x).Dom := trivial instance addCommMonoid : AddCommMonoid PartENat where add_comm _ _ := Part.ext' and_comm fun _ _ => add_comm _ _ zero_add _ := Part.ext' (iff_of_eq (true_and _)) fun _ _ => zero_add _ add_zero _ := Part.ext' (iff_of_eq (and_true _)) fun _ _ => add_zero _ add_assoc _ _ _ := Part.ext' and_assoc fun _ _ => add_assoc _ _ _ nsmul := nsmulRec instance : AddCommMonoidWithOne PartENat := { PartENat.addCommMonoid with natCast := some natCast_zero := rfl natCast_succ := fun _ => Part.ext' (iff_of_eq (true_and _)).symm fun _ _ => rfl } theorem some_eq_natCast (n : β„•) : some n = n := rfl instance : CharZero PartENat where cast_injective := Part.some_injective /-- Alias of `Nat.cast_inj` specialized to `PartENat` -/ theorem natCast_inj {x y : β„•} : (x : PartENat) = y ↔ x = y := Nat.cast_inj @[simp] theorem dom_natCast (x : β„•) : (x : PartENat).Dom := trivial @[simp] theorem dom_ofNat (x : β„•) [x.AtLeastTwo] : (ofNat(x) : PartENat).Dom := trivial @[simp] theorem dom_zero : (0 : PartENat).Dom := trivial @[simp] theorem dom_one : (1 : PartENat).Dom := trivial instance : CanLift PartENat β„• (↑) Dom := ⟨fun n hn => ⟨n.get hn, Part.some_get _⟩⟩ instance : LE PartENat := ⟨fun x y => βˆƒ h : y.Dom β†’ x.Dom, βˆ€ hy : y.Dom, x.get (h hy) ≀ y.get hy⟩ instance : Top PartENat := ⟨none⟩ instance : Bot PartENat := ⟨0⟩ instance : Max PartENat := ⟨fun x y => ⟨x.Dom ∧ y.Dom, fun h => x.get h.1 βŠ” y.get h.2⟩⟩ theorem le_def (x y : PartENat) : x ≀ y ↔ βˆƒ h : y.Dom β†’ x.Dom, βˆ€ hy : y.Dom, x.get (h hy) ≀ y.get hy := Iff.rfl @[elab_as_elim] protected theorem casesOn' {P : PartENat β†’ Prop} : βˆ€ a : PartENat, P ⊀ β†’ (βˆ€ n : β„•, P (some n)) β†’ P a := Part.induction_on @[elab_as_elim] protected theorem casesOn {P : PartENat β†’ Prop} : βˆ€ a : PartENat, P ⊀ β†’ (βˆ€ n : β„•, P n) β†’ P a := by exact PartENat.casesOn' -- not a simp lemma as we will provide a `LinearOrderedAddCommMonoidWithTop` instance later theorem top_add (x : PartENat) : ⊀ + x = ⊀ := Part.ext' (iff_of_eq (false_and _)) fun h => h.left.elim -- not a simp lemma as we will provide a `LinearOrderedAddCommMonoidWithTop` instance later theorem add_top (x : PartENat) : x + ⊀ = ⊀ := by rw [add_comm, top_add] @[simp] theorem natCast_get {x : PartENat} (h : x.Dom) : (x.get h : PartENat) = x := by exact Part.ext' (iff_of_true trivial h) fun _ _ => rfl @[simp, norm_cast] theorem get_natCast' (x : β„•) (h : (x : PartENat).Dom) : get (x : PartENat) h = x := by rw [← natCast_inj, natCast_get] theorem get_natCast {x : β„•} : get (x : PartENat) (dom_natCast x) = x := get_natCast' _ _ theorem coe_add_get {x : β„•} {y : PartENat} (h : ((x : PartENat) + y).Dom) : get ((x : PartENat) + y) h = x + get y h.2 := by rfl @[simp] theorem get_add {x y : PartENat} (h : (x + y).Dom) : get (x + y) h = x.get h.1 + y.get h.2 := rfl @[simp] theorem get_zero (h : (0 : PartENat).Dom) : (0 : PartENat).get h = 0 := rfl @[simp] theorem get_one (h : (1 : PartENat).Dom) : (1 : PartENat).get h = 1 := rfl @[simp] theorem get_ofNat' (x : β„•) [x.AtLeastTwo] (h : (ofNat(x) : PartENat).Dom) : Part.get (ofNat(x) : PartENat) h = ofNat(x) := get_natCast' x h nonrec theorem get_eq_iff_eq_some {a : PartENat} {ha : a.Dom} {b : β„•} : a.get ha = b ↔ a = some b := get_eq_iff_eq_some theorem get_eq_iff_eq_coe {a : PartENat} {ha : a.Dom} {b : β„•} : a.get ha = b ↔ a = b := by rw [get_eq_iff_eq_some] rfl theorem dom_of_le_of_dom {x y : PartENat} : x ≀ y β†’ y.Dom β†’ x.Dom := fun ⟨h, _⟩ => h theorem dom_of_le_some {x : PartENat} {y : β„•} (h : x ≀ some y) : x.Dom := dom_of_le_of_dom h trivial theorem dom_of_le_natCast {x : PartENat} {y : β„•} (h : x ≀ y) : x.Dom := by exact dom_of_le_some h instance decidableLe (x y : PartENat) [Decidable x.Dom] [Decidable y.Dom] : Decidable (x ≀ y) := if hx : x.Dom then decidable_of_decidable_of_iff (le_def x y).symm else if hy : y.Dom then isFalse fun h => hx <| dom_of_le_of_dom h hy else isTrue ⟨fun h => (hy h).elim, fun h => (hy h).elim⟩ instance partialOrder : PartialOrder PartENat where le_refl _ := ⟨id, fun _ => le_rfl⟩ le_trans := fun _ _ _ ⟨hxy₁, hxyβ‚‚βŸ© ⟨hyz₁, hyzβ‚‚βŸ© => ⟨hxy₁ ∘ hyz₁, fun _ => le_trans (hxyβ‚‚ _) (hyzβ‚‚ _)⟩ lt_iff_le_not_ge _ _ := Iff.rfl le_antisymm := fun _ _ ⟨hxy₁, hxyβ‚‚βŸ© ⟨hyx₁, hyxβ‚‚βŸ© => Part.ext' ⟨hyx₁, hxyβ‚βŸ© fun _ _ => le_antisymm (hxyβ‚‚ _) (hyxβ‚‚ _) theorem lt_def (x y : PartENat) : x < y ↔ βˆƒ hx : x.Dom, βˆ€ hy : y.Dom, x.get hx < y.get hy := by rw [lt_iff_le_not_ge, le_def, le_def, not_exists] constructor Β· rintro ⟨⟨hyx, H⟩, h⟩ by_cases hx : x.Dom Β· use hx intro hy specialize H hy specialize h fun _ => hy rw [not_forall] at h cutsat Β· specialize h fun hx' => (hx hx').elim rw [not_forall] at h obtain ⟨hx', h⟩ := h exact (hx hx').elim Β· rintro ⟨hx, H⟩ exact ⟨⟨fun _ => hx, fun hy => (H hy).le⟩, fun hxy h => not_lt_of_ge (h _) (H _)⟩ noncomputable instance isOrderedAddMonoid : IsOrderedAddMonoid PartENat := { add_le_add_left := fun a b ⟨h₁, hβ‚‚βŸ© c => PartENat.casesOn c (by simp [top_add]) fun c => ⟨fun h => And.intro (dom_natCast _) (h₁ h.2), fun h => by simpa only [coe_add_get] using add_le_add_left (hβ‚‚ _) c⟩ } instance semilatticeSup : SemilatticeSup PartENat := { PartENat.partialOrder with sup := (Β· βŠ” Β·) le_sup_left := fun _ _ => ⟨And.left, fun _ => le_sup_left⟩ le_sup_right := fun _ _ => ⟨And.right, fun _ => le_sup_right⟩ sup_le := fun _ _ _ ⟨hx₁, hxβ‚‚βŸ© ⟨hy₁, hyβ‚‚βŸ© => ⟨fun hz => ⟨hx₁ hz, hy₁ hz⟩, fun _ => sup_le (hxβ‚‚ _) (hyβ‚‚ _)⟩ } instance orderBot : OrderBot PartENat where bot_le _ := ⟨fun _ => trivial, fun _ => Nat.zero_le _⟩ instance orderTop : OrderTop PartENat where le_top _ := ⟨fun h => False.elim h, fun hy => False.elim hy⟩ instance : ZeroLEOneClass PartENat where zero_le_one := bot_le /-- Alias of `Nat.cast_le` specialized to `PartENat` -/ theorem coe_le_coe {x y : β„•} : (x : PartENat) ≀ y ↔ x ≀ y := Nat.cast_le /-- Alias of `Nat.cast_lt` specialized to `PartENat` -/ theorem coe_lt_coe {x y : β„•} : (x : PartENat) < y ↔ x < y := Nat.cast_lt @[simp] theorem get_le_get {x y : PartENat} {hx : x.Dom} {hy : y.Dom} : x.get hx ≀ y.get hy ↔ x ≀ y := by conv => lhs rw [← coe_le_coe, natCast_get, natCast_get] theorem le_coe_iff (x : PartENat) (n : β„•) : x ≀ n ↔ βˆƒ h : x.Dom, x.get h ≀ n := by change (βˆƒ h : True β†’ x.Dom, _) ↔ βˆƒ h : x.Dom, x.get h ≀ n simp only [forall_prop_of_true, dom_natCast, get_natCast'] theorem lt_coe_iff (x : PartENat) (n : β„•) : x < n ↔ βˆƒ h : x.Dom, x.get h < n := by simp only [lt_def, forall_prop_of_true, get_natCast', dom_natCast] theorem coe_le_iff (n : β„•) (x : PartENat) : (n : PartENat) ≀ x ↔ βˆ€ h : x.Dom, n ≀ x.get h := by rw [← some_eq_natCast] simp only [le_def, exists_prop_of_true, dom_some, forall_true_iff] rfl theorem coe_lt_iff (n : β„•) (x : PartENat) : (n : PartENat) < x ↔ βˆ€ h : x.Dom, n < x.get h := by rw [← some_eq_natCast] simp only [lt_def, exists_prop_of_true, dom_some] rfl nonrec theorem eq_zero_iff {x : PartENat} : x = 0 ↔ x ≀ 0 := eq_bot_iff theorem ne_zero_iff {x : PartENat} : x β‰  0 ↔ βŠ₯ < x := bot_lt_iff_ne_bot.symm theorem dom_of_lt {x y : PartENat} : x < y β†’ x.Dom := PartENat.casesOn x not_top_lt fun _ _ => dom_natCast _ theorem top_eq_none : (⊀ : PartENat) = Part.none := rfl @[simp] theorem natCast_lt_top (x : β„•) : (x : PartENat) < ⊀ := Ne.lt_top fun h => absurd (congr_arg Dom h) <| by simp only [dom_natCast]; exact true_ne_false @[simp] theorem zero_lt_top : (0 : PartENat) < ⊀ := natCast_lt_top 0 @[simp] theorem one_lt_top : (1 : PartENat) < ⊀ := natCast_lt_top 1 @[simp] theorem ofNat_lt_top (x : β„•) [x.AtLeastTwo] : (ofNat(x) : PartENat) < ⊀ := natCast_lt_top x @[simp] theorem natCast_ne_top (x : β„•) : (x : PartENat) β‰  ⊀ := ne_of_lt (natCast_lt_top x) @[simp] theorem zero_ne_top : (0 : PartENat) β‰  ⊀ := natCast_ne_top 0 @[simp] theorem one_ne_top : (1 : PartENat) β‰  ⊀ := natCast_ne_top 1 @[simp] theorem ofNat_ne_top (x : β„•) [x.AtLeastTwo] : (ofNat(x) : PartENat) β‰  ⊀ := natCast_ne_top x theorem not_isMax_natCast (x : β„•) : Β¬IsMax (x : PartENat) := not_isMax_of_lt (natCast_lt_top x) theorem ne_top_iff {x : PartENat} : x β‰  ⊀ ↔ βˆƒ n : β„•, x = n := by simpa only [← some_eq_natCast] using Part.ne_none_iff theorem ne_top_iff_dom {x : PartENat} : x β‰  ⊀ ↔ x.Dom := by classical exact not_iff_comm.1 Part.eq_none_iff'.symm theorem not_dom_iff_eq_top {x : PartENat} : Β¬x.Dom ↔ x = ⊀ := Iff.not_left ne_top_iff_dom.symm theorem ne_top_of_lt {x y : PartENat} (h : x < y) : x β‰  ⊀ := ne_of_lt <| lt_of_lt_of_le h le_top theorem eq_top_iff_forall_lt (x : PartENat) : x = ⊀ ↔ βˆ€ n : β„•, (n : PartENat) < x := by constructor Β· rintro rfl n exact natCast_lt_top _ Β· contrapose! rw [ne_top_iff] rintro ⟨n, rfl⟩ exact ⟨n, irrefl _⟩ theorem eq_top_iff_forall_le (x : PartENat) : x = ⊀ ↔ βˆ€ n : β„•, (n : PartENat) ≀ x := (eq_top_iff_forall_lt x).trans ⟨fun h n => (h n).le, fun h n => lt_of_lt_of_le (coe_lt_coe.mpr n.lt_succ_self) (h (n + 1))⟩ theorem pos_iff_one_le {x : PartENat} : 0 < x ↔ 1 ≀ x := PartENat.casesOn x (by simp only [le_top, natCast_lt_top, ← @Nat.cast_zero PartENat]) fun n => by rw [← Nat.cast_zero, ← Nat.cast_one, PartENat.coe_lt_coe, PartENat.coe_le_coe] rfl instance isTotal : IsTotal PartENat (Β· ≀ Β·) where total x y := PartENat.casesOn (P := fun z => z ≀ y ∨ y ≀ z) x (Or.inr le_top) (PartENat.casesOn y (fun _ => Or.inl le_top) fun x y => (le_total x y).elim (Or.inr ∘ coe_le_coe.2) (Or.inl ∘ coe_le_coe.2)) noncomputable instance linearOrder : LinearOrder PartENat := { PartENat.partialOrder with le_total := IsTotal.total toDecidableLE := Classical.decRel _ max := (Β· βŠ” Β·) max_def a b := congr_funβ‚‚ (@sup_eq_maxDefault PartENat _ (_) _) _ _ } instance boundedOrder : BoundedOrder PartENat := { PartENat.orderTop, PartENat.orderBot with } noncomputable instance lattice : Lattice PartENat := { PartENat.semilatticeSup with inf := min inf_le_left := min_le_left inf_le_right := min_le_right le_inf := fun _ _ _ => le_min } instance : CanonicallyOrderedAdd PartENat where le_self_add a b := PartENat.casesOn b (le_top.trans_eq (add_top _).symm) fun _ => PartENat.casesOn a (top_add _).ge fun _ => (coe_le_coe.2 le_self_add).trans_eq (Nat.cast_add _ _) le_add_self a b := PartENat.casesOn b (le_top.trans_eq (top_add _).symm) fun _ => PartENat.casesOn a (add_top _).ge fun _ => (coe_le_coe.2 le_add_self).trans_eq (Nat.cast_add _ _) exists_add_of_le {a b} := PartENat.casesOn b (fun _ => ⟨⊀, (add_top _).symm⟩) fun b => PartENat.casesOn a (fun h => ((natCast_lt_top _).not_ge h).elim) fun a h => ⟨(b - a : β„•), by rw [← Nat.cast_add, natCast_inj, add_comm, tsub_add_cancel_of_le (coe_le_coe.1 h)]⟩ theorem eq_natCast_sub_of_add_eq_natCast {x y : PartENat} {n : β„•} (h : x + y = n) : x = ↑(n - y.get (dom_of_le_natCast ((le_add_left le_rfl).trans_eq h))) := by lift x to β„• using dom_of_le_natCast ((le_add_right le_rfl).trans_eq h) lift y to β„• using dom_of_le_natCast ((le_add_left le_rfl).trans_eq h) rw [← Nat.cast_add, natCast_inj] at h rw [get_natCast, natCast_inj, eq_tsub_of_add_eq h] protected theorem add_lt_add_right {x y z : PartENat} (h : x < y) (hz : z β‰  ⊀) : x + z < y + z := by rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩ rcases ne_top_iff.mp hz with ⟨k, rfl⟩ induction y using PartENat.casesOn Β· rw [top_add] exact_mod_cast natCast_lt_top _ intro h norm_cast at h exact_mod_cast add_lt_add_right h _ protected theorem add_lt_add_iff_right {x y z : PartENat} (hz : z β‰  ⊀) : x + z < y + z ↔ x < y := ⟨lt_of_add_lt_add_right, fun h => PartENat.add_lt_add_right h hz⟩ protected theorem add_lt_add_iff_left {x y z : PartENat} (hz : z β‰  ⊀) : z + x < z + y ↔ x < y := by rw [add_comm z, add_comm z, PartENat.add_lt_add_iff_right hz] protected theorem lt_add_iff_pos_right {x y : PartENat} (hx : x β‰  ⊀) : x < x + y ↔ 0 < y := by conv_rhs => rw [← PartENat.add_lt_add_iff_left hx] rw [add_zero] theorem lt_add_one {x : PartENat} (hx : x β‰  ⊀) : x < x + 1 := by rw [PartENat.lt_add_iff_pos_right hx] norm_cast theorem le_of_lt_add_one {x y : PartENat} (h : x < y + 1) : x ≀ y := by induction y using PartENat.casesOn Β· apply le_top intro h rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩ exact_mod_cast Nat.le_of_lt_succ (by norm_cast at h) theorem add_one_le_of_lt {x y : PartENat} (h : x < y) : x + 1 ≀ y := by induction y using PartENat.casesOn Β· apply le_top intro h rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩ exact_mod_cast Nat.succ_le_of_lt (by norm_cast at h) theorem add_one_le_iff_lt {x y : PartENat} (hx : x β‰  ⊀) : x + 1 ≀ y ↔ x < y := by refine ⟨fun h => ?_, add_one_le_of_lt⟩ rcases ne_top_iff.mp hx with ⟨m, rfl⟩ induction y using PartENat.casesOn Β· apply natCast_lt_top intro h exact_mod_cast Nat.lt_of_succ_le (by norm_cast at h) theorem coe_succ_le_iff {n : β„•} {e : PartENat} : ↑n.succ ≀ e ↔ ↑n < e := by rw [Nat.succ_eq_add_one n, Nat.cast_add, Nat.cast_one, add_one_le_iff_lt (natCast_ne_top n)] theorem lt_add_one_iff_lt {x y : PartENat} (hx : x β‰  ⊀) : x < y + 1 ↔ x ≀ y := by refine ⟨le_of_lt_add_one, fun h => ?_⟩ rcases ne_top_iff.mp hx with ⟨m, rfl⟩ induction y using PartENat.casesOn Β· rw [top_add] apply natCast_lt_top intro h exact_mod_cast Nat.lt_succ_of_le (by norm_cast at h) lemma lt_coe_succ_iff_le {x : PartENat} {n : β„•} (hx : x β‰  ⊀) : x < n.succ ↔ x ≀ n := by rw [Nat.succ_eq_add_one n, Nat.cast_add, Nat.cast_one, lt_add_one_iff_lt hx] theorem add_eq_top_iff {a b : PartENat} : a + b = ⊀ ↔ a = ⊀ ∨ b = ⊀ := by refine PartENat.casesOn a ?_ ?_ <;> refine PartENat.casesOn b ?_ ?_ <;> simp [top_add, add_top] simp only [← Nat.cast_add, PartENat.natCast_ne_top, forall_const, not_false_eq_true] protected theorem add_right_cancel_iff {a b c : PartENat} (hc : c β‰  ⊀) : a + c = b + c ↔ a = b := by rcases ne_top_iff.1 hc with ⟨c, rfl⟩ refine PartENat.casesOn a ?_ ?_ <;> refine PartENat.casesOn b ?_ ?_ <;> simp [add_eq_top_iff, natCast_ne_top, @eq_comm _ (⊀ : PartENat), top_add] simp only [← Nat.cast_add, add_left_cancel_iff, PartENat.natCast_inj, add_comm, forall_const] protected theorem add_left_cancel_iff {a b c : PartENat} (ha : a β‰  ⊀) : a + b = a + c ↔ b = c := by rw [add_comm a, add_comm a, PartENat.add_right_cancel_iff ha] section WithTop /-- Computably converts a `PartENat` to a `β„•βˆž`. -/ def toWithTop (x : PartENat) [Decidable x.Dom] : β„•βˆž := x.toOption theorem toWithTop_top : have : Decidable (⊀ : PartENat).Dom := Part.noneDecidable toWithTop ⊀ = ⊀ := rfl @[simp] theorem toWithTop_top' {h : Decidable (⊀ : PartENat).Dom} : toWithTop ⊀ = ⊀ := by convert toWithTop_top theorem toWithTop_zero : have : Decidable (0 : PartENat).Dom := someDecidable 0 toWithTop 0 = 0 := rfl @[simp] theorem toWithTop_zero' {h : Decidable (0 : PartENat).Dom} : toWithTop 0 = 0 := by convert toWithTop_zero theorem toWithTop_one : have : Decidable (1 : PartENat).Dom := someDecidable 1 toWithTop 1 = 1 := rfl @[simp] theorem toWithTop_one' {h : Decidable (1 : PartENat).Dom} : toWithTop 1 = 1 := by convert toWithTop_one theorem toWithTop_some (n : β„•) : toWithTop (some n) = n := rfl theorem toWithTop_natCast (n : β„•) {_ : Decidable (n : PartENat).Dom} : toWithTop n = n := by simp only [← toWithTop_some] congr @[simp] theorem toWithTop_natCast' (n : β„•) {_ : Decidable (n : PartENat).Dom} : toWithTop (n : PartENat) = n := by rw [toWithTop_natCast n] @[simp] theorem toWithTop_ofNat (n : β„•) [n.AtLeastTwo] {_ : Decidable (OfNat.ofNat n : PartENat).Dom} : toWithTop (ofNat(n) : PartENat) = OfNat.ofNat n := toWithTop_natCast' n @[simp] theorem toWithTop_le {x y : PartENat} [hx : Decidable x.Dom] [hy : Decidable y.Dom] : toWithTop x ≀ toWithTop y ↔ x ≀ y := by induction y using PartENat.casesOn generalizing hy Β· simp induction x using PartENat.casesOn generalizing hx Β· simp Β· simp @[simp] theorem toWithTop_lt {x y : PartENat} [Decidable x.Dom] [Decidable y.Dom] : toWithTop x < toWithTop y ↔ x < y := lt_iff_lt_of_le_iff_le toWithTop_le end WithTop /-- Coercion from `β„•βˆž` to `PartENat`. -/ @[coe] def ofENat : β„•βˆž β†’ PartENat := fun x => match x with | Option.none => none | Option.some n => some n instance : Coe β„•βˆž PartENat := ⟨ofENat⟩ example (n : β„•) : ((n : β„•βˆž) : PartENat) = ↑n := rfl @[simp, norm_cast] lemma ofENat_top : ofENat ⊀ = ⊀ := rfl @[simp, norm_cast] lemma ofENat_coe (n : β„•) : ofENat n = n := rfl @[simp, norm_cast] theorem ofENat_zero : ofENat 0 = 0 := rfl @[simp, norm_cast] theorem ofENat_one : ofENat 1 = 1 := rfl @[simp, norm_cast] theorem ofENat_ofNat (n : Nat) [n.AtLeastTwo] : ofENat ofNat(n) = OfNat.ofNat n := rfl @[simp, norm_cast] theorem toWithTop_ofENat (n : β„•βˆž) {_ : Decidable (n : PartENat).Dom} : toWithTop (↑n) = n := by cases n with | top => simp | coe n => simp @[simp, norm_cast] theorem ofENat_toWithTop (x : PartENat) {_ : Decidable (x : PartENat).Dom} : toWithTop x = x := by induction x using PartENat.casesOn <;> simp @[simp, norm_cast] theorem ofENat_le {x y : β„•βˆž} : ofENat x ≀ ofENat y ↔ x ≀ y := by classical rw [← toWithTop_le, toWithTop_ofENat, toWithTop_ofENat] @[simp, norm_cast] theorem ofENat_lt {x y : β„•βˆž} : ofENat x < ofENat y ↔ x < y := by classical rw [← toWithTop_lt, toWithTop_ofENat, toWithTop_ofENat] section WithTopEquiv open scoped Classical in @[simp] theorem toWithTop_add {x y : PartENat} : toWithTop (x + y) = toWithTop x + toWithTop y := by refine PartENat.casesOn y ?_ ?_ <;> refine PartENat.casesOn x ?_ ?_ <;> simp [add_top, top_add, ← Nat.cast_add] open scoped Classical in /-- `Equiv` between `PartENat` and `β„•βˆž` (for the order isomorphism see `withTopOrderIso`). -/ @[simps] noncomputable def withTopEquiv : PartENat ≃ β„•βˆž where toFun x := toWithTop x invFun x := ↑x left_inv x := by simp right_inv x := by simp theorem withTopEquiv_top : withTopEquiv ⊀ = ⊀ := by simp theorem withTopEquiv_natCast (n : Nat) : withTopEquiv n = n := by simp theorem withTopEquiv_zero : withTopEquiv 0 = 0 := by simp theorem withTopEquiv_one : withTopEquiv 1 = 1 := by simp theorem withTopEquiv_ofNat (n : Nat) [n.AtLeastTwo] : withTopEquiv ofNat(n) = OfNat.ofNat n := by simp theorem withTopEquiv_le {x y : PartENat} : withTopEquiv x ≀ withTopEquiv y ↔ x ≀ y := by simp theorem withTopEquiv_lt {x y : PartENat} : withTopEquiv x < withTopEquiv y ↔ x < y := by simp theorem withTopEquiv_symm_top : withTopEquiv.symm ⊀ = ⊀ := by simp theorem withTopEquiv_symm_coe (n : Nat) : withTopEquiv.symm n = n := by simp theorem withTopEquiv_symm_zero : withTopEquiv.symm 0 = 0 := by simp theorem withTopEquiv_symm_one : withTopEquiv.symm 1 = 1 := by simp theorem withTopEquiv_symm_ofNat (n : Nat) [n.AtLeastTwo] : withTopEquiv.symm ofNat(n) = OfNat.ofNat n := by simp theorem withTopEquiv_symm_le {x y : β„•βˆž} : withTopEquiv.symm x ≀ withTopEquiv.symm y ↔ x ≀ y := by simp theorem withTopEquiv_symm_lt {x y : β„•βˆž} : withTopEquiv.symm x < withTopEquiv.symm y ↔ x < y := by simp /-- `toWithTop` induces an order isomorphism between `PartENat` and `β„•βˆž`. -/ noncomputable def withTopOrderIso : PartENat ≃o β„•βˆž := { withTopEquiv with map_rel_iff' := @fun _ _ => withTopEquiv_le } /-- `toWithTop` induces an additive monoid isomorphism between `PartENat` and `β„•βˆž`. -/ noncomputable def withTopAddEquiv : PartENat ≃+ β„•βˆž := { withTopEquiv with map_add' := fun x y => by simp only [withTopEquiv] exact toWithTop_add } end WithTopEquiv theorem lt_wf : @WellFounded PartENat (Β· < Β·) := by classical change WellFounded fun a b : PartENat => a < b simp_rw [← withTopEquiv_lt] exact InvImage.wf _ wellFounded_lt instance : WellFoundedLT PartENat := ⟨lt_wf⟩ instance wellFoundedRelation : WellFoundedRelation PartENat := ⟨(Β· < Β·), lt_wf⟩ section Find variable (P : β„• β†’ Prop) [DecidablePred P] /-- The smallest `PartENat` satisfying a (decidable) predicate `P : β„• β†’ Prop` -/ def find : PartENat := βŸ¨βˆƒ n, P n, Nat.find⟩ @[simp] theorem find_get (h : (find P).Dom) : (find P).get h = Nat.find h := rfl theorem find_dom (h : βˆƒ n, P n) : (find P).Dom := h theorem lt_find (n : β„•) (h : βˆ€ m ≀ n, Β¬P m) : (n : PartENat) < find P := by rw [coe_lt_iff] intro h₁ rw [find_get] have hβ‚‚ := @Nat.find_spec P _ h₁ revert hβ‚‚ contrapose! exact h _ theorem lt_find_iff (n : β„•) : (n : PartENat) < find P ↔ βˆ€ m ≀ n, Β¬P m := by refine ⟨?_, lt_find P n⟩ intro h m hm by_cases H : (find P).Dom Β· apply Nat.find_min H rw [coe_lt_iff] at h specialize h H exact lt_of_le_of_lt hm h Β· exact not_exists.mp H m theorem find_le (n : β„•) (h : P n) : find P ≀ n := by rw [le_coe_iff] exact ⟨⟨_, h⟩, @Nat.find_min' P _ _ _ h⟩ theorem find_eq_top_iff : find P = ⊀ ↔ βˆ€ n, Β¬P n := (eq_top_iff_forall_lt _).trans ⟨fun h n => (lt_find_iff P n).mp (h n) _ le_rfl, fun h n => lt_find P n fun _ _ => h _⟩ end Find noncomputable instance : LinearOrderedAddCommMonoidWithTop PartENat := { PartENat.linearOrder, PartENat.isOrderedAddMonoid, PartENat.orderTop with top_add' := top_add } noncomputable instance : CompleteLinearOrder PartENat := { lattice, withTopOrderIso.symm.toGaloisInsertion.liftCompleteLattice, linearOrder, linearOrder.toBiheytingAlgebra with } end PartENat
.lake/packages/mathlib/Mathlib/Data/Nat/Totient.lean
import Mathlib.Algebra.CharP.Two import Mathlib.Algebra.Order.BigOperators.Ring.Finset import Mathlib.Data.Nat.Cast.Field import Mathlib.Data.Nat.Factorization.Basic import Mathlib.Data.Nat.Factorization.Induction import Mathlib.Data.Nat.Periodic /-! # Euler's totient function This file defines [Euler's totient function](https://en.wikipedia.org/wiki/Euler's_totient_function) `Nat.totient n` which counts the number of naturals less than `n` that are coprime with `n`. We prove the divisor sum formula, namely that `n` equals `Ο†` summed over the divisors of `n`. See `sum_totient`. We also prove two lemmas to help compute totients, namely `totient_mul` and `totient_prime_pow`. -/ assert_not_exists Algebra LinearMap open Finset namespace Nat /-- Euler's totient function. This counts the number of naturals strictly less than `n` which are coprime with `n`. -/ def totient (n : β„•) : β„• := #{a ∈ range n | n.Coprime a} @[inherit_doc] scoped notation "Ο†" => Nat.totient @[simp] theorem totient_zero : Ο† 0 = 0 := rfl @[simp] theorem totient_one : Ο† 1 = 1 := rfl theorem totient_eq_card_coprime (n : β„•) : Ο† n = #{a ∈ range n | n.Coprime a} := rfl /-- A characterisation of `Nat.totient` that avoids `Finset`. -/ theorem totient_eq_card_lt_and_coprime (n : β„•) : Ο† n = Nat.card { m | m < n ∧ n.Coprime m } := by let e : { m | m < n ∧ n.Coprime m } ≃ {x ∈ range n | n.Coprime x} := { toFun := fun m => ⟨m, by simpa only [Finset.mem_filter, Finset.mem_range] using m.property⟩ invFun := fun m => ⟨m, by simpa only [Finset.mem_filter, Finset.mem_range] using m.property⟩ left_inv := fun m => by simp only [Subtype.coe_eta] right_inv := fun m => by simp only [Subtype.coe_eta] } rw [totient_eq_card_coprime, card_congr e, card_eq_fintype_card, Fintype.card_coe] theorem totient_le (n : β„•) : Ο† n ≀ n := ((range n).card_filter_le _).trans_eq (card_range n) theorem totient_lt (n : β„•) (hn : 1 < n) : Ο† n < n := (card_lt_card (filter_ssubset.2 ⟨0, by simp [hn.ne', pos_of_gt hn]⟩)).trans_eq (card_range n) @[simp] theorem totient_eq_zero : βˆ€ {n : β„•}, Ο† n = 0 ↔ n = 0 | 0 => by decide | n + 1 => suffices βˆƒ x < n + 1, (n + 1).gcd x = 1 by simpa [totient, filter_eq_empty_iff] ⟨1 % (n + 1), mod_lt _ n.succ_pos, by rw [gcd_comm, ← gcd_rec, gcd_one_right]⟩ @[simp] theorem totient_pos {n : β„•} : 0 < Ο† n ↔ 0 < n := by simp [pos_iff_ne_zero] instance neZero_totient {n : β„•} [NeZero n] : NeZero n.totient := ⟨(totient_pos.mpr <| NeZero.pos n).ne'⟩ theorem filter_coprime_Ico_eq_totient (a n : β„•) : #{x ∈ Ico n (n + a) | a.Coprime x} = totient a := by rw [totient, filter_Ico_card_eq_of_periodic, count_eq_card_filter_range] exact periodic_coprime a theorem Ico_filter_coprime_le {a : β„•} (k n : β„•) (a_ne_zero : a β‰  0) : #{x ∈ Ico k (k + n) | a.Coprime x} ≀ totient a * (n / a + 1) := by conv_lhs => rw [← Nat.mod_add_div n a] induction n / a with | zero => rw [← filter_coprime_Ico_eq_totient a k] simp only [add_zero, mul_one, mul_zero, zero_add] gcongr exact le_of_lt (mod_lt n (pos_iff_ne_zero.mpr a_ne_zero)) | succ i ih => ?_ simp only [mul_succ] simp_rw [← add_assoc] at ih ⊒ calc #{x ∈ Ico k (k + n % a + a * i + a) | a.Coprime x} ≀ #{x ∈ Ico k (k + n % a + a * i) βˆͺ Ico (k + n % a + a * i) (k + n % a + a * i + a) | a.Coprime x} := by gcongr apply Ico_subset_Ico_union_Ico _ ≀ #{x ∈ Ico k (k + n % a + a * i) | a.Coprime x} + a.totient := by rw [filter_union, ← filter_coprime_Ico_eq_totient a (k + n % a + a * i)] apply card_union_le _ ≀ a.totient * i + a.totient + a.totient := by grw [← mul_add_one, ih] open ZMod /-- Note this takes an explicit `Fintype ((ZMod n)Λ£)` argument to avoid trouble with instance diamonds. -/ @[simp] theorem _root_.ZMod.card_units_eq_totient (n : β„•) [NeZero n] [Fintype (ZMod n)Λ£] : Fintype.card (ZMod n)Λ£ = Ο† n := calc Fintype.card (ZMod n)Λ£ = Fintype.card { x : ZMod n // x.val.Coprime n } := Fintype.card_congr ZMod.unitsEquivCoprime _ = Ο† n := by obtain ⟨m, rfl⟩ : βˆƒ m, n = m + 1 := exists_eq_succ_of_ne_zero NeZero.out simp only [totient, Finset.card_eq_sum_ones, Fintype.card_subtype, Finset.sum_filter, ← Fin.sum_univ_eq_sum_range, @Nat.coprime_comm (m + 1)] rfl theorem totient_even {n : β„•} (hn : 2 < n) : Even n.totient := by haveI : Fact (1 < n) := ⟨one_lt_two.trans hn⟩ haveI : NeZero n := NeZero.of_gt hn suffices 2 = orderOf (-1 : (ZMod n)Λ£) by rw [← ZMod.card_units_eq_totient, even_iff_two_dvd, this] exact orderOf_dvd_card rw [← orderOf_units, Units.coe_neg_one, orderOf_neg_one, ringChar.eq (ZMod n) n, if_neg hn.ne'] theorem totient_mul {m n : β„•} (h : m.Coprime n) : Ο† (m * n) = Ο† m * Ο† n := if hmn0 : m * n = 0 then by rcases Nat.mul_eq_zero.1 hmn0 with h | h <;> simp only [totient_zero, mul_zero, zero_mul, h] else by haveI : NeZero (m * n) := ⟨hmn0⟩ haveI : NeZero m := ⟨left_ne_zero_of_mul hmn0⟩ haveI : NeZero n := ⟨right_ne_zero_of_mul hmn0⟩ simp only [← ZMod.card_units_eq_totient] rw [Fintype.card_congr (Units.mapEquiv (ZMod.chineseRemainder h).toMulEquiv).toEquiv, Fintype.card_congr (@MulEquiv.prodUnits (ZMod m) (ZMod n) _ _).toEquiv, Fintype.card_prod] /-- For `d ∣ n`, the totient of `n/d` equals the number of values `k < n` such that `gcd n k = d` -/ theorem totient_div_of_dvd {n d : β„•} (hnd : d ∣ n) : Ο† (n / d) = #{k ∈ range n | n.gcd k = d} := by rcases d.eq_zero_or_pos with (rfl | hd0); Β· simp [eq_zero_of_zero_dvd hnd] rcases hnd with ⟨x, rfl⟩ rw [Nat.mul_div_cancel_left x hd0] apply Finset.card_bij fun k _ => d * k Β· simp only [mem_filter, mem_range, and_imp, Coprime] refine fun a ha1 ha2 => ⟨by gcongr, ?_⟩ rw [gcd_mul_left, ha2, mul_one] Β· simp [hd0.ne'] Β· simp only [mem_filter, mem_range, exists_prop, and_imp] refine fun b hb1 hb2 => ?_ have : d ∣ b := by rw [← hb2] apply gcd_dvd_right rcases this with ⟨q, rfl⟩ refine ⟨q, ⟨⟨(mul_lt_mul_iff_rightβ‚€ hd0).1 hb1, ?_⟩, rfl⟩⟩ rwa [gcd_mul_left, mul_eq_left hd0.ne'] at hb2 theorem sum_totient (n : β„•) : n.divisors.sum Ο† = n := by rcases n.eq_zero_or_pos with (rfl | hn) Β· simp rw [← sum_div_divisors n Ο†] have : n = βˆ‘ d ∈ n.divisors, #{k ∈ range n | n.gcd k = d} := by nth_rw 1 [← card_range n] refine card_eq_sum_card_fiberwise fun x _ => mem_divisors.2 ⟨?_, hn.ne'⟩ apply gcd_dvd_left nth_rw 3 [this] exact sum_congr rfl fun x hx => totient_div_of_dvd (dvd_of_mem_divisors hx) theorem sum_totient' (n : β„•) : βˆ‘ m ∈ range n.succ with m ∣ n, Ο† m = n := by convert sum_totient _ using 1 simp only [Nat.divisors, sum_filter, range_eq_Ico] rw [sum_eq_sum_Ico_succ_bot] <;> simp /-- When `p` is prime, then the totient of `p ^ (n + 1)` is `p ^ n * (p - 1)` -/ theorem totient_prime_pow_succ {p : β„•} (hp : p.Prime) (n : β„•) : Ο† (p ^ (n + 1)) = p ^ n * (p - 1) := calc Ο† (p ^ (n + 1)) = #{a ∈ range (p ^ (n + 1)) | (p ^ (n + 1)).Coprime a} := totient_eq_card_coprime _ _ = #(range (p ^ (n + 1)) \ (range (p ^ n)).image (Β· * p)) := congr_arg card (by rw [sdiff_eq_filter] apply filter_congr simp only [mem_range, coprime_pow_left_iff n.succ_pos, mem_image, not_exists, hp.coprime_iff_not_dvd] intro a ha constructor Β· intro hap b h; rcases h with ⟨_, rfl⟩ exact hap (dvd_mul_left _ _) Β· rintro h ⟨b, rfl⟩ rw [pow_succ'] at ha exact h b ⟨lt_of_mul_lt_mul_left ha (zero_le _), mul_comm _ _⟩) _ = _ := by have h1 : Function.Injective (Β· * p) := mul_left_injectiveβ‚€ hp.ne_zero have h2 : (range (p ^ n)).image (Β· * p) βŠ† range (p ^ (n + 1)) := fun a => by simp only [mem_image, mem_range, exists_imp] rintro b ⟨h, rfl⟩ rw [Nat.pow_succ] exact (mul_lt_mul_iff_leftβ‚€ hp.pos).2 h rw [card_sdiff_of_subset h2, Finset.card_image_of_injective _ h1, card_range, card_range, ← one_mul (p ^ n), pow_succ', ← tsub_mul, one_mul, mul_comm] /-- When `p` is prime, then the totient of `p ^ n` is `p ^ (n - 1) * (p - 1)` -/ theorem totient_prime_pow {p : β„•} (hp : p.Prime) {n : β„•} (hn : 0 < n) : Ο† (p ^ n) = p ^ (n - 1) * (p - 1) := by rcases exists_eq_succ_of_ne_zero (pos_iff_ne_zero.1 hn) with ⟨m, rfl⟩ exact totient_prime_pow_succ hp _ theorem totient_prime {p : β„•} (hp : p.Prime) : Ο† p = p - 1 := by rw [← pow_one p, totient_prime_pow hp] <;> simp theorem totient_eq_iff_prime {p : β„•} (hp : 0 < p) : p.totient = p - 1 ↔ p.Prime := by refine ⟨fun h => ?_, totient_prime⟩ replace hp : 1 < p := by apply lt_of_le_of_ne Β· rwa [succ_le_iff] Β· rintro rfl rw [totient_one, tsub_self] at h exact one_ne_zero h rw [totient_eq_card_coprime, range_eq_Ico, ← Finset.insert_Ico_add_one_left_eq_Ico hp.le, Finset.filter_insert, if_neg (not_coprime_of_dvd_of_dvd hp (dvd_refl p) (dvd_zero p)), ← Nat.card_Ico 1 p] at h refine p.prime_of_coprime hp fun n hn hnz => Finset.filter_card_eq h n <| Finset.mem_Ico.mpr ⟨?_, hn⟩ cutsat theorem card_units_zmod_lt_sub_one {p : β„•} (hp : 1 < p) [Fintype (ZMod p)Λ£] : Fintype.card (ZMod p)Λ£ ≀ p - 1 := by haveI : NeZero p := ⟨(pos_of_gt hp).ne'⟩ rw [ZMod.card_units_eq_totient p] exact Nat.le_sub_one_of_lt (Nat.totient_lt p hp) theorem prime_iff_card_units (p : β„•) [Fintype (ZMod p)Λ£] : p.Prime ↔ Fintype.card (ZMod p)Λ£ = p - 1 := by rcases eq_zero_or_neZero p with hp | hp Β· subst hp simp only [ZMod, not_prime_zero, false_iff, zero_tsub] -- the subst created a non-defeq but subsingleton instance diamond; resolve it suffices Fintype.card β„€Λ£ β‰  0 by convert this simp rw [ZMod.card_units_eq_totient, Nat.totient_eq_iff_prime <| NeZero.pos p] @[simp] theorem totient_two : Ο† 2 = 1 := (totient_prime prime_two).trans rfl /-- Euler's totient function is only odd at `1` or `2`. -/ theorem odd_totient_iff {n : β„•} : Odd (Ο† n) ↔ n = 1 ∨ n = 2 := by rcases n with _ | _ | _ | _ <;> simp [Nat.totient_even] theorem totient_eq_one_iff : βˆ€ {n : β„•}, n.totient = 1 ↔ n = 1 ∨ n = 2 | 0 => by simp | 1 => by simp | 2 => by simp | n + 3 => by have : 3 ≀ n + 3 := le_add_self simp only [succ_succ_ne_one, false_or] exact ⟨fun h => not_even_one.elim <| h β–Έ totient_even this, by rintro ⟨⟩⟩ theorem dvd_two_of_totient_le_one {a : β„•} (han : 0 < a) (ha : a.totient ≀ 1) : a ∣ 2 := by rcases totient_eq_one_iff.mp <| le_antisymm ha <| totient_pos.2 han with rfl | rfl <;> norm_num theorem odd_totient_iff_eq_one {n : β„•} : Odd (Ο† n) ↔ Ο† n = 1 := by simp [Nat.odd_totient_iff, Nat.totient_eq_one_iff] /-- `Nat.totient m` and `Nat.totient n` are coprime iff one of them is 1. -/ theorem totient_coprime_totient_iff (m n : β„•) : (Ο† m).Coprime (Ο† n) ↔ (m = 1 ∨ m = 2) ∨ (n = 1 ∨ n = 2) := by constructor Β· rw [← not_imp_not] simp_rw [← odd_totient_iff, not_or, not_odd_iff_even, even_iff_two_dvd] exact fun h ↦ Nat.not_coprime_of_dvd_of_dvd one_lt_two h.1 h.2 Β· simp_rw [← totient_eq_one_iff] rintro (h | h) <;> rw [h] exacts [Nat.coprime_one_left _, Nat.coprime_one_right _] /-! ### Euler's product formula for the totient function We prove several different statements of this formula. -/ /-- Euler's product formula for the totient function. -/ theorem totient_eq_prod_factorization {n : β„•} (hn : n β‰  0) : Ο† n = n.factorization.prod fun p k => p ^ (k - 1) * (p - 1) := by rw [multiplicative_factorization Ο† (@totient_mul) totient_one hn] apply Finsupp.prod_congr _ intro p hp have h := zero_lt_iff.mpr (Finsupp.mem_support_iff.mp hp) rw [totient_prime_pow (prime_of_mem_primeFactors hp) h] /-- Euler's product formula for the totient function. -/ theorem totient_mul_prod_primeFactors (n : β„•) : (Ο† n * ∏ p ∈ n.primeFactors, p) = n * ∏ p ∈ n.primeFactors, (p - 1) := by by_cases hn : n = 0; Β· simp [hn] rw [totient_eq_prod_factorization hn] nth_rw 3 [← factorization_prod_pow_eq_self hn] simp only [prod_primeFactors_prod_factorization, ← Finsupp.prod_mul] refine Finsupp.prod_congr (M := β„•) (N := β„•) fun p hp => ?_ rw [Finsupp.mem_support_iff, ← zero_lt_iff] at hp rw [mul_comm, ← mul_assoc, ← pow_succ', Nat.sub_one, Nat.succ_pred_eq_of_pos hp] /-- Euler's product formula for the totient function. -/ theorem totient_eq_div_primeFactors_mul (n : β„•) : Ο† n = (n / ∏ p ∈ n.primeFactors, p) * ∏ p ∈ n.primeFactors, (p - 1) := by rw [← mul_div_left n.totient, totient_mul_prod_primeFactors, mul_comm, Nat.mul_div_assoc _ (prod_primeFactors_dvd n), mul_comm] exact prod_pos (fun p => pos_of_mem_primeFactors) /-- Euler's product formula for the totient function. -/ theorem totient_eq_mul_prod_factors (n : β„•) : (Ο† n : β„š) = n * ∏ p ∈ n.primeFactors, (1 - (p : β„š)⁻¹) := by by_cases hn : n = 0 Β· simp [hn] have hn' : (n : β„š) β‰  0 := by simp [hn] have hpQ : (∏ p ∈ n.primeFactors, (p : β„š)) β‰  0 := by rw [← cast_prod, cast_ne_zero, ← zero_lt_iff, prod_primeFactors_prod_factorization] exact prod_pos fun p hp => pos_of_mem_primeFactors hp simp only [totient_eq_div_primeFactors_mul n, prod_primeFactors_dvd n, cast_mul, cast_prod, cast_div_charZero, mul_comm_div, mul_right_inj' hn', div_eq_iff hpQ, ← prod_mul_distrib] refine prod_congr rfl fun p hp => ?_ have hp := pos_of_mem_primeFactorsList (List.mem_toFinset.mp hp) have hp' : (p : β„š) β‰  0 := cast_ne_zero.mpr hp.ne.symm rw [sub_mul, one_mul, mul_comm, mul_inv_cancelβ‚€ hp', cast_pred hp] theorem totient_gcd_mul_totient_mul (a b : β„•) : Ο† (a.gcd b) * Ο† (a * b) = Ο† a * Ο† b * a.gcd b := by have shuffle : βˆ€ a1 a2 b1 b2 c1 c2 : β„•, b1 ∣ a1 β†’ b2 ∣ a2 β†’ a1 / b1 * c1 * (a2 / b2 * c2) = a1 * a2 / (b1 * b2) * (c1 * c2) := by intro a1 a2 b1 b2 c1 c2 h1 h2 calc a1 / b1 * c1 * (a2 / b2 * c2) = a1 / b1 * (a2 / b2) * (c1 * c2) := by apply mul_mul_mul_comm _ = a1 * a2 / (b1 * b2) * (c1 * c2) := by congr 1 exact div_mul_div_comm h1 h2 simp only [totient_eq_div_primeFactors_mul] rw [shuffle, shuffle] rotate_left repeat' apply prod_primeFactors_dvd simp only [prod_primeFactors_gcd_mul_prod_primeFactors_mul] rw [eq_comm, mul_comm, ← mul_assoc, ← Nat.mul_div_assoc] exact mul_dvd_mul (prod_primeFactors_dvd a) (prod_primeFactors_dvd b) theorem totient_super_multiplicative (a b : β„•) : Ο† a * Ο† b ≀ Ο† (a * b) := by let d := a.gcd b rcases (zero_le a).eq_or_lt with (rfl | ha0) Β· simp have hd0 : 0 < d := Nat.gcd_pos_of_pos_left _ ha0 apply le_of_mul_le_mul_right _ hd0 grw [← totient_gcd_mul_totient_mul a b, mul_comm, d.totient_le] @[gcongr] theorem totient_dvd_of_dvd {a b : β„•} (h : a ∣ b) : Ο† a ∣ Ο† b := by rcases eq_or_ne a 0 with (rfl | ha0) Β· simp [zero_dvd_iff.1 h] rcases eq_or_ne b 0 with (rfl | hb0) Β· simp have hab' := primeFactors_mono h hb0 rw [totient_eq_prod_factorization ha0, totient_eq_prod_factorization hb0] refine Finsupp.prod_dvd_prod_of_subset_of_dvd hab' fun p _ => mul_dvd_mul ?_ dvd_rfl exact pow_dvd_pow p (tsub_le_tsub_right ((factorization_le_iff_dvd ha0 hb0).2 h p) 1) theorem totient_mul_of_prime_of_dvd {p n : β„•} (hp : p.Prime) (h : p ∣ n) : (p * n).totient = p * n.totient := by have h1 := totient_gcd_mul_totient_mul p n rw [gcd_eq_left h, mul_assoc] at h1 simpa [(totient_pos.2 hp.pos).ne', mul_comm] using h1 theorem totient_mul_of_prime_of_not_dvd {p n : β„•} (hp : p.Prime) (h : Β¬p ∣ n) : (p * n).totient = (p - 1) * n.totient := by rw [totient_mul _, totient_prime hp] simpa [h] using coprime_or_dvd_of_prime hp n end Nat namespace Mathlib.Meta.Positivity open Lean Meta Qq /-- Extension for `Nat.totient`. -/ @[positivity Nat.totient _] def evalNatTotient : PositivityExt where eval {u Ξ±} z p e := do match u, Ξ±, e with | 0, ~q(β„•), ~q(Nat.totient $n) => assumeInstancesCommute match ← core z p n with | .positive pa => return .positive q(Nat.totient_pos.mpr $pa) | _ => failure | _, _, _ => throwError "not Nat.totient" end Mathlib.Meta.Positivity
.lake/packages/mathlib/Mathlib/Data/Nat/PSub.lean
import Mathlib.Algebra.Group.Basic import Mathlib.Algebra.Group.Nat.Defs import Mathlib.Data.Nat.Basic /-! # Partial predecessor and partial subtraction on the natural numbers The usual definition of natural number subtraction (`Nat.sub`) returns 0 as a "garbage value" for `a - b` when `a < b`. Similarly, `Nat.pred 0` is defined to be `0`. The functions in this file wrap the result in an `Option` type instead: ## Main definitions - `Nat.ppred`: a partial predecessor operation - `Nat.psub`: a partial subtraction operation -/ namespace Nat /-- Partial predecessor operation. Returns `ppred n = some m` if `n = m + 1`, otherwise `none`. -/ def ppred : β„• β†’ Option β„• | 0 => none | n + 1 => some n @[simp] theorem ppred_zero : ppred 0 = none := rfl @[simp] theorem ppred_succ {n : β„•} : ppred (succ n) = some n := rfl /-- Partial subtraction operation. Returns `psub m n = some k` if `m = n + k`, otherwise `none`. -/ def psub (m : β„•) : β„• β†’ Option β„• | 0 => some m | n + 1 => psub m n >>= ppred @[simp] theorem psub_zero {m : β„•} : psub m 0 = some m := rfl @[simp] theorem psub_succ {m n : β„•} : psub m (succ n) = psub m n >>= ppred := rfl theorem pred_eq_ppred (n : β„•) : pred n = (ppred n).getD 0 := by cases n <;> rfl theorem sub_eq_psub (m : β„•) : βˆ€ n, m - n = (psub m n).getD 0 | 0 => rfl | n + 1 => (pred_eq_ppred (m - n)).trans <| by rw [sub_eq_psub m n, psub]; cases psub m n <;> rfl @[simp] theorem ppred_eq_some {m : β„•} : βˆ€ {n}, ppred n = some m ↔ succ m = n | 0 => by constructor <;> intro h <;> contradiction | n + 1 => by constructor <;> intro h <;> injection h <;> subst m <;> rfl @[simp] theorem ppred_eq_none : βˆ€ {n : β„•}, ppred n = none ↔ n = 0 | 0 => by simp | n + 1 => by constructor <;> intro <;> contradiction theorem psub_eq_some {m : β„•} : βˆ€ {n k}, psub m n = some k ↔ k + n = m | 0, k => by simp [eq_comm] | n + 1, k => by apply Option.bind_eq_some_iff.trans simp only [psub_eq_some, ppred_eq_some] simp [add_comm, add_left_comm] theorem psub_eq_none {m n : β„•} : psub m n = none ↔ m < n := by rcases s : psub m n Β· simp only [true_iff] refine lt_of_not_ge fun h => ?_ obtain ⟨k, e⟩ := le.dest h injection s.symm.trans (psub_eq_some.2 <| (add_comm _ _).trans e) Β· grind [psub_eq_some] theorem ppred_eq_pred {n} (h : 0 < n) : ppred n = some (pred n) := ppred_eq_some.2 <| succ_pred_eq_of_pos h theorem psub_eq_sub {m n} (h : n ≀ m) : psub m n = some (m - n) := psub_eq_some.2 <| Nat.sub_add_cancel h theorem psub_add (m n k) : psub m (n + k) = (do psub (← psub m n) k) := by induction k with | zero => simp | succ n ih => simp only [ih, add_succ, psub_succ, bind_assoc] /-- Same as `psub`, but with a more efficient implementation. -/ @[inline] def psub' (m n : β„•) : Option β„• := if n ≀ m then some (m - n) else none theorem psub'_eq_psub (m n) : psub' m n = psub m n := by rw [psub'] split_ifs with h Β· exact (psub_eq_sub h).symm Β· exact (psub_eq_none.2 (not_le.1 h)).symm end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Pairing.lean
import Mathlib.Algebra.Notation.Prod import Mathlib.Data.Nat.Sqrt import Mathlib.Data.Set.Lattice.Image /-! # Naturals pairing function This file defines a pairing function for the naturals as follows: ```text 0 1 4 9 16 2 3 5 10 17 6 7 8 11 18 12 13 14 15 19 20 21 22 23 24 ``` It has the advantage of being monotone in both directions and sending `⟦0, n^2 - 1⟧` to `⟦0, n - 1⟧²`. -/ assert_not_exists Monoid open Prod Decidable Function namespace Nat /-- Pairing function for the natural numbers. -/ @[pp_nodot] def pair (a b : β„•) : β„• := if a < b then b * b + a else a * a + a + b /-- Unpairing function for the natural numbers. -/ @[pp_nodot] def unpair (n : β„•) : β„• Γ— β„• := let s := sqrt n if n - s * s < s then (n - s * s, s) else (s, n - s * s - s) @[simp] theorem pair_unpair (n : β„•) : pair (unpair n).1 (unpair n).2 = n := by dsimp only [unpair]; let s := sqrt n have sm : s * s + (n - s * s) = n := Nat.add_sub_cancel' (sqrt_le _) split_ifs with h Β· simp [s, pair, h, sm] Β· have hl : n - s * s - s ≀ s := Nat.sub_le_iff_le_add.2 (Nat.sub_le_iff_le_add'.2 <| by rw [← Nat.add_assoc]; apply sqrt_le_add) simp [s, pair, hl.not_gt, Nat.add_assoc, Nat.add_sub_cancel' (le_of_not_gt h), sm] theorem pair_eq_of_unpair_eq {n a b} (H : unpair n = (a, b)) : pair a b = n := by simpa [H] using pair_unpair n @[deprecated (since := "2025-05-24")] alias pair_unpair' := pair_eq_of_unpair_eq @[simp] theorem unpair_pair (a b : β„•) : unpair (pair a b) = (a, b) := by dsimp only [pair]; split_ifs with h Β· show unpair (b * b + a) = (a, b) have be : sqrt (b * b + a) = b := sqrt_add_eq _ (le_trans (le_of_lt h) (Nat.le_add_left _ _)) simp [unpair, be, Nat.add_sub_cancel_left, h] Β· show unpair (a * a + a + b) = (a, b) have ae : sqrt (a * a + (a + b)) = a := by rw [sqrt_add_eq] exact Nat.add_le_add_left (le_of_not_gt h) _ simp [unpair, ae, Nat.add_assoc, Nat.add_sub_cancel_left] /-- An equivalence between `β„• Γ— β„•` and `β„•`. -/ @[simps -fullyApplied] def pairEquiv : β„• Γ— β„• ≃ β„• := ⟨uncurry pair, unpair, fun ⟨a, b⟩ => unpair_pair a b, pair_unpair⟩ theorem surjective_unpair : Surjective unpair := pairEquiv.symm.surjective @[simp] theorem pair_eq_pair {a b c d : β„•} : pair a b = pair c d ↔ a = c ∧ b = d := pairEquiv.injective.eq_iff.trans (@Prod.ext_iff β„• β„• (a, b) (c, d)) theorem unpair_lt {n : β„•} (n1 : 1 ≀ n) : (unpair n).1 < n := by let s := sqrt n simp only [unpair] by_cases h : n - s * s < s <;> simp only [h, ↓reduceIte, gt_iff_lt, s] Β· exact lt_of_lt_of_le h (sqrt_le_self _) Β· simp only [not_lt] at h have s0 : 0 < s := sqrt_pos.2 n1 exact lt_of_le_of_lt h (Nat.sub_lt n1 (Nat.mul_pos s0 s0)) @[simp] theorem unpair_zero : unpair 0 = 0 := by rw [unpair] simp theorem unpair_left_le : βˆ€ n : β„•, (unpair n).1 ≀ n | 0 => by simp | _ + 1 => le_of_lt (unpair_lt (Nat.succ_pos _)) theorem left_le_pair (a b : β„•) : a ≀ pair a b := by simpa using unpair_left_le (pair a b) theorem right_le_pair (a b : β„•) : b ≀ pair a b := by by_cases h : a < b Β· simpa [pair, h] using le_trans (le_mul_self _) (Nat.le_add_right _ _) Β· simp [pair, h] theorem unpair_right_le (n : β„•) : (unpair n).2 ≀ n := by simpa using right_le_pair n.unpair.1 n.unpair.2 theorem pair_lt_pair_left {a₁ aβ‚‚} (b) (h : a₁ < aβ‚‚) : pair a₁ b < pair aβ‚‚ b := by by_cases h₁ : a₁ < b <;> simp only [pair, h₁, ↓reduceIte, Nat.add_assoc] Β· by_cases hβ‚‚ : aβ‚‚ < b Β· simp [hβ‚‚, h] simp only [hβ‚‚, ↓reduceIte] apply Nat.add_lt_add_of_le_of_lt Β· exact Nat.mul_self_le_mul_self (not_lt.mp hβ‚‚) Β· exact Nat.lt_add_right _ h Β· simp at h₁ simp only [not_lt_of_gt (lt_of_le_of_lt h₁ h), ite_false] apply add_lt_add Β· exact Nat.mul_self_lt_mul_self h Β· apply Nat.add_lt_add_right; assumption theorem pair_lt_pair_right (a) {b₁ bβ‚‚} (h : b₁ < bβ‚‚) : pair a b₁ < pair a bβ‚‚ := by by_cases h₁ : a < b₁ Β· simpa [pair, h₁, Nat.add_assoc, lt_trans h₁ h, h] using mul_self_lt_mul_self h Β· simp only [pair, h₁, ↓reduceIte, Nat.add_assoc] by_cases hβ‚‚ : a < bβ‚‚; swap; Β· simp [hβ‚‚, h] simp only [hβ‚‚, ↓reduceIte] rw [Nat.add_comm, Nat.add_comm _ a, Nat.add_assoc, Nat.add_lt_add_iff_left] rwa [Nat.add_comm, ← sqrt_lt, sqrt_add_eq] exact le_trans (not_lt.mp h₁) (Nat.le_add_left _ _) theorem pair_lt_max_add_one_sq (m n : β„•) : pair m n < (max m n + 1) ^ 2 := by simp only [pair, Nat.pow_two, Nat.mul_add, Nat.add_mul, Nat.mul_one, Nat.one_mul, Nat.add_assoc] split_ifs <;> simp [Nat.le_of_lt, not_lt.1, *] <;> omega theorem max_sq_add_min_le_pair (m n : β„•) : max m n ^ 2 + min m n ≀ pair m n := by rw [pair] rcases lt_or_ge m n with h | h Β· rw [if_pos h, max_eq_right h.le, min_eq_left h.le, Nat.pow_two] rw [if_neg h.not_gt, max_eq_left h, min_eq_right h, Nat.pow_two, Nat.add_assoc, Nat.add_le_add_iff_left] exact Nat.le_add_left _ _ theorem add_le_pair (m n : β„•) : m + n ≀ pair m n := by simp only [pair, Nat.add_assoc] split_ifs Β· have := le_mul_self n cutsat Β· exact Nat.le_add_left _ _ theorem unpair_add_le (n : β„•) : (unpair n).1 + (unpair n).2 ≀ n := (add_le_pair _ _).trans_eq (pair_unpair _) end Nat open Nat section CompleteLattice theorem iSup_unpair {Ξ±} [CompleteLattice Ξ±] (f : β„• β†’ β„• β†’ Ξ±) : ⨆ n : β„•, f n.unpair.1 n.unpair.2 = ⨆ (i : β„•) (j : β„•), f i j := by rw [← (iSup_prod : ⨆ i : β„• Γ— β„•, f i.1 i.2 = _), ← Nat.surjective_unpair.iSup_comp] theorem iInf_unpair {Ξ±} [CompleteLattice Ξ±] (f : β„• β†’ β„• β†’ Ξ±) : β¨… n : β„•, f n.unpair.1 n.unpair.2 = β¨… (i : β„•) (j : β„•), f i j := iSup_unpair (show β„• β†’ β„• β†’ Ξ±α΅’α΅ˆ from f) end CompleteLattice namespace Set theorem iUnion_unpair_prod {Ξ± Ξ²} {s : β„• β†’ Set Ξ±} {t : β„• β†’ Set Ξ²} : ⋃ n : β„•, s n.unpair.fst Γ—Λ’ t n.unpair.snd = (⋃ n, s n) Γ—Λ’ ⋃ n, t n := by rw [← Set.iUnion_prod] exact surjective_unpair.iUnion_comp (fun x => s x.fst Γ—Λ’ t x.snd) theorem iUnion_unpair {Ξ±} (f : β„• β†’ β„• β†’ Set Ξ±) : ⋃ n : β„•, f n.unpair.1 n.unpair.2 = ⋃ (i : β„•) (j : β„•), f i j := iSup_unpair f theorem iInter_unpair {Ξ±} (f : β„• β†’ β„• β†’ Set Ξ±) : β‹‚ n : β„•, f n.unpair.1 n.unpair.2 = β‹‚ (i : β„•) (j : β„•), f i j := iInf_unpair f end Set
.lake/packages/mathlib/Mathlib/Data/Nat/Lattice.lean
import Mathlib.Data.Set.Accumulate import Mathlib.Order.ConditionallyCompleteLattice.Finset import Mathlib.Order.Interval.Finset.Nat /-! # Conditionally complete linear order structure on `β„•` In this file we * define a `ConditionallyCompleteLinearOrderBot` structure on `β„•`; * prove a few lemmas about `iSup`/`iInf`/`Set.iUnion`/`Set.iInter` and natural numbers. -/ assert_not_exists MonoidWithZero open Set namespace Nat open scoped Classical in noncomputable instance : InfSet β„• := ⟨fun s ↦ if h : βˆƒ n, n ∈ s then @Nat.find (fun n ↦ n ∈ s) _ h else 0⟩ open scoped Classical in noncomputable instance : SupSet β„• := ⟨fun s ↦ if h : βˆƒ n, βˆ€ a ∈ s, a ≀ n then @Nat.find (fun n ↦ βˆ€ a ∈ s, a ≀ n) _ h else 0⟩ open scoped Classical in theorem sInf_def {s : Set β„•} (h : s.Nonempty) : sInf s = @Nat.find (fun n ↦ n ∈ s) _ h := dif_pos _ open scoped Classical in theorem sSup_def {s : Set β„•} (h : βˆƒ n, βˆ€ a ∈ s, a ≀ n) : sSup s = @Nat.find (fun n ↦ βˆ€ a ∈ s, a ≀ n) _ h := dif_pos _ theorem _root_.Set.Infinite.Nat.sSup_eq_zero {s : Set β„•} (h : s.Infinite) : sSup s = 0 := dif_neg fun ⟨n, hn⟩ ↦ let ⟨k, hks, hk⟩ := h.exists_gt n (hn k hks).not_gt hk @[simp] theorem sInf_eq_zero {s : Set β„•} : sInf s = 0 ↔ 0 ∈ s ∨ s = βˆ… := by cases eq_empty_or_nonempty s with | inl h => subst h simp only [or_true, InfSet.sInf, mem_empty_iff_false, exists_false, dif_neg, not_false_iff] | inr h => simp only [h.ne_empty, or_false, Nat.sInf_def, h, Nat.find_eq_zero] @[simp] theorem sInf_empty : sInf βˆ… = 0 := by rw [sInf_eq_zero] right rfl @[simp] theorem iInf_of_empty {ΞΉ : Sort*} [IsEmpty ΞΉ] (f : ΞΉ β†’ β„•) : iInf f = 0 := by rw [iInf_of_isEmpty, sInf_empty] /-- This combines `Nat.iInf_of_empty` with `ciInf_const`. -/ @[simp] lemma iInf_const_zero {ΞΉ : Sort*} : β¨… _ : ΞΉ, 0 = 0 := (isEmpty_or_nonempty ΞΉ).elim (fun h ↦ by simp) fun h ↦ sInf_eq_zero.2 <| by simp theorem sInf_mem {s : Set β„•} (h : s.Nonempty) : sInf s ∈ s := by classical rw [Nat.sInf_def h] exact Nat.find_spec h theorem notMem_of_lt_sInf {s : Set β„•} {m : β„•} (hm : m < sInf s) : m βˆ‰ s := by classical cases eq_empty_or_nonempty s with | inl h => subst h; apply notMem_empty | inr h => rw [Nat.sInf_def h] at hm; exact Nat.find_min h hm @[deprecated (since := "2025-05-23")] alias not_mem_of_lt_sInf := notMem_of_lt_sInf protected theorem sInf_le {s : Set β„•} {m : β„•} (hm : m ∈ s) : sInf s ≀ m := by classical rw [Nat.sInf_def ⟨m, hm⟩] exact Nat.find_min' ⟨m, hm⟩ hm theorem nonempty_of_pos_sInf {s : Set β„•} (h : 0 < sInf s) : s.Nonempty := by by_contra contra rw [Set.not_nonempty_iff_eq_empty] at contra have h' : sInf s β‰  0 := ne_of_gt h apply h' rw [Nat.sInf_eq_zero] right assumption theorem nonempty_of_sInf_eq_succ {s : Set β„•} {k : β„•} (h : sInf s = k + 1) : s.Nonempty := nonempty_of_pos_sInf (h.symm β–Έ succ_pos k : sInf s > 0) theorem eq_Ici_of_nonempty_of_upward_closed {s : Set β„•} (hs : s.Nonempty) (hs' : βˆ€ k₁ kβ‚‚ : β„•, k₁ ≀ kβ‚‚ β†’ k₁ ∈ s β†’ kβ‚‚ ∈ s) : s = Ici (sInf s) := ext fun n ↦ ⟨fun H ↦ Nat.sInf_le H, fun H ↦ hs' (sInf s) n H (sInf_mem hs)⟩ theorem sInf_upward_closed_eq_succ_iff {s : Set β„•} (hs : βˆ€ k₁ kβ‚‚ : β„•, k₁ ≀ kβ‚‚ β†’ k₁ ∈ s β†’ kβ‚‚ ∈ s) (k : β„•) : sInf s = k + 1 ↔ k + 1 ∈ s ∧ k βˆ‰ s := by classical constructor Β· intro H rw [eq_Ici_of_nonempty_of_upward_closed (nonempty_of_sInf_eq_succ _) hs, H, mem_Ici, mem_Ici] Β· exact ⟨le_rfl, k.not_succ_le_self⟩ Β· exact k Β· assumption Β· rintro ⟨H, H'⟩ rw [sInf_def (⟨_, H⟩ : s.Nonempty), find_eq_iff] exact ⟨H, fun n hnk hns ↦ H' <| hs n k (Nat.lt_succ_iff.mp hnk) hns⟩ /-- This instance is necessary, otherwise the lattice operations would be derived via `ConditionallyCompleteLinearOrderBot` and marked as noncomputable. -/ instance : Lattice β„• := LinearOrder.toLattice open scoped Classical in noncomputable instance : ConditionallyCompleteLinearOrderBot β„• := { (inferInstance : OrderBot β„•), (LinearOrder.toLattice : Lattice β„•), (inferInstance : LinearOrder β„•) with le_csSup := fun s a hb ha ↦ by rw [sSup_def hb]; revert a ha; exact @Nat.find_spec _ _ hb csSup_le := fun s a _ ha ↦ by rw [sSup_def ⟨a, ha⟩]; exact Nat.find_min' _ ha le_csInf := fun s a hs hb ↦ by rw [sInf_def hs]; exact hb (@Nat.find_spec (fun n ↦ n ∈ s) _ _) csInf_le := fun s a _ ha ↦ by rw [sInf_def ⟨a, ha⟩]; exact Nat.find_min' _ ha csSup_empty := by simp only [sSup_def, Set.mem_empty_iff_false, forall_const, forall_prop_of_false, not_false_iff, exists_const] apply bot_unique (Nat.find_min' _ _) trivial csSup_of_not_bddAbove := by intro s hs simp only [sSup, mem_empty_iff_false, IsEmpty.forall_iff, forall_const, exists_const, dite_true] rw [dif_neg] Β· exact le_antisymm (zero_le _) (find_le trivial) Β· exact hs csInf_of_not_bddBelow := fun s hs ↦ by simp at hs } theorem sSup_mem {s : Set β„•} (h₁ : s.Nonempty) (hβ‚‚ : BddAbove s) : sSup s ∈ s := let ⟨k, hk⟩ := hβ‚‚ h₁.csSup_mem ((finite_le_nat k).subset hk) theorem sInf_add {n : β„•} {p : β„• β†’ Prop} (hn : n ≀ sInf { m | p m }) : sInf { m | p (m + n) } + n = sInf { m | p m } := by classical obtain h | ⟨m, hm⟩ := { m | p (m + n) }.eq_empty_or_nonempty Β· rw [h, Nat.sInf_empty, zero_add] obtain hnp | hnp := hn.eq_or_lt Β· exact hnp suffices hp : p (sInf { m | p m } - n + n) from (h.subset hp).elim rw [Nat.sub_add_cancel hn] exact csInf_mem (nonempty_of_pos_sInf <| n.zero_le.trans_lt hnp) Β· have hp : βˆƒ n, n ∈ { m | p m } := ⟨_, hm⟩ rw [Nat.sInf_def ⟨m, hm⟩, Nat.sInf_def hp] rw [Nat.sInf_def hp] at hn exact find_add hn theorem sInf_add' {n : β„•} {p : β„• β†’ Prop} (h : 0 < sInf { m | p m }) : sInf { m | p m } + n = sInf { m | p (m - n) } := by suffices h₁ : n ≀ sInf {m | p (m - n)} by convert sInf_add h₁ simp_rw [Nat.add_sub_cancel_right] obtain ⟨m, hm⟩ := nonempty_of_pos_sInf h refine le_csInf ⟨m + n, ?_⟩ fun b hb ↦ le_of_not_gt fun hbn ↦ ne_of_mem_of_not_mem ?_ (notMem_of_lt_sInf h) (Nat.sub_eq_zero_of_le hbn.le) Β· dsimp rwa [Nat.add_sub_cancel_right] Β· exact hb section variable {Ξ± : Type*} [CompleteLattice Ξ±] theorem iSup_lt_succ (u : β„• β†’ Ξ±) (n : β„•) : ⨆ k < n + 1, u k = (⨆ k < n, u k) βŠ” u n := by simp_rw [Nat.lt_add_one_iff, biSup_le_eq_sup] theorem iSup_lt_succ' (u : β„• β†’ Ξ±) (n : β„•) : ⨆ k < n + 1, u k = u 0 βŠ” ⨆ k < n, u (k + 1) := by rw [← sup_iSup_nat_succ] simp theorem iInf_lt_succ (u : β„• β†’ Ξ±) (n : β„•) : β¨… k < n + 1, u k = (β¨… k < n, u k) βŠ“ u n := @iSup_lt_succ Ξ±α΅’α΅ˆ _ _ _ theorem iInf_lt_succ' (u : β„• β†’ Ξ±) (n : β„•) : β¨… k < n + 1, u k = u 0 βŠ“ β¨… k < n, u (k + 1) := @iSup_lt_succ' Ξ±α΅’α΅ˆ _ _ _ theorem iSup_le_succ (u : β„• β†’ Ξ±) (n : β„•) : ⨆ k ≀ n + 1, u k = (⨆ k ≀ n, u k) βŠ” u (n + 1) := by simp_rw [← Nat.lt_succ_iff, iSup_lt_succ] theorem iSup_le_succ' (u : β„• β†’ Ξ±) (n : β„•) : ⨆ k ≀ n + 1, u k = u 0 βŠ” ⨆ k ≀ n, u (k + 1) := by simp_rw [← Nat.lt_succ_iff, iSup_lt_succ'] theorem iInf_le_succ (u : β„• β†’ Ξ±) (n : β„•) : β¨… k ≀ n + 1, u k = (β¨… k ≀ n, u k) βŠ“ u (n + 1) := @iSup_le_succ Ξ±α΅’α΅ˆ _ _ _ theorem iInf_le_succ' (u : β„• β†’ Ξ±) (n : β„•) : β¨… k ≀ n + 1, u k = u 0 βŠ“ β¨… k ≀ n, u (k + 1) := @iSup_le_succ' Ξ±α΅’α΅ˆ _ _ _ end end Nat namespace Set variable {Ξ± : Type*} theorem biUnion_lt_succ (u : β„• β†’ Set Ξ±) (n : β„•) : ⋃ k < n + 1, u k = (⋃ k < n, u k) βˆͺ u n := Nat.iSup_lt_succ u n theorem biUnion_lt_succ' (u : β„• β†’ Set Ξ±) (n : β„•) : ⋃ k < n + 1, u k = u 0 βˆͺ ⋃ k < n, u (k + 1) := Nat.iSup_lt_succ' u n theorem biInter_lt_succ (u : β„• β†’ Set Ξ±) (n : β„•) : β‹‚ k < n + 1, u k = (β‹‚ k < n, u k) ∩ u n := Nat.iInf_lt_succ u n theorem biInter_lt_succ' (u : β„• β†’ Set Ξ±) (n : β„•) : β‹‚ k < n + 1, u k = u 0 ∩ β‹‚ k < n, u (k + 1) := Nat.iInf_lt_succ' u n theorem biUnion_le_succ (u : β„• β†’ Set Ξ±) (n : β„•) : ⋃ k ≀ n + 1, u k = (⋃ k ≀ n, u k) βˆͺ u (n + 1) := Nat.iSup_le_succ u n theorem biUnion_le_succ' (u : β„• β†’ Set Ξ±) (n : β„•) : ⋃ k ≀ n + 1, u k = u 0 βˆͺ ⋃ k ≀ n, u (k + 1) := Nat.iSup_le_succ' u n theorem biInter_le_succ (u : β„• β†’ Set Ξ±) (n : β„•) : β‹‚ k ≀ n + 1, u k = (β‹‚ k ≀ n, u k) ∩ u (n + 1) := Nat.iInf_le_succ u n theorem biInter_le_succ' (u : β„• β†’ Set Ξ±) (n : β„•) : β‹‚ k ≀ n + 1, u k = u 0 ∩ β‹‚ k ≀ n, u (k + 1) := Nat.iInf_le_succ' u n theorem accumulate_succ (u : β„• β†’ Set Ξ±) (n : β„•) : Accumulate u (n + 1) = Accumulate u n βˆͺ u (n + 1) := biUnion_le_succ u n end Set
.lake/packages/mathlib/Mathlib/Data/Nat/Log.lean
import Mathlib.Data.Nat.BinaryRec import Mathlib.Order.Interval.Set.Defs import Mathlib.Order.Monotone.Basic import Mathlib.Tactic.Bound.Attribute import Mathlib.Tactic.Contrapose import Mathlib.Tactic.Monotonicity.Attr /-! # Natural number logarithms This file defines two `β„•`-valued analogs of the logarithm of `n` with base `b`: * `log b n`: Lower logarithm, or floor **log**. Greatest `k` such that `b^k ≀ n`. * `clog b n`: Upper logarithm, or **c**eil **log**. Least `k` such that `n ≀ b^k`. These are interesting because, for `1 < b`, `Nat.log b` and `Nat.clog b` are respectively right and left adjoints of `Nat.pow b`. See `pow_le_iff_le_log` and `le_pow_iff_clog_le`. -/ assert_not_exists OrderTop namespace Nat /-! ### Floor logarithm -/ /-- `log b n`, is the logarithm of natural number `n` in base `b`. It returns the largest `k : β„•` such that `b^k ≀ n`, so if `b^k = n`, it returns exactly `k`. -/ @[pp_nodot] def log (b : β„•) : β„• β†’ β„• | n => if h : b ≀ n ∧ 1 < b then log b (n / b) + 1 else 0 decreasing_by -- putting this in the def triggers the `unusedHavesSuffices` linter: -- https://github.com/leanprover-community/batteries/issues/428 have : n / b < n := div_lt_self ((Nat.zero_lt_one.trans h.2).trans_le h.1) h.2 decreasing_trivial @[simp] theorem log_eq_zero_iff {b n : β„•} : log b n = 0 ↔ n < b ∨ b ≀ 1 := by rw [log, dite_eq_right_iff] simp only [Nat.add_eq_zero_iff, Nat.one_ne_zero, and_false, imp_false, not_and_or, not_le, not_lt] theorem log_of_lt {b n : β„•} (hb : n < b) : log b n = 0 := log_eq_zero_iff.2 (Or.inl hb) theorem log_of_left_le_one {b : β„•} (hb : b ≀ 1) (n) : log b n = 0 := log_eq_zero_iff.2 (Or.inr hb) @[simp] theorem log_pos_iff {b n : β„•} : 0 < log b n ↔ b ≀ n ∧ 1 < b := by rw [Nat.pos_iff_ne_zero, Ne, log_eq_zero_iff, not_or, not_lt, not_le] @[bound] theorem log_pos {b n : β„•} (hb : 1 < b) (hbn : b ≀ n) : 0 < log b n := log_pos_iff.2 ⟨hbn, hb⟩ theorem log_of_one_lt_of_le {b n : β„•} (h : 1 < b) (hn : b ≀ n) : log b n = log b (n / b) + 1 := by rw [log] exact if_pos ⟨hn, h⟩ @[simp] lemma log_zero_left : βˆ€ n, log 0 n = 0 := log_of_left_le_one <| Nat.zero_le _ @[simp] theorem log_zero_right (b : β„•) : log b 0 = 0 := log_eq_zero_iff.2 (le_total 1 b) @[simp] theorem log_one_left : βˆ€ n, log 1 n = 0 := log_of_left_le_one le_rfl @[simp] theorem log_one_right (b : β„•) : log b 1 = 0 := log_eq_zero_iff.2 (lt_or_ge _ _) /-- `pow b` and `log b` (almost) form a Galois connection. See also `Nat.pow_le_of_le_log` and `Nat.le_log_of_pow_le` for individual implications under weaker assumptions. -/ theorem le_log_iff_pow_le {b : β„•} (hb : 1 < b) {x y : β„•} (hy : y β‰  0) : x ≀ log b y ↔ b ^ x ≀ y := by induction y using Nat.strong_induction_on generalizing x with | h y ih => ?_ cases x with | zero => dsimp; cutsat | succ x => rw [log]; split_ifs with h Β· have b_pos : 0 < b := lt_of_succ_lt hb rw [Nat.add_le_add_iff_right, ih (y / b) (div_lt_self (Nat.pos_iff_ne_zero.2 hy) hb) (Nat.div_pos h.1 b_pos).ne', le_div_iff_mul_le b_pos, pow_succ', Nat.mul_comm] Β· exact iff_of_false (not_succ_le_zero _) (fun hby => h ⟨(le_self_pow x.succ_ne_zero _).trans hby, hb⟩) @[deprecated le_log_iff_pow_le (since := "2025-10-05")] theorem pow_le_iff_le_log {b : β„•} (hb : 1 < b) {x y : β„•} (hy : y β‰  0) : b ^ x ≀ y ↔ x ≀ log b y := (le_log_iff_pow_le hb hy).symm theorem log_lt_iff_lt_pow {b : β„•} (hb : 1 < b) {x y : β„•} (hy : y β‰  0) : log b y < x ↔ y < b ^ x := lt_iff_lt_of_le_iff_le (le_log_iff_pow_le hb hy) @[deprecated log_lt_iff_lt_pow (since := "2025-10-05")] theorem lt_pow_iff_log_lt {b : β„•} (hb : 1 < b) {x y : β„•} (hy : y β‰  0) : y < b ^ x ↔ log b y < x := (log_lt_iff_lt_pow hb hy).symm theorem pow_le_of_le_log {b x y : β„•} (hy : y β‰  0) (h : x ≀ log b y) : b ^ x ≀ y := by refine (le_or_gt b 1).elim (fun hb => ?_) fun hb => (le_log_iff_pow_le hb hy).1 h rw [log_of_left_le_one hb, Nat.le_zero] at h rwa [h, Nat.pow_zero, one_le_iff_ne_zero] theorem le_log_of_pow_le {b x y : β„•} (hb : 1 < b) (h : b ^ x ≀ y) : x ≀ log b y := by rcases ne_or_eq y 0 with (hy | rfl) exacts [(le_log_iff_pow_le hb hy).2 h, (h.not_gt (Nat.pow_pos (Nat.zero_lt_one.trans hb))).elim] theorem pow_log_le_self (b : β„•) {x : β„•} (hx : x β‰  0) : b ^ log b x ≀ x := pow_le_of_le_log hx le_rfl theorem log_lt_of_lt_pow {b x y : β„•} (hy : y β‰  0) : y < b ^ x β†’ log b y < x := lt_imp_lt_of_le_imp_le (pow_le_of_le_log hy) theorem lt_pow_of_log_lt {b x y : β„•} (hb : 1 < b) : log b y < x β†’ y < b ^ x := lt_imp_lt_of_le_imp_le (le_log_of_pow_le hb) lemma log_lt_self (b : β„•) {x : β„•} (hx : x β‰  0) : log b x < x := match le_or_gt b 1 with | .inl h => log_of_left_le_one h x β–Έ Nat.pos_iff_ne_zero.2 hx | .inr h => log_lt_of_lt_pow hx <| Nat.lt_pow_self h lemma log_le_self (b x : β„•) : log b x ≀ x := if hx : x = 0 then by simp [hx] else (log_lt_self b hx).le theorem lt_pow_succ_log_self {b : β„•} (hb : 1 < b) (x : β„•) : x < b ^ (log b x).succ := lt_pow_of_log_lt hb (lt_succ_self _) theorem log_eq_iff {b m n : β„•} (h : m β‰  0 ∨ 1 < b ∧ n β‰  0) : log b n = m ↔ b ^ m ≀ n ∧ n < b ^ (m + 1) := by rcases em (1 < b ∧ n β‰  0) with (⟨hb, hn⟩ | hbn) Β· rw [le_antisymm_iff, ← Nat.lt_succ_iff, le_log_iff_pow_le, log_lt_iff_lt_pow, and_comm] <;> assumption have hm : m β‰  0 := h.resolve_right hbn rw [not_and_or, not_lt, Ne, not_not] at hbn rcases hbn with (hb | rfl) Β· obtain rfl | rfl := le_one_iff_eq_zero_or_eq_one.1 hb any_goals simp only [ne_eq, lt_self_iff_false, not_lt_zero, false_and, or_false] at h simp [h, eq_comm (a := 0), Nat.zero_pow (Nat.pos_iff_ne_zero.2 _)] <;> omega Β· simp [@eq_comm _ 0, hm] theorem log_eq_of_pow_le_of_lt_pow {b m n : β„•} (h₁ : b ^ m ≀ n) (hβ‚‚ : n < b ^ (m + 1)) : log b n = m := by rcases eq_or_ne m 0 with (rfl | hm) Β· rw [Nat.pow_one] at hβ‚‚ exact log_of_lt hβ‚‚ Β· exact (log_eq_iff (Or.inl hm)).2 ⟨h₁, hβ‚‚βŸ© @[simp] theorem log_pow {b : β„•} (hb : 1 < b) (x : β„•) : log b (b ^ x) = x := log_eq_of_pow_le_of_lt_pow le_rfl (Nat.pow_lt_pow_right hb x.lt_succ_self) theorem log_eq_one_iff' {b n : β„•} : log b n = 1 ↔ b ≀ n ∧ n < b * b := by rw [log_eq_iff (Or.inl Nat.one_ne_zero), Nat.pow_add, Nat.pow_one] theorem log_eq_one_iff {b n : β„•} : log b n = 1 ↔ n < b * b ∧ 1 < b ∧ b ≀ n := log_eq_one_iff'.trans ⟨fun h => ⟨h.2, lt_mul_self_iff.1 (h.1.trans_lt h.2), h.1⟩, fun h => ⟨h.2.2, h.1⟩⟩ @[simp] theorem log_mul_base {b n : β„•} (hb : 1 < b) (hn : n β‰  0) : log b (n * b) = log b n + 1 := by apply log_eq_of_pow_le_of_lt_pow <;> rw [pow_succ', Nat.mul_comm b] exacts [Nat.mul_le_mul_right _ (pow_log_le_self _ hn), (Nat.mul_lt_mul_right (Nat.zero_lt_one.trans hb)).2 (lt_pow_succ_log_self hb _)] theorem pow_log_le_add_one (b : β„•) : βˆ€ x, b ^ log b x ≀ x + 1 | 0 => by rw [log_zero_right, Nat.pow_zero] | x + 1 => (pow_log_le_self b x.succ_ne_zero).trans (x + 1).le_succ theorem log_monotone {b : β„•} : Monotone (log b) := by refine monotone_nat_of_le_succ fun n => ?_ rcases le_or_gt b 1 with hb | hb Β· rw [log_of_left_le_one hb] exact zero_le _ Β· exact le_log_of_pow_le hb (pow_log_le_add_one _ _) @[mono, gcongr] theorem log_mono_right {b n m : β„•} (h : n ≀ m) : log b n ≀ log b m := log_monotone h theorem log_lt_log_succ_iff {b n : β„•} (hb : 1 < b) (hn : n β‰  0) : log b n < log b (n + 1) ↔ b ^ log b (n + 1) = n + 1 := by refine ⟨fun H ↦ ?_, fun H ↦ ?_⟩ Β· apply le_antisymm _ (Nat.lt_pow_of_log_lt hb H) exact Nat.pow_log_le_self b (Ne.symm (Nat.zero_ne_add_one n)) Β· apply Nat.log_lt_of_lt_pow hn simp [H] theorem log_eq_log_succ_iff {b n : β„•} (hb : 1 < b) (hn : n β‰  0) : log b n = log b (n + 1) ↔ b ^ log b (n + 1) β‰  n + 1 := by rw [ne_eq, ← log_lt_log_succ_iff hb hn, not_lt] simp only [le_antisymm_iff, and_iff_right_iff_imp] exact fun _ ↦ log_monotone (le_add_right n 1) theorem log_anti_left {b c n : β„•} (hc : 1 < c) (hb : c ≀ b) : log b n ≀ log c n := by rcases eq_or_ne n 0 with (rfl | hn); Β· rw [log_zero_right, log_zero_right] apply le_log_of_pow_le hc calc c ^ log b n ≀ b ^ log b n := Nat.pow_le_pow_left hb _ _ ≀ n := pow_log_le_self _ hn theorem log_antitone_left {n : β„•} : AntitoneOn (fun b => log b n) (Set.Ioi 1) := fun _ hc _ _ hb => log_anti_left (Set.mem_Iio.1 hc) hb @[gcongr, mono] theorem log_mono {b c m n : β„•} (hc : 1 < c) (hb : c ≀ b) (hmn : m ≀ n) : log b m ≀ log c n := (log_anti_left hc hb).trans <| by gcongr @[simp] theorem log_div_base (b n : β„•) : log b (n / b) = log b n - 1 := by rcases le_or_gt b 1 with hb | hb Β· rw [log_of_left_le_one hb, log_of_left_le_one hb, Nat.zero_sub] rcases lt_or_ge n b with h | h Β· rw [div_eq_of_lt h, log_of_lt h, log_zero_right] rw [log_of_one_lt_of_le hb h, Nat.add_sub_cancel_right] lemma log_div_base_pow (b n k : β„•) : log b (n / b ^ k) = log b n - k := by induction k with | zero => grind | succ k hk => rw [Nat.pow_succ, ← Nat.div_div_eq_div_mul, log_div_base, hk, sub_add_eq] @[simp] theorem log_div_mul_self (b n : β„•) : log b (n / b * b) = log b n := by rcases le_or_gt b 1 with hb | hb Β· rw [log_of_left_le_one hb, log_of_left_le_one hb] rcases lt_or_ge n b with h | h Β· rw [div_eq_of_lt h, Nat.zero_mul, log_zero_right, log_of_lt h] rw [log_mul_base hb (Nat.div_pos h (by cutsat)).ne', log_div_base, Nat.sub_add_cancel (succ_le_iff.2 <| log_pos hb h)] theorem add_pred_div_lt {b n : β„•} (hb : 1 < b) (hn : 2 ≀ n) : (n + b - 1) / b < n := by rw [div_lt_iff_lt_mul (by cutsat), ← succ_le_iff, ← pred_eq_sub_one, succ_pred_eq_of_pos (by cutsat)] exact Nat.add_le_mul hn hb lemma log_two_bit {b n} (hn : n β‰  0) : Nat.log 2 (n.bit b) = Nat.log 2 n + 1 := by rw [← log_div_mul_self, bit_div_two, log_mul_base Nat.one_lt_two hn] lemma log2_eq_log_two {n : β„•} : Nat.log2 n = Nat.log 2 n := by rcases eq_or_ne n 0 with rfl | hn Β· rw [log2_zero, log_zero_right] apply eq_of_forall_le_iff intro m rw [Nat.le_log2 hn, Nat.le_log_iff_pow_le Nat.one_lt_two hn] /-! ### Ceil logarithm -/ /-- `clog b n`, is the upper logarithm of natural number `n` in base `b`. It returns the smallest `k : β„•` such that `n ≀ b^k`, so if `b^k = n`, it returns exactly `k`. -/ @[pp_nodot] def clog (b : β„•) : β„• β†’ β„• | n => if h : 1 < b ∧ 1 < n then clog b ((n + b - 1) / b) + 1 else 0 decreasing_by -- putting this in the def triggers the `unusedHavesSuffices` linter: -- https://github.com/leanprover-community/batteries/issues/428 have : (n + b - 1) / b < n := add_pred_div_lt h.1 h.2 decreasing_trivial theorem clog_of_left_le_one {b : β„•} (hb : b ≀ 1) (n : β„•) : clog b n = 0 := by rw [clog, dif_neg fun h : 1 < b ∧ 1 < n => h.1.not_ge hb] theorem clog_of_right_le_one {n : β„•} (hn : n ≀ 1) (b : β„•) : clog b n = 0 := by rw [clog, dif_neg fun h : 1 < b ∧ 1 < n => h.2.not_ge hn] @[simp] lemma clog_zero_left (n : β„•) : clog 0 n = 0 := clog_of_left_le_one (Nat.zero_le _) _ @[simp] lemma clog_zero_right (b : β„•) : clog b 0 = 0 := clog_of_right_le_one (Nat.zero_le _) _ @[simp] theorem clog_one_left (n : β„•) : clog 1 n = 0 := clog_of_left_le_one le_rfl _ @[simp] theorem clog_one_right (b : β„•) : clog b 1 = 0 := clog_of_right_le_one le_rfl _ theorem clog_of_two_le {b n : β„•} (hb : 1 < b) (hn : 2 ≀ n) : clog b n = clog b ((n + b - 1) / b) + 1 := by rw [clog, dif_pos (⟨hb, hn⟩ : 1 < b ∧ 1 < n)] theorem clog_pos {b n : β„•} (hb : 1 < b) (hn : 2 ≀ n) : 0 < clog b n := by rw [clog_of_two_le hb hn] exact zero_lt_succ _ theorem clog_eq_one {b n : β„•} (hn : 2 ≀ n) (h : n ≀ b) : clog b n = 1 := by rw [clog_of_two_le (hn.trans h) hn, clog_of_right_le_one] rw [← Nat.lt_succ_iff, Nat.div_lt_iff_lt_mul] <;> omega /-- `clog b` and `pow b` form a Galois connection. -/ theorem clog_le_iff_le_pow {b : β„•} (hb : 1 < b) {x y : β„•} : clog b x ≀ y ↔ x ≀ b ^ y := by induction x using Nat.strong_induction_on generalizing y with | h x ih => ?_ cases y Β· rw [Nat.pow_zero] refine ⟨?_, fun h => (clog_of_right_le_one h b).le⟩ simp_rw [← not_lt] contrapose! exact clog_pos hb have b_pos : 0 < b := zero_lt_of_lt hb rw [clog]; split_ifs with h Β· rw [Nat.add_le_add_iff_right, ih ((x + b - 1) / b) (add_pred_div_lt hb h.2), Nat.div_le_iff_le_mul_add_pred b_pos, Nat.mul_comm b, ← Nat.pow_succ, Nat.add_sub_assoc (Nat.succ_le_of_lt b_pos), Nat.add_le_add_iff_right] Β· exact iff_of_true (zero_le _) ((not_lt.1 (not_and.1 h hb)).trans <| succ_le_of_lt <| Nat.pow_pos b_pos) @[deprecated clog_le_iff_le_pow (since := "2025-10-05")] theorem le_pow_iff_clog_le {b : β„•} (hb : 1 < b) {x y : β„•} : x ≀ b ^ y ↔ clog b x ≀ y := (clog_le_iff_le_pow hb).symm theorem lt_clog_iff_pow_lt {b : β„•} (hb : 1 < b) {x y : β„•} : y < clog b x ↔ b ^ y < x := lt_iff_lt_of_le_iff_le (clog_le_iff_le_pow hb) @[deprecated lt_clog_iff_pow_lt (since := "2025-10-05")] theorem pow_lt_iff_lt_clog {b : β„•} (hb : 1 < b) {x y : β„•} : b ^ y < x ↔ y < clog b x := (lt_clog_iff_pow_lt hb).symm @[simp] theorem clog_pow (b x : β„•) (hb : 1 < b) : clog b (b ^ x) = x := eq_of_forall_ge_iff fun z ↦ by rw [clog_le_iff_le_pow hb, Nat.pow_le_pow_iff_right hb] theorem pow_pred_clog_lt_self {b : β„•} (hb : 1 < b) {x : β„•} (hx : 1 < x) : b ^ (clog b x).pred < x := by rw [← lt_clog_iff_pow_lt hb] exact pred_lt (clog_pos hb hx).ne' theorem le_pow_clog {b : β„•} (hb : 1 < b) (x : β„•) : x ≀ b ^ clog b x := (clog_le_iff_le_pow hb).1 le_rfl @[mono, gcongr] theorem clog_mono_right (b : β„•) {n m : β„•} (h : n ≀ m) : clog b n ≀ clog b m := by rcases le_or_gt b 1 with hb | hb Β· rw [clog_of_left_le_one hb] exact zero_le _ Β· rw [clog_le_iff_le_pow hb] exact h.trans (le_pow_clog hb _) theorem clog_anti_left {b c n : β„•} (hc : 1 < c) (hb : c ≀ b) : clog b n ≀ clog c n := by rw [clog_le_iff_le_pow (lt_of_lt_of_le hc hb)] calc n ≀ c ^ clog c n := le_pow_clog hc _ _ ≀ b ^ clog c n := Nat.pow_le_pow_left hb _ theorem clog_monotone (b : β„•) : Monotone (clog b) := fun _ _ => clog_mono_right _ theorem clog_antitone_left {n : β„•} : AntitoneOn (fun b : β„• => clog b n) (Set.Ioi 1) := fun _ hc _ _ hb => clog_anti_left (Set.mem_Iio.1 hc) hb @[mono, gcongr] theorem clog_mono {b c m n : β„•} (hc : 1 < c) (hb : c ≀ b) (hmn : m ≀ n) : clog b m ≀ clog c n := (clog_anti_left hc hb).trans <| by gcongr @[simp] theorem log_le_clog (b n : β„•) : log b n ≀ clog b n := by obtain hb | hb := le_or_gt b 1 Β· rw [log_of_left_le_one hb] exact zero_le _ cases n with | zero => rw [log_zero_right] exact zero_le _ | succ n => exact (Nat.pow_le_pow_iff_right hb).1 ((pow_log_le_self b n.succ_ne_zero).trans <| le_pow_clog hb _) theorem clog_lt_clog_succ_iff {b n : β„•} (hb : 1 < b) : clog b n < clog b (n + 1) ↔ b ^ clog b n = n := by refine ⟨fun H ↦ ?_, fun H ↦ ?_⟩ Β· apply le_antisymm _ (le_pow_clog hb n) apply le_of_lt_succ exact (lt_clog_iff_pow_lt hb).mp H Β· rw [lt_clog_iff_pow_lt hb, H] exact n.lt_add_one theorem clog_eq_clog_succ_iff {b n : β„•} (hb : 1 < b) : clog b n = clog b (n + 1) ↔ b ^ clog b n β‰  n := by rw [ne_eq, ← clog_lt_clog_succ_iff hb, not_lt] simp only [le_antisymm_iff, and_iff_right_iff_imp] exact fun _ ↦ clog_monotone b (le_add_right n 1) /-! ### Computating the logarithm efficiently -/ section computation private lemma logC_aux {m b : β„•} (hb : 1 < b) (hbm : b ≀ m) : m / (b * b) < m / b := by have hb' : 0 < b := zero_lt_of_lt hb rw [div_lt_iff_lt_mul (Nat.mul_pos hb' hb'), ← Nat.mul_assoc, ← div_lt_iff_lt_mul hb'] exact (Nat.lt_mul_iff_one_lt_right (Nat.div_pos hbm hb')).2 hb /- The linter complains about `h : m < pw` being unused, but we need it in the `decreasing_by`. -/ set_option linter.unusedVariables false in /-- An alternate definition for `Nat.log` which computes more efficiently. For mathematical purposes, use `Nat.log` instead, and see `Nat.log_eq_logC`. Note a tail-recursive version of `Nat.log` is also possible: ``` def logTR (b n : β„•) : β„• := let rec go : β„• β†’ β„• β†’ β„• | n, acc => if h : b ≀ n ∧ 1 < b then go (n / b) (acc + 1) else acc decreasing_by have : n / b < n := Nat.div_lt_self (by omega) h.2 decreasing_trivial go n 0 ``` but performs worse for large numbers than `Nat.logC`: ``` #eval Nat.logTR 2 (2 ^ 1000000) #eval Nat.logC 2 (2 ^ 1000000) ``` The definition `Nat.logC` is not tail-recursive, however, but the stack limit will only be reached if the output size is around 2^10000, meaning the input will be around 2^(2^10000), which will take far too long to compute in the first place. Adapted from https://downloads.haskell.org/~ghc/9.0.1/docs/html/libraries/ghc-bignum-1.0/GHC-Num-BigNat.html#v:bigNatLogBase-35- -/ @[pp_nodot] def logC (b m : β„•) : β„• := if h : 1 < b then let (_, e) := step b h; e else 0 where /-- An auxiliary definition for `Nat.logC`, where the base of the logarithm is _squared_ in each loop. This allows significantly faster computation of the logarithm: it takes logarithmic time in the size of the output, rather than linear time. -/ step (pw : β„•) (hpw : 1 < pw) : β„• Γ— β„• := if h : m < pw then (m, 0) else let (q, e) := step (pw * pw) (Nat.mul_lt_mul_of_lt_of_lt hpw hpw) if q < pw then (q, 2 * e) else (q / pw, 2 * e + 1) termination_by m / pw decreasing_by have : m / (pw * pw) < m / pw := logC_aux hpw (le_of_not_gt h) decreasing_trivial private lemma logC_step {m pw q e : β„•} (hpw : 1 < pw) (hqe : logC.step m pw hpw = (q, e)) : pw ^ e * q ≀ m ∧ q < pw ∧ (m < pw ^ e * (q + 1)) ∧ (0 < m β†’ 0 < q) := by induction pw, hpw using logC.step.induct m generalizing q e with | case1 pw hpw hmpw => rw [logC.step, dif_pos hmpw] at hqe cases hqe simpa | case2 pw hpw hmpw q' e' hqe' hqpw ih => simp only [logC.step, dif_neg hmpw, hqe', if_pos hqpw] at hqe cases hqe rw [Nat.pow_mul, Nat.pow_two] exact ⟨(ih hqe').1, hqpw, (ih hqe').2.2⟩ | case3 pw hpw hmpw q' e' hqe' hqpw ih => simp only [Nat.logC.step, dif_neg hmpw, hqe', if_neg hqpw] at hqe cases hqe rw [Nat.pow_succ, Nat.mul_assoc, Nat.pow_mul, Nat.pow_two, Nat.mul_assoc] refine ⟨(ih hqe').1.trans' (Nat.mul_le_mul_left _ (Nat.mul_div_le _ _)), Nat.div_lt_of_lt_mul (ih hqe').2.1, (ih hqe').2.2.1.trans_le ?_, fun _ => Nat.div_pos (le_of_not_gt hqpw) (by cutsat)⟩ exact Nat.mul_le_mul_left _ (Nat.lt_mul_div_succ _ (zero_lt_of_lt hpw)) private lemma logC_spec {b m : β„•} (hb : 1 < b) (hm : 0 < m) : b ^ logC b m ≀ m ∧ m < b ^ (logC b m + 1) := by rw [logC, dif_pos hb] split next q e heq => obtain ⟨h₁, hβ‚‚, h₃, hβ‚„βŸ© := logC_step hb heq exact ⟨h₁.trans' (Nat.le_mul_of_pos_right _ (hβ‚„ hm)), h₃.trans_le (Nat.mul_le_mul_left _ hβ‚‚)⟩ private lemma logC_of_left_le_one {b m : β„•} (hb : b ≀ 1) : logC b m = 0 := by rw [logC, dif_neg hb.not_gt] private lemma logC_zero {b : β„•} : logC b 0 = 0 := by rcases le_or_gt b 1 with hb | hb case inl => exact logC_of_left_le_one hb case inr => rw [logC, dif_pos hb] split next q e heq => rw [logC.step, dif_pos (zero_lt_of_lt hb)] at heq rw [(Prod.mk.inj heq).2] /-- The result of `Nat.log` agrees with the result of `Nat.logC`. The latter will be computed more efficiently, but the former is easier to prove things about and has more lemmas. This lemma is tagged @[csimp] so that the code generated for `Nat.log` uses `Nat.logC` instead. -/ @[csimp] theorem log_eq_logC : log = logC := by ext b m rcases le_or_gt b 1 with hb | hb case inl => rw [logC_of_left_le_one hb, Nat.log_of_left_le_one hb] case inr => rcases eq_or_ne m 0 with rfl | hm case inl => rw [Nat.log_zero_right, logC_zero] case inr => rw [Nat.log_eq_iff (Or.inr ⟨hb, hm⟩)] exact logC_spec hb (zero_lt_of_ne_zero hm) end computation end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Upto.lean
import Mathlib.Algebra.Order.Group.Nat import Mathlib.Algebra.Order.Sub.Basic /-! # `Nat.Upto` `Nat.Upto p`, with `p` a predicate on `β„•`, is a subtype of elements `n : β„•` such that no value (strictly) below `n` satisfies `p`. This type has the property that `>` is well-founded when `βˆƒ i, p i`, which allows us to implement searches on `β„•`, starting at `0` and with an unknown upper-bound. It is similar to the well-founded relation constructed to define `Nat.find` with the difference that, in `Nat.Upto p`, `p` does not need to be decidable. In fact, `Nat.find` could be slightly altered to factor decidability out of its well-founded relation and would then fulfill the same purpose as this file. -/ namespace Nat /-- The subtype of natural numbers `i` which have the property that no `j` less than `i` satisfies `p`. This is an initial segment of the natural numbers, up to and including the first value satisfying `p`. We will be particularly interested in the case where there exists a value satisfying `p`, because in this case the `>` relation is well-founded. -/ abbrev Upto (p : β„• β†’ Prop) : Type := { i : β„• // βˆ€ j < i, Β¬p j } namespace Upto variable {p : β„• β†’ Prop} /-- Lift the "greater than" relation on natural numbers to `Nat.Upto`. -/ protected def GT (p) (x y : Upto p) : Prop := x.1 > y.1 instance : LT (Upto p) := ⟨fun x y => x.1 < y.1⟩ /-- The "greater than" relation on `Upto p` is well founded if (and only if) there exists a value satisfying `p`. -/ protected theorem wf : (βˆƒ x, p x) β†’ WellFounded (Upto.GT p) | ⟨x, h⟩ => by suffices Upto.GT p = InvImage (Β· < Β·) fun y : Nat.Upto p => x - y.val by rw [this] exact (measure _).wf ext ⟨a, ha⟩ ⟨b, _⟩ dsimp [InvImage, Upto.GT] rw [tsub_lt_tsub_iff_left_of_le (le_of_not_gt fun h' => ha _ h' h)] /-- Zero is always a member of `Nat.Upto p` because it has no predecessors. -/ def zero : Nat.Upto p := ⟨0, fun _ h => False.elim (Nat.not_lt_zero _ h)⟩ /-- The successor of `n` is in `Nat.Upto p` provided that `n` doesn't satisfy `p`. -/ def succ (x : Nat.Upto p) (h : Β¬p x.val) : Nat.Upto p := ⟨x.val.succ, fun j h' => by rcases Nat.lt_succ_iff_lt_or_eq.1 h' with (h' | rfl) <;> [exact x.2 _ h'; exact h]⟩ end Upto end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Find.lean
import Mathlib.Data.Nat.Basic import Mathlib.Tactic.Push import Batteries.WF /-! # `Nat.find` and `Nat.findGreatest` -/ variable {m n k : β„•} {p q : β„• β†’ Prop} namespace Nat section Find /-! ### `Nat.find` -/ private def lbp (m n : β„•) : Prop := m = n + 1 ∧ βˆ€ k ≀ n, Β¬p k variable [DecidablePred p] (H : βˆƒ n, p n) private def wf_lbp : WellFounded (@lbp p) := ⟨let ⟨n, pn⟩ := H suffices βˆ€ m k, n ≀ k + m β†’ Acc lbp k from fun _ => this _ _ (Nat.le_add_left _ _) fun m => Nat.recOn m (fun _ kn => ⟨_, fun y r => match y, r with | _, ⟨rfl, a⟩ => absurd pn (a _ kn)⟩) fun m IH k kn => ⟨_, fun y r => match y, r with | _, ⟨rfl, _a⟩ => IH _ (by rw [Nat.add_right_comm]; exact kn)⟩⟩ /-- Find the smallest `n` satisfying `p n`. Returns a subtype. -/ protected def findX : { n // p n ∧ βˆ€ m < n, Β¬p m } := @WellFounded.fix _ (fun k => (βˆ€ n < k, Β¬p n) β†’ { n // p n ∧ βˆ€ m < n, Β¬p m }) lbp (wf_lbp H) (fun m IH al => if pm : p m then ⟨m, pm, al⟩ else have : βˆ€ n ≀ m, Β¬p n := fun n h => Or.elim (Nat.lt_or_eq_of_le h) (al n) fun e => by rw [e]; exact pm IH _ ⟨rfl, this⟩ fun n h => this n <| Nat.le_of_succ_le_succ h) 0 fun _ h => absurd h (Nat.not_lt_zero _) /-- If `p` is a (decidable) predicate on `β„•` and `hp : βˆƒ (n : β„•), p n` is a proof that there exists some natural number satisfying `p`, then `Nat.find hp` is the smallest natural number satisfying `p`. Note that `Nat.find` is protected, meaning that you can't just write `find`, even if the `Nat` namespace is open. The API for `Nat.find` is: * `Nat.find_spec` is the proof that `Nat.find hp` satisfies `p`. * `Nat.find_min` is the proof that if `m < Nat.find hp` then `m` does not satisfy `p`. * `Nat.find_min'` is the proof that if `m` does satisfy `p` then `Nat.find hp ≀ m`. -/ protected def find : β„• := (Nat.findX H).1 protected theorem find_spec : p (Nat.find H) := (Nat.findX H).2.left grind_pattern Nat.find_spec => Nat.find H protected theorem find_min : βˆ€ {m : β„•}, m < Nat.find H β†’ Β¬p m := @(Nat.findX H).2.right protected theorem find_min' {m : β„•} (h : p m) : Nat.find H ≀ m := Nat.le_of_not_gt fun l => Nat.find_min H l h lemma find_eq_iff (h : βˆƒ n : β„•, p n) : Nat.find h = m ↔ p m ∧ βˆ€ n < m, Β¬p n := by constructor Β· grind [Nat.find_min] Β· rintro ⟨hm, hlt⟩ have := Nat.find_min' h hm grind @[simp] lemma find_lt_iff (h : βˆƒ n : β„•, p n) (n : β„•) : Nat.find h < n ↔ βˆƒ m < n, p m := ⟨fun h2 ↦ ⟨Nat.find h, h2, Nat.find_spec h⟩, fun ⟨_, hmn, hm⟩ ↦ Nat.lt_of_le_of_lt (Nat.find_min' h hm) hmn⟩ @[simp] lemma find_le_iff (h : βˆƒ n : β„•, p n) (n : β„•) : Nat.find h ≀ n ↔ βˆƒ m ≀ n, p m := by simp only [← Nat.lt_succ_iff, find_lt_iff] @[simp] lemma le_find_iff (h : βˆƒ n : β„•, p n) (n : β„•) : n ≀ Nat.find h ↔ βˆ€ m < n, Β¬p m := by simp only [← not_lt, find_lt_iff, not_exists, not_and] @[simp] lemma lt_find_iff (h : βˆƒ n : β„•, p n) (n : β„•) : n < Nat.find h ↔ βˆ€ m ≀ n, Β¬p m := by simp only [← succ_le_iff, le_find_iff, succ_le_succ_iff] @[simp] lemma find_eq_zero (h : βˆƒ n : β„•, p n) : Nat.find h = 0 ↔ p 0 := by simp [find_eq_iff] /-- If a predicate `q` holds at some `x` and implies `p` up to that `x`, then the earliest `xq` such that `q xq` is at least the smallest `xp` where `p xp`. The stronger version of `Nat.find_mono`, since this one needs implication only up to `Nat.find _` while the other requires `q` implying `p` everywhere. -/ lemma find_mono_of_le [DecidablePred q] {x : β„•} (hx : q x) (hpq : βˆ€ n ≀ x, q n β†’ p n) : Nat.find ⟨x, show p x from hpq _ le_rfl hx⟩ ≀ Nat.find ⟨x, hx⟩ := Nat.find_min' _ (hpq _ (Nat.find_min' _ hx) (Nat.find_spec ⟨x, hx⟩)) /-- A weak version of `Nat.find_mono_of_le`, requiring `q` implies `p` everywhere. -/ lemma find_mono [DecidablePred q] (h : βˆ€ n, q n β†’ p n) {hp : βˆƒ n, p n} {hq : βˆƒ n, q n} : Nat.find hp ≀ Nat.find hq := let ⟨_, hq⟩ := hq; find_mono_of_le hq fun _ _ ↦ h _ /-- If a predicate `p` holds at some `x` and agrees with `q` up to that `x`, then their `Nat.find` agree. The stronger version of `Nat.find_congr'`, since this one needs agreement only up to `Nat.find _` while the other requires `p = q`. Usage of this lemma will likely be via `obtain ⟨x, hx⟩ := hp; apply Nat.find_congr hx` to unify `q`, or provide it explicitly with `rw [Nat.find_congr (q := q) hx]`. -/ lemma find_congr [DecidablePred q] {x : β„•} (hx : p x) (hpq : βˆ€ n ≀ x, p n ↔ q n) : Nat.find ⟨x, hx⟩ = Nat.find ⟨x, show q x from hpq _ le_rfl |>.1 hx⟩ := le_antisymm (find_mono_of_le (hpq _ le_rfl |>.1 hx) fun _ h ↦ (hpq _ h).mpr) (find_mono_of_le hx fun _ h ↦ (hpq _ h).mp) /-- A weak version of `Nat.find_congr`, requiring `p = q` everywhere. -/ lemma find_congr' [DecidablePred q] {hp : βˆƒ n, p n} {hq : βˆƒ n, q n} (hpq : βˆ€ {n}, p n ↔ q n) : Nat.find hp = Nat.find hq := let ⟨_, hp⟩ := hp; find_congr hp fun _ _ ↦ hpq lemma find_le {h : βˆƒ n, p n} (hn : p n) : Nat.find h ≀ n := (Nat.find_le_iff _ _).2 ⟨n, le_refl _, hn⟩ lemma find_comp_succ (h₁ : βˆƒ n, p n) (hβ‚‚ : βˆƒ n, p (n + 1)) (h0 : Β¬p 0) : Nat.find h₁ = Nat.find hβ‚‚ + 1 := by refine (find_eq_iff _).2 ⟨Nat.find_spec hβ‚‚, fun n hn ↦ ?_⟩ cases n exacts [h0, @Nat.find_min (fun n ↦ p (n + 1)) _ hβ‚‚ _ (succ_lt_succ_iff.1 hn)] lemma find_pos (h : βˆƒ n : β„•, p n) : 0 < Nat.find h ↔ Β¬p 0 := Nat.pos_iff_ne_zero.trans (Nat.find_eq_zero _).not lemma find_add {hβ‚˜ : βˆƒ m, p (m + n)} {hβ‚™ : βˆƒ n, p n} (hn : n ≀ Nat.find hβ‚™) : Nat.find hβ‚˜ + n = Nat.find hβ‚™ := by refine le_antisymm ((le_find_iff _ _).2 fun m hm hpm => Nat.not_le.2 hm ?_) ?_ Β· have hnm : n ≀ m := le_trans hn (find_le hpm) refine Nat.add_le_of_le_sub hnm (find_le ?_) rwa [Nat.sub_add_cancel hnm] Β· rw [← Nat.sub_le_iff_le_add] refine (le_find_iff _ _).2 fun m hm hpm => Nat.not_le.2 hm ?_ rw [Nat.sub_le_iff_le_add] exact find_le hpm end Find /-! ### `Nat.findGreatest` -/ section FindGreatest /-- `Nat.findGreatest P n` is the largest `i ≀ n` such that `P i` holds, or `0` if no such `i` exists -/ def findGreatest (P : β„• β†’ Prop) [DecidablePred P] : β„• β†’ β„• | 0 => 0 | n + 1 => if P (n + 1) then n + 1 else Nat.findGreatest P n variable {P Q : β„• β†’ Prop} [DecidablePred P] {n : β„•} @[simp] lemma findGreatest_zero : Nat.findGreatest P 0 = 0 := rfl lemma findGreatest_succ (n : β„•) : Nat.findGreatest P (n + 1) = if P (n + 1) then n + 1 else Nat.findGreatest P n := rfl @[simp] lemma findGreatest_eq : βˆ€ {n}, P n β†’ Nat.findGreatest P n = n | 0, _ => rfl | n + 1, h => by simp [Nat.findGreatest, h] @[simp] lemma findGreatest_of_not (h : Β¬ P (n + 1)) : findGreatest P (n + 1) = findGreatest P n := by simp [Nat.findGreatest, h] lemma findGreatest_eq_iff : Nat.findGreatest P k = m ↔ m ≀ k ∧ (m β‰  0 β†’ P m) ∧ βˆ€ ⦃n⦄, m < n β†’ n ≀ k β†’ Β¬P n := by induction k generalizing m with | zero => rw [eq_comm, Iff.comm] simp only [Nat.le_zero, ne_eq, findGreatest_zero, and_iff_left_iff_imp] rintro rfl exact ⟨fun h ↦ (h rfl).elim, fun n hlt heq ↦ by cutsat⟩ | succ k ihk => by_cases hk : P (k + 1) Β· rw [findGreatest_eq hk] constructor Β· rintro rfl exact ⟨le_refl _, fun _ ↦ hk, fun n hlt hle ↦ by cutsat⟩ Β· rintro ⟨hle, h0, hm⟩ rcases Decidable.lt_or_eq_of_le hle with hlt | rfl exacts [(hm hlt (le_refl _) hk).elim, rfl] Β· rw [findGreatest_of_not hk, ihk] grind lemma findGreatest_eq_zero_iff : Nat.findGreatest P k = 0 ↔ βˆ€ ⦃n⦄, 0 < n β†’ n ≀ k β†’ Β¬P n := by simp [findGreatest_eq_iff] @[simp] lemma findGreatest_pos : 0 < Nat.findGreatest P k ↔ βˆƒ n, 0 < n ∧ n ≀ k ∧ P n := by rw [Nat.pos_iff_ne_zero, Ne, findGreatest_eq_zero_iff]; push_neg; rfl lemma findGreatest_spec (hmb : m ≀ n) (hm : P m) : P (Nat.findGreatest P n) := by by_cases h : Nat.findGreatest P n = 0 Β· cases m Β· rwa [h] exact ((findGreatest_eq_zero_iff.1 h) (zero_lt_succ _) hmb hm).elim Β· exact (findGreatest_eq_iff.1 rfl).2.1 h lemma findGreatest_le (n : β„•) : Nat.findGreatest P n ≀ n := (findGreatest_eq_iff.1 rfl).1 lemma le_findGreatest (hmb : m ≀ n) (hm : P m) : m ≀ Nat.findGreatest P n := le_of_not_gt fun hlt => (findGreatest_eq_iff.1 rfl).2.2 hlt hmb hm lemma findGreatest_mono_right (P : β„• β†’ Prop) [DecidablePred P] {m n} (hmn : m ≀ n) : Nat.findGreatest P m ≀ Nat.findGreatest P n := by induction hmn with | refl => simp | step hmk ih => rw [findGreatest_succ] split_ifs Β· exact le_trans ih <| le_trans (findGreatest_le _) (le_succ _) Β· exact ih lemma findGreatest_mono_left [DecidablePred Q] (hPQ : βˆ€ n, P n β†’ Q n) (n : β„•) : Nat.findGreatest P n ≀ Nat.findGreatest Q n := by induction n with | zero => rfl | succ n hn => by_cases h : P (n + 1) Β· rw [findGreatest_eq h, findGreatest_eq (hPQ _ h)] Β· rw [findGreatest_of_not h] exact le_trans hn (Nat.findGreatest_mono_right _ <| le_succ _) lemma findGreatest_mono [DecidablePred Q] (hPQ : βˆ€ n, P n β†’ Q n) (hmn : m ≀ n) : Nat.findGreatest P m ≀ Nat.findGreatest Q n := le_trans (Nat.findGreatest_mono_right _ hmn) (findGreatest_mono_left hPQ _) theorem findGreatest_is_greatest (hk : Nat.findGreatest P n < k) (hkb : k ≀ n) : Β¬P k := (findGreatest_eq_iff.1 rfl).2.2 hk hkb theorem findGreatest_of_ne_zero (h : Nat.findGreatest P n = m) (h0 : m β‰  0) : P m := (findGreatest_eq_iff.1 h).2.1 h0 end FindGreatest end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/NthRoot/Defs.lean
import Mathlib.Init /-! # Definition of `Nat.nthRoot` In this file we define `Nat.nthRoot n a` to be the floor of the `n`th root of `a`. The function is defined in terms of natural numbers with no dependencies outside of prelude. -/ /-- `Nat.nthRoot n a = ⌊(a : ℝ) ^ (1 / n : ℝ)βŒ‹β‚Š` defined in terms of natural numbers. We use Newton's method to find a root of $x^n = a$, so it converges superexponentially fast. -/ def Nat.nthRoot : Nat β†’ Nat β†’ Nat | 0, _ => 1 | 1, a => a | n + 2, a => go n a a a where /-- Auxiliary definition for `Nat.nthRoot`. Given natural numbers `n`, `a`, `fuel`, `guess` such that `⌊(a : ℝ) ^ (1 / (n + 2) : ℝ)βŒ‹β‚Š ≀ guess ≀ fuel`, returns `⌊(a : ℝ) ^ (1 / (n + 2) : ℝ)βŒ‹β‚Š`. The auxiliary number `guess` is the current approximation in Newton's method, tracked in the arguments so that the definition uses a tail recursion which is unfolded into a loop by the compiler. The auxiliary number `fuel` is an upper estimate on the number of steps in Newton's method. Any number `fuel β‰₯ guess` is guaranteed to work, but smaller numbers may work as well. If `fuel` is too small, then `Nat.nthRoot.go` returns the result of the `fuel`th step of Newton's method. -/ go (n a : Nat) | 0, guess => guess | fuel + 1, guess => let next := (a / guess ^ (n + 1) + (n + 1) * guess) / (n + 2) if next < guess then go n a fuel next else guess
.lake/packages/mathlib/Mathlib/Data/Nat/Order/Lemmas.lean
import Mathlib.Data.Nat.Find import Mathlib.Data.Set.Basic import Mathlib.Tactic.ByContra /-! # Further lemmas about the natural numbers The distinction between this file and `Mathlib/Algebra/Order/Ring/Nat.lean` is not particularly clear. They were separated for now to minimize the porting requirements for tactics during the transition to mathlib4. Please feel free to reorganize these two files. -/ assert_not_exists RelIso namespace Nat /-! ### Sets -/ instance Subtype.orderBot (s : Set β„•) [DecidablePred (Β· ∈ s)] [h : Nonempty s] : OrderBot s where bot := ⟨Nat.find (nonempty_subtype.1 h), Nat.find_spec (nonempty_subtype.1 h)⟩ bot_le x := Nat.find_min' _ x.2 instance Subtype.semilatticeSup (s : Set β„•) : SemilatticeSup s := { Subtype.instLinearOrder s, LinearOrder.toLattice with } theorem Subtype.coe_bot {s : Set β„•} [DecidablePred (Β· ∈ s)] [h : Nonempty s] : ((βŠ₯ : s) : β„•) = Nat.find (nonempty_subtype.1 h) := rfl theorem set_eq_univ {S : Set β„•} : S = Set.univ ↔ 0 ∈ S ∧ βˆ€ k : β„•, k ∈ S β†’ k + 1 ∈ S := ⟨by rintro rfl; simp, fun ⟨h0, hs⟩ => Set.eq_univ_of_forall (set_induction h0 hs)⟩ lemma exists_not_and_succ_of_not_zero_of_exists {p : β„• β†’ Prop} (H' : Β¬ p 0) (H : βˆƒ n, p n) : βˆƒ n, Β¬ p n ∧ p (n + 1) := by classical let k := Nat.find H have hk : p k := Nat.find_spec H suffices 0 < k from ⟨k - 1, Nat.find_min H <| Nat.pred_lt this.ne', by rwa [Nat.sub_add_cancel this]⟩ by_contra! contra rw [le_zero_eq] at contra exact H' (contra β–Έ hk) end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Choose/Sum.lean
import Mathlib.Algebra.BigOperators.Intervals import Mathlib.Algebra.BigOperators.NatAntidiagonal import Mathlib.Algebra.BigOperators.Ring.Finset import Mathlib.Algebra.Order.BigOperators.Group.Finset import Mathlib.Tactic.Linarith import Mathlib.Tactic.Ring /-! # Sums of binomial coefficients This file includes variants of the binomial theorem and other results on sums of binomial coefficients. Theorems whose proofs depend on such sums may also go in this file for import reasons. -/ open Nat Finset variable {R : Type*} namespace Commute variable [Semiring R] {x y : R} /-- A version of the **binomial theorem** for commuting elements in noncommutative semirings. -/ theorem add_pow (h : Commute x y) (n : β„•) : (x + y) ^ n = βˆ‘ m ∈ range (n + 1), x ^ m * y ^ (n - m) * n.choose m := by let t : β„• β†’ β„• β†’ R := fun n m ↦ x ^ m * y ^ (n - m) * n.choose m change (x + y) ^ n = βˆ‘ m ∈ range (n + 1), t n m have h_first : βˆ€ n, t n 0 = y ^ n := fun n ↦ by simp only [t, choose_zero_right, pow_zero, cast_one, mul_one, one_mul, tsub_zero] have h_last : βˆ€ n, t n n.succ = 0 := fun n ↦ by simp only [t, choose_succ_self, cast_zero, mul_zero] have h_middle : βˆ€ n i : β„•, i ∈ range n.succ β†’ (t n.succ i.succ) = x * t n i + y * t n i.succ := by intro n i h_mem have h_le : i ≀ n := le_of_lt_succ (mem_range.mp h_mem) dsimp only [t] rw [choose_succ_succ, cast_add, mul_add] congr 1 Β· rw [pow_succ' x, succ_sub_succ, mul_assoc, mul_assoc, mul_assoc] Β· rw [← mul_assoc y, ← mul_assoc y, (h.symm.pow_right i.succ).eq] by_cases h_eq : i = n Β· rw [h_eq, choose_succ_self, cast_zero, mul_zero, mul_zero] Β· rw [succ_sub (lt_of_le_of_ne h_le h_eq)] rw [pow_succ' y, mul_assoc, mul_assoc, mul_assoc, mul_assoc] induction n with | zero => rw [pow_zero, sum_range_succ, range_zero, sum_empty, zero_add] dsimp only [t] rw [pow_zero, pow_zero, choose_self, cast_one, mul_one, mul_one] | succ n ih => rw [sum_range_succ', h_first, sum_congr rfl (h_middle n), sum_add_distrib, add_assoc, pow_succ' (x + y), ih, add_mul, mul_sum, mul_sum] congr 1 rw [sum_range_succ', sum_range_succ, h_first, h_last, mul_zero, add_zero, _root_.pow_succ'] /-- A version of `Commute.add_pow` that avoids β„•-subtraction by summing over the antidiagonal and also with the binomial coefficient applied via scalar action of β„•. -/ theorem add_pow' (h : Commute x y) (n : β„•) : (x + y) ^ n = βˆ‘ m ∈ antidiagonal n, n.choose m.1 β€’ (x ^ m.1 * y ^ m.2) := by simp_rw [Nat.sum_antidiagonal_eq_sum_range_succ fun m p ↦ n.choose m β€’ (x ^ m * y ^ p), nsmul_eq_mul, cast_comm, h.add_pow] end Commute /-- The **binomial theorem** -/ theorem add_pow [CommSemiring R] (x y : R) (n : β„•) : (x + y) ^ n = βˆ‘ m ∈ range (n + 1), x ^ m * y ^ (n - m) * n.choose m := (Commute.all x y).add_pow n /-- A special case of the **binomial theorem** -/ theorem sub_pow [CommRing R] (x y : R) (n : β„•) : (x - y) ^ n = βˆ‘ m ∈ range (n + 1), (-1) ^ (m + n) * x ^ m * y ^ (n - m) * n.choose m := by rw [sub_eq_add_neg, add_pow] congr! 1 with m hm have : (-1 : R) ^ (n - m) = (-1) ^ (n + m) := by rw [mem_range] at hm simp [show n + m = n - m + 2 * m by cutsat, pow_add] rw [neg_pow, this] ring namespace Nat /-- The sum of entries in a row of Pascal's triangle -/ theorem sum_range_choose (n : β„•) : (βˆ‘ m ∈ range (n + 1), n.choose m) = 2 ^ n := by have := (add_pow 1 1 n).symm simpa [one_add_one_eq_two] using this theorem sum_range_choose_halfway (m : β„•) : (βˆ‘ i ∈ range (m + 1), (2 * m + 1).choose i) = 4 ^ m := have : (βˆ‘ i ∈ range (m + 1), (2 * m + 1).choose (2 * m + 1 - i)) = βˆ‘ i ∈ range (m + 1), (2 * m + 1).choose i := sum_congr rfl fun i hi ↦ choose_symm <| by linarith [mem_range.1 hi] mul_right_injectiveβ‚€ two_ne_zero <| calc (2 * βˆ‘ i ∈ range (m + 1), (2 * m + 1).choose i) = (βˆ‘ i ∈ range (m + 1), (2 * m + 1).choose i) + βˆ‘ i ∈ range (m + 1), (2 * m + 1).choose (2 * m + 1 - i) := by rw [two_mul, this] _ = (βˆ‘ i ∈ range (m + 1), (2 * m + 1).choose i) + βˆ‘ i ∈ Ico (m + 1) (2 * m + 2), (2 * m + 1).choose i := by rw [range_eq_Ico, sum_Ico_reflect _ _ (by cutsat)] congr cutsat _ = βˆ‘ i ∈ range (2 * m + 2), (2 * m + 1).choose i := sum_range_add_sum_Ico _ (by cutsat) _ = 2 ^ (2 * m + 1) := sum_range_choose (2 * m + 1) _ = 2 * 4 ^ m := by rw [pow_succ, pow_mul, mul_comm]; rfl theorem choose_middle_le_pow (n : β„•) : (2 * n + 1).choose n ≀ 4 ^ n := by have t : (2 * n + 1).choose n ≀ βˆ‘ i ∈ range (n + 1), (2 * n + 1).choose i := single_le_sum (fun x _ ↦ by cutsat) (self_mem_range_succ n) simpa [sum_range_choose_halfway n] using t theorem four_pow_le_two_mul_add_one_mul_central_binom (n : β„•) : 4 ^ n ≀ (2 * n + 1) * (2 * n).choose n := calc 4 ^ n = (1 + 1) ^ (2 * n) := by simp [pow_mul] _ = βˆ‘ m ∈ range (2 * n + 1), (2 * n).choose m := by simp [-Nat.reduceAdd, add_pow] _ ≀ βˆ‘ _ ∈ range (2 * n + 1), (2 * n).choose (2 * n / 2) := by gcongr; apply choose_le_middle _ = (2 * n + 1) * choose (2 * n) n := by simp /-- **Zhu Shijie's identity** aka hockey-stick identity, version with `Icc`. -/ theorem sum_Icc_choose (n k : β„•) : βˆ‘ m ∈ Icc k n, m.choose k = (n + 1).choose (k + 1) := by rcases lt_or_ge n k with h | h Β· rw [choose_eq_zero_of_lt (by cutsat), Icc_eq_empty_of_lt h, sum_empty] Β· induction n, h using le_induction with | base => simp | succ n _ ih => rw [← Ico_insert_right (by cutsat), sum_insert (by simp), Ico_add_one_right_eq_Icc, ih, choose_succ_succ' (n + 1)] /-- **Zhu Shijie's identity** aka hockey-stick identity, version with `range`. Summing `(i + k).choose k` for `i ∈ [0, n]` gives `(n + k + 1).choose (k + 1)`. Combinatorial interpretation: `(i + k).choose k` is the number of decompositions of `[0, i)` in `k + 1` (possibly empty) intervals (this follows from a stars and bars description). In particular, `(n + k + 1).choose (k + 1)` corresponds to decomposing `[0, n)` into `k + 2` intervals. By putting away the last interval (of some length `n - i`), we have to decompose the remaining interval `[0, i)` into `k + 1` intervals, hence the sum. -/ lemma sum_range_add_choose (n k : β„•) : βˆ‘ i ∈ Finset.range (n + 1), (i + k).choose k = (n + k + 1).choose (k + 1) := by rw [← sum_Icc_choose, range_eq_Ico] convert (sum_map _ (addRightEmbedding k) (Β·.choose k)).symm using 2 rw [map_add_right_Ico, zero_add, add_right_comm, Ico_add_one_right_eq_Icc] end Nat theorem Int.alternating_sum_range_choose {n : β„•} : (βˆ‘ m ∈ range (n + 1), ((-1) ^ m * n.choose m : β„€)) = if n = 0 then 1 else 0 := by cases n with | zero => simp | succ n => have h := add_pow (-1 : β„€) 1 n.succ simp only [one_pow, mul_one, neg_add_cancel] at h rw [← h, zero_pow n.succ_ne_zero, if_neg n.succ_ne_zero] theorem Int.alternating_sum_range_choose_of_ne {n : β„•} (h0 : n β‰  0) : (βˆ‘ m ∈ range (n + 1), ((-1) ^ m * n.choose m : β„€)) = 0 := by rw [Int.alternating_sum_range_choose, if_neg h0] namespace Finset theorem sum_powerset_apply_card {Ξ± Ξ² : Type*} [AddCommMonoid Ξ±] (f : β„• β†’ Ξ±) {x : Finset Ξ²} : βˆ‘ m ∈ x.powerset, f #m = βˆ‘ m ∈ range (#x + 1), (#x).choose m β€’ f m := by trans βˆ‘ m ∈ range (#x + 1), βˆ‘ j ∈ x.powerset with #j = m, f #j Β· refine (sum_fiberwise_of_maps_to ?_ _).symm intro y hy rw [mem_range, Nat.lt_succ_iff] rw [mem_powerset] at hy exact card_le_card hy Β· refine sum_congr rfl fun y _ ↦ ?_ rw [← card_powersetCard, ← sum_const] refine sum_congr powersetCard_eq_filter.symm fun z hz ↦ ?_ rw [(mem_powersetCard.1 hz).2] theorem sum_powerset_neg_one_pow_card {Ξ± : Type*} [DecidableEq Ξ±] {x : Finset Ξ±} : (βˆ‘ m ∈ x.powerset, (-1 : β„€) ^ #m) = if x = βˆ… then 1 else 0 := by rw [sum_powerset_apply_card] simp only [nsmul_eq_mul', ← card_eq_zero, Int.alternating_sum_range_choose] theorem sum_powerset_neg_one_pow_card_of_nonempty {Ξ± : Type*} {x : Finset Ξ±} (h0 : x.Nonempty) : (βˆ‘ m ∈ x.powerset, (-1 : β„€) ^ #m) = 0 := by classical rw [sum_powerset_neg_one_pow_card] exact if_neg (nonempty_iff_ne_empty.mp h0) variable [NonAssocSemiring R] @[to_additive sum_choose_succ_nsmul] theorem prod_pow_choose_succ {M : Type*} [CommMonoid M] (f : β„• β†’ β„• β†’ M) (n : β„•) : (∏ i ∈ range (n + 2), f i (n + 1 - i) ^ (n + 1).choose i) = (∏ i ∈ range (n + 1), f i (n + 1 - i) ^ n.choose i) * ∏ i ∈ range (n + 1), f (i + 1) (n - i) ^ n.choose i := by have A : (∏ i ∈ range (n + 1), f (i + 1) (n - i) ^ (n.choose (i + 1))) * f 0 (n + 1) = ∏ i ∈ range (n + 1), f i (n + 1 - i) ^ (n.choose i) := by rw [prod_range_succ, prod_range_succ']; simp rw [prod_range_succ'] simpa [choose_succ_succ, pow_add, prod_mul_distrib, A, mul_assoc] using mul_comm _ _ @[to_additive sum_antidiagonal_choose_succ_nsmul] theorem prod_antidiagonal_pow_choose_succ {M : Type*} [CommMonoid M] (f : β„• β†’ β„• β†’ M) (n : β„•) : (∏ ij ∈ antidiagonal (n + 1), f ij.1 ij.2 ^ (n + 1).choose ij.1) = (∏ ij ∈ antidiagonal n, f ij.1 (ij.2 + 1) ^ n.choose ij.1) * ∏ ij ∈ antidiagonal n, f (ij.1 + 1) ij.2 ^ n.choose ij.2 := by simp only [Nat.prod_antidiagonal_eq_prod_range_succ_mk, prod_pow_choose_succ] have : βˆ€ i ∈ range (n + 1), i ≀ n := fun i hi ↦ by simpa [Nat.lt_succ_iff] using hi congr 1 Β· refine prod_congr rfl fun i hi ↦ ?_ rw [tsub_add_eq_add_tsub (this _ hi)] Β· refine prod_congr rfl fun i hi ↦ ?_ rw [choose_symm (this _ hi)] /-- The sum of `(n+1).choose i * f i (n+1-i)` can be split into two sums at rank `n`, respectively of `n.choose i * f i (n+1-i)` and `n.choose i * f (i+1) (n-i)`. -/ theorem sum_choose_succ_mul (f : β„• β†’ β„• β†’ R) (n : β„•) : (βˆ‘ i ∈ range (n + 2), ((n + 1).choose i : R) * f i (n + 1 - i)) = (βˆ‘ i ∈ range (n + 1), (n.choose i : R) * f i (n + 1 - i)) + βˆ‘ i ∈ range (n + 1), (n.choose i : R) * f (i + 1) (n - i) := by simpa only [nsmul_eq_mul] using sum_choose_succ_nsmul f n /-- The sum along the antidiagonal of `(n+1).choose i * f i j` can be split into two sums along the antidiagonal at rank `n`, respectively of `n.choose i * f i (j+1)` and `n.choose j * f (i+1) j`. -/ theorem sum_antidiagonal_choose_succ_mul (f : β„• β†’ β„• β†’ R) (n : β„•) : (βˆ‘ ij ∈ antidiagonal (n + 1), ((n + 1).choose ij.1 : R) * f ij.1 ij.2) = (βˆ‘ ij ∈ antidiagonal n, (n.choose ij.1 : R) * f ij.1 (ij.2 + 1)) + βˆ‘ ij ∈ antidiagonal n, (n.choose ij.2 : R) * f (ij.1 + 1) ij.2 := by simpa only [nsmul_eq_mul] using sum_antidiagonal_choose_succ_nsmul f n theorem sum_antidiagonal_choose_add (d n : β„•) : (βˆ‘ ij ∈ antidiagonal n, (d + ij.2).choose d) = (d + n + 1).choose (d + 1) := by induction n with | zero => simp | succ n hn => rw [Nat.sum_antidiagonal_succ, hn, Nat.choose_succ_succ (d + (n + 1)), ← add_assoc] end Finset
.lake/packages/mathlib/Mathlib/Data/Nat/Choose/Dvd.lean
import Mathlib.Data.Nat.Choose.Basic import Mathlib.Data.Nat.Prime.Factorial /-! # Divisibility properties of binomial coefficients -/ namespace Nat namespace Prime variable {p a b k : β„•} theorem dvd_choose_add (hp : Prime p) (hap : a < p) (hbp : b < p) (h : p ≀ a + b) : p ∣ choose (a + b) a := by have h₁ : p ∣ (a + b)! := hp.dvd_factorial.2 h rw [← add_choose_mul_factorial_mul_factorial, ← choose_symm_add, hp.dvd_mul, hp.dvd_mul, hp.dvd_factorial, hp.dvd_factorial] at h₁ exact (h₁.resolve_right hbp.not_ge).resolve_right hap.not_ge lemma dvd_choose (hp : Prime p) (ha : a < p) (hab : b - a < p) (h : p ≀ b) : p ∣ choose b a := have : a + (b - a) = b := Nat.add_sub_of_le (ha.le.trans h) this β–Έ hp.dvd_choose_add ha hab (this.symm β–Έ h) lemma dvd_choose_self (hp : Prime p) (hk : k β‰  0) (hkp : k < p) : p ∣ choose p k := hp.dvd_choose hkp (sub_lt ((zero_le _).trans_lt hkp) <| zero_lt_of_ne_zero hk) le_rfl lemma coprime_choose_of_lt (hp : p.Prime) (hb : b < p) (ha : a ≀ b) : p.Coprime (b.choose a) := by rw [Nat.choose_eq_descFactorial_div_factorial] exact (hp.coprime_descFactorial_of_lt_of_le hb ha).coprime_div_right (Nat.factorial_dvd_descFactorial b a) end Prime end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Choose/Mul.lean
import Mathlib.Data.Nat.Choose.Basic import Mathlib.Tactic.Ring.RingNF /-! # Two lemmas on choose The proofs of these lemmas use the `ring` tactic and can't be given in `Mathlib/Data/Nat/Choose/Basic.lean` -/ namespace Nat theorem choose_mul_add {m n : β„•} (hn : n β‰  0) : (m * n + n).choose n = (m + 1) * (m * n + n - 1).choose (n - 1) := by rw [← Nat.mul_left_inj (mul_ne_zero (factorial_ne_zero (m * n)) (factorial_ne_zero n))] set p := n - 1 have hp : n = p + 1 := (succ_pred_eq_of_ne_zero hn).symm simp only [hp, add_succ_sub_one] calc (m * (p + 1) + (p + 1)).choose (p + 1) * ((m * (p + 1))! * (p + 1)!) = (m * (p + 1) + (p + 1)).choose (p + 1) * (m * (p + 1))! * (p + 1)! := by ring _ = (m * (p + 1) + (p + 1))! := by rw [add_choose_mul_factorial_mul_factorial] _ = ((m * (p + 1) + p) + 1)! := by ring_nf _ = ((m * (p + 1) + p) + 1) * (m * (p + 1) + p)! := by rw [factorial_succ] _ = (m * (p + 1) + p)! * ((p + 1) * (m + 1)) := by ring _ = ((m * (p + 1) + p).choose p * (m * (p + 1))! * (p)!) * ((p + 1) * (m + 1)) := by rw [add_choose_mul_factorial_mul_factorial] _ = (m * (p + 1) + p).choose p * (m * (p + 1))! * (((p + 1) * (p)!) * (m + 1)) := by ring _ = (m * (p + 1) + p).choose p * (m * (p + 1))! * ((p + 1)! * (m + 1)) := by rw [factorial_succ] _ = (m + 1) * (m * (p + 1) + p).choose p * ((m * (p + 1))! * (p + 1)!) := by ring theorem choose_mul_right {m n : β„•} (hn : n β‰  0) : (m * n).choose n = m * (m * n - 1).choose (n - 1) := by by_cases hm : m = 0 Β· simp only [hm, zero_mul, choose_eq_zero_iff] exact Nat.pos_of_ne_zero hn Β· set p := m - 1; have hp : m = p + 1 := (succ_pred_eq_of_ne_zero hm).symm simp only [hp] rw [add_mul, one_mul, choose_mul_add hn] end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Choose/Basic.lean
import Mathlib.Data.Nat.Factorial.Basic import Mathlib.Order.Monotone.Defs /-! # Binomial coefficients This file defines binomial coefficients and proves simple lemmas (i.e. those not requiring more imports). For the lemma that `n.choose k` counts the `k`-element-subsets of an `n`-element set, see `Fintype.card_powersetCard` in `Mathlib/Data/Finset/Powerset.lean`. ## Main definition and results * `Nat.choose`: binomial coefficients, defined inductively * `Nat.choose_eq_factorial_div_factorial`: a proof that `choose n k = n! / (k! * (n - k)!)` * `Nat.choose_symm`: symmetry of binomial coefficients * `Nat.choose_le_succ_of_lt_half_left`: `choose n k` is increasing for small values of `k` * `Nat.choose_le_middle`: `choose n r` is maximised when `r` is `n/2` * `Nat.descFactorial_eq_factorial_mul_choose`: Relates binomial coefficients to the descending factorial. This is used to prove `Nat.choose_le_pow` and variants. We provide similar statements for the ascending factorial. * `Nat.multichoose`: whereas `choose` counts combinations, `multichoose` counts multicombinations. The fact that this is indeed the correct counting function for multisets is proved in `Sym.card_sym_eq_multichoose` in `Data.Sym.Card`. * `Nat.multichoose_eq` : a proof that `multichoose n k = (n + k - 1).choose k`. This is central to the "stars and bars" technique in informal mathematics, where we switch between counting multisets of size `k` over an alphabet of size `n` to counting strings of `k` elements ("stars") separated by `n-1` dividers ("bars"). See `Data.Sym.Card` for more detail. ## Tags binomial coefficient, combination, multicombination, stars and bars -/ namespace Nat /-- `choose n k` is the number of `k`-element subsets in an `n`-element set. Also known as binomial coefficients. For the fact that this is the number of `k`-element-subsets of an `n`-element set, see `Fintype.card_powersetCard`. -/ def choose : β„• β†’ β„• β†’ β„• | _, 0 => 1 | 0, _ + 1 => 0 | n + 1, k + 1 => choose n k + choose n (k + 1) @[simp] theorem choose_zero_right (n : β„•) : choose n 0 = 1 := by cases n <;> rfl @[simp] theorem choose_zero_succ (k : β„•) : choose 0 (succ k) = 0 := rfl theorem choose_succ_succ (n k : β„•) : choose (succ n) (succ k) = choose n k + choose n (succ k) := rfl theorem choose_succ_succ' (n k : β„•) : choose (n + 1) (k + 1) = choose n k + choose n (k + 1) := rfl theorem choose_succ_left (n k : β„•) (hk : 0 < k) : choose (n + 1) k = choose n (k - 1) + choose n k := by obtain ⟨l, rfl⟩ : βˆƒ l, k = l + 1 := Nat.exists_eq_add_of_le' hk rfl theorem choose_succ_right (n k : β„•) (hn : 0 < n) : choose n (k + 1) = choose (n - 1) k + choose (n - 1) (k + 1) := by obtain ⟨l, rfl⟩ : βˆƒ l, n = l + 1 := Nat.exists_eq_add_of_le' hn rfl theorem choose_eq_choose_pred_add {n k : β„•} (hn : 0 < n) (hk : 0 < k) : choose n k = choose (n - 1) (k - 1) + choose (n - 1) k := by obtain ⟨l, rfl⟩ : βˆƒ l, k = l + 1 := Nat.exists_eq_add_of_le' hk rw [choose_succ_right _ _ hn, Nat.add_one_sub_one] theorem choose_eq_zero_of_lt : βˆ€ {n k}, n < k β†’ choose n k = 0 | _, 0, hk => absurd hk (Nat.not_lt_zero _) | 0, _ + 1, _ => choose_zero_succ _ | n + 1, k + 1, hk => by have hnk : n < k := lt_of_succ_lt_succ hk have hnk1 : n < k + 1 := lt_of_succ_lt hk rw [choose_succ_succ, choose_eq_zero_of_lt hnk, choose_eq_zero_of_lt hnk1] @[simp] theorem choose_self (n : β„•) : choose n n = 1 := by induction n <;> simp [*, choose, choose_eq_zero_of_lt (lt_succ_self _)] @[simp] theorem choose_succ_self (n : β„•) : choose n (succ n) = 0 := choose_eq_zero_of_lt (lt_succ_self _) @[simp] lemma choose_one_right (n : β„•) : choose n 1 = n := by induction n <;> simp [*, choose, Nat.add_comm] -- The `n + 1`-st triangle number is `n` more than the `n`-th triangle number theorem triangle_succ (n : β„•) : (n + 1) * (n + 1 - 1) / 2 = n * (n - 1) / 2 + n := by rw [← add_mul_div_left, Nat.mul_comm 2 n, ← Nat.mul_add, Nat.add_sub_cancel, Nat.mul_comm] cases n <;> rfl; apply zero_lt_succ /-- `choose n 2` is the `n`-th triangle number. -/ theorem choose_two_right (n : β„•) : choose n 2 = n * (n - 1) / 2 := by induction n with | zero => simp | succ n ih => rw [triangle_succ n, choose, ih] simp [Nat.add_comm] theorem choose_pos : βˆ€ {n k}, k ≀ n β†’ 0 < choose n k | 0, _, hk => by rw [Nat.eq_zero_of_le_zero hk]; decide | n + 1, 0, _ => by simp | _ + 1, _ + 1, hk => Nat.add_pos_left (choose_pos (le_of_succ_le_succ hk)) _ theorem choose_eq_zero_iff {n k : β„•} : n.choose k = 0 ↔ n < k := ⟨fun h => lt_of_not_ge (mt Nat.choose_pos h.symm.not_lt), Nat.choose_eq_zero_of_lt⟩ theorem choose_ne_zero_iff {n k : β„•} : n.choose k β‰  0 ↔ k ≀ n := not_iff_not.1 <| by simp [choose_eq_zero_iff] lemma choose_ne_zero {n k : β„•} (h : k ≀ n) : n.choose k β‰  0 := (choose_pos h).ne' theorem succ_mul_choose_eq : βˆ€ n k, succ n * choose n k = choose (succ n) (succ k) * succ k | 0, 0 => by decide | 0, k + 1 => by simp [choose] | n + 1, 0 => by simp [choose, mul_succ, Nat.add_comm] | n + 1, k + 1 => by rw [choose_succ_succ (succ n) (succ k), Nat.add_mul, ← succ_mul_choose_eq n, mul_succ, ← succ_mul_choose_eq n, Nat.add_right_comm, ← Nat.mul_add, ← choose_succ_succ, ← succ_mul] theorem choose_mul_factorial_mul_factorial : βˆ€ {n k}, k ≀ n β†’ choose n k * k ! * (n - k)! = n ! | 0, _, hk => by simp [Nat.eq_zero_of_le_zero hk] | n + 1, 0, _ => by simp | n + 1, succ k, hk => by rcases lt_or_eq_of_le hk with hk₁ | hk₁ Β· have h : choose n k * k.succ ! * (n - k)! = (k + 1) * n ! := by rw [← choose_mul_factorial_mul_factorial (le_of_succ_le_succ hk)] simp [factorial_succ, Nat.mul_comm, Nat.mul_left_comm, Nat.mul_assoc] have h₁ : (n - k)! = (n - k) * (n - k.succ)! := by rw [← succ_sub_succ, succ_sub (le_of_lt_succ hk₁), factorial_succ] have hβ‚‚ : choose n (succ k) * k.succ ! * ((n - k) * (n - k.succ)!) = (n - k) * n ! := by rw [← choose_mul_factorial_mul_factorial (le_of_lt_succ hk₁)] simp [factorial_succ, Nat.mul_comm, Nat.mul_left_comm, Nat.mul_assoc] have h₃ : k * n ! ≀ n * n ! := Nat.mul_le_mul_right _ (le_of_succ_le_succ hk) rw [choose_succ_succ, Nat.add_mul, Nat.add_mul, succ_sub_succ, h, h₁, hβ‚‚, Nat.add_mul, Nat.mul_sub_right_distrib, factorial_succ, ← Nat.add_sub_assoc h₃, Nat.add_assoc, ← Nat.add_mul, Nat.add_sub_cancel_left, Nat.add_comm] Β· rw [hk₁]; simp [Nat.mul_comm, choose, Nat.sub_self] theorem choose_mul {n k s : β„•} (hkn : k ≀ n) (hsk : s ≀ k) : n.choose k * k.choose s = n.choose s * (n - s).choose (k - s) := have h : 0 < (n - k)! * (k - s)! * s ! := by apply_rules [factorial_pos, Nat.mul_pos] Nat.mul_right_cancel h <| calc n.choose k * k.choose s * ((n - k)! * (k - s)! * s !) = n.choose k * (k.choose s * s ! * (k - s)!) * (n - k)! := by rw [Nat.mul_assoc, Nat.mul_assoc, Nat.mul_assoc, Nat.mul_assoc _ s !, Nat.mul_assoc, Nat.mul_comm (n - k)!, Nat.mul_comm s !] _ = n ! := by rw [choose_mul_factorial_mul_factorial hsk, choose_mul_factorial_mul_factorial hkn] _ = n.choose s * s ! * ((n - s).choose (k - s) * (k - s)! * (n - s - (k - s))!) := by rw [choose_mul_factorial_mul_factorial (Nat.sub_le_sub_right hkn _), choose_mul_factorial_mul_factorial (hsk.trans hkn)] _ = n.choose s * (n - s).choose (k - s) * ((n - k)! * (k - s)! * s !) := by rw [Nat.sub_sub_sub_cancel_right hsk, Nat.mul_assoc, Nat.mul_left_comm s !, Nat.mul_assoc, Nat.mul_comm (k - s)!, Nat.mul_comm s !, Nat.mul_right_comm, ← Nat.mul_assoc] theorem choose_eq_factorial_div_factorial {n k : β„•} (hk : k ≀ n) : choose n k = n ! / (k ! * (n - k)!) := by rw [← choose_mul_factorial_mul_factorial hk, Nat.mul_assoc] exact (mul_div_left _ (Nat.mul_pos (factorial_pos _) (factorial_pos _))).symm theorem add_choose (i j : β„•) : (i + j).choose j = (i + j)! / (i ! * j !) := by rw [choose_eq_factorial_div_factorial (Nat.le_add_left j i), Nat.add_sub_cancel_right, Nat.mul_comm] theorem add_choose_mul_factorial_mul_factorial (i j : β„•) : (i + j).choose j * i ! * j ! = (i + j)! := by rw [← choose_mul_factorial_mul_factorial (Nat.le_add_left _ _), Nat.add_sub_cancel_right, Nat.mul_right_comm] theorem factorial_mul_factorial_dvd_factorial {n k : β„•} (hk : k ≀ n) : k ! * (n - k)! ∣ n ! := by rw [← choose_mul_factorial_mul_factorial hk, Nat.mul_assoc]; exact Nat.dvd_mul_left _ _ theorem factorial_mul_factorial_dvd_factorial_add (i j : β„•) : i ! * j ! ∣ (i + j)! := by suffices i ! * (i + j - i)! ∣ (i + j)! by rwa [Nat.add_sub_cancel_left i j] at this exact factorial_mul_factorial_dvd_factorial (Nat.le_add_right _ _) @[simp] theorem choose_symm {n k : β„•} (hk : k ≀ n) : choose n (n - k) = choose n k := by rw [choose_eq_factorial_div_factorial hk, choose_eq_factorial_div_factorial (Nat.sub_le _ _), Nat.sub_sub_self hk, Nat.mul_comm] theorem choose_symm_of_eq_add {n a b : β„•} (h : n = a + b) : Nat.choose n a = Nat.choose n b := by suffices choose n (n - b) = choose n b by rw [h, Nat.add_sub_cancel_right] at this; rwa [h] exact choose_symm (h β–Έ le_add_left _ _) theorem choose_symm_add {a b : β„•} : choose (a + b) a = choose (a + b) b := choose_symm_of_eq_add rfl theorem choose_symm_half (m : β„•) : choose (2 * m + 1) (m + 1) = choose (2 * m + 1) m := by apply choose_symm_of_eq_add rw [Nat.add_comm m 1, Nat.add_assoc 1 m m, Nat.add_comm (2 * m) 1, Nat.two_mul m] theorem choose_succ_right_eq (n k : β„•) : choose n (k + 1) * (k + 1) = choose n k * (n - k) := by have e : (n + 1) * choose n k = choose n (k + 1) * (k + 1) + choose n k * (k + 1) := by rw [← Nat.add_mul, Nat.add_comm (choose _ _), ← choose_succ_succ, succ_mul_choose_eq] rw [← Nat.sub_eq_of_eq_add e, Nat.mul_comm, ← Nat.mul_sub_left_distrib, Nat.add_sub_add_right] @[simp] theorem choose_succ_self_right : βˆ€ n : β„•, (n + 1).choose n = n + 1 | 0 => rfl | n + 1 => by rw [choose_succ_succ, choose_succ_self_right n, choose_self] theorem choose_mul_succ_eq (n k : β„•) : n.choose k * (n + 1) = (n + 1).choose k * (n + 1 - k) := by cases k with | zero => simp | succ k => obtain hk | hk := le_or_gt (k + 1) (n + 1) Β· rw [choose_succ_succ, Nat.add_mul, succ_sub_succ, ← choose_succ_right_eq, ← succ_sub_succ, Nat.mul_sub_left_distrib, Nat.add_sub_cancel' (Nat.mul_le_mul_left _ hk)] Β· rw [choose_eq_zero_of_lt hk, choose_eq_zero_of_lt (n.lt_succ_self.trans hk), Nat.zero_mul, Nat.zero_mul] theorem ascFactorial_eq_factorial_mul_choose (n k : β„•) : (n + 1).ascFactorial k = k ! * (n + k).choose k := by rw [Nat.mul_comm] apply Nat.mul_right_cancel (n + k - k).factorial_pos rw [choose_mul_factorial_mul_factorial <| Nat.le_add_left k n, Nat.add_sub_cancel_right, ← factorial_mul_ascFactorial, Nat.mul_comm] theorem ascFactorial_eq_factorial_mul_choose' (n k : β„•) : n.ascFactorial k = k ! * (n + k - 1).choose k := by cases n Β· cases k Β· rw [ascFactorial_zero, choose_zero_right, factorial_zero, Nat.mul_one] Β· simp only [zero_ascFactorial, Nat.zero_add, succ_sub_succ_eq_sub, Nat.sub_zero, choose_succ_self, Nat.mul_zero] rw [ascFactorial_eq_factorial_mul_choose] simp only [succ_add_sub_one] theorem factorial_dvd_ascFactorial (n k : β„•) : k ! ∣ n.ascFactorial k := ⟨(n + k - 1).choose k, ascFactorial_eq_factorial_mul_choose' _ _⟩ theorem choose_eq_asc_factorial_div_factorial (n k : β„•) : (n + k).choose k = (n + 1).ascFactorial k / k ! := by apply Nat.mul_left_cancel k.factorial_pos rw [← ascFactorial_eq_factorial_mul_choose] exact (Nat.mul_div_cancel' <| factorial_dvd_ascFactorial _ _).symm theorem choose_eq_asc_factorial_div_factorial' (n k : β„•) : (n + k - 1).choose k = n.ascFactorial k / k ! := Nat.eq_div_of_mul_eq_right k.factorial_ne_zero (ascFactorial_eq_factorial_mul_choose' _ _).symm theorem descFactorial_eq_factorial_mul_choose (n k : β„•) : n.descFactorial k = k ! * n.choose k := by obtain h | h := Nat.lt_or_ge n k Β· rw [descFactorial_eq_zero_iff_lt.2 h, choose_eq_zero_of_lt h, Nat.mul_zero] rw [Nat.mul_comm] apply Nat.mul_right_cancel (n - k).factorial_pos rw [choose_mul_factorial_mul_factorial h, ← factorial_mul_descFactorial h, Nat.mul_comm] theorem factorial_dvd_descFactorial (n k : β„•) : k ! ∣ n.descFactorial k := ⟨n.choose k, descFactorial_eq_factorial_mul_choose _ _⟩ theorem choose_eq_descFactorial_div_factorial (n k : β„•) : n.choose k = n.descFactorial k / k ! := Nat.eq_div_of_mul_eq_right k.factorial_ne_zero (descFactorial_eq_factorial_mul_choose _ _).symm /-- A faster implementation of `choose`, to be used during bytecode evaluation and in compiled code. -/ def fast_choose n k := Nat.descFactorial n k / Nat.factorial k @[csimp] lemma choose_eq_fast_choose : Nat.choose = fast_choose := funext (fun _ => funext (Nat.choose_eq_descFactorial_div_factorial _)) /-! ### Inequalities -/ /-- Show that `Nat.choose` is increasing for small values of the right argument. -/ theorem choose_le_succ_of_lt_half_left {r n : β„•} (h : r < n / 2) : choose n r ≀ choose n (r + 1) := by refine Nat.le_of_mul_le_mul_right ?_ (Nat.sub_pos_of_lt (h.trans_le (n.div_le_self 2))) rw [← choose_succ_right_eq] apply Nat.mul_le_mul_left rw [← Nat.lt_iff_add_one_le, Nat.lt_sub_iff_add_lt, ← Nat.mul_two] exact lt_of_lt_of_le (Nat.mul_lt_mul_of_pos_right h Nat.zero_lt_two) (n.div_mul_le_self 2) /-- Show that for small values of the right argument, the middle value is largest. -/ private theorem choose_le_middle_of_le_half_left {n r : β„•} (hr : r ≀ n / 2) : choose n r ≀ choose n (n / 2) := by induction hr using decreasingInduction with | self => rfl | of_succ k hk ih => exact (choose_le_succ_of_lt_half_left hk).trans ih /-- `choose n r` is maximised when `r` is `n/2`. -/ theorem choose_le_middle (r n : β„•) : choose n r ≀ choose n (n / 2) := by rcases le_or_gt r n with b | b Β· rcases le_or_gt r (n / 2) with a | h Β· apply choose_le_middle_of_le_half_left a Β· rw [← choose_symm b] apply choose_le_middle_of_le_half_left cutsat Β· rw [choose_eq_zero_of_lt b] apply zero_le /-! #### Inequalities about increasing the first argument -/ theorem choose_le_succ (a c : β„•) : choose a c ≀ choose a.succ c := by cases c <;> simp [Nat.choose_succ_succ] theorem choose_le_add (a b c : β„•) : choose a c ≀ choose (a + b) c := by induction b with | zero => simp | succ b_n b_ih => exact b_ih.trans (choose_le_succ (a + b_n) c) theorem choose_le_choose {a b : β„•} (c : β„•) (h : a ≀ b) : choose a c ≀ choose b c := Nat.add_sub_cancel' h β–Έ choose_le_add a (b - a) c theorem choose_mono (b : β„•) : Monotone fun a => choose a b := fun _ _ => choose_le_choose b /-! #### Multichoose Whereas `choose n k` is the number of subsets of cardinality `k` from a type of cardinality `n`, `multichoose n k` is the number of multisets of cardinality `k` from a type of cardinality `n`. Alternatively, whereas `choose n k` counts the number of combinations, i.e. ways to select `k` items (up to permutation) from `n` items without replacement, `multichoose n k` counts the number of multicombinations, i.e. ways to select `k` items (up to permutation) from `n` items with replacement. Note that `multichoose` is *not* the multinomial coefficient, although it can be computed in terms of multinomial coefficients. For details see https://mathworld.wolfram.com/Multichoose.html TODO: Prove that `choose (-n) k = (-1)^k * multichoose n k`, where `choose` is the generalized binomial coefficient. <https://github.com/leanprover-community/mathlib/pull/15072#issuecomment-1171415738> -/ /-- `multichoose n k` is the number of multisets of cardinality `k` from a type of cardinality `n`. -/ def multichoose : β„• β†’ β„• β†’ β„• | _, 0 => 1 | 0, _ + 1 => 0 | n + 1, k + 1 => multichoose n (k + 1) + multichoose (n + 1) k @[simp] theorem multichoose_zero_right (n : β„•) : multichoose n 0 = 1 := by cases n <;> simp [multichoose] @[simp] theorem multichoose_zero_succ (k : β„•) : multichoose 0 (k + 1) = 0 := by simp [multichoose] theorem multichoose_succ_succ (n k : β„•) : multichoose (n + 1) (k + 1) = multichoose n (k + 1) + multichoose (n + 1) k := by simp [multichoose] @[simp] theorem multichoose_one (k : β„•) : multichoose 1 k = 1 := by induction k with | zero => simp | succ k IH => simp [multichoose_succ_succ 0 k, IH] @[simp] theorem multichoose_two (k : β„•) : multichoose 2 k = k + 1 := by induction k with | zero => simp | succ k IH => rw [multichoose, IH]; simp [Nat.add_comm] @[simp] theorem multichoose_one_right (n : β„•) : multichoose n 1 = n := by induction n with | zero => simp | succ n IH => simp [multichoose_succ_succ n 0, IH] theorem multichoose_eq : βˆ€ n k : β„•, multichoose n k = (n + k - 1).choose k | _, 0 => by simp | 0, k + 1 => by simp | n + 1, k + 1 => by have : n + (k + 1) < (n + 1) + (k + 1) := Nat.add_lt_add_right (Nat.lt_succ_self _) _ have : (n + 1) + k < (n + 1) + (k + 1) := Nat.add_lt_add_left (Nat.lt_succ_self _) _ rw [multichoose_succ_succ, Nat.add_comm, Nat.succ_add_sub_one, ← Nat.add_assoc, Nat.choose_succ_succ] simp [multichoose_eq n (k + 1), multichoose_eq (n + 1) k] end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Choose/Lucas.lean
import Mathlib.Algebra.CharP.Lemmas import Mathlib.Data.ZMod.Basic import Mathlib.RingTheory.Polynomial.Basic /-! # Lucas's theorem This file contains a proof of [Lucas's theorem](https://en.wikipedia.org/wiki/Lucas's_theorem) about binomial coefficients, which says that for primes `p`, `n` choose `k` is congruent to product of `n_i` choose `k_i` modulo `p`, where `n_i` and `k_i` are the base-`p` digits of `n` and `k`, respectively. ## Main statements * `lucas_theorem`: the binomial coefficient `n choose k` is congruent to the product of `n_i choose k_i` modulo `p`, where `n_i` and `k_i` are the base-`p` digits of `n` and `k`, respectively. -/ open Finset hiding choose open Nat Polynomial namespace Choose variable {n k p : β„•} [Fact p.Prime] /-- For primes `p`, `choose n k` is congruent to `choose (n % p) (k % p) * choose (n / p) (k / p)` modulo `p`. Also see `choose_modEq_choose_mod_mul_choose_div_nat` for the version with `MOD`. -/ theorem choose_modEq_choose_mod_mul_choose_div : choose n k ≑ choose (n % p) (k % p) * choose (n / p) (k / p) [ZMOD p] := by have decompose : ((X : (ZMod p)[X]) + 1) ^ n = (X + 1) ^ (n % p) * (X ^ p + 1) ^ (n / p) := by simpa using add_pow_eq_mul_pow_add_pow_div_char (X : (ZMod p)[X]) 1 p _ simp only [← ZMod.intCast_eq_intCast_iff, ← coeff_X_add_one_pow _ n k, ← eq_intCast (Int.castRingHom (ZMod p)), ← coeff_map, Polynomial.map_pow, Polynomial.map_add, Polynomial.map_one, map_X, decompose] simp only [add_pow, one_pow, mul_one, ← pow_mul, sum_mul_sum] conv_lhs => enter [1, 2, k, 2, k'] rw [← mul_assoc, mul_right_comm _ _ (X ^ (p * k')), ← pow_add, mul_assoc, ← cast_mul] have h_iff : βˆ€ x ∈ range (n % p + 1) Γ—Λ’ range (n / p + 1), k = x.1 + p * x.2 ↔ (k % p, k / p) = x := by intro ⟨x₁, xβ‚‚βŸ© hx rw [Prod.mk.injEq] constructor <;> intro h Β· simp only [mem_product, mem_range] at hx have h' : x₁ < p := lt_of_lt_of_le hx.left <| mod_lt _ Fin.pos' rw [h, add_mul_mod_self_left, add_mul_div_left _ _ Fin.pos', eq_comm (b := xβ‚‚)] exact ⟨mod_eq_of_lt h', right_eq_add.mpr (div_eq_of_lt h')⟩ Β· rw [← h.left, ← h.right, mod_add_div] simp only [finset_sum_coeff, coeff_mul_natCast, coeff_X_pow, ite_mul, zero_mul, ← cast_mul] rw [← sum_product', sum_congr rfl (fun a ha ↦ if_congr (h_iff a ha) rfl rfl), sum_ite_eq] split_ifs with h Β· simp Β· rw [mem_product, mem_range, mem_range, not_and_or, lt_succ, not_le, not_lt] at h cases h <;> simp [choose_eq_zero_of_lt (by tauto)] /-- For primes `p`, `choose n k` is congruent to `choose (n % p) (k % p) * choose (n / p) (k / p)` modulo `p`. Also see `choose_modEq_choose_mod_mul_choose_div` for the version with `ZMOD`. -/ theorem choose_modEq_choose_mod_mul_choose_div_nat : choose n k ≑ choose (n % p) (k % p) * choose (n / p) (k / p) [MOD p] := by rw [← Int.natCast_modEq_iff] exact_mod_cast choose_modEq_choose_mod_mul_choose_div /-- For primes `p`, `choose n k` is congruent to the product of `choose (⌊n / p ^ iβŒ‹ % p) (⌊k / p ^ iβŒ‹ % p)` over i < a, multiplied by `choose (⌊n / p ^ aβŒ‹) (⌊k / p ^ aβŒ‹)`, modulo `p`. -/ theorem choose_modEq_choose_mul_prod_range_choose (a : β„•) : choose n k ≑ choose (n / p ^ a) (k / p ^ a) * ∏ i ∈ range a, choose (n / p ^ i % p) (k / p ^ i % p) [ZMOD p] := match a with | Nat.zero => by simp | Nat.succ a => (choose_modEq_choose_mul_prod_range_choose a).trans <| by rw [prod_range_succ, cast_mul, ← mul_assoc, mul_right_comm] gcongr apply choose_modEq_choose_mod_mul_choose_div.trans simp_rw [pow_succ, Nat.div_div_eq_div_mul, mul_comm, Int.ModEq.refl] /-- **Lucas's Theorem**: For primes `p`, `choose n k` is congruent to the product of `choose (⌊n / p ^ iβŒ‹ % p) (⌊k / p ^ iβŒ‹ % p)` over `i` modulo `p`. -/ theorem choose_modEq_prod_range_choose {a : β„•} (ha₁ : n < p ^ a) (haβ‚‚ : k < p ^ a) : choose n k ≑ ∏ i ∈ range a, choose (n / p ^ i % p) (k / p ^ i % p) [ZMOD p] := by apply (choose_modEq_choose_mul_prod_range_choose a).trans simp_rw [Nat.div_eq_of_lt ha₁, Nat.div_eq_of_lt haβ‚‚, choose, cast_one, one_mul, cast_prod, Int.ModEq.refl] /-- **Lucas's Theorem**: For primes `p`, `choose n k` is congruent to the product of `choose (⌊n / p ^ iβŒ‹ % p) (⌊k / p ^ iβŒ‹ % p)` over `i` modulo `p`. -/ theorem choose_modEq_prod_range_choose_nat {a : β„•} (ha₁ : n < p ^ a) (haβ‚‚ : k < p ^ a) : choose n k ≑ ∏ i ∈ range a, choose (n / p ^ i % p) (k / p ^ i % p) [MOD p] := by rw [← Int.natCast_modEq_iff] exact_mod_cast choose_modEq_prod_range_choose ha₁ haβ‚‚ alias lucas_theorem := choose_modEq_prod_range_choose alias lucas_theorem_nat := choose_modEq_prod_range_choose_nat end Choose
.lake/packages/mathlib/Mathlib/Data/Nat/Choose/Factorization.lean
import Mathlib.Algebra.Order.Ring.GeomSum import Mathlib.Data.Nat.Choose.Central import Mathlib.Data.Nat.Digits.Lemmas import Mathlib.Data.Nat.Factorization.Basic /-! # Factorization of Binomial Coefficients This file contains a few results on the multiplicity of prime factors within certain size bounds in binomial coefficients. These include: * `Nat.factorization_choose_le_log`: a logarithmic upper bound on the multiplicity of a prime in a binomial coefficient. * `Nat.factorization_choose_le_one`: Primes above `sqrt n` appear at most once in the factorization of `n` choose `k`. * `Nat.factorization_centralBinom_of_two_mul_self_lt_three_mul`: Primes from `2 * n / 3` to `n` do not appear in the factorization of the `n`th central binomial coefficient. * `Nat.factorization_choose_eq_zero_of_lt`: Primes greater than `n` do not appear in the factorization of `n` choose `k`. These results appear in the [ErdΕ‘s proof of Bertrand's postulate](aigner1999proofs). -/ open Finset List Finsupp namespace Nat variable {a b c : β„•} /-- **Legendre's Theorem** The multiplicity of a prime in `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 factorization_factorial {p : β„•} (hp : p.Prime) : βˆ€ {n b : β„•}, log p n < b β†’ (n)!.factorization p = βˆ‘ i ∈ Ico 1 b, n / p ^ i | 0, b, _ => by simp | n + 1, b, hb => calc (n + 1)!.factorization p = (n + 1).factorization p + (n)!.factorization p := by rw [factorial_succ, factorization_mul (zero_ne_add_one n).symm n.factorial_ne_zero, coe_add, Pi.add_apply] _ = #{i ∈ Ico 1 b | p ^ i ∣ n + 1} + βˆ‘ i ∈ Ico 1 b, n / p ^ i := by rw [factorization_factorial hp ((log_mono_right <| le_succ _).trans_lt hb), add_left_inj] apply factorization_eq_card_pow_dvd_of_lt hp (zero_lt_succ n) (lt_pow_of_log_lt hp.one_lt hb) _ = βˆ‘ i ∈ Ico 1 b, (n / p ^ i + if p ^ i ∣ n + 1 then 1 else 0) := by simp [Nat.add_comm, sum_add_distrib, sum_boole] _ = βˆ‘ i ∈ Ico 1 b, (n + 1) / p ^ i := Finset.sum_congr rfl fun _ _ => Nat.succ_div.symm /-- For a prime number `p`, taking `(p - 1)` times the factorization of `p` in `n!` equals `n` minus the sum of base `p` digits of `n`. -/ theorem sub_one_mul_factorization_factorial {n p : β„•} (hp : p.Prime) : (p - 1) * (n)!.factorization p = n - (p.digits n).sum := by simp only [factorization_factorial hp <| lt_succ_of_lt <| lt.base (log p n), ← Finset.sum_Ico_add' _ 0 _ 1, Ico_zero_eq_range, ← sub_one_mul_sum_log_div_pow_eq_sub_sum_digits] /-- The factorization of `p` in `(p * (n + 1))!` is one more than the sum of the factorizations of `p` in `(p * n)!` and `n + 1`. -/ theorem factorization_factorial_mul_succ {n p : β„•} (hp : p.Prime) : (p * (n + 1))!.factorization p = (p * n)!.factorization p + (n + 1).factorization p + 1 := by have h0 : 2 ≀ p := hp.two_le have h1 : 1 ≀ p * n + 1 := Nat.le_add_left _ _ have h2 : p * n + 1 ≀ p * (n + 1) := by linarith have h3 : p * n + 1 ≀ p * (n + 1) + 1 := by omega have h4 m (hm : m ∈ Ico (p * n + 1) (p * (n + 1))) : m.factorization p = 0 := by apply factorization_eq_zero_of_not_dvd exact not_dvd_of_lt_of_lt_mul_succ (mem_Ico.mp hm).left (mem_Ico.mp hm).right rw [← prod_Ico_id_eq_factorial, factorization_prod_apply (fun _ hx ↦ ne_zero_of_lt (mem_Ico.mp hx).left), ← sum_Ico_consecutive _ h1 h3, add_assoc, sum_Ico_succ_top h2, ← prod_Ico_id_eq_factorial, factorization_prod_apply (fun _ hx ↦ ne_zero_of_lt (mem_Ico.mp hx).left), factorization_mul (ne_zero_of_lt h0) (zero_ne_add_one n).symm, coe_add, Pi.add_apply, hp.factorization_self, sum_congr rfl h4, sum_const_zero, zero_add, add_comm 1] /-- The factorization of `p` in `(p * n)!` is `n` more than that of `n!`. -/ theorem factorization_factorial_mul {n p : β„•} (hp : p.Prime) : (p * n)!.factorization p = (n)!.factorization p + n := by induction n with | zero => simp | succ n ih => simp [factorization_factorial_mul_succ hp, ih, factorial_succ, factorization_mul (zero_ne_add_one n).symm (factorial_ne_zero n)] ring theorem factorization_factorial_le_div_pred {p : β„•} (hp : p.Prime) (n : β„•) : (n)!.factorization p ≀ (n / (p - 1) : β„•) := by rw [factorization_factorial hp (Nat.lt_add_one (log p n))] exact Nat.geom_sum_Ico_le hp.two_le _ _ lemma multiplicity_choose_aux {p n b k : β„•} (hp : p.Prime) (hkn : k ≀ n) : βˆ‘ i ∈ Finset.Ico 1 b, n / p ^ i = ((βˆ‘ i ∈ Finset.Ico 1 b, k / p ^ i) + βˆ‘ i ∈ Finset.Ico 1 b, (n - k) / p ^ i) + #{i ∈ Ico 1 b | p ^ i ≀ k % p ^ i + (n - k) % p ^ i} := calc βˆ‘ i ∈ Finset.Ico 1 b, n / p ^ i = βˆ‘ i ∈ Finset.Ico 1 b, (k + (n - k)) / p ^ i := by simp only [add_tsub_cancel_of_le hkn] _ = βˆ‘ i ∈ Finset.Ico 1 b, (k / p ^ i + (n - k) / p ^ i + if p ^ i ≀ k % p ^ i + (n - k) % p ^ i then 1 else 0) := by simp only [Nat.add_div (pow_pos hp.pos _)] _ = _ := by simp [sum_add_distrib, sum_boole] /-- The factorization of `p` in `choose (n + k) k` is the number of carries when `k` and `n` are added in base `p`. The set is expressed by filtering `Ico 1 b` where `b` is any bound greater than `log p (n + k)`. -/ theorem factorization_choose' {p n k b : β„•} (hp : p.Prime) (hnb : log p (n + k) < b) : (choose (n + k) k).factorization p = #{i ∈ Ico 1 b | p ^ i ≀ k % p ^ i + n % p ^ i} := by have h₁ : (choose (n + k) k).factorization p + (k ! * n !).factorization p = #{i ∈ Ico 1 b | p ^ i ≀ k % p ^ i + n % p ^ i} + (k ! * n !).factorization p := by have h2 := (add_tsub_cancel_right n k) β–Έ choose_mul_factorial_mul_factorial (le_add_left k n) rw [← Pi.add_apply, ← coe_add, ← factorization_mul (ne_of_gt <| choose_pos (le_add_left k n)) (by positivity), ← mul_assoc, h2, factorization_factorial hp hnb, factorization_mul (factorial_ne_zero k) (factorial_ne_zero n), coe_add, Pi.add_apply, factorization_factorial hp ((log_mono_right (le_add_left k n)).trans_lt hnb), factorization_factorial hp ((log_mono_right (le_add_left n k)).trans_lt (add_comm n k β–Έ hnb)), multiplicity_choose_aux hp (le_add_left k n)] simp only [add_tsub_cancel_right, add_comm] exact Nat.add_right_cancel h₁ /-- The factorization of `p` in `choose n k` is the number of carries when `k` and `n - k` are added in base `p`. The set is expressed by filtering `Ico 1 b` where `b` is any bound greater than `log p n`. -/ theorem factorization_choose {p n k b : β„•} (hp : p.Prime) (hkn : k ≀ n) (hnb : log p n < b) : (choose n k).factorization p = #{i ∈ Ico 1 b | p ^ i ≀ k % p ^ i + (n - k) % p ^ i} := by rw [←factorization_choose' hp ((Nat.sub_add_cancel hkn).symm β–Έ hnb), Nat.sub_add_cancel hkn] /-- Modified version of `emultiplicity_le_emultiplicity_of_dvd_right` but for factorization. -/ theorem factorization_le_factorization_of_dvd_right (h : b ∣ c) (hb : b β‰  0) (hc : c β‰  0) : b.factorization a ≀ c.factorization a := by obtain ⟨k, rfl⟩ := h; simp [factorization_mul hb (Nat.ne_zero_of_mul_ne_zero_right hc)] /-- A lower bound on the factorization of `p` in `choose n k`. -/ theorem factorization_le_factorization_choose_add {p : β„•} : βˆ€ {n k : β„•}, k ≀ n β†’ k β‰  0 β†’ n.factorization p ≀ (choose n k).factorization p + k.factorization p | n, 0, _, _ => by tauto | 0, x + 1, _, _ => by simp | n + 1, k + 1, hkn, hk => by rw [← Pi.add_apply, ← coe_add, ← factorization_mul (ne_of_gt <| choose_pos hkn) (zero_ne_add_one k).symm] refine factorization_le_factorization_of_dvd_right ?_ (zero_ne_add_one n).symm (Nat.mul_ne_zero (ne_of_gt <| choose_pos hkn) (by positivity)) rw [← succ_mul_choose_eq] exact dvd_mul_right _ _ variable {p n k : β„•} theorem factorization_choose_prime_pow_add_factorization (hp : p.Prime) (hkn : k ≀ p ^ n) (hk0 : k β‰  0) : (choose (p ^ n) k).factorization p + k.factorization p = n := by apply le_antisymm Β· have hdisj : Disjoint {i ∈ Ico 1 n.succ | p ^ i ≀ k % p ^ i + (p ^ n - k) % p ^ i} {i ∈ Ico 1 n.succ | p ^ i ∣ k} := by simp +contextual [Finset.disjoint_right, dvd_iff_mod_eq_zero, Nat.mod_lt _ (pow_pos hp.pos _)] rw [factorization_choose hp hkn (lt_succ_self _), factorization_eq_card_pow_dvd_of_lt hp hk0.bot_lt (lt_of_le_of_lt hkn <| Nat.pow_lt_pow_succ hp.one_lt), log_pow hp.one_lt, ← card_union_of_disjoint hdisj, filter_union_right] have filter_le_Ico := (Ico 1 n.succ).card_filter_le fun x => p ^ x ≀ k % p ^ x + (p ^ n - k) % p ^ x ∨ p ^ x ∣ k rwa [card_Ico 1 n.succ] at filter_le_Ico Β· nth_rewrite 1 [← factorization_pow_self (n:=n) hp] exact factorization_le_factorization_choose_add hkn hk0 theorem factorization_choose_prime_pow {p n k : β„•} (hp : p.Prime) (hkn : k ≀ p ^ n) (hk0 : k β‰  0) : (choose (p ^ n) k).factorization p = n - k.factorization p := by nth_rewrite 2 [← factorization_choose_prime_pow_add_factorization hp hkn hk0] rw [Nat.add_sub_cancel_right] end Nat namespace Nat variable {p n k : β„•} /-- A logarithmic upper bound on the multiplicity of a prime in a binomial coefficient. -/ theorem factorization_choose_le_log : (choose n k).factorization p ≀ log p n := by by_cases h : (choose n k).factorization p = 0 Β· simp [h] have hp : p.Prime := Not.imp_symm (choose n k).factorization_eq_zero_of_not_prime h have hkn : k ≀ n := by refine le_of_not_gt fun hnk => h ?_ simp [choose_eq_zero_of_lt hnk] rw [factorization_choose hp hkn (Nat.lt_add_one _)] exact (card_filter_le ..).trans_eq (Nat.card_Ico _ _) /-- A `pow` form of `Nat.factorization_choose_le` -/ theorem pow_factorization_choose_le (hn : 0 < n) : p ^ (choose n k).factorization p ≀ n := pow_le_of_le_log hn.ne' factorization_choose_le_log /-- Primes greater than about `sqrt n` appear only to multiplicity 0 or 1 in the binomial coefficient. -/ theorem factorization_choose_le_one (p_large : n < p ^ 2) : (choose n k).factorization p ≀ 1 := by apply factorization_choose_le_log.trans rcases eq_or_ne n 0 with (rfl | hn0); Β· simp exact Nat.lt_succ_iff.1 (log_lt_of_lt_pow hn0 p_large) theorem factorization_choose_of_lt_three_mul (hp' : p β‰  2) (hk : p ≀ k) (hk' : p ≀ n - k) (hn : n < 3 * p) : (choose n k).factorization p = 0 := by rcases em' p.Prime with hp | hp Β· exact factorization_eq_zero_of_not_prime (choose n k) hp rcases lt_or_ge n k with hnk | hkn Β· simp [choose_eq_zero_of_lt hnk] simp only [factorization_choose hp hkn (Nat.lt_add_one _), card_eq_zero, filter_eq_empty_iff, mem_Ico, not_le, and_imp] intro i hi₁ hi rcases eq_or_lt_of_le hi₁ with (rfl | hi) Β· rw [pow_one, ← add_lt_add_iff_left (2 * p), ← succ_mul, two_mul, add_add_add_comm] exact lt_of_le_of_lt (add_le_add (add_le_add_right (le_mul_of_one_le_right' ((one_le_div_iff hp.pos).mpr hk)) (k % p)) (add_le_add_right (le_mul_of_one_le_right' ((one_le_div_iff hp.pos).mpr hk')) ((n - k) % p))) (by rwa [div_add_mod, div_add_mod, add_tsub_cancel_of_le hkn]) Β· replace hn : n < p ^ i := by have : 3 ≀ p := lt_of_le_of_ne hp.two_le hp'.symm calc n < 3 * p := hn _ ≀ p * p := by gcongr _ = p ^ 2 := (sq p).symm _ ≀ p ^ i := pow_right_monoβ‚€ hp.one_lt.le hi rwa [mod_eq_of_lt (lt_of_le_of_lt hkn hn), mod_eq_of_lt (lt_of_le_of_lt tsub_le_self hn), add_tsub_cancel_of_le hkn] /-- Primes greater than about `2 * n / 3` and less than `n` do not appear in the factorization of `centralBinom n`. -/ theorem factorization_centralBinom_of_two_mul_self_lt_three_mul (n_big : 2 < n) (p_le_n : p ≀ n) (big : 2 * n < 3 * p) : (centralBinom n).factorization p = 0 := by refine factorization_choose_of_lt_three_mul ?_ p_le_n (p_le_n.trans ?_) big Β· cutsat Β· rw [two_mul, add_tsub_cancel_left] theorem factorization_factorial_eq_zero_of_lt (h : n < p) : (factorial n).factorization p = 0 := by induction n with | zero => simp | succ n hn => rw [factorial_succ, factorization_mul n.succ_ne_zero n.factorial_ne_zero, Finsupp.coe_add, Pi.add_apply, hn (lt_of_succ_lt h), add_zero, factorization_eq_zero_of_lt h] theorem factorization_choose_eq_zero_of_lt (h : n < p) : (choose n k).factorization p = 0 := by by_cases! hnk : n < k; Β· simp [choose_eq_zero_of_lt hnk] rw [choose_eq_factorial_div_factorial hnk, factorization_div (factorial_mul_factorial_dvd_factorial hnk), Finsupp.coe_tsub, Pi.sub_apply, factorization_factorial_eq_zero_of_lt h, zero_tsub] /-- If a prime `p` has positive multiplicity in the `n`th central binomial coefficient, `p` is no more than `2 * n` -/ theorem factorization_centralBinom_eq_zero_of_two_mul_lt (h : 2 * n < p) : (centralBinom n).factorization p = 0 := factorization_choose_eq_zero_of_lt h /-- Contrapositive form of `Nat.factorization_centralBinom_eq_zero_of_two_mul_lt` -/ theorem le_two_mul_of_factorization_centralBinom_pos (h_pos : 0 < (centralBinom n).factorization p) : p ≀ 2 * n := le_of_not_gt (pos_iff_ne_zero.mp h_pos ∘ factorization_centralBinom_eq_zero_of_two_mul_lt) /-- A binomial coefficient is the product of its prime factors, which are at most `n`. -/ theorem prod_pow_factorization_choose (n k : β„•) (hkn : k ≀ n) : (∏ p ∈ Finset.range (n + 1), p ^ (Nat.choose n k).factorization p) = choose n k := by conv_rhs => rw [← factorization_prod_pow_eq_self (choose_ne_zero hkn)] rw [eq_comm] apply Finset.prod_subset Β· intro p hp rw [Finset.mem_range] contrapose! hp rw [Finsupp.mem_support_iff, Classical.not_not, factorization_choose_eq_zero_of_lt hp] Β· intro p _ h2 simp [Classical.not_not.1 (mt Finsupp.mem_support_iff.2 h2)] /-- The `n`th central binomial coefficient is the product of its prime factors, which are at most `2n`. -/ theorem prod_pow_factorization_centralBinom (n : β„•) : (∏ p ∈ Finset.range (2 * n + 1), p ^ (centralBinom n).factorization p) = centralBinom n := by apply prod_pow_factorization_choose cutsat end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Choose/Vandermonde.lean
import Mathlib.Algebra.Polynomial.Coeff import Mathlib.Data.Nat.Choose.Basic /-! # Vandermonde's identity In this file we prove Vandermonde's identity (`Nat.add_choose_eq`): `(m + n).choose k = βˆ‘ (i, j) ∈ antidiagonal k, m.choose i * n.choose j` We follow the algebraic proof from https://en.wikipedia.org/wiki/Vandermonde%27s_identity#Algebraic_proof . -/ open Polynomial Finset Finset.Nat /-- Vandermonde's identity -/ theorem Nat.add_choose_eq (m n k : β„•) : (m + n).choose k = βˆ‘ ij ∈ antidiagonal k, m.choose ij.1 * n.choose ij.2 := by calc (m + n).choose k = ((X + 1) ^ (m + n)).coeff k := by rw [coeff_X_add_one_pow, Nat.cast_id] _ = ((X + 1) ^ m * (X + 1) ^ n).coeff k := by rw [pow_add] _ = βˆ‘ ij ∈ antidiagonal k, m.choose ij.1 * n.choose ij.2 := by rw [coeff_mul, Finset.sum_congr rfl] simp only [coeff_X_add_one_pow, Nat.cast_id, imp_true_iff]
.lake/packages/mathlib/Mathlib/Data/Nat/Choose/Central.lean
import Mathlib.Data.Nat.Choose.Basic import Mathlib.Data.Nat.GCD.Basic import Mathlib.Tactic.Ring import Mathlib.Tactic.Linarith /-! # Central binomial coefficients This file proves properties of the central binomial coefficients (that is, `Nat.choose (2 * n) n`). ## Main definition and results * `Nat.centralBinom`: the central binomial coefficient, `(2 * n).choose n`. * `Nat.succ_mul_centralBinom_succ`: the inductive relationship between successive central binomial coefficients. * `Nat.four_pow_lt_mul_centralBinom`: an exponential lower bound on the central binomial coefficient. * `succ_dvd_centralBinom`: The result that `n+1 ∣ n.centralBinom`, ensuring that the explicit definition of the Catalan numbers is integer-valued. -/ namespace Nat /-- The central binomial coefficient, `Nat.choose (2 * n) n`. -/ def centralBinom (n : β„•) := (2 * n).choose n theorem centralBinom_eq_two_mul_choose (n : β„•) : centralBinom n = (2 * n).choose n := rfl theorem centralBinom_pos (n : β„•) : 0 < centralBinom n := choose_pos (Nat.le_mul_of_pos_left _ zero_lt_two) theorem centralBinom_ne_zero (n : β„•) : centralBinom n β‰  0 := (centralBinom_pos n).ne' @[simp] theorem centralBinom_zero : centralBinom 0 = 1 := choose_zero_right _ /-- The central binomial coefficient is the largest binomial coefficient. -/ theorem choose_le_centralBinom (r n : β„•) : choose (2 * n) r ≀ centralBinom n := calc (2 * n).choose r ≀ (2 * n).choose (2 * n / 2) := choose_le_middle r (2 * n) _ = (2 * n).choose n := by rw [Nat.mul_div_cancel_left n zero_lt_two] theorem two_le_centralBinom (n : β„•) (n_pos : 0 < n) : 2 ≀ centralBinom n := calc 2 ≀ 2 * n := Nat.le_mul_of_pos_right _ n_pos _ = (2 * n).choose 1 := (choose_one_right (2 * n)).symm _ ≀ centralBinom n := choose_le_centralBinom 1 n /-- An inductive property of the central binomial coefficient. -/ theorem succ_mul_centralBinom_succ (n : β„•) : (n + 1) * centralBinom (n + 1) = 2 * (2 * n + 1) * centralBinom n := calc (n + 1) * (2 * (n + 1)).choose (n + 1) = (2 * n + 2).choose (n + 1) * (n + 1) := mul_comm _ _ _ = (2 * n + 1).choose n * (2 * n + 2) := by rw [choose_succ_right_eq, choose_mul_succ_eq] _ = 2 * ((2 * n + 1).choose n * (n + 1)) := by ring _ = 2 * ((2 * n + 1).choose n * (2 * n + 1 - n)) := by rw [two_mul n, add_assoc, Nat.add_sub_cancel_left] _ = 2 * ((2 * n).choose n * (2 * n + 1)) := by rw [choose_mul_succ_eq] _ = 2 * (2 * n + 1) * (2 * n).choose n := by rw [mul_assoc, mul_comm (2 * n + 1)] /-- An exponential lower bound on the central binomial coefficient. This bound is of interest because it appears in [Tochiori's refinement of ErdΕ‘s's proof of Bertrand's postulate](tochiori_bertrand). -/ theorem four_pow_lt_mul_centralBinom (n : β„•) (n_big : 4 ≀ n) : 4 ^ n < n * centralBinom n := by induction n using Nat.strong_induction_on with | _ n IH rcases lt_trichotomy n 4 with (hn | rfl | hn) Β· clear IH; exact False.elim ((not_lt.2 n_big) hn) Β· norm_num [centralBinom, choose] obtain ⟨n, rfl⟩ : βˆƒ m, n = m + 1 := Nat.exists_eq_succ_of_ne_zero (Nat.ne_zero_of_lt hn) calc 4 ^ (n + 1) _ = 4 * 4 ^ n := by rw [pow_succ'] _ < 4 * (n * centralBinom n) := by gcongr; exact IH n n.lt_succ_self (Nat.le_of_lt_succ hn) _ ≀ 2 * (2 * n + 1) * centralBinom n := by rw [← mul_assoc]; linarith _ = (n + 1) * centralBinom (n + 1) := (succ_mul_centralBinom_succ n).symm /-- An exponential lower bound on the central binomial coefficient. This bound is weaker than `Nat.four_pow_lt_mul_centralBinom`, but it is of historical interest because it appears in ErdΕ‘s's proof of Bertrand's postulate. -/ theorem four_pow_le_two_mul_self_mul_centralBinom : βˆ€ (n : β„•) (_ : 0 < n), 4 ^ n ≀ 2 * n * centralBinom n | 0, pr => (Nat.not_lt_zero _ pr).elim | 1, _ => by simp [centralBinom, choose] | 2, _ => by simp [centralBinom, choose] | 3, _ => by simp [centralBinom, choose] | n + 4, _ => calc 4 ^ (n+4) ≀ (n+4) * centralBinom (n+4) := (four_pow_lt_mul_centralBinom _ le_add_self).le _ ≀ 2 * (n+4) * centralBinom (n+4) := by rw [mul_assoc]; refine Nat.le_mul_of_pos_left _ zero_lt_two theorem two_dvd_centralBinom_succ (n : β„•) : 2 ∣ centralBinom (n + 1) := by use (n + 1 + n).choose n rw [centralBinom_eq_two_mul_choose, two_mul, ← add_assoc, choose_succ_succ' (n + 1 + n) n, choose_symm_add, ← two_mul] theorem two_dvd_centralBinom_of_one_le {n : β„•} (h : 0 < n) : 2 ∣ centralBinom n := by rw [← Nat.succ_pred_eq_of_pos h] exact two_dvd_centralBinom_succ n.pred /-- A crucial lemma to ensure that Catalan numbers can be defined via their explicit formula `catalan n = n.centralBinom / (n + 1)`. -/ theorem succ_dvd_centralBinom (n : β„•) : n + 1 ∣ n.centralBinom := by have h_s : (n + 1).Coprime (2 * n + 1) := by rw [two_mul, add_assoc, coprime_add_self_right, coprime_self_add_left] exact coprime_one_left n apply h_s.dvd_of_dvd_mul_left apply Nat.dvd_of_mul_dvd_mul_left zero_lt_two rw [← mul_assoc, ← succ_mul_centralBinom_succ, mul_comm] exact mul_dvd_mul_left _ (two_dvd_centralBinom_succ n) end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Choose/Multinomial.lean
import Mathlib.Algebra.Order.Antidiag.Pi import Mathlib.Data.Finsupp.Multiset import Mathlib.Data.Nat.Choose.Sum import Mathlib.Data.Nat.Factorial.BigOperators import Mathlib.Data.Nat.Factorial.DoubleFactorial /-! # Multinomial This file defines the multinomial coefficient and several small lemma's for manipulating it. ## Main declarations - `Nat.multinomial`: the multinomial coefficient ## Main results - `Finset.sum_pow`: The expansion of `(s.sum x) ^ n` using multinomial coefficients -/ open Finset open scoped Nat namespace Nat variable {Ξ± : Type*} (s : Finset Ξ±) (f : Ξ± β†’ β„•) {a b : Ξ±} (n : β„•) /-- The multinomial coefficient. Gives the number of strings consisting of symbols from `s`, where `c ∈ s` appears with multiplicity `f c`. Defined as `(βˆ‘ i ∈ s, f i)! / ∏ i ∈ s, (f i)!`. -/ def multinomial : β„• := (βˆ‘ i ∈ s, f i)! / ∏ i ∈ s, (f i)! theorem multinomial_pos : 0 < multinomial s f := Nat.div_pos (le_of_dvd (factorial_pos _) (prod_factorial_dvd_factorial_sum s f)) (prod_factorial_pos s f) theorem multinomial_spec : (∏ i ∈ s, (f i)!) * multinomial s f = (βˆ‘ i ∈ s, f i)! := Nat.mul_div_cancel' (prod_factorial_dvd_factorial_sum s f) @[simp] lemma multinomial_empty : multinomial βˆ… f = 1 := by simp [multinomial] variable {s f} lemma multinomial_cons (ha : a βˆ‰ s) (f : Ξ± β†’ β„•) : multinomial (s.cons a ha) f = (f a + βˆ‘ i ∈ s, f i).choose (f a) * multinomial s f := by rw [multinomial, Nat.div_eq_iff_eq_mul_left _ (prod_factorial_dvd_factorial_sum _ _), prod_cons, multinomial, mul_assoc, mul_left_comm _ (f a)!, Nat.div_mul_cancel (prod_factorial_dvd_factorial_sum _ _), ← mul_assoc, Nat.choose_symm_add, Nat.add_choose_mul_factorial_mul_factorial, Finset.sum_cons] positivity lemma multinomial_insert [DecidableEq Ξ±] (ha : a βˆ‰ s) (f : Ξ± β†’ β„•) : multinomial (insert a s) f = (f a + βˆ‘ i ∈ s, f i).choose (f a) * multinomial s f := by rw [← cons_eq_insert _ _ ha, multinomial_cons] @[simp] lemma multinomial_singleton (a : Ξ±) (f : Ξ± β†’ β„•) : multinomial {a} f = 1 := by rw [← cons_empty, multinomial_cons]; simp @[simp] theorem multinomial_insert_one [DecidableEq Ξ±] (h : a βˆ‰ s) (h₁ : f a = 1) : multinomial (insert a s) f = (s.sum f).succ * multinomial s f := by simp only [multinomial] rw [Finset.sum_insert h, Finset.prod_insert h, h₁, add_comm, ← succ_eq_add_one, factorial_succ] simp only [factorial, succ_eq_add_one, zero_add, mul_one, one_mul] rw [Nat.mul_div_assoc _ (prod_factorial_dvd_factorial_sum _ _)] theorem multinomial_congr {f g : Ξ± β†’ β„•} (h : βˆ€ a ∈ s, f a = g a) : multinomial s f = multinomial s g := by simp only [multinomial]; congr 1 Β· rw [Finset.sum_congr rfl h] Β· exact Finset.prod_congr rfl fun a ha => by rw [h a ha] /-! ### Connection to binomial coefficients When `Nat.multinomial` is applied to a `Finset` of two elements `{a, b}`, the result a binomial coefficient. We use `binomial` in the names of lemmas that involves `Nat.multinomial {a, b}`. -/ theorem binomial_eq [DecidableEq Ξ±] (h : a β‰  b) : multinomial {a, b} f = (f a + f b)! / ((f a)! * (f b)!) := by simp [multinomial, Finset.sum_pair h, Finset.prod_pair h] theorem binomial_eq_choose [DecidableEq Ξ±] (h : a β‰  b) : multinomial {a, b} f = (f a + f b).choose (f a) := by simp [binomial_eq h, choose_eq_factorial_div_factorial (Nat.le_add_right _ _)] theorem binomial_spec [DecidableEq Ξ±] (hab : a β‰  b) : (f a)! * (f b)! * multinomial {a, b} f = (f a + f b)! := by simpa [Finset.sum_pair hab, Finset.prod_pair hab] using multinomial_spec {a, b} f theorem binomial_one [DecidableEq Ξ±] (h : a β‰  b) (h₁ : f a = 1) : multinomial {a, b} f = (f b).succ := by simp [h, h₁] theorem binomial_succ_succ [DecidableEq Ξ±] (h : a β‰  b) : multinomial {a, b} (Function.update (Function.update f a (f a).succ) b (f b).succ) = multinomial {a, b} (Function.update f a (f a).succ) + multinomial {a, b} (Function.update f b (f b).succ) := by simp only [binomial_eq_choose, Function.update_apply, h, Ne, ite_true, ite_false, not_false_eq_true] rw [if_neg h.symm] rw [add_succ, choose_succ_succ, succ_add_eq_add_succ] ring theorem succ_mul_binomial [DecidableEq Ξ±] (h : a β‰  b) : (f a + f b).succ * multinomial {a, b} f = (f a).succ * multinomial {a, b} (Function.update f a (f a).succ) := by rw [binomial_eq_choose h, binomial_eq_choose h, mul_comm (f a).succ, Function.update_self, Function.update_of_ne h.symm] rw [succ_mul_choose_eq (f a + f b) (f a), succ_add (f a) (f b)] /-! ### Simple cases -/ theorem multinomial_univ_two (a b : β„•) : multinomial Finset.univ ![a, b] = (a + b)! / (a ! * b !) := by rw [multinomial, Fin.sum_univ_two, Fin.prod_univ_two] dsimp only [Matrix.cons_val] theorem multinomial_univ_three (a b c : β„•) : multinomial Finset.univ ![a, b, c] = (a + b + c)! / (a ! * b ! * c !) := by rw [multinomial, Fin.sum_univ_three, Fin.prod_univ_three] rfl end Nat /-! ### Alternative definitions -/ namespace Finsupp variable {Ξ± : Type*} /-- Alternative multinomial definition based on a finsupp, using the support for the big operations -/ def multinomial (f : Ξ± β†’β‚€ β„•) : β„• := (f.sum fun _ => id)! / f.prod fun _ n => n ! theorem multinomial_eq (f : Ξ± β†’β‚€ β„•) : f.multinomial = Nat.multinomial f.support f := rfl theorem multinomial_update (a : Ξ±) (f : Ξ± β†’β‚€ β„•) : f.multinomial = (f.sum fun _ => id).choose (f a) * (f.update a 0).multinomial := by simp only [multinomial_eq] classical by_cases h : a ∈ f.support Β· rw [← Finset.insert_erase h, Nat.multinomial_insert (Finset.notMem_erase a _), Finset.add_sum_erase _ f h, support_update_zero] congr 1 exact Nat.multinomial_congr fun _ h ↦ (Function.update_of_ne (mem_erase.1 h).1 0 f).symm rw [notMem_support_iff] at h rw [h, Nat.choose_zero_right, one_mul, ← h, update_self] end Finsupp namespace Multiset variable {Ξ± : Type*} /-- Alternative definition of multinomial based on `Multiset` delegating to the finsupp definition -/ def multinomial [DecidableEq Ξ±] (m : Multiset Ξ±) : β„• := m.toFinsupp.multinomial theorem multinomial_filter_ne [DecidableEq Ξ±] (a : Ξ±) (m : Multiset Ξ±) : m.multinomial = m.card.choose (m.count a) * (m.filter (a β‰  Β·)).multinomial := by dsimp only [multinomial] convert Finsupp.multinomial_update a _ Β· rw [← Finsupp.card_toMultiset, m.toFinsupp_toMultiset] Β· ext1 a rw [toFinsupp_apply, count_filter, Finsupp.coe_update] split_ifs with h Β· rw [Function.update_of_ne h.symm, toFinsupp_apply] Β· rw [not_ne_iff.1 h, Function.update_self] @[simp] theorem multinomial_zero [DecidableEq Ξ±] : multinomial (0 : Multiset Ξ±) = 1 := by simp [multinomial, Finsupp.multinomial] end Multiset namespace Finset open _root_.Nat /-! ### Multinomial theorem -/ variable {Ξ± R : Type*} [DecidableEq Ξ±] section Semiring variable [Semiring R] open scoped Function -- required for scoped `on` notation -- TODO: Can we prove one of the following two from the other one? /-- The **multinomial theorem**. -/ lemma sum_pow_eq_sum_piAntidiag_of_commute (s : Finset Ξ±) (f : Ξ± β†’ R) (hc : (s : Set Ξ±).Pairwise (Commute on f)) (n : β„•) : (βˆ‘ i ∈ s, f i) ^ n = βˆ‘ k ∈ piAntidiag s n, multinomial s k * s.noncommProd (fun i ↦ f i ^ k i) (hc.mono' fun _ _ h ↦ h.pow_pow ..) := by classical induction s using Finset.cons_induction generalizing n with | empty => cases n <;> simp | cons a s has ih => ?_ rw [Finset.sum_cons, piAntidiag_cons, sum_disjiUnion] simp only [sum_map, Pi.add_apply, multinomial_cons, Pi.add_apply, if_true, Nat.cast_mul, noncommProd_cons, if_true, sum_add_distrib, sum_ite_eq', has, if_false, add_zero, addRightEmbedding_apply] suffices βˆ€ p : β„• Γ— β„•, p ∈ antidiagonal n β†’ βˆ‘ g ∈ piAntidiag s p.2, ((g a + p.1 + s.sum g).choose (g a + p.1) : R) * multinomial s (g + fun i ↦ ite (i = a) p.1 0) * (f a ^ (g a + p.1) * s.noncommProd (fun i ↦ f i ^ (g i + ite (i = a) p.1 0)) ((hc.mono (by simp)).mono' fun i j h ↦ h.pow_pow ..)) = βˆ‘ g ∈ piAntidiag s p.2, n.choose p.1 * multinomial s g * (f a ^ p.1 * s.noncommProd (fun i ↦ f i ^ g i) ((hc.mono (by simp)).mono' fun i j h ↦ h.pow_pow ..)) by rw [sum_congr rfl this] simp only [Nat.antidiagonal_eq_map, sum_map, Function.Embedding.coeFn_mk] rw [(Commute.sum_right _ _ _ fun i hi ↦ hc (by simp) (by simp [hi]) (by simpa [eq_comm] using ne_of_mem_of_not_mem hi has)).add_pow] simp only [ih (hc.mono (by simp)), sum_mul, mul_sum] refine sum_congr rfl fun i _ ↦ sum_congr rfl fun g _ ↦ ?_ rw [← Nat.cast_comm, (Nat.commute_cast (f a ^ i) _).left_comm, mul_assoc] refine fun p hp ↦ sum_congr rfl fun f hf ↦ ?_ rw [mem_piAntidiag] at hf rw [not_imp_comm.1 (hf.2 _) has, zero_add, hf.1] congr 2 Β· rw [mem_antidiagonal.1 hp] Β· rw [multinomial_congr] intro t ht rw [Pi.add_apply, if_neg, add_zero] exact ne_of_mem_of_not_mem ht has refine noncommProd_congr rfl (fun t ht ↦ ?_) _ rw [if_neg, add_zero] exact ne_of_mem_of_not_mem ht has /-- The **multinomial theorem**. -/ theorem sum_pow_of_commute (x : Ξ± β†’ R) (s : Finset Ξ±) (hc : (s : Set Ξ±).Pairwise (Commute on x)) : βˆ€ n, s.sum x ^ n = βˆ‘ k : s.sym n, k.1.1.multinomial * (k.1.1.map <| x).noncommProd (Multiset.map_set_pairwise <| hc.mono <| mem_sym_iff.1 k.2) := by induction s using Finset.induction with | empty => rw [sum_empty] rintro (_ | n) Β· rw [_root_.pow_zero, Fintype.sum_subsingleton] swap Β· exact ⟨0, by simp [eq_iff_true_of_subsingleton]⟩ convert (@one_mul R _ _).symm convert @Nat.cast_one R _ simp Β· rw [_root_.pow_succ, mul_zero] haveI : IsEmpty (Finset.sym (βˆ… : Finset Ξ±) n.succ) := Finset.instIsEmpty apply (Fintype.sum_empty _).symm | insert a s ha ih => ?_ intro n; specialize ih (hc.mono <| s.subset_insert a) rw [sum_insert ha, (Commute.sum_right s _ _ _).add_pow, sum_range]; swap Β· exact fun _ hb => hc (mem_insert_self a s) (mem_insert_of_mem hb) (ne_of_mem_of_not_mem hb ha).symm Β· simp_rw [ih, mul_sum, sum_mul, sum_sigma', univ_sigma_univ] refine (Fintype.sum_equiv (symInsertEquiv ha) _ _ fun m => ?_).symm rw [m.1.1.multinomial_filter_ne a] conv in m.1.1.map _ => rw [← m.1.1.filter_add_not (a = Β·), Multiset.map_add] simp_rw [Multiset.noncommProd_add, m.1.1.filter_eq, Multiset.map_replicate, m.1.2] rw [Multiset.noncommProd_eq_pow_card _ _ _ fun _ => Multiset.eq_of_mem_replicate] rw [Multiset.card_replicate, Nat.cast_mul, mul_assoc, Nat.cast_comm] congr 1; simp_rw [← mul_assoc, Nat.cast_comm]; rfl end Semiring section CommSemiring variable [CommSemiring R] {f : Ξ± β†’ R} {s : Finset Ξ±} lemma sum_pow_eq_sum_piAntidiag (s : Finset Ξ±) (f : Ξ± β†’ R) (n : β„•) : (βˆ‘ i ∈ s, f i) ^ n = βˆ‘ k ∈ piAntidiag s n, multinomial s k * ∏ i ∈ s, f i ^ k i := by simp_rw [← noncommProd_eq_prod] rw [← sum_pow_eq_sum_piAntidiag_of_commute _ _ fun _ _ _ _ _ ↦ Commute.all ..] theorem sum_pow (x : Ξ± β†’ R) (n : β„•) : s.sum x ^ n = βˆ‘ k ∈ s.sym n, k.val.multinomial * (k.val.map x).prod := by conv_rhs => rw [← sum_coe_sort] convert sum_pow_of_commute x s (fun _ _ _ _ _ ↦ Commute.all ..) n rw [Multiset.noncommProd_eq_prod] end CommSemiring end Finset namespace Nat variable {ΞΉ : Type*} {s : Finset ΞΉ} {f : ΞΉ β†’ β„•} lemma multinomial_two_mul_le_mul_multinomial : multinomial s (fun i ↦ 2 * f i) ≀ ((βˆ‘ i ∈ s, f i) ^ βˆ‘ i ∈ s, f i) * multinomial s f := by rw [multinomial, multinomial, ← mul_sum, ← Nat.mul_div_assoc _ (prod_factorial_dvd_factorial_sum ..)] refine Nat.div_le_div_of_mul_le_mul (by positivity) ((prod_factorial_dvd_factorial_sum ..).trans (Nat.dvd_mul_left ..)) ?_ calc (2 * βˆ‘ i ∈ s, f i)! * ∏ i ∈ s, (f i)! ≀ ((2 * βˆ‘ i ∈ s, f i) ^ (βˆ‘ i ∈ s, f i) * (βˆ‘ i ∈ s, f i)!) * ∏ i ∈ s, (f i)! := by gcongr; exact Nat.factorial_two_mul_le _ _ = ((βˆ‘ i ∈ s, f i) ^ βˆ‘ i ∈ s, f i) * (βˆ‘ i ∈ s, f i)! * ∏ i ∈ s, 2 ^ f i * (f i)! := by rw [mul_pow, ← prod_pow_eq_pow_sum, prod_mul_distrib]; ring _ ≀ ((βˆ‘ i ∈ s, f i) ^ βˆ‘ i ∈ s, f i) * (βˆ‘ i ∈ s, f i)! * ∏ i ∈ s, (2 * f i)! := by gcongr rw [← doubleFactorial_two_mul] exact doubleFactorial_le_factorial _ end Nat namespace Sym variable {n : β„•} {Ξ± : Type*} [DecidableEq Ξ±] theorem multinomial_coe_fill_of_notMem {m : Fin (n + 1)} {s : Sym Ξ± (n - m)} {x : Ξ±} (hx : x βˆ‰ s) : (fill x m s : Multiset Ξ±).multinomial = n.choose m * (s : Multiset Ξ±).multinomial := by rw [Multiset.multinomial_filter_ne x] rw [← mem_coe] at hx refine congrArgβ‚‚ _ ?_ ?_ Β· rw [card_coe, count_coe_fill_self_of_notMem hx] Β· refine congrArg _ ?_ rw [coe_fill, coe_replicate, Multiset.filter_add] rw [Multiset.filter_eq_self.mpr] Β· rw [add_eq_left] rw [Multiset.filter_eq_nil] exact fun j hj ↦ by simp [Multiset.mem_replicate.mp hj] Β· exact fun j hj h ↦ hx <| by simpa [h] using hj @[deprecated (since := "2025-05-23")] alias multinomial_coe_fill_of_not_mem := multinomial_coe_fill_of_notMem end Sym
.lake/packages/mathlib/Mathlib/Data/Nat/Choose/Cast.lean
import Mathlib.Algebra.Field.Defs import Mathlib.Algebra.GroupWithZero.Units.Basic import Mathlib.Data.Nat.Choose.Basic import Mathlib.Data.Nat.Factorial.Cast /-! # Cast of binomial coefficients This file allows calculating the binomial coefficient `a.choose b` as an element of a division ring of characteristic `0`. -/ open Nat variable (K : Type*) namespace Nat section DivisionSemiring variable [DivisionSemiring K] [CharZero K] theorem cast_choose {a b : β„•} (h : a ≀ b) : (b.choose a : K) = b ! / (a ! * (b - a)!) := by have : βˆ€ {n : β„•}, (n ! : K) β‰  0 := Nat.cast_ne_zero.2 (factorial_pos _).ne' rw [eq_div_iff_mul_eq (mul_ne_zero this this)] rw_mod_cast [← mul_assoc, choose_mul_factorial_mul_factorial h] theorem cast_add_choose {a b : β„•} : ((a + b).choose a : K) = (a + b)! / (a ! * b !) := by rw [cast_choose K (le_add_right _ _), Nat.add_sub_cancel_left] end DivisionSemiring section DivisionRing variable [DivisionRing K] [NeZero (2 : K)] theorem cast_choose_two (a : β„•) : (a.choose 2 : K) = a * (a - 1) / 2 := by rw [← cast_descFactorial_two, descFactorial_eq_factorial_mul_choose, factorial_two, mul_comm, cast_mul, cast_two, eq_div_iff_mul_eq two_ne_zero] end DivisionRing end Nat