source
stringlengths
17
118
lean4
stringlengths
0
335k
.lake/packages/mathlib/Mathlib/Data/Nat/Choose/Bounds.lean
import Mathlib.Algebra.Field.Defs import Mathlib.Algebra.Order.Ring.Defs import Mathlib.Data.Nat.Cast.Order.Basic import Mathlib.Data.Nat.Choose.Basic /-! # Inequalities for binomial coefficients This file proves exponential bounds on binomial coefficients. We might want to add here the bounds `n^r/r^r ≤ n.choose r ≤ e^r n^r/r^r` in the future. ## Main declarations * `Nat.choose_le_pow_div`: `n.choose r ≤ n^r / r!` * `Nat.pow_le_choose`: `(n + 1 - r)^r / r! ≤ n.choose r`. Beware of the fishy ℕ-subtraction. -/ open Nat variable {α : Type*} [Semifield α] [LinearOrder α] [IsStrictOrderedRing α] {n k : ℕ} namespace Nat theorem choose_le_pow_div (r n : ℕ) : (n.choose r : α) ≤ (n ^ r : α) / r ! := by rw [le_div_iff₀'] · norm_cast rw [← Nat.descFactorial_eq_factorial_mul_choose] exact n.descFactorial_le_pow r exact mod_cast r.factorial_pos lemma choose_lt_pow_div (hn : n ≠ 0) (hk : 2 ≤ k) : (n.choose k : α) < (n ^ k : α) / k ! := by rw [lt_div_iff₀' (mod_cast k.factorial_pos)] norm_cast rw [← Nat.descFactorial_eq_factorial_mul_choose] exact descFactorial_lt_pow hn hk lemma choose_le_descFactorial (n k : ℕ) : n.choose k ≤ n.descFactorial k := by rw [choose_eq_descFactorial_div_factorial] exact Nat.div_le_self _ _ lemma choose_lt_descFactorial (hk : 2 ≤ k) (hkn : k ≤ n) : n.choose k < n.descFactorial k := by rw [choose_eq_descFactorial_div_factorial]; exact Nat.div_lt_self (by simpa) (by simpa) lemma choose_le_pow (n k : ℕ) : n.choose k ≤ n ^ k := (choose_le_descFactorial n k).trans (descFactorial_le_pow n k) lemma choose_lt_pow (hn : n ≠ 0) (hk : 2 ≤ k) : n.choose k < n ^ k := (choose_le_descFactorial n k).trans_lt (descFactorial_lt_pow hn hk) -- horrific casting is due to ℕ-subtraction theorem pow_le_choose (r n : ℕ) : ((n + 1 - r : ℕ) ^ r : α) / r ! ≤ n.choose r := by rw [div_le_iff₀'] · norm_cast rw [← Nat.descFactorial_eq_factorial_mul_choose] exact n.pow_sub_le_descFactorial r exact mod_cast r.factorial_pos theorem choose_succ_le_two_pow (n k : ℕ) : (n + 1).choose k ≤ 2 ^ n := by by_cases lt : n + 1 < k · simp [choose_eq_zero_of_lt lt] · cases n with | zero => cases k <;> simp_all | succ n => rcases k with - | k · rw [choose_zero_right] exact Nat.one_le_two_pow · rw [choose_succ_succ', two_pow_succ] exact Nat.add_le_add (choose_succ_le_two_pow n k) (choose_succ_le_two_pow n (k + 1)) theorem choose_lt_two_pow (n k : ℕ) (p : 0 < n) : n.choose k < 2 ^ n := by refine lt_of_le_of_lt ?_ (Nat.two_pow_pred_lt_two_pow p) rw [← Nat.sub_add_cancel p] exact choose_succ_le_two_pow (n - 1) k theorem choose_le_two_pow (n k : ℕ) : n.choose k ≤ 2 ^ n := by obtain (rfl | hn) := eq_zero_or_pos n · cases k <;> simp · exact (Nat.choose_lt_two_pow _ _ hn).le end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Cast/SetInterval.lean
import Mathlib.Algebra.Ring.Int.Defs import Mathlib.Data.Nat.Cast.Order.Basic import Mathlib.Order.Interval.Set.OrdConnected import Mathlib.Order.Nat import Mathlib.Order.UpperLower.Basic /-! # Images of intervals under `Nat.cast : ℕ → ℤ` In this file we prove that the image of each `Set.Ixx` interval under `Nat.cast : ℕ → ℤ` is the corresponding interval in `ℤ`. -/ open Set namespace Nat @[simp] theorem range_cast_int : range ((↑) : ℕ → ℤ) = Ici 0 := Subset.antisymm (range_subset_iff.2 Int.natCast_nonneg) CanLift.prf theorem image_cast_int_Icc (a b : ℕ) : (↑) '' Icc a b = Icc (a : ℤ) b := (castOrderEmbedding (α := ℤ)).image_Icc (by simp [ordConnected_Ici]) a b theorem image_cast_int_Ico (a b : ℕ) : (↑) '' Ico a b = Ico (a : ℤ) b := (castOrderEmbedding (α := ℤ)).image_Ico (by simp [ordConnected_Ici]) a b theorem image_cast_int_Ioc (a b : ℕ) : (↑) '' Ioc a b = Ioc (a : ℤ) b := (castOrderEmbedding (α := ℤ)).image_Ioc (by simp [ordConnected_Ici]) a b theorem image_cast_int_Ioo (a b : ℕ) : (↑) '' Ioo a b = Ioo (a : ℤ) b := (castOrderEmbedding (α := ℤ)).image_Ioo (by simp [ordConnected_Ici]) a b theorem image_cast_int_Iic (a : ℕ) : (↑) '' Iic a = Icc (0 : ℤ) a := by rw [← Icc_bot, image_cast_int_Icc]; rfl theorem image_cast_int_Iio (a : ℕ) : (↑) '' Iio a = Ico (0 : ℤ) a := by rw [← Ico_bot, image_cast_int_Ico]; rfl theorem image_cast_int_Ici (a : ℕ) : (↑) '' Ici a = Ici (a : ℤ) := (castOrderEmbedding (α := ℤ)).image_Ici (by simp [isUpperSet_Ici]) a theorem image_cast_int_Ioi (a : ℕ) : (↑) '' Ioi a = Ioi (a : ℤ) := (castOrderEmbedding (α := ℤ)).image_Ioi (by simp [isUpperSet_Ici]) a end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Cast/WithTop.lean
import Mathlib.Algebra.Ring.Nat import Mathlib.Algebra.Order.Monoid.Unbundled.WithTop /-! # Lemma about the coercion `ℕ → WithBot ℕ`. An orphaned lemma about casting from `ℕ` to `WithBot ℕ`, exiled here during the port to minimize imports of `Algebra.Order.Ring.Rat`. -/ instance : WellFoundedRelation (WithTop ℕ) where rel := (· < ·) wf := IsWellFounded.wf theorem Nat.cast_withTop (n : ℕ) : Nat.cast n = WithTop.some n := rfl theorem Nat.cast_withBot (n : ℕ) : Nat.cast n = WithBot.some n := rfl
.lake/packages/mathlib/Mathlib/Data/Nat/Cast/Synonym.lean
import Mathlib.Data.Nat.Cast.Defs import Mathlib.Order.Synonym /-! # Cast of natural numbers (additional theorems) This file proves additional properties about the *canonical* homomorphism from the natural numbers into an additive monoid with a one (`Nat.cast`). -/ variable {α : Type*} /-! ### Order dual -/ open OrderDual instance [h : NatCast α] : NatCast αᵒᵈ := h instance [h : AddMonoidWithOne α] : AddMonoidWithOne αᵒᵈ := h instance [h : AddCommMonoidWithOne α] : AddCommMonoidWithOne αᵒᵈ := h @[simp] theorem toDual_natCast [NatCast α] (n : ℕ) : toDual (n : α) = n := rfl @[simp] theorem toDual_ofNat [NatCast α] (n : ℕ) [n.AtLeastTwo] : (toDual (ofNat(n) : α)) = ofNat(n) := rfl @[simp] theorem ofDual_natCast [NatCast α] (n : ℕ) : (ofDual n : α) = n := rfl @[simp] theorem ofDual_ofNat [NatCast α] (n : ℕ) [n.AtLeastTwo] : (ofDual (ofNat(n) : αᵒᵈ)) = ofNat(n) := rfl /-! ### Lexicographic order -/ instance [h : NatCast α] : NatCast (Lex α) := h instance [h : AddMonoidWithOne α] : AddMonoidWithOne (Lex α) := h instance [h : AddCommMonoidWithOne α] : AddCommMonoidWithOne (Lex α) := h @[simp] theorem toLex_natCast [NatCast α] (n : ℕ) : toLex (n : α) = n := rfl @[simp] theorem toLex_ofNat [NatCast α] (n : ℕ) [n.AtLeastTwo] : toLex (ofNat(n) : α) = OfNat.ofNat n := rfl @[simp] theorem ofLex_natCast [NatCast α] (n : ℕ) : (ofLex n : α) = n := rfl @[simp] theorem ofLex_ofNat [NatCast α] (n : ℕ) [n.AtLeastTwo] : ofLex (ofNat(n) : Lex α) = OfNat.ofNat n := rfl
.lake/packages/mathlib/Mathlib/Data/Nat/Cast/Prod.lean
import Mathlib.Algebra.Group.Prod import Mathlib.Data.Nat.Cast.Defs /-! # The product of two `AddMonoidWithOne`s. -/ assert_not_exists MonoidWithZero variable {α β : Type*} namespace Prod variable [AddMonoidWithOne α] [AddMonoidWithOne β] instance instAddMonoidWithOne : AddMonoidWithOne (α × β) := { Prod.instAddMonoid, @Prod.instOne α β _ _ with natCast := fun n => (n, n) natCast_zero := congr_arg₂ Prod.mk Nat.cast_zero Nat.cast_zero natCast_succ := fun _ => congr_arg₂ Prod.mk (Nat.cast_succ _) (Nat.cast_succ _) } @[simp] theorem fst_natCast (n : ℕ) : (n : α × β).fst = n := by induction n <;> simp [*] @[simp] theorem fst_ofNat (n : ℕ) [n.AtLeastTwo] : (ofNat(n) : α × β).1 = (ofNat(n) : α) := rfl @[simp] theorem snd_natCast (n : ℕ) : (n : α × β).snd = n := by induction n <;> simp [*] @[simp] theorem snd_ofNat (n : ℕ) [n.AtLeastTwo] : (ofNat(n) : α × β).2 = (ofNat(n) : β) := rfl end Prod
.lake/packages/mathlib/Mathlib/Data/Nat/Cast/Commute.lean
import Mathlib.Algebra.GroupWithZero.Commute import Mathlib.Algebra.Ring.Commute /-! # Cast of natural numbers: lemmas about `Commute` -/ variable {α : Type*} namespace Nat section Commute variable [NonAssocSemiring α] theorem cast_commute (n : ℕ) (x : α) : Commute (n : α) x := by induction n with | zero => rw [Nat.cast_zero]; exact Commute.zero_left x | succ n ihn => rw [Nat.cast_succ]; exact ihn.add_left (Commute.one_left x) theorem _root_.Commute.ofNat_left (n : ℕ) [n.AtLeastTwo] (x : α) : Commute (OfNat.ofNat n) x := n.cast_commute x theorem cast_comm (n : ℕ) (x : α) : (n : α) * x = x * n := (cast_commute n x).eq theorem commute_cast (x : α) (n : ℕ) : Commute x n := (n.cast_commute x).symm theorem _root_.Commute.ofNat_right (x : α) (n : ℕ) [n.AtLeastTwo] : Commute x (OfNat.ofNat n) := n.commute_cast x end Commute end Nat namespace SemiconjBy variable [Semiring α] {a x y : α} @[simp] lemma natCast_mul_right (h : SemiconjBy a x y) (n : ℕ) : SemiconjBy a (n * x) (n * y) := SemiconjBy.mul_right (Nat.commute_cast _ _) h @[simp] lemma natCast_mul_left (h : SemiconjBy a x y) (n : ℕ) : SemiconjBy (n * a) x y := SemiconjBy.mul_left (Nat.cast_commute _ _) h lemma natCast_mul_natCast_mul (h : SemiconjBy a x y) (m n : ℕ) : SemiconjBy (m * a) (n * x) (n * y) := by simp [h] end SemiconjBy namespace Commute variable [Semiring α] {a b : α} @[simp] lemma natCast_mul_right (h : Commute a b) (n : ℕ) : Commute a (n * b) := SemiconjBy.natCast_mul_right h n @[simp] lemma natCast_mul_left (h : Commute a b) (n : ℕ) : Commute (n * a) b := SemiconjBy.natCast_mul_left h n lemma natCast_mul_natCast_mul (h : Commute a b) (m n : ℕ) : Commute (m * a) (n * b) := by simp [h] variable (a) (m n : ℕ) lemma self_natCast_mul : Commute a (n * a) := (Commute.refl a).natCast_mul_right n lemma natCast_mul_self : Commute (n * a) a := (Commute.refl a).natCast_mul_left n lemma self_natCast_mul_natCast_mul : Commute (m * a) (n * a) := (Commute.refl a).natCast_mul_natCast_mul m n end Commute
.lake/packages/mathlib/Mathlib/Data/Nat/Cast/Basic.lean
import Mathlib.Algebra.Divisibility.Hom import Mathlib.Algebra.Group.Even import Mathlib.Algebra.Group.Nat.Hom import Mathlib.Algebra.Ring.Hom.Defs import Mathlib.Algebra.Ring.Nat /-! # Cast of natural numbers (additional theorems) This file proves additional properties about the *canonical* homomorphism from the natural numbers into an additive monoid with a one (`Nat.cast`). ## Main declarations * `castAddMonoidHom`: `cast` bundled as an `AddMonoidHom`. * `castRingHom`: `cast` bundled as a `RingHom`. -/ assert_not_exists IsOrderedMonoid Commute.zero_right Commute.add_right abs_eq_max_neg NeZero.natCast_ne -- TODO: `MulOpposite.op_natCast` was not intended to be imported -- assert_not_exists MulOpposite.op_natCast open Additive Multiplicative variable {α β : Type*} namespace Nat /-- `Nat.cast : ℕ → α` as an `AddMonoidHom`. -/ def castAddMonoidHom (α : Type*) [AddMonoidWithOne α] : ℕ →+ α where toFun := Nat.cast map_add' := cast_add map_zero' := cast_zero @[simp] theorem coe_castAddMonoidHom [AddMonoidWithOne α] : (castAddMonoidHom α : ℕ → α) = Nat.cast := rfl lemma _root_.Even.natCast [AddMonoidWithOne α] {n : ℕ} (hn : Even n) : Even (n : α) := hn.map <| Nat.castAddMonoidHom α section NonAssocSemiring variable [NonAssocSemiring α] @[simp, norm_cast] lemma cast_mul (m n : ℕ) : ((m * n : ℕ) : α) = m * n := by induction n <;> simp [mul_add, *] variable (α) in /-- `Nat.cast : ℕ → α` as a `RingHom` -/ def castRingHom : ℕ →+* α := { castAddMonoidHom α with toFun := Nat.cast, map_one' := cast_one, map_mul' := cast_mul } @[simp, norm_cast] lemma coe_castRingHom : (castRingHom α : ℕ → α) = Nat.cast := rfl lemma _root_.nsmul_eq_mul' (a : α) (n : ℕ) : n • a = a * n := by induction n with | zero => rw [zero_nsmul, Nat.cast_zero, mul_zero] | succ n ih => rw [succ_nsmul, ih, Nat.cast_succ, mul_add, mul_one] lemma ofNat_nsmul_eq_mul (n : ℕ) [n.AtLeastTwo] (a : α) : ofNat(n) • a = ofNat(n) * a := by simp [nsmul_eq_mul] end NonAssocSemiring section Semiring variable [Semiring α] {m n : ℕ} @[simp, norm_cast] lemma cast_pow (m : ℕ) : ∀ n : ℕ, ↑(m ^ n) = (m ^ n : α) | 0 => by simp | n + 1 => by rw [_root_.pow_succ', _root_.pow_succ', cast_mul, cast_pow m n] @[gcongr] lemma cast_dvd_cast (h : m ∣ n) : (m : α) ∣ (n : α) := map_dvd (Nat.castRingHom α) h alias _root_.Dvd.dvd.natCast := cast_dvd_cast end Semiring end Nat section AddMonoidHomClass variable {A B F : Type*} [AddMonoidWithOne B] [FunLike F ℕ A] [AddMonoidWithOne A] -- these versions are primed so that the `RingHomClass` versions aren't theorem eq_natCast' [AddMonoidHomClass F ℕ A] (f : F) (h1 : f 1 = 1) : ∀ n : ℕ, f n = n | 0 => by simp | n + 1 => by rw [map_add, h1, eq_natCast' f h1 n, Nat.cast_add_one] theorem map_natCast' {A} [AddMonoidWithOne A] [FunLike F A B] [AddMonoidHomClass F A B] (f : F) (h : f 1 = 1) : ∀ n : ℕ, f n = n := eq_natCast' ((f : A →+ B).comp <| Nat.castAddMonoidHom _) (by simpa) theorem map_ofNat' {A} [AddMonoidWithOne A] [FunLike F A B] [AddMonoidHomClass F A B] (f : F) (h : f 1 = 1) (n : ℕ) [n.AtLeastTwo] : f (OfNat.ofNat n) = OfNat.ofNat n := map_natCast' f h n end AddMonoidHomClass section MonoidWithZeroHomClass variable {A F : Type*} [MulZeroOneClass A] [FunLike F ℕ A] /-- If two `MonoidWithZeroHom`s agree on the positive naturals they are equal. -/ theorem ext_nat'' [ZeroHomClass F ℕ A] (f g : F) (h_pos : ∀ {n : ℕ}, 0 < n → f n = g n) : f = g := by apply DFunLike.ext rintro (_ | n) · simp · exact h_pos n.succ_pos @[ext] theorem MonoidWithZeroHom.ext_nat {f g : ℕ →*₀ A} : (∀ {n : ℕ}, 0 < n → f n = g n) → f = g := ext_nat'' f g end MonoidWithZeroHomClass section RingHomClass variable {R S F : Type*} [NonAssocSemiring R] [NonAssocSemiring S] @[simp] theorem eq_natCast [FunLike F ℕ R] [RingHomClass F ℕ R] (f : F) : ∀ n, f n = n := eq_natCast' f <| map_one f @[simp] theorem map_natCast [FunLike F R S] [RingHomClass F R S] (f : F) : ∀ n : ℕ, f (n : R) = n := map_natCast' f <| map_one f /-- This lemma is not marked `@[simp]` lemma because its `#discr_tree_key` (for the LHS) would just be `DFunLike.coe _ _`, due to the `ofNat` that https://github.com/leanprover/lean4/issues/2867 forces us to include, and therefore it would negatively impact performance. If that issue is resolved, this can be marked `@[simp]`. -/ theorem map_ofNat [FunLike F R S] [RingHomClass F R S] (f : F) (n : ℕ) [Nat.AtLeastTwo n] : (f ofNat(n) : S) = OfNat.ofNat n := map_natCast f n theorem ext_nat [FunLike F ℕ R] [RingHomClass F ℕ R] (f g : F) : f = g := ext_nat' f g <| by simp theorem NeZero.nat_of_neZero {R S} [NonAssocSemiring R] [NonAssocSemiring S] {F} [FunLike F R S] [RingHomClass F R S] (f : F) {n : ℕ} [hn : NeZero (n : S)] : NeZero (n : R) := .of_map (f := f) (neZero := by simp only [map_natCast, hn]) end RingHomClass namespace RingHom /-- This is primed to match `eq_intCast'`. -/ theorem eq_natCast' {R} [NonAssocSemiring R] (f : ℕ →+* R) : f = Nat.castRingHom R := RingHom.ext <| eq_natCast f end RingHom @[simp, norm_cast] theorem Nat.cast_id (n : ℕ) : n.cast = n := rfl @[simp] theorem Nat.castRingHom_nat : Nat.castRingHom ℕ = RingHom.id ℕ := rfl /-- We don't use `RingHomClass` here, since that might cause type-class slowdown for `Subsingleton`. -/ instance Nat.uniqueRingHom {R : Type*} [NonAssocSemiring R] : Unique (ℕ →+* R) where default := Nat.castRingHom R uniq := RingHom.eq_natCast' namespace Pi variable {π : α → Type*} section NatCast variable [∀ a, NatCast (π a)] instance instNatCast : NatCast (∀ a, π a) where natCast n _ := n @[simp] theorem natCast_apply (n : ℕ) (a : α) : (n : ∀ a, π a) a = n := rfl @[push ←] theorem natCast_def (n : ℕ) : (n : ∀ a, π a) = fun _ ↦ ↑n := rfl end NatCast section OfNat -- This instance is low priority, as `to_additive` only works with the one that comes from `One` -- and `Zero`. instance (priority := low) instOfNat (n : ℕ) [∀ i, OfNat (π i) n] : OfNat ((i : α) → π i) n where ofNat _ := OfNat.ofNat n @[simp] theorem ofNat_apply (n : ℕ) [∀ i, OfNat (π i) n] (a : α) : (ofNat(n) : ∀ a, π a) a = ofNat(n) := rfl @[push ←] lemma ofNat_def (n : ℕ) [∀ i, OfNat (π i) n] : (ofNat(n) : ∀ a, π a) = fun _ ↦ ofNat(n) := rfl end OfNat end Pi theorem Sum.elim_natCast_natCast {α β γ : Type*} [NatCast γ] (n : ℕ) : Sum.elim (n : α → γ) (n : β → γ) = n := Sum.elim_lam_const_lam_const (γ := γ) n
.lake/packages/mathlib/Mathlib/Data/Nat/Cast/Defs.lean
import Mathlib.Algebra.Group.Defs import Mathlib.Data.Nat.Init import Mathlib.Tactic.SplitIfs /-! # Cast of natural numbers This file defines the *canonical* homomorphism from the natural numbers into an `AddMonoid` with a one. In additive monoids with one, there exists a unique such homomorphism and we store it in the `natCast : ℕ → R` field. Preferentially, the homomorphism is written as the coercion `Nat.cast`. ## Main declarations * `NatCast`: Type class for `Nat.cast`. * `AddMonoidWithOne`: Type class for which `Nat.cast` is a canonical monoid homomorphism from `ℕ`. * `Nat.cast`: Canonical homomorphism `ℕ → R`. -/ variable {R : Type*} /-- The numeral `((0+1)+⋯)+1`. -/ protected def Nat.unaryCast [One R] [Zero R] [Add R] : ℕ → R | 0 => 0 | n + 1 => Nat.unaryCast n + 1 /-- Recognize numeric literals which are at least `2` as terms of `R` via `Nat.cast`. This instance is what makes things like `37 : R` type check. Note that `0` and `1` are not needed because they are recognized as terms of `R` (at least when `R` is an `AddMonoidWithOne`) through `Zero` and `One`, respectively. -/ @[nolint unusedArguments] instance (priority := 100) instOfNatAtLeastTwo {n : ℕ} [NatCast R] [Nat.AtLeastTwo n] : OfNat R n where ofNat := n.cast library_note2 «no_index around OfNat.ofNat» /-- When writing lemmas about `OfNat.ofNat` that assume `Nat.AtLeastTwo`, the term needs to be wrapped in `no_index` so as not to confuse `simp`, as `no_index (OfNat.ofNat n)`. Rather than referencing this library note, use `ofNat(n)` as a shorthand for `no_index (OfNat.ofNat n)`. Some discussion is [on Zulip here](https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/.E2.9C.94.20Polynomial.2Ecoeff.20example/near/395438147). -/ @[simp, norm_cast] theorem Nat.cast_ofNat {n : ℕ} [NatCast R] [Nat.AtLeastTwo n] : (Nat.cast ofNat(n) : R) = ofNat(n) := rfl /-! ### Additive monoids with one -/ /-- An `AddMonoidWithOne` is an `AddMonoid` with a `1`. It also contains data for the unique homomorphism `ℕ → R`. -/ class AddMonoidWithOne (R : Type*) extends NatCast R, AddMonoid R, One R where natCast := Nat.unaryCast /-- The canonical map `ℕ → R` sends `0 : ℕ` to `0 : R`. -/ natCast_zero : natCast 0 = 0 := by intros; rfl /-- The canonical map `ℕ → R` is a homomorphism. -/ natCast_succ : ∀ n, natCast (n + 1) = natCast n + 1 := by intros; rfl /-- An `AddCommMonoidWithOne` is an `AddMonoidWithOne` satisfying `a + b = b + a`. -/ class AddCommMonoidWithOne (R : Type*) extends AddMonoidWithOne R, AddCommMonoid R library_note2 «coercion into rings» /-- Coercions such as `Nat.castCoe` that go from a concrete structure such as `ℕ` to an arbitrary ring `R` should be set up as follows: ```lean instance : CoeTail ℕ R where coe := ... instance : CoeHTCT ℕ R where coe := ... ``` It needs to be `CoeTail` instead of `Coe` because otherwise type-class inference would loop when constructing the transitive coercion `ℕ → ℕ → ℕ → ...`. Sometimes we also need to declare the `CoeHTCT` instance if we need to shadow another coercion (e.g. `Nat.cast` should be used over `Int.ofNat`). -/ namespace Nat variable [AddMonoidWithOne R] @[simp, norm_cast] theorem cast_zero : ((0 : ℕ) : R) = 0 := AddMonoidWithOne.natCast_zero -- Lemmas about `Nat.succ` need to get a low priority, so that they are tried last. -- This is because `Nat.succ _` matches `1`, `3`, `x+1`, etc. -- Rewriting would then produce really wrong terms. @[norm_cast 500] theorem cast_succ (n : ℕ) : ((succ n : ℕ) : R) = n + 1 := AddMonoidWithOne.natCast_succ _ theorem cast_add_one (n : ℕ) : ((n + 1 : ℕ) : R) = n + 1 := cast_succ _ @[simp, norm_cast] theorem cast_ite (P : Prop) [Decidable P] (m n : ℕ) : ((ite P m n : ℕ) : R) = ite P (m : R) (n : R) := by split_ifs <;> rfl end Nat namespace Nat @[simp, norm_cast] theorem cast_one [AddMonoidWithOne R] : ((1 : ℕ) : R) = 1 := by rw [cast_succ, Nat.cast_zero, zero_add] @[simp, norm_cast] theorem cast_add [AddMonoidWithOne R] (m n : ℕ) : ((m + n : ℕ) : R) = m + n := by induction n with | zero => simp | succ n ih => rw [add_succ, cast_succ, ih, cast_succ, add_assoc] /-- Computationally friendlier cast than `Nat.unaryCast`, using binary representation. -/ protected def binCast [Zero R] [One R] [Add R] : ℕ → R | 0 => 0 | n + 1 => if (n + 1) % 2 = 0 then (Nat.binCast ((n + 1) / 2)) + (Nat.binCast ((n + 1) / 2)) else (Nat.binCast ((n + 1) / 2)) + (Nat.binCast ((n + 1) / 2)) + 1 @[simp] theorem binCast_eq [AddMonoidWithOne R] (n : ℕ) : (Nat.binCast n : R) = ((n : ℕ) : R) := by induction n using Nat.strongRecOn with | ind k hk => ?_ cases k with | zero => rw [Nat.binCast, Nat.cast_zero] | succ k => rw [Nat.binCast] by_cases h : (k + 1) % 2 = 0 · conv => rhs; rw [← Nat.mod_add_div (k + 1) 2] rw [if_pos h, hk _ <| Nat.div_lt_self (Nat.succ_pos k) (Nat.le_refl 2), ← Nat.cast_add] rw [h, Nat.zero_add, Nat.succ_mul, Nat.one_mul] · conv => rhs; rw [← Nat.mod_add_div (k + 1) 2] rw [if_neg h, hk _ <| Nat.div_lt_self (Nat.succ_pos k) (Nat.le_refl 2), ← Nat.cast_add] have h1 := Or.resolve_left (Nat.mod_two_eq_zero_or_one (succ k)) h rw [h1, Nat.add_comm 1, Nat.succ_mul, Nat.one_mul] simp only [Nat.cast_add, Nat.cast_one] theorem cast_two [NatCast R] : ((2 : ℕ) : R) = (2 : R) := rfl theorem cast_three [NatCast R] : ((3 : ℕ) : R) = (3 : R) := rfl theorem cast_four [NatCast R] : ((4 : ℕ) : R) = (4 : R) := rfl attribute [simp, norm_cast] Int.natAbs_natCast end Nat /-- `AddMonoidWithOne` implementation using unary recursion. -/ protected abbrev AddMonoidWithOne.unary [AddMonoid R] [One R] : AddMonoidWithOne R := { ‹One R›, ‹AddMonoid R› with } /-- `AddMonoidWithOne` implementation using binary recursion. -/ protected abbrev AddMonoidWithOne.binary [AddMonoid R] [One R] : AddMonoidWithOne R := { ‹One R›, ‹AddMonoid R› with natCast := Nat.binCast, natCast_zero := by simp only [Nat.binCast], natCast_succ := fun n => by letI : AddMonoidWithOne R := AddMonoidWithOne.unary rw [Nat.binCast_eq, Nat.binCast_eq, Nat.cast_succ] } theorem one_add_one_eq_two [AddMonoidWithOne R] : 1 + 1 = (2 : R) := by rw [← Nat.cast_one, ← Nat.cast_add] apply congrArg decide theorem two_add_one_eq_three [AddMonoidWithOne R] : 2 + 1 = (3 : R) := by rw [← one_add_one_eq_two, ← Nat.cast_one, ← Nat.cast_add, ← Nat.cast_add] apply congrArg decide theorem three_add_one_eq_four [AddMonoidWithOne R] : 3 + 1 = (4 : R) := by rw [← two_add_one_eq_three, ← one_add_one_eq_two, ← Nat.cast_one, ← Nat.cast_add, ← Nat.cast_add, ← Nat.cast_add] apply congrArg decide theorem two_add_two_eq_four [AddMonoidWithOne R] : 2 + 2 = (4 : R) := by simp [← one_add_one_eq_two, ← Nat.cast_one, ← three_add_one_eq_four, ← two_add_one_eq_three, add_assoc] section nsmul @[simp] lemma nsmul_one {A} [AddMonoidWithOne A] : ∀ n : ℕ, n • (1 : A) = n | 0 => by simp [zero_nsmul] | n + 1 => by simp [succ_nsmul, nsmul_one n] end nsmul
.lake/packages/mathlib/Mathlib/Data/Nat/Cast/Field.lean
import Mathlib.Algebra.CharZero.Defs import Mathlib.Data.Nat.Cast.Basic import Mathlib.Tactic.Common import Mathlib.Algebra.Field.Defs import Mathlib.Algebra.GroupWithZero.Units.Basic /-! # Cast of naturals into fields This file concerns the canonical homomorphism `ℕ → F`, where `F` is a field. ## Main results * `Nat.cast_div`: if `n` divides `m`, then `↑(m / n) = ↑m / ↑n` -/ namespace Nat variable {K : Type*} [DivisionSemiring K] {d m n : ℕ} @[simp] lemma cast_div (hnm : n ∣ m) (hn : (n : K) ≠ 0) : (↑(m / n) : K) = m / n := by obtain ⟨k, rfl⟩ := hnm have : n ≠ 0 := by rintro rfl; simp at hn rw [Nat.mul_div_cancel_left _ <| zero_lt_of_ne_zero this, mul_comm n, cast_mul, mul_div_cancel_right₀ _ hn] variable [CharZero K] @[simp, norm_cast] lemma cast_div_charZero (hnm : n ∣ m) : (↑(m / n) : K) = m / n := by obtain rfl | hn := eq_or_ne n 0 <;> simp [*] lemma cast_div_div_div_cancel_right (hn : d ∣ n) (hm : d ∣ m) : (↑(m / d) : K) / (↑(n / d) : K) = (m : K) / n := by rcases eq_or_ne d 0 with (rfl | hd); · simp [Nat.zero_dvd.1 hm] replace hd : (d : K) ≠ 0 := by norm_cast rw [cast_div hm, cast_div hn, div_div_div_cancel_right₀ hd] <;> exact hd end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Cast/NeZero.lean
import Mathlib.Data.Nat.Cast.Defs /-! # Lemmas about nonzero elements of an `AddMonoidWithOne` -/ open Nat namespace NeZero theorem one_le {n : ℕ} [NeZero n] : 1 ≤ n := by have := NeZero.ne n; cutsat lemma natCast_ne (n : ℕ) (R) [AddMonoidWithOne R] [h : NeZero (n : R)] : (n : R) ≠ 0 := h.out lemma of_neZero_natCast (R) [AddMonoidWithOne R] {n : ℕ} [h : NeZero (n : R)] : NeZero n := ⟨by rintro rfl; exact h.out Nat.cast_zero⟩ lemma pos_of_neZero_natCast (R) [AddMonoidWithOne R] {n : ℕ} [NeZero (n : R)] : 0 < n := Nat.pos_of_ne_zero (of_neZero_natCast R).out end NeZero
.lake/packages/mathlib/Mathlib/Data/Nat/Cast/Order/Ring.lean
import Mathlib.Algebra.Order.Group.Unbundled.Abs import Mathlib.Algebra.Order.Ring.Nat import Mathlib.Algebra.Order.Sub.Basic import Mathlib.Data.Nat.Cast.Order.Basic /-! # Cast of natural numbers: lemmas about bundled ordered semirings -/ variable {R α : Type*} namespace Nat section OrderedSemiring /- Note: even though the section indicates `OrderedSemiring`, which is the common use case, we use a generic collection of instances so that it applies in other settings (e.g., in a `StarOrderedRing`, or the `selfAdjoint` or `StarOrderedRing.positive` parts thereof). -/ variable [AddMonoidWithOne α] [PartialOrder α] variable [AddLeftMono α] [ZeroLEOneClass α] /-- Specialisation of `Nat.cast_nonneg'`, which seems to be easier for Lean to use. -/ @[simp] theorem cast_nonneg {α} [Semiring α] [PartialOrder α] [IsOrderedRing α] (n : ℕ) : 0 ≤ (n : α) := cast_nonneg' n /-- Specialisation of `Nat.ofNat_nonneg'`, which seems to be easier for Lean to use. -/ @[simp] theorem ofNat_nonneg {α} [Semiring α] [PartialOrder α] [IsOrderedRing α] (n : ℕ) [n.AtLeastTwo] : 0 ≤ (ofNat(n) : α) := ofNat_nonneg' n @[simp, norm_cast] theorem cast_min {α} [Semiring α] [LinearOrder α] [IsStrictOrderedRing α] (m n : ℕ) : (↑(min m n : ℕ) : α) = min (m : α) n := (@mono_cast α _).map_min @[simp, norm_cast] theorem cast_max {α} [Semiring α] [LinearOrder α] [IsStrictOrderedRing α] (m n : ℕ) : (↑(max m n : ℕ) : α) = max (m : α) n := (@mono_cast α _).map_max section Nontrivial variable [NeZero (1 : α)] /-- Specialisation of `Nat.cast_pos'`, which seems to be easier for Lean to use. -/ @[simp] theorem cast_pos {α} [Semiring α] [PartialOrder α] [IsOrderedRing α] [Nontrivial α] {n : ℕ} : (0 : α) < n ↔ 0 < n := cast_pos' /-- See also `Nat.ofNat_pos`, specialised for an `OrderedSemiring`. -/ @[simp low] theorem ofNat_pos' {n : ℕ} [n.AtLeastTwo] : 0 < (ofNat(n) : α) := cast_pos'.mpr (NeZero.pos n) /-- Specialisation of `Nat.ofNat_pos'`, which seems to be easier for Lean to use. -/ @[simp] theorem ofNat_pos {α} [Semiring α] [PartialOrder α] [IsOrderedRing α] [Nontrivial α] {n : ℕ} [n.AtLeastTwo] : 0 < (ofNat(n) : α) := ofNat_pos' end Nontrivial end OrderedSemiring /-- A version of `Nat.cast_sub` that works for `ℝ≥0` and `ℚ≥0`. Note that this proof doesn't work for `ℕ∞` and `ℝ≥0∞`, so we use type-specific lemmas for these types. -/ @[simp, norm_cast] theorem cast_tsub [CommSemiring α] [PartialOrder α] [IsOrderedRing α] [CanonicallyOrderedAdd α] [Sub α] [OrderedSub α] [AddLeftReflectLE α] (m n : ℕ) : ↑(m - n) = (m - n : α) := by rcases le_total m n with h | h · rw [Nat.sub_eq_zero_of_le h, cast_zero, tsub_eq_zero_of_le] exact mono_cast h · rcases le_iff_exists_add'.mp h with ⟨m, rfl⟩ rw [add_tsub_cancel_right, cast_add, add_tsub_cancel_right] section Lattice variable [Ring R] [Lattice R] [IsOrderedRing R] @[simp, norm_cast] theorem abs_cast (n : ℕ) : |(n : R)| = n := abs_of_nonneg n.cast_nonneg @[simp] theorem abs_ofNat (n : ℕ) [n.AtLeastTwo] : |(ofNat(n) : R)| = ofNat(n) := abs_cast n end Lattice section PartialOrderedRing variable [Ring R] [PartialOrder R] [IsStrictOrderedRing R] {m n : ℕ} @[simp, norm_cast] lemma neg_cast_eq_cast : (-m : R) = n ↔ m = 0 ∧ n = 0 := by simp [neg_eq_iff_add_eq_zero, ← cast_add] @[simp, norm_cast] lemma cast_eq_neg_cast : (m : R) = -n ↔ m = 0 ∧ n = 0 := by simp [eq_neg_iff_add_eq_zero, ← cast_add] end PartialOrderedRing lemma mul_le_pow {a : ℕ} (ha : a ≠ 1) (b : ℕ) : a * b ≤ a ^ b := by induction b generalizing a with | zero => simp | succ b hb => rw [mul_add_one, pow_succ] rcases a with (_ | _ | a) · simp · simp at ha · rw [mul_add_one, mul_add_one, add_comm (_ * a), add_assoc _ (_ * a)] rcases b with (_ | b) · simp [add_comm] refine add_le_add (hb (by simp)) ?_ rw [pow_succ'] refine (le_add_left ?_ ?_).trans' ?_ exact le_mul_of_one_le_right' (one_le_pow _ _ (by simp)) lemma two_mul_sq_add_one_le_two_pow_two_mul (k : ℕ) : 2 * k ^ 2 + 1 ≤ 2 ^ (2 * k) := by induction k with | zero => simp | succ k hk => grw [add_pow_two, one_pow, mul_one, add_assoc, mul_add, add_right_comm, hk, mul_add 2 k, pow_add, mul_one, pow_two, ← mul_assoc, mul_two, mul_two, add_assoc] gcongr rw [← two_mul, ← pow_succ'] exact le_add_of_le_right (mul_le_pow (by simp) _) end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Cast/Order/Basic.lean
import Mathlib.Algebra.Order.Monoid.Unbundled.Basic import Mathlib.Algebra.Order.ZeroLEOne import Mathlib.Data.Nat.Cast.Basic import Mathlib.Data.Nat.Cast.NeZero import Mathlib.Order.Hom.Basic /-! # Cast of natural numbers: lemmas about order -/ assert_not_exists IsOrderedMonoid variable {α : Type*} namespace Nat section OrderedSemiring /- Note: even though the section indicates `OrderedSemiring`, which is the common use case, we use a generic collection of instances so that it applies in other settings (e.g., in a `StarOrderedRing`, or the `selfAdjoint` or `StarOrderedRing.positive` parts thereof). -/ variable [AddMonoidWithOne α] [PartialOrder α] variable [AddLeftMono α] [ZeroLEOneClass α] @[gcongr, mono] theorem mono_cast : Monotone (Nat.cast : ℕ → α) := monotone_nat_of_le_succ fun n ↦ by rw [Nat.cast_succ]; exact le_add_of_nonneg_right zero_le_one /-- See also `Nat.cast_nonneg`, specialised for an `OrderedSemiring`. -/ @[simp low] theorem cast_nonneg' (n : ℕ) : 0 ≤ (n : α) := @Nat.cast_zero α _ ▸ mono_cast (Nat.zero_le n) /-- See also `Nat.ofNat_nonneg`, specialised for an `OrderedSemiring`. -/ @[simp low] theorem ofNat_nonneg' (n : ℕ) [n.AtLeastTwo] : 0 ≤ (ofNat(n) : α) := cast_nonneg' n section Nontrivial variable [NeZero (1 : α)] theorem cast_add_one_pos (n : ℕ) : 0 < (n : α) + 1 := by apply zero_lt_one.trans_le convert (@mono_cast α _).imp (?_ : 1 ≤ n + 1) <;> simp /-- See also `Nat.cast_pos`, specialised for an `OrderedSemiring`. -/ @[simp low] theorem cast_pos' {n : ℕ} : (0 : α) < n ↔ 0 < n := by cases n <;> simp [cast_add_one_pos] end Nontrivial variable [CharZero α] {m n : ℕ} @[gcongr] theorem strictMono_cast : StrictMono (Nat.cast : ℕ → α) := mono_cast.strictMono_of_injective cast_injective /-- `Nat.cast : ℕ → α` as an `OrderEmbedding` -/ @[simps! -fullyApplied] def castOrderEmbedding : ℕ ↪o α := OrderEmbedding.ofStrictMono Nat.cast Nat.strictMono_cast @[simp, norm_cast] theorem cast_le : (m : α) ≤ n ↔ m ≤ n := strictMono_cast.le_iff_le @[simp, norm_cast, mono] theorem cast_lt : (m : α) < n ↔ m < n := strictMono_cast.lt_iff_lt @[simp, norm_cast] theorem one_lt_cast : 1 < (n : α) ↔ 1 < n := by rw [← cast_one, cast_lt] @[simp, norm_cast] theorem one_le_cast : 1 ≤ (n : α) ↔ 1 ≤ n := by rw [← cast_one, cast_le] theorem one_le_cast_iff_ne_zero : 1 ≤ (n : α) ↔ n ≠ 0 := one_le_cast.trans one_le_iff_ne_zero @[simp, norm_cast] theorem cast_lt_one : (n : α) < 1 ↔ n = 0 := by rw [← cast_one, cast_lt, Nat.lt_succ_iff, le_zero] @[simp, norm_cast] theorem cast_le_one : (n : α) ≤ 1 ↔ n ≤ 1 := by rw [← cast_one, cast_le] @[simp] lemma cast_nonpos : (n : α) ≤ 0 ↔ n = 0 := by norm_cast; cutsat section variable [m.AtLeastTwo] @[simp] theorem ofNat_le_cast : (ofNat(m) : α) ≤ n ↔ (OfNat.ofNat m : ℕ) ≤ n := cast_le @[simp] theorem ofNat_lt_cast : (ofNat(m) : α) < n ↔ (OfNat.ofNat m : ℕ) < n := cast_lt end variable [n.AtLeastTwo] @[simp] theorem cast_le_ofNat : (m : α) ≤ (ofNat(n) : α) ↔ m ≤ OfNat.ofNat n := cast_le @[simp] theorem cast_lt_ofNat : (m : α) < (ofNat(n) : α) ↔ m < OfNat.ofNat n := cast_lt @[simp] theorem one_lt_ofNat : 1 < (ofNat(n) : α) := one_lt_cast.mpr AtLeastTwo.one_lt @[simp] theorem one_le_ofNat : 1 ≤ (ofNat(n) : α) := one_le_cast.mpr NeZero.one_le @[simp] theorem not_ofNat_le_one : ¬(ofNat(n) : α) ≤ 1 := (cast_le_one.not.trans not_le).mpr AtLeastTwo.one_lt @[simp] theorem not_ofNat_lt_one : ¬(ofNat(n) : α) < 1 := mt le_of_lt not_ofNat_le_one variable [m.AtLeastTwo] -- TODO: These lemmas need to be `@[simp]` for confluence in the presence of `cast_lt`, `cast_le`, -- and `Nat.cast_ofNat`, but their LHSs match literally every inequality, so they're too expensive. -- If https://github.com/leanprover/lean4/issues/2867 is fixed in a performant way, these can be made `@[simp]`. -- @[simp] theorem ofNat_le : (ofNat(m) : α) ≤ (ofNat(n) : α) ↔ (OfNat.ofNat m : ℕ) ≤ OfNat.ofNat n := cast_le -- @[simp] theorem ofNat_lt : (ofNat(m) : α) < (ofNat(n) : α) ↔ (OfNat.ofNat m : ℕ) < OfNat.ofNat n := cast_lt end OrderedSemiring end Nat instance [AddMonoidWithOne α] [CharZero α] : Nontrivial α where exists_pair_ne := ⟨1, 0, (Nat.cast_one (R := α) ▸ Nat.cast_ne_zero.2 (by decide))⟩ section RingHomClass variable {R S F : Type*} [NonAssocSemiring R] [NonAssocSemiring S] [FunLike F R S] theorem NeZero.nat_of_injective {n : ℕ} [NeZero (n : R)] [RingHomClass F R S] {f : F} (hf : Function.Injective f) : NeZero (n : S) := ⟨fun h ↦ NeZero.natCast_ne n R <| hf <| by simpa only [map_natCast, map_zero f]⟩ end RingHomClass
.lake/packages/mathlib/Mathlib/Data/Nat/Cast/Order/Field.lean
import Mathlib.Algebra.Order.Field.Basic /-! # Cast of naturals into ordered fields This file concerns the canonical homomorphism `ℕ → F`, where `F` is a `LinearOrderedSemifield`. ## Main results * `Nat.cast_div_le`: in all cases, `↑(m / n) ≤ ↑m / ↑ n` -/ namespace Nat section LinearOrderedSemifield variable {α : Type*} [Semifield α] [LinearOrder α] [IsStrictOrderedRing α] lemma cast_inv_le_one : ∀ n : ℕ, (n⁻¹ : α) ≤ 1 | 0 => by simp | n + 1 => inv_le_one_of_one_le₀ <| by simp [Nat.cast_nonneg] /-- Natural division is always less than division in the field. -/ theorem cast_div_le {m n : ℕ} : ((m / n : ℕ) : α) ≤ m / n := by cases n · rw [cast_zero, div_zero, Nat.div_zero, cast_zero] rw [le_div_iff₀, ← Nat.cast_mul, @Nat.cast_le] · exact Nat.div_mul_le_self m _ · exact Nat.cast_pos.2 (Nat.succ_pos _) theorem inv_pos_of_nat {n : ℕ} : 0 < ((n : α) + 1)⁻¹ := inv_pos.2 <| add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one theorem one_div_pos_of_nat {n : ℕ} : 0 < 1 / ((n : α) + 1) := by rw [one_div] exact inv_pos_of_nat theorem one_div_le_one_div {n m : ℕ} (h : n ≤ m) : 1 / ((m : α) + 1) ≤ 1 / ((n : α) + 1) := by refine one_div_le_one_div_of_le ?_ ?_ · exact Nat.cast_add_one_pos _ · simpa theorem one_div_lt_one_div {n m : ℕ} (h : n < m) : 1 / ((m : α) + 1) < 1 / ((n : α) + 1) := by refine one_div_lt_one_div_of_lt ?_ ?_ · exact Nat.cast_add_one_pos _ · simpa theorem one_div_cast_pos {n : ℕ} (hn : n ≠ 0) : 0 < 1 / (n : α) := one_div_pos.mpr (cast_pos.mpr (Nat.pos_of_ne_zero hn)) theorem one_div_cast_nonneg (n : ℕ) : 0 ≤ 1 / (n : α) := one_div_nonneg.mpr (cast_nonneg' n) theorem one_div_cast_ne_zero {n : ℕ} (hn : n ≠ 0) : 1 / (n : α) ≠ 0 := _root_.ne_of_gt (one_div_cast_pos hn) end LinearOrderedSemifield section LinearOrderedField variable {α : Type*} [Field α] [LinearOrder α] [IsStrictOrderedRing α] theorem one_sub_one_div_cast_nonneg [AddRightMono α] (n : ℕ) : 0 ≤ 1 - 1 / (n : α) := by rw [sub_nonneg, one_div] exact cast_inv_le_one n theorem one_sub_one_div_cast_le_one [AddLeftMono α] (n : ℕ) : 1 - 1 / (n : α) ≤ 1 := by rw [sub_le_self_iff] exact one_div_cast_nonneg n end LinearOrderedField end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Factorization/PrimePow.lean
import Mathlib.Algebra.IsPrimePow import Mathlib.Data.Nat.Factorization.Basic import Mathlib.Data.Nat.Prime.Pow import Mathlib.NumberTheory.Divisors /-! # Prime powers and factorizations This file deals with factorizations of prime powers. -/ theorem IsPrimePow.minFac_pow_factorization_eq {n : ℕ} (hn : IsPrimePow n) : n.minFac ^ n.factorization n.minFac = n := by obtain ⟨p, k, hp, hk, rfl⟩ := hn rw [← Nat.prime_iff] at hp rw [hp.pow_minFac hk.ne', hp.factorization_pow, Finsupp.single_eq_same] theorem isPrimePow_of_minFac_pow_factorization_eq {n : ℕ} (h : n.minFac ^ n.factorization n.minFac = n) (hn : n ≠ 1) : IsPrimePow n := by rcases eq_or_ne n 0 with (rfl | hn') · simp_all refine ⟨_, _, (Nat.minFac_prime hn).prime, ?_, h⟩ simp [pos_iff_ne_zero, ← Finsupp.mem_support_iff, Nat.support_factorization, hn', Nat.minFac_prime hn, Nat.minFac_dvd] theorem isPrimePow_iff_minFac_pow_factorization_eq {n : ℕ} (hn : n ≠ 1) : IsPrimePow n ↔ n.minFac ^ n.factorization n.minFac = n := ⟨fun h => h.minFac_pow_factorization_eq, fun h => isPrimePow_of_minFac_pow_factorization_eq h hn⟩ theorem isPrimePow_iff_factorization_eq_single {n : ℕ} : IsPrimePow n ↔ ∃ p k : ℕ, 0 < k ∧ n.factorization = Finsupp.single p k := by rw [isPrimePow_nat_iff] refine exists₂_congr fun p k => ?_ constructor · rintro ⟨hp, hk, hn⟩ exact ⟨hk, by rw [← hn, Nat.Prime.factorization_pow hp]⟩ · rintro ⟨hk, hn⟩ have hn0 : n ≠ 0 := by rintro rfl simp_all only [Finsupp.single_eq_zero, eq_comm, Nat.factorization_zero, hk.ne'] rw [Nat.eq_pow_of_factorization_eq_single hn0 hn] exact ⟨Nat.prime_of_mem_primeFactors <| Finsupp.mem_support_iff.2 (by simp [hn, hk.ne'] : n.factorization p ≠ 0), hk, rfl⟩ theorem isPrimePow_iff_card_primeFactors_eq_one {n : ℕ} : IsPrimePow n ↔ n.primeFactors.card = 1 := by simp_rw [isPrimePow_iff_factorization_eq_single, ← Nat.support_factorization, Finsupp.card_support_eq_one', pos_iff_ne_zero] theorem IsPrimePow.exists_ordCompl_eq_one {n : ℕ} (h : IsPrimePow n) : ∃ p : ℕ, p.Prime ∧ ordCompl[p] n = 1 := by rcases eq_or_ne n 0 with (rfl | hn0); · cases not_isPrimePow_zero h rcases isPrimePow_iff_factorization_eq_single.mp h with ⟨p, k, hk0, h1⟩ rcases em' p.Prime with (pp | pp) · refine absurd ?_ hk0.ne' simp [← Nat.factorization_eq_zero_of_not_prime n pp, h1] refine ⟨p, pp, ?_⟩ refine Nat.eq_of_factorization_eq (Nat.ordCompl_pos p hn0).ne' (by simp) fun q => ?_ rw [Nat.factorization_ordCompl n p, h1] simp theorem exists_ordCompl_eq_one_iff_isPrimePow {n : ℕ} (hn : n ≠ 1) : IsPrimePow n ↔ ∃ p : ℕ, p.Prime ∧ ordCompl[p] n = 1 := by refine ⟨fun h => IsPrimePow.exists_ordCompl_eq_one h, fun h => ?_⟩ rcases h with ⟨p, pp, h⟩ rw [isPrimePow_nat_iff] rw [← Nat.eq_of_dvd_of_div_eq_one (Nat.ordProj_dvd n p) h] at hn ⊢ refine ⟨p, n.factorization p, pp, ?_, by simp⟩ contrapose! hn simp [Nat.le_zero.1 hn] /-- An equivalent definition for prime powers: `n` is a prime power iff there is a unique prime dividing it. -/ theorem isPrimePow_iff_unique_prime_dvd {n : ℕ} : IsPrimePow n ↔ ∃! p : ℕ, p.Prime ∧ p ∣ n := by rw [isPrimePow_nat_iff] constructor · rintro ⟨p, k, hp, hk, rfl⟩ refine ⟨p, ⟨hp, dvd_pow_self _ hk.ne'⟩, ?_⟩ rintro q ⟨hq, hq'⟩ exact (Nat.prime_dvd_prime_iff_eq hq hp).1 (hq.dvd_of_dvd_pow hq') rintro ⟨p, ⟨hp, hn⟩, hq⟩ rcases eq_or_ne n 0 with (rfl | hn₀) · cases (hq 2 ⟨Nat.prime_two, dvd_zero 2⟩).trans (hq 3 ⟨Nat.prime_three, dvd_zero 3⟩).symm refine ⟨p, n.factorization p, hp, hp.factorization_pos_of_dvd hn₀ hn, ?_⟩ simp only [and_imp] at hq apply Nat.dvd_antisymm (Nat.ordProj_dvd _ _) -- We need to show n ∣ p ^ n.factorization p apply Nat.dvd_of_primeFactorsList_subperm hn₀ rw [hp.primeFactorsList_pow, List.subperm_ext_iff] intro q hq' rw [Nat.mem_primeFactorsList hn₀] at hq' cases hq _ hq'.1 hq'.2 simp theorem isPrimePow_pow_iff {n k : ℕ} (hk : k ≠ 0) : IsPrimePow (n ^ k) ↔ IsPrimePow n := by simp only [isPrimePow_iff_unique_prime_dvd] apply existsUnique_congr simp +contextual [Nat.prime_iff, Prime.dvd_pow_iff_dvd, hk] theorem Nat.Coprime.isPrimePow_dvd_mul {n a b : ℕ} (hab : Nat.Coprime a b) (hn : IsPrimePow n) : n ∣ a * b ↔ n ∣ a ∨ n ∣ b := by rcases eq_or_ne a 0 with (rfl | ha) · simp rcases eq_or_ne b 0 with (rfl | hb) · simp refine ⟨?_, fun h => Or.elim h (fun i => i.trans ((@dvd_mul_right a b a hab).mpr (dvd_refl a))) fun i => i.trans ((@dvd_mul_left a b b hab.symm).mpr (dvd_refl b))⟩ obtain ⟨p, k, hp, _, rfl⟩ := (isPrimePow_nat_iff _).1 hn simp only [hp.pow_dvd_iff_le_factorization (mul_ne_zero ha hb), Nat.factorization_mul ha hb, hp.pow_dvd_iff_le_factorization ha, hp.pow_dvd_iff_le_factorization hb, Pi.add_apply, Finsupp.coe_add] have : a.factorization p = 0 ∨ b.factorization p = 0 := by rw [← Finsupp.notMem_support_iff, ← Finsupp.notMem_support_iff, ← not_and_or, ← Finset.mem_inter] intro t simpa using hab.disjoint_primeFactors.le_bot t rcases this with h | h <;> simp [h, imp_or] theorem Nat.mul_divisors_filter_prime_pow {a b : ℕ} (hab : a.Coprime b) : {d ∈ (a * b).divisors | IsPrimePow d} = {d ∈ a.divisors ∪ b.divisors | IsPrimePow d} := by rcases eq_or_ne a 0 with (rfl | ha) · simp only [Nat.coprime_zero_left] at hab simp [hab, Finset.filter_singleton, not_isPrimePow_one] rcases eq_or_ne b 0 with (rfl | hb) · simp only [Nat.coprime_zero_right] at hab simp [hab, Finset.filter_singleton, not_isPrimePow_one] ext n simp only [ha, hb, Finset.mem_union, Finset.mem_filter, Nat.mul_eq_zero, and_true, Ne, and_congr_left_iff, not_false_iff, Nat.mem_divisors, or_self_iff] apply hab.isPrimePow_dvd_mul @[deprecated Nat.factorization_minFac_ne_zero (since := "2025-07-21")] lemma IsPrimePow.factorization_minFac_ne_zero {n : ℕ} (hn : IsPrimePow n) : n.factorization n.minFac ≠ 0 := Nat.factorization_minFac_ne_zero (one_lt hn) /-- The canonical equivalence between pairs `(p, k)` with `p` a prime and `k : ℕ` and the set of prime powers given by `(p, k) ↦ p^(k+1)`. -/ def Nat.Primes.prodNatEquiv : Nat.Primes × ℕ ≃ {n : ℕ // IsPrimePow n} where toFun pk := ⟨pk.1 ^ (pk.2 + 1), ⟨pk.1, pk.2 + 1, prime_iff.mp pk.1.prop, pk.2.add_one_pos, rfl⟩⟩ invFun n := (⟨n.val.minFac, minFac_prime n.prop.ne_one⟩, n.val.factorization n.val.minFac - 1) left_inv := fun (p, k) ↦ by simp only [p.prop.pow_minFac k.add_one_ne_zero, Subtype.coe_eta, factorization_pow, p.prop, Prime.factorization, Finsupp.smul_single, smul_eq_mul, mul_one, Finsupp.single_add, Finsupp.coe_add, Pi.add_apply, Finsupp.single_eq_same, add_tsub_cancel_right] right_inv n := by ext1 dsimp only rw [sub_one_add_one (Nat.factorization_minFac_ne_zero n.prop.one_lt), n.prop.minFac_pow_factorization_eq] @[simp] lemma Nat.Primes.prodNatEquiv_apply (p : Nat.Primes) (k : ℕ) : prodNatEquiv (p, k) = ⟨p ^ (k + 1), p, k + 1, prime_iff.mp p.prop, k.add_one_pos, rfl⟩ := by rfl @[simp] lemma Nat.Primes.coe_prodNatEquiv_apply (p : Nat.Primes) (k : ℕ) : (prodNatEquiv (p, k) : ℕ) = p ^ (k + 1) := rfl @[simp] lemma Nat.Primes.prodNatEquiv_symm_apply {n : ℕ} (hn : IsPrimePow n) : prodNatEquiv.symm ⟨n, hn⟩ = (⟨n.minFac, minFac_prime hn.ne_one⟩, n.factorization n.minFac - 1) := rfl
.lake/packages/mathlib/Mathlib/Data/Nat/Factorization/Root.lean
import Mathlib.Algebra.Order.Floor.Div import Mathlib.Algebra.Order.Ring.Nat import Mathlib.Data.Nat.Factorization.Defs /-! # Roots of natural numbers, rounded up and down This file defines the flooring and ceiling root of a natural number. `Nat.floorRoot n a`/`Nat.ceilRoot n a`, the `n`-th flooring/ceiling root of `a`, is the natural number whose `p`-adic valuation is the floor/ceil of the `p`-adic valuation of `a`. For example the `2`-nd flooring and ceiling roots of `2^3 * 3^2 * 5` are `2 * 3` and `2^2 * 3 * 5` respectively. Note this is **not** the `n`-th root of `a` as a real number, rounded up or down. These operations are respectively the right and left adjoints to the map `a ↦ a ^ n` where `ℕ` is ordered by divisibility. This is useful because it lets us characterise the numbers `a` whose `n`-th power divide `n` as the divisors of some fixed number (aka `floorRoot n b`). See `Nat.pow_dvd_iff_dvd_floorRoot`. Similarly, it lets us characterise the `b` whose `n`-th power is a multiple of `a` as the multiples of some fixed number (aka `ceilRoot n a`). See `Nat.dvd_pow_iff_ceilRoot_dvd`. ## TODO * `norm_num` extension -/ open Finsupp namespace Nat variable {a b n : ℕ} /-- Flooring root of a natural number. This divides the valuation of every prime number rounding down. Eg if `n = 2`, `a = 2^3 * 3^2 * 5`, then `floorRoot n a = 2 * 3`. In order theory terms, this is the upper or right adjoint of the map `a ↦ a ^ n : ℕ → ℕ` where `ℕ` is ordered by divisibility. To ensure that the adjunction (`Nat.pow_dvd_iff_dvd_floorRoot`) holds in as many cases as possible, we special-case the following values: * `floorRoot 0 a = 0` * `floorRoot n 0 = 0` -/ def floorRoot (n a : ℕ) : ℕ := if n = 0 ∨ a = 0 then 0 else a.factorization.prod fun p k ↦ p ^ (k / n) /-- The RHS is a noncomputable version of `Nat.floorRoot` with better order-theoretic properties. -/ lemma floorRoot_def : floorRoot n a = if n = 0 ∨ a = 0 then 0 else (a.factorization ⌊/⌋ n).prod (· ^ ·) := by unfold floorRoot; split_ifs with h <;> simp [Finsupp.floorDiv_def, prod_mapRange_index pow_zero] @[simp] lemma floorRoot_zero_left (a : ℕ) : floorRoot 0 a = 0 := by simp [floorRoot] @[simp] lemma floorRoot_zero_right (n : ℕ) : floorRoot n 0 = 0 := by simp [floorRoot] @[simp] lemma floorRoot_one_left (a : ℕ) : floorRoot 1 a = a := by simp [floorRoot]; split_ifs <;> simp [*] @[simp] lemma floorRoot_one_right (hn : n ≠ 0) : floorRoot n 1 = 1 := by simp [floorRoot, hn] @[simp] lemma floorRoot_pow_self (hn : n ≠ 0) (a : ℕ) : floorRoot n (a ^ n) = a := by simp [floorRoot_def, pos_iff_ne_zero.2, hn]; split_ifs <;> simp [*] lemma floorRoot_ne_zero : floorRoot n a ≠ 0 ↔ n ≠ 0 ∧ a ≠ 0 := by simp +contextual [floorRoot, not_or] @[simp] lemma floorRoot_eq_zero : floorRoot n a = 0 ↔ n = 0 ∨ a = 0 := floorRoot_ne_zero.not_right.trans <| by simp only [not_and_or, ne_eq, not_not] @[simp] lemma factorization_floorRoot (n a : ℕ) : (floorRoot n a).factorization = a.factorization ⌊/⌋ n := by rw [floorRoot_def] split_ifs with h · obtain rfl | rfl := h <;> simp refine prod_pow_factorization_eq_self fun p hp ↦ ?_ have : p.Prime ∧ p ∣ a ∧ ¬a = 0 := by simpa using support_floorDiv_subset hp exact this.1 /-- Galois connection between `a ↦ a ^ n : ℕ → ℕ` and `floorRoot n : ℕ → ℕ` where `ℕ` is ordered by divisibility. -/ lemma pow_dvd_iff_dvd_floorRoot : a ^ n ∣ b ↔ a ∣ floorRoot n b := by obtain rfl | hn := eq_or_ne n 0 · simp obtain rfl | hb := eq_or_ne b 0 · simp obtain rfl | ha := eq_or_ne a 0 · simp [hn] rw [← factorization_le_iff_dvd (pow_ne_zero _ ha) hb, ← factorization_le_iff_dvd ha (floorRoot_ne_zero.2 ⟨hn, hb⟩), factorization_pow, factorization_floorRoot, le_floorDiv_iff_smul_le (β := ℕ →₀ ℕ) (pos_iff_ne_zero.2 hn)] lemma floorRoot_pow_dvd : floorRoot n a ^ n ∣ a := pow_dvd_iff_dvd_floorRoot.2 dvd_rfl /-- Ceiling root of a natural number. This divides the valuation of every prime number rounding up. Eg if `n = 3`, `a = 2^4 * 3^2 * 5`, then `ceilRoot n a = 2^2 * 3 * 5`. In order theory terms, this is the lower or left adjoint of the map `a ↦ a ^ n : ℕ → ℕ` where `ℕ` is ordered by divisibility. To ensure that the adjunction (`Nat.dvd_pow_iff_ceilRoot_dvd`) holds in as many cases as possible, we special-case the following values: * `ceilRoot 0 a = 0` (this one is not strictly necessary) * `ceilRoot n 0 = 0` -/ def ceilRoot (n a : ℕ) : ℕ := if n = 0 ∨ a = 0 then 0 else a.factorization.prod fun p k ↦ p ^ ((k + n - 1) / n) /-- The RHS is a noncomputable version of `Nat.ceilRoot` with better order-theoretic properties. -/ lemma ceilRoot_def : ceilRoot n a = if n = 0 ∨ a = 0 then 0 else (a.factorization ⌈/⌉ n).prod (· ^ ·) := by unfold ceilRoot split_ifs with h <;> simp [Finsupp.ceilDiv_def, prod_mapRange_index pow_zero, Nat.ceilDiv_eq_add_pred_div] @[simp] lemma ceilRoot_zero_left (a : ℕ) : ceilRoot 0 a = 0 := by simp [ceilRoot] @[simp] lemma ceilRoot_zero_right (n : ℕ) : ceilRoot n 0 = 0 := by simp [ceilRoot] @[simp] lemma ceilRoot_one_left (a : ℕ) : ceilRoot 1 a = a := by simp [ceilRoot]; split_ifs <;> simp [*] @[simp] lemma ceilRoot_one_right (hn : n ≠ 0) : ceilRoot n 1 = 1 := by simp [ceilRoot, hn] @[simp] lemma ceilRoot_pow_self (hn : n ≠ 0) (a : ℕ) : ceilRoot n (a ^ n) = a := by simp [ceilRoot_def, pos_iff_ne_zero.2, hn]; split_ifs <;> simp [*] lemma ceilRoot_ne_zero : ceilRoot n a ≠ 0 ↔ n ≠ 0 ∧ a ≠ 0 := by simp +contextual [ceilRoot_def, not_or] @[simp] lemma ceilRoot_eq_zero : ceilRoot n a = 0 ↔ n = 0 ∨ a = 0 := ceilRoot_ne_zero.not_right.trans <| by simp only [not_and_or, ne_eq, not_not] @[simp] lemma factorization_ceilRoot (n a : ℕ) : (ceilRoot n a).factorization = a.factorization ⌈/⌉ n := by rw [ceilRoot_def] split_ifs with h · obtain rfl | rfl := h <;> simp refine prod_pow_factorization_eq_self fun p hp ↦ ?_ have : p.Prime ∧ p ∣ a ∧ ¬a = 0 := by simpa using support_ceilDiv_subset hp exact this.1 /-- Galois connection between `ceilRoot n : ℕ → ℕ` and `a ↦ a ^ n : ℕ → ℕ` where `ℕ` is ordered by divisibility. Note that this cannot possibly hold for `n = 0`, regardless of the value of `ceilRoot 0 a`, because the statement reduces to `a = 1 ↔ ceilRoot 0 a ∣ b`, which is false for e.g. `a = 0`, `b = ceilRoot 0 a`. -/ lemma dvd_pow_iff_ceilRoot_dvd (hn : n ≠ 0) : a ∣ b ^ n ↔ ceilRoot n a ∣ b := by obtain rfl | ha := eq_or_ne a 0 · aesop obtain rfl | hb := eq_or_ne b 0 · simp [hn] rw [← factorization_le_iff_dvd ha (pow_ne_zero _ hb), ← factorization_le_iff_dvd (ceilRoot_ne_zero.2 ⟨hn, ha⟩) hb, factorization_pow, factorization_ceilRoot, ceilDiv_le_iff_le_smul (β := ℕ →₀ ℕ) (pos_iff_ne_zero.2 hn)] lemma dvd_ceilRoot_pow (hn : n ≠ 0) : a ∣ ceilRoot n a ^ n := (dvd_pow_iff_ceilRoot_dvd hn).2 dvd_rfl end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Factorization/LCM.lean
import Mathlib.Data.Nat.Factorization.Basic import Mathlib.Data.Nat.GCD.BigOperators /-! # Lemmas about `factorizationLCMLeft` This file contains some lemmas about `factorizationLCMLeft`. These were split from `Mathlib.Data.Nat.Factorization.Basic` to reduce transitive imports. -/ open Finset List Finsupp namespace Nat variable (a b) @[simp] lemma factorizationLCMLeft_zero_left : factorizationLCMLeft 0 b = 1 := by simp [factorizationLCMLeft] @[simp] lemma factorizationLCMLeft_zero_right : factorizationLCMLeft a 0 = 1 := by simp [factorizationLCMLeft] @[simp] lemma factorizationLCRight_zero_left : factorizationLCMRight 0 b = 1 := by simp [factorizationLCMRight] @[simp] lemma factorizationLCMRight_zero_right : factorizationLCMRight a 0 = 1 := by simp [factorizationLCMRight] lemma factorizationLCMLeft_pos : 0 < factorizationLCMLeft a b := by apply Nat.pos_of_ne_zero rw [factorizationLCMLeft, Finsupp.prod_ne_zero_iff] intro p _ H by_cases h : b.factorization p ≤ a.factorization p · simp only [h, reduceIte, pow_eq_zero_iff', ne_eq] at H simpa [H.1] using H.2 · simp only [h, reduceIte, one_ne_zero] at H lemma factorizationLCMRight_pos : 0 < factorizationLCMRight a b := by apply Nat.pos_of_ne_zero rw [factorizationLCMRight, Finsupp.prod_ne_zero_iff] intro p _ H by_cases h : b.factorization p ≤ a.factorization p · simp only [h, reduceIte, reduceCtorEq] at H · simp only [h, ↓reduceIte, pow_eq_zero_iff', ne_eq] at H simpa [H.1] using H.2 lemma coprime_factorizationLCMLeft_factorizationLCMRight : (factorizationLCMLeft a b).Coprime (factorizationLCMRight a b) := by rw [factorizationLCMLeft, factorizationLCMRight] refine coprime_prod_left_iff.mpr fun p hp ↦ coprime_prod_right_iff.mpr fun q hq ↦ ?_ dsimp only; split_ifs with h h' any_goals simp only [coprime_one_right_eq_true, coprime_one_left_eq_true] refine coprime_pow_primes _ _ (prime_of_mem_primeFactors hp) (prime_of_mem_primeFactors hq) ?_ contrapose! h'; rwa [← h'] variable {a b} lemma factorizationLCMLeft_mul_factorizationLCMRight (ha : a ≠ 0) (hb : b ≠ 0) : (factorizationLCMLeft a b) * (factorizationLCMRight a b) = lcm a b := by rw [← factorization_prod_pow_eq_self (lcm_ne_zero ha hb), factorizationLCMLeft, factorizationLCMRight, ← prod_mul] congr; ext p n; split_ifs <;> simp variable (a b) lemma factorizationLCMLeft_dvd_left : factorizationLCMLeft a b ∣ a := by rcases eq_or_ne a 0 with rfl | ha · simp only [dvd_zero] rcases eq_or_ne b 0 with rfl | hb · simp [factorizationLCMLeft] nth_rewrite 2 [← factorization_prod_pow_eq_self ha] rw [prod_of_support_subset (s := (lcm a b).factorization.support)] · apply prod_dvd_prod_of_dvd; rintro p -; dsimp only; split_ifs with le · rw [factorization_lcm ha hb]; apply pow_dvd_pow; exact sup_le le_rfl le · apply one_dvd · intro p hp; rw [mem_support_iff] at hp ⊢ rw [factorization_lcm ha hb]; exact (lt_sup_iff.mpr <| .inl <| Nat.pos_of_ne_zero hp).ne' · intros; rw [pow_zero] lemma factorizationLCMRight_dvd_right : factorizationLCMRight a b ∣ b := by rcases eq_or_ne a 0 with rfl | ha · simp [factorizationLCMRight] rcases eq_or_ne b 0 with rfl | hb · simp only [dvd_zero] nth_rewrite 2 [← factorization_prod_pow_eq_self hb] rw [prod_of_support_subset (s := (lcm a b).factorization.support)] · apply Finset.prod_dvd_prod_of_dvd; rintro p -; dsimp only; split_ifs with le · apply one_dvd · rw [factorization_lcm ha hb]; apply pow_dvd_pow; exact sup_le (not_le.1 le).le le_rfl · intro p hp; rw [mem_support_iff] at hp ⊢ rw [factorization_lcm ha hb]; exact (lt_sup_iff.mpr <| .inr <| Nat.pos_of_ne_zero hp).ne' · intros; rw [pow_zero] end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Factorization/Basic.lean
import Mathlib.Algebra.Order.Interval.Finset.SuccPred import Mathlib.Data.Nat.Factorization.Defs import Mathlib.Order.Interval.Finset.Nat /-! # Basic lemmas on prime factorizations -/ open Finset List Finsupp namespace Nat variable {a b m n p : ℕ} /-! ### Basic facts about factorization -/ /-! ## Lemmas characterising when `n.factorization p = 0` -/ theorem factorization_eq_zero_of_lt {n p : ℕ} (h : n < p) : n.factorization p = 0 := Finsupp.notMem_support_iff.mp (mt le_of_mem_primeFactors (not_le_of_gt h)) theorem dvd_of_factorization_pos {n p : ℕ} (hn : n.factorization p ≠ 0) : p ∣ n := dvd_of_mem_primeFactorsList <| mem_primeFactors_iff_mem_primeFactorsList.1 <| mem_support_iff.2 hn theorem factorization_eq_zero_iff_remainder {p r : ℕ} (i : ℕ) (pp : p.Prime) (hr0 : r ≠ 0) : ¬p ∣ r ↔ (p * i + r).factorization p = 0 := by refine ⟨factorization_eq_zero_of_remainder i, fun h => ?_⟩ rw [factorization_eq_zero_iff] at h contrapose! h refine ⟨pp, ?_, ?_⟩ · rwa [← Nat.dvd_add_iff_right (dvd_mul_right p i)] · contrapose! hr0 exact (add_eq_zero.1 hr0).2 /-- The only numbers with empty prime factorization are `0` and `1` -/ theorem factorization_eq_zero_iff' (n : ℕ) : n.factorization = 0 ↔ n = 0 ∨ n = 1 := by rw [factorization_eq_primeFactorsList_multiset n] simp [Multiset.coe_eq_zero] /-! ## Lemmas about factorizations of products and powers -/ /-- Modified version of `factorization_prod` that accounts for inputs. -/ theorem factorization_prod_apply {α : Type*} {p : ℕ} {S : Finset α} {g : α → ℕ} (hS : ∀ x ∈ S, g x ≠ 0) : (S.prod g).factorization p = S.sum fun x => (g x).factorization p := by rw [factorization_prod hS, finset_sum_apply] /-- A product over `n.factorization` can be written as a product over `n.primeFactors`; -/ lemma prod_factorization_eq_prod_primeFactors {β : Type*} [CommMonoid β] (f : ℕ → ℕ → β) : n.factorization.prod f = ∏ p ∈ n.primeFactors, f p (n.factorization p) := rfl /-- A product over `n.primeFactors` can be written as a product over `n.factorization`; -/ lemma prod_primeFactors_prod_factorization {β : Type*} [CommMonoid β] (f : ℕ → β) : ∏ p ∈ n.primeFactors, f p = n.factorization.prod (fun p _ ↦ f p) := rfl /-! ## Lemmas about factorizations of primes and prime powers -/ /-- The multiplicity of prime `p` in `p` is `1` -/ theorem Prime.factorization_self {p : ℕ} (hp : Prime p) : p.factorization p = 1 := by simp [hp] theorem factorization_pow_self {p n : ℕ} (hp : p.Prime) : (p ^ n).factorization p = n := by simp [factorization_pow, Prime.factorization_self hp] /-- If the factorization of `n` contains just one number `p` then `n` is a power of `p` -/ theorem eq_pow_of_factorization_eq_single {n p k : ℕ} (hn : n ≠ 0) (h : n.factorization = Finsupp.single p k) : n = p ^ k := by rw [← Nat.factorization_prod_pow_eq_self hn, h] simp /-- The only prime factor of prime `p` is `p` itself. -/ theorem Prime.eq_of_factorization_pos {p q : ℕ} (hp : Prime p) (h : p.factorization q ≠ 0) : p = q := by simpa [hp.factorization, single_apply] using h /-! ### Equivalence between `ℕ+` and `ℕ →₀ ℕ` with support in the primes. -/ theorem eq_factorization_iff {n : ℕ} {f : ℕ →₀ ℕ} (hn : n ≠ 0) (hf : ∀ p ∈ f.support, Prime p) : f = n.factorization ↔ f.prod (· ^ ·) = n := ⟨fun h => by rw [h, factorization_prod_pow_eq_self hn], fun h => by rw [← h, prod_pow_factorization_eq_self hf]⟩ theorem factorizationEquiv_inv_apply {f : ℕ →₀ ℕ} (hf : ∀ p ∈ f.support, Prime p) : (factorizationEquiv.symm ⟨f, hf⟩).1 = f.prod (· ^ ·) := rfl theorem ordProj_of_not_prime (n p : ℕ) (hp : ¬p.Prime) : ordProj[p] n = 1 := by simp [hp] theorem ordCompl_of_not_prime (n p : ℕ) (hp : ¬p.Prime) : ordCompl[p] n = n := by simp [hp] theorem ordCompl_dvd (n p : ℕ) : ordCompl[p] n ∣ n := div_dvd_of_dvd (ordProj_dvd n p) theorem ordProj_pos (n p : ℕ) : 0 < ordProj[p] n := by if pp : p.Prime then simp [Nat.pow_pos pp.pos] else simp [pp] theorem ordProj_le {n : ℕ} (p : ℕ) (hn : n ≠ 0) : ordProj[p] n ≤ n := le_of_dvd hn.bot_lt (Nat.ordProj_dvd n p) theorem ordCompl_pos {n : ℕ} (p : ℕ) (hn : n ≠ 0) : 0 < ordCompl[p] n := by if pp : p.Prime then exact Nat.div_pos (ordProj_le p hn) (ordProj_pos n p) else simpa [Nat.factorization_eq_zero_of_not_prime n pp] using hn.bot_lt theorem ordCompl_le (n p : ℕ) : ordCompl[p] n ≤ n := Nat.div_le_self _ _ theorem ordProj_mul_ordCompl_eq_self (n p : ℕ) : ordProj[p] n * ordCompl[p] n = n := Nat.mul_div_cancel' (ordProj_dvd n p) theorem ordProj_mul {a b : ℕ} (p : ℕ) (ha : a ≠ 0) (hb : b ≠ 0) : ordProj[p] (a * b) = ordProj[p] a * ordProj[p] b := by simp [factorization_mul ha hb, pow_add] theorem ordCompl_mul (a b p : ℕ) : ordCompl[p] (a * b) = ordCompl[p] a * ordCompl[p] b := by if ha : a = 0 then simp [ha] else if hb : b = 0 then simp [hb] else simp only [ordProj_mul p ha hb] rw [div_mul_div_comm (ordProj_dvd a p) (ordProj_dvd b p)] /-! ### Factorization and divisibility -/ /-- A crude upper bound on `n.factorization p` -/ theorem factorization_lt {n : ℕ} (p : ℕ) (hn : n ≠ 0) : n.factorization p < n := by by_cases pp : p.Prime · exact (Nat.pow_lt_pow_iff_right pp.one_lt).1 <| (ordProj_le p hn).trans_lt <| Nat.lt_pow_self pp.one_lt · simpa only [factorization_eq_zero_of_not_prime n pp] using hn.bot_lt /-- An upper bound on `n.factorization p` -/ theorem factorization_le_of_le_pow {n p b : ℕ} (hb : n ≤ p ^ b) : n.factorization p ≤ b := by if hn : n = 0 then simp [hn] else if pp : p.Prime then exact (Nat.pow_le_pow_iff_right pp.one_lt).1 ((ordProj_le p hn).trans hb) else simp [factorization_eq_zero_of_not_prime n pp] theorem factorization_prime_le_iff_dvd {d n : ℕ} (hd : d ≠ 0) (hn : n ≠ 0) : (∀ p : ℕ, p.Prime → d.factorization p ≤ n.factorization p) ↔ d ∣ n := by rw [← factorization_le_iff_dvd hd hn] refine ⟨fun h p => (em p.Prime).elim (h p) fun hp => ?_, fun h p _ => h p⟩ simp_rw [factorization_eq_zero_of_not_prime _ hp] rfl theorem factorization_le_factorization_mul_left {a b : ℕ} (hb : b ≠ 0) : a.factorization ≤ (a * b).factorization := by rcases eq_or_ne a 0 with (rfl | ha) · simp rw [factorization_le_iff_dvd ha <| mul_ne_zero ha hb] exact Dvd.intro b rfl theorem factorization_le_factorization_mul_right {a b : ℕ} (ha : a ≠ 0) : b.factorization ≤ (a * b).factorization := by rw [mul_comm] apply factorization_le_factorization_mul_left ha theorem Prime.pow_dvd_iff_le_factorization {p k n : ℕ} (pp : Prime p) (hn : n ≠ 0) : p ^ k ∣ n ↔ k ≤ n.factorization p := by rw [← factorization_le_iff_dvd (Nat.pow_pos pp.pos).ne' hn, pp.factorization_pow, single_le_iff] theorem Prime.pow_dvd_iff_dvd_ordProj {p k n : ℕ} (pp : Prime p) (hn : n ≠ 0) : p ^ k ∣ n ↔ p ^ k ∣ ordProj[p] n := by rw [pow_dvd_pow_iff_le_right pp.one_lt, pp.pow_dvd_iff_le_factorization hn] theorem Prime.dvd_iff_one_le_factorization {p n : ℕ} (pp : Prime p) (hn : n ≠ 0) : p ∣ n ↔ 1 ≤ n.factorization p := Iff.trans (by simp) (pp.pow_dvd_iff_le_factorization hn) theorem exists_factorization_lt_of_lt {a b : ℕ} (ha : a ≠ 0) (hab : a < b) : ∃ p : ℕ, a.factorization p < b.factorization p := by have hb : b ≠ 0 := (ha.bot_lt.trans hab).ne' contrapose! hab rw [← Finsupp.le_def, factorization_le_iff_dvd hb ha] at hab exact le_of_dvd ha.bot_lt hab @[simp] theorem factorization_div {d n : ℕ} (h : d ∣ n) : (n / d).factorization = n.factorization - d.factorization := by rcases eq_or_ne d 0 with (rfl | hd); · simp [zero_dvd_iff.mp h] rcases eq_or_ne n 0 with (rfl | hn); · simp [tsub_eq_zero_of_le] apply add_left_injective d.factorization simp only rw [tsub_add_cancel_of_le <| (Nat.factorization_le_iff_dvd hd hn).mpr h, ← Nat.factorization_mul (Nat.div_pos (Nat.le_of_dvd hn.bot_lt h) hd.bot_lt).ne' hd, Nat.div_mul_cancel h] theorem dvd_ordProj_of_dvd {n p : ℕ} (hn : n ≠ 0) (pp : p.Prime) (h : p ∣ n) : p ∣ ordProj[p] n := dvd_pow_self p (Prime.factorization_pos_of_dvd pp hn h).ne' theorem not_dvd_ordCompl {n p : ℕ} (hp : Prime p) (hn : n ≠ 0) : ¬p ∣ ordCompl[p] n := by rw [Nat.Prime.dvd_iff_one_le_factorization hp (ordCompl_pos p hn).ne'] rw [Nat.factorization_div (Nat.ordProj_dvd n p)] simp [hp.factorization] theorem coprime_ordCompl {n p : ℕ} (hp : Prime p) (hn : n ≠ 0) : Coprime p (ordCompl[p] n) := (or_iff_left (not_dvd_ordCompl hp hn)).mp <| coprime_or_dvd_of_prime hp _ theorem factorization_ordCompl (n p : ℕ) : (ordCompl[p] n).factorization = n.factorization.erase p := by if hn : n = 0 then simp [hn] else if pp : p.Prime then ?_ else simp [pp] ext q rcases eq_or_ne q p with (rfl | hqp) · simp only [Finsupp.erase_same, factorization_eq_zero_iff, not_dvd_ordCompl pp hn] simp · rw [Finsupp.erase_ne hqp, factorization_div (ordProj_dvd n p)] simp [pp.factorization, hqp.symm] -- `ordCompl[p] n` is the largest divisor of `n` not divisible by `p`. theorem dvd_ordCompl_of_dvd_not_dvd {p d n : ℕ} (hdn : d ∣ n) (hpd : ¬p ∣ d) : d ∣ ordCompl[p] n := by if hn0 : n = 0 then simp [hn0] else if hd0 : d = 0 then simp [hd0] at hpd else rw [← factorization_le_iff_dvd hd0 (ordCompl_pos p hn0).ne', factorization_ordCompl] intro q if hqp : q = p then simp [factorization_eq_zero_iff, hqp, hpd] else simp [hqp, (factorization_le_iff_dvd hd0 hn0).2 hdn q] /-- If `n` is a nonzero natural number and `p ≠ 1`, then there are natural numbers `e` and `n'` such that `n'` is not divisible by `p` and `n = p^e * n'`. -/ theorem exists_eq_pow_mul_and_not_dvd {n : ℕ} (hn : n ≠ 0) (p : ℕ) (hp : p ≠ 1) : ∃ e n' : ℕ, ¬p ∣ n' ∧ n = p ^ e * n' := let ⟨a', h₁, h₂⟩ := (Nat.finiteMultiplicity_iff.mpr ⟨hp, Nat.pos_of_ne_zero hn⟩).exists_eq_pow_mul_and_not_dvd ⟨_, a', h₂, h₁⟩ /-- Any nonzero natural number is the product of an odd part `m` and a power of two `2 ^ k`. -/ theorem exists_eq_two_pow_mul_odd {n : ℕ} (hn : n ≠ 0) : ∃ k m : ℕ, Odd m ∧ n = 2 ^ k * m := let ⟨k, m, hm, hn⟩ := exists_eq_pow_mul_and_not_dvd hn 2 (succ_ne_self 1) ⟨k, m, not_even_iff_odd.1 (mt Even.two_dvd hm), hn⟩ theorem dvd_iff_div_factorization_eq_tsub {d n : ℕ} (hd : d ≠ 0) (hdn : d ≤ n) : d ∣ n ↔ (n / d).factorization = n.factorization - d.factorization := by refine ⟨factorization_div, ?_⟩ rcases eq_or_lt_of_le hdn with (rfl | hd_lt_n); · simp have h1 : n / d ≠ 0 := by simp [*] intro h rw [dvd_iff_le_div_mul n d] by_contra h2 obtain ⟨p, hp⟩ := exists_factorization_lt_of_lt (mul_ne_zero h1 hd) (not_le.mp h2) rwa [factorization_mul h1 hd, add_apply, ← lt_tsub_iff_right, h, tsub_apply, lt_self_iff_false] at hp theorem ordProj_dvd_ordProj_of_dvd {a b : ℕ} (hb0 : b ≠ 0) (hab : a ∣ b) (p : ℕ) : ordProj[p] a ∣ ordProj[p] b := by rcases em' p.Prime with (pp | pp); · simp [pp] rcases eq_or_ne a 0 with (rfl | ha0); · simp rw [pow_dvd_pow_iff_le_right pp.one_lt] exact (factorization_le_iff_dvd ha0 hb0).2 hab p theorem ordCompl_dvd_ordCompl_of_dvd {a b : ℕ} (hab : a ∣ b) (p : ℕ) : ordCompl[p] a ∣ ordCompl[p] b := by rcases em' p.Prime with (pp | pp) · simp [pp, hab] rcases eq_or_ne b 0 with (rfl | hb0) · simp rcases eq_or_ne a 0 with (rfl | ha0) · cases hb0 (zero_dvd_iff.1 hab) have ha := (Nat.div_pos (ordProj_le p ha0) (ordProj_pos a p)).ne' have hb := (Nat.div_pos (ordProj_le p hb0) (ordProj_pos b p)).ne' rw [← factorization_le_iff_dvd ha hb, factorization_ordCompl a p, factorization_ordCompl b p] intro q rcases eq_or_ne q p with (rfl | hqp) · simp simp_rw [erase_ne hqp] exact (factorization_le_iff_dvd ha0 hb0).2 hab q theorem ordCompl_dvd_ordCompl_iff_dvd (a b : ℕ) : (∀ p : ℕ, ordCompl[p] a ∣ ordCompl[p] b) ↔ a ∣ b := by refine ⟨fun h => ?_, fun hab p => ordCompl_dvd_ordCompl_of_dvd hab p⟩ rcases eq_or_ne b 0 with (rfl | hb0) · simp if pa : a.Prime then ?_ else simpa [pa] using h a if pb : b.Prime then ?_ else simpa [pb] using h b rw [prime_dvd_prime_iff_eq pa pb] by_contra hab apply pa.ne_one rw [← Nat.dvd_one, ← Nat.mul_dvd_mul_iff_left hb0.bot_lt, mul_one] simpa [Prime.factorization_self pb, Prime.factorization pa, hab] using h b theorem dvd_iff_prime_pow_dvd_dvd (n d : ℕ) : d ∣ n ↔ ∀ p k : ℕ, Prime p → p ^ k ∣ d → p ^ k ∣ n := by rcases eq_or_ne n 0 with (rfl | hn) · simp rcases eq_or_ne d 0 with (rfl | hd) · simp only [zero_dvd_iff, hn, false_iff, not_forall] exact ⟨2, n, prime_two, dvd_zero _, mt (le_of_dvd hn.bot_lt) (n.lt_two_pow_self).not_ge⟩ refine ⟨fun h p k _ hpkd => dvd_trans hpkd h, ?_⟩ rw [← factorization_prime_le_iff_dvd hd hn] intro h p pp simp_rw [← pp.pow_dvd_iff_le_factorization hn] exact h p _ pp (ordProj_dvd _ _) theorem prod_primeFactors_dvd (n : ℕ) : ∏ p ∈ n.primeFactors, p ∣ n := by by_cases hn : n = 0 · subst hn simp · simpa [prod_primeFactorsList hn] using (n.primeFactorsList : Multiset ℕ).toFinset_prod_dvd_prod theorem factorization_gcd {a b : ℕ} (ha_pos : a ≠ 0) (hb_pos : b ≠ 0) : (gcd a b).factorization = a.factorization ⊓ b.factorization := by let dfac := a.factorization ⊓ b.factorization let d := dfac.prod (· ^ ·) have dfac_prime : ∀ p : ℕ, p ∈ dfac.support → Prime p := by intro p hp have : p ∈ a.primeFactorsList ∧ p ∈ b.primeFactorsList := by simpa [dfac] using hp exact prime_of_mem_primeFactorsList this.1 have h1 : d.factorization = dfac := prod_pow_factorization_eq_self dfac_prime have hd_pos : d ≠ 0 := (factorizationEquiv.invFun ⟨dfac, dfac_prime⟩).2.ne' suffices d = gcd a b by rwa [← this] apply gcd_greatest · rw [← factorization_le_iff_dvd hd_pos ha_pos, h1] exact inf_le_left · rw [← factorization_le_iff_dvd hd_pos hb_pos, h1] exact inf_le_right · intro e hea heb rcases Decidable.eq_or_ne e 0 with (rfl | he_pos) · simp only [zero_dvd_iff] at hea contradiction have hea' := (factorization_le_iff_dvd he_pos ha_pos).mpr hea have heb' := (factorization_le_iff_dvd he_pos hb_pos).mpr heb simp [dfac, ← factorization_le_iff_dvd he_pos hd_pos, h1, hea', heb'] theorem factorization_lcm {a b : ℕ} (ha : a ≠ 0) (hb : b ≠ 0) : (a.lcm b).factorization = a.factorization ⊔ b.factorization := by rw [← add_right_inj (a.gcd b).factorization, ← factorization_mul (mt gcd_eq_zero_iff.1 fun h => ha h.1) (lcm_ne_zero ha hb), gcd_mul_lcm, factorization_gcd ha hb, factorization_mul ha hb] ext1 exact (min_add_max _ _).symm @[to_additive sum_primeFactors_gcd_add_sum_primeFactors_mul] theorem prod_primeFactors_gcd_mul_prod_primeFactors_mul {β : Type*} [CommMonoid β] (m n : ℕ) (f : ℕ → β) : (m.gcd n).primeFactors.prod f * (m * n).primeFactors.prod f = m.primeFactors.prod f * n.primeFactors.prod f := by obtain rfl | hm₀ := eq_or_ne m 0 · simp obtain rfl | hn₀ := eq_or_ne n 0 · simp · rw [primeFactors_mul hm₀ hn₀, primeFactors_gcd hm₀ hn₀, mul_comm, Finset.prod_union_inter] theorem setOf_pow_dvd_eq_Icc_factorization {n p : ℕ} (pp : p.Prime) (hn : n ≠ 0) : { i : ℕ | i ≠ 0 ∧ p ^ i ∣ n } = Set.Icc 1 (n.factorization p) := by ext simp [one_le_iff_ne_zero, pp.pow_dvd_iff_le_factorization hn] /-- The set of positive powers of prime `p` that divide `n` is exactly the set of positive natural numbers up to `n.factorization p`. -/ theorem Icc_factorization_eq_pow_dvd (n : ℕ) {p : ℕ} (pp : Prime p) : Icc 1 (n.factorization p) = {i ∈ Ico 1 n | p ^ i ∣ n} := by rcases eq_or_ne n 0 with (rfl | hn) · simp ext x simp only [mem_Icc, Finset.mem_filter, mem_Ico, and_assoc, and_congr_right_iff, pp.pow_dvd_iff_le_factorization hn, iff_and_self] exact fun _ H => lt_of_le_of_lt H (factorization_lt p hn) theorem factorization_eq_card_pow_dvd (n : ℕ) {p : ℕ} (pp : p.Prime) : n.factorization p = #{i ∈ Ico 1 n | p ^ i ∣ n} := by simp [← Icc_factorization_eq_pow_dvd n pp] theorem Ico_filter_pow_dvd_eq {n p b : ℕ} (pp : p.Prime) (hn : n ≠ 0) (hb : n ≤ p ^ b) : {i ∈ Ico 1 n | p ^ i ∣ n} = {i ∈ Icc 1 b | p ^ i ∣ n} := by ext x simp only [Finset.mem_filter, mem_Ico, mem_Icc, and_congr_left_iff, and_congr_right_iff] rintro h1 - exact iff_of_true (lt_of_pow_dvd_right hn pp.two_le h1) <| (Nat.pow_le_pow_iff_right pp.one_lt).1 <| (le_of_dvd hn.bot_lt h1).trans hb theorem Ico_pow_dvd_eq_Ico_of_lt {n p b : ℕ} (pp : p.Prime) (hn : n ≠ 0) (hb : n < p ^ b) : {i ∈ Ico 1 n | p ^ i ∣ n} = {i ∈ Ico 1 b | p ^ i ∣ n} := by ext i simp only [Finset.mem_filter, mem_Ico, and_congr_left_iff, and_congr_right_iff] refine fun h1 h2 ↦ ⟨fun h ↦ ?_, fun h ↦ lt_of_pow_dvd_right hn (Prime.one_lt pp) h1⟩ rcases p with - | p · rw [zero_pow (by cutsat), zero_dvd_iff] at h1 exact (hn h1).elim · rw [← Nat.pow_lt_pow_iff_right (Prime.one_lt pp)] apply lt_of_le_of_lt (le_of_dvd (Nat.zero_lt_of_ne_zero hn) h1) hb /-- The factorization of `m` in `n` is the number of positive natural numbers `i` such that `m ^ i` divides `n`. Note `m` is prime. This set is expressed by filtering `Ico 1 b` where `b` is any bound greater than `log m n`. -/ theorem factorization_eq_card_pow_dvd_of_lt (hm : m.Prime) (hn : 0 < n) (hb : n < m ^ b) : n.factorization m = #{i ∈ Ico 1 b | m ^ i ∣ n} := by rwa [factorization_eq_card_pow_dvd n hm, Ico_pow_dvd_eq_Ico_of_lt hm (by cutsat)] /-! ### Factorization and coprimes -/ /-- If `p` is a prime factor of `a` then the power of `p` in `a` is the same that in `a * b`, for any `b` coprime to `a`. -/ theorem factorization_eq_of_coprime_left {p a b : ℕ} (hab : Coprime a b) (hpa : p ∈ a.primeFactorsList) : (a * b).factorization p = a.factorization p := by rw [factorization_mul_apply_of_coprime hab, ← primeFactorsList_count_eq, ← primeFactorsList_count_eq, count_eq_zero_of_not_mem (coprime_primeFactorsList_disjoint hab hpa), add_zero] /-- If `p` is a prime factor of `b` then the power of `p` in `b` is the same that in `a * b`, for any `a` coprime to `b`. -/ theorem factorization_eq_of_coprime_right {p a b : ℕ} (hab : Coprime a b) (hpb : p ∈ b.primeFactorsList) : (a * b).factorization p = b.factorization p := by rw [mul_comm] exact factorization_eq_of_coprime_left (coprime_comm.mp hab) hpb /-- Two positive naturals are equal if their prime padic valuations are equal -/ theorem eq_iff_prime_padicValNat_eq (a b : ℕ) (ha : a ≠ 0) (hb : b ≠ 0) : a = b ↔ ∀ p : ℕ, p.Prime → padicValNat p a = padicValNat p b := by constructor · rintro rfl simp · intro h refine eq_of_factorization_eq ha hb fun p => ?_ by_cases pp : p.Prime · simp [factorization_def, pp, h p pp] · simp [factorization_eq_zero_of_not_prime, pp] theorem prod_pow_prime_padicValNat (n : Nat) (hn : n ≠ 0) (m : Nat) (pr : n < m) : ∏ p ∈ range m with p.Prime, p ^ padicValNat p n = n := by nth_rw 2 [← factorization_prod_pow_eq_self hn] rw [eq_comm] apply Finset.prod_subset_one_on_sdiff · exact fun p hp => Finset.mem_filter.mpr ⟨Finset.mem_range.2 <| pr.trans_le' <| le_of_mem_primeFactors hp, prime_of_mem_primeFactors hp⟩ · intro p hp obtain ⟨hp1, hp2⟩ := Finset.mem_sdiff.mp hp rw [← factorization_def n (Finset.mem_filter.mp hp1).2] simp [Finsupp.notMem_support_iff.mp hp2] · intro p hp simp [factorization_def n (prime_of_mem_primeFactors hp)] lemma prod_pow_primeFactors_factorization (hn : n ≠ 0) : n = ∏ (p : n.primeFactors), (p : ℕ) ^ (n.factorization p) := by nth_rw 1 [← factorization_prod_pow_eq_self hn] rw [prod_factorization_eq_prod_primeFactors _] exact prod_subtype n.primeFactors (fun _ ↦ Iff.rfl) fun a ↦ a ^ n.factorization a lemma pairwise_coprime_pow_primeFactors_factorization : Pairwise (Function.onFun Nat.Coprime fun (p : n.primeFactors) ↦ p ^ n.factorization p) := by intro p1 p2 hp refine Nat.Coprime.pow (n.factorization p1) (n.factorization p2) ?_ refine (Nat.coprime_primes ?_ ?_).mpr <| Subtype.coe_ne_coe.mpr hp · exact Nat.prime_of_mem_primeFactors p1.2 · exact Nat.prime_of_mem_primeFactors p2.2 /-! ### Lemmas about factorizations of particular functions -/ /-- Exactly `n / p` naturals in `[1, n]` are multiples of `p`. See `Nat.card_multiples'` for an alternative spelling of the statement. -/ theorem card_multiples (n p : ℕ) : #{e ∈ range n | p ∣ e + 1} = n / p := by induction n with | zero => simp | succ n hn => simp [Nat.succ_div, add_ite, add_zero, Finset.range_add_one, filter_insert, apply_ite card, card_insert_of_notMem, hn] /-- Exactly `n / p` naturals in `(0, n]` are multiples of `p`. -/ theorem Ioc_filter_dvd_card_eq_div (n p : ℕ) : #{x ∈ Ioc 0 n | p ∣ x} = n / p := by induction n <;> simp [Nat.succ_div, add_ite, ← insert_Ioc_right_eq_Ioc_add_one, filter_insert, apply_ite card, *] /-- There are exactly `⌊N/n⌋` positive multiples of `n` that are `≤ N`. See `Nat.card_multiples` for a "shifted-by-one" version. -/ lemma card_multiples' (N n : ℕ) : #{k ∈ range N.succ | k ≠ 0 ∧ n ∣ k} = N / n := by induction N with | zero => simp [Finset.filter_false_of_mem] | succ N ih => rw [Finset.range_add_one, Finset.filter_insert] by_cases h : n ∣ N.succ · simp [h, succ_div_of_dvd, ih] · simp [h, succ_div_of_not_dvd, ih] end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Factorization/Defs.lean
import Batteries.Data.List.Count import Mathlib.Data.Finsupp.Multiset import Mathlib.Data.Finsupp.Order import Mathlib.Data.Nat.PrimeFin import Mathlib.NumberTheory.Padics.PadicVal.Defs /-! # Prime factorizations `n.factorization` is the finitely supported function `ℕ →₀ ℕ` mapping each prime factor of `n` to its multiplicity in `n`. For example, since 2000 = 2^4 * 5^3, * `factorization 2000 2` is 4 * `factorization 2000 5` is 3 * `factorization 2000 k` is 0 for all other `k : ℕ`. ## TODO * As discussed in this Zulip thread: https://leanprover.zulipchat.com/#narrow/stream/217875/topic/Multiplicity.20in.20the.20naturals We have lots of disparate ways of talking about the multiplicity of a prime in a natural number, including `factors.count`, `padicValNat`, `multiplicity`, and the material in `Data/PNat/Factors`. Move some of this material to this file, prove results about the relationships between these definitions, and (where appropriate) choose a uniform canonical way of expressing these ideas. * Moreover, the results here should be generalised to an arbitrary unique factorization monoid with a normalization function, and then deduplicated. The basics of this have been started in `Mathlib/RingTheory/UniqueFactorizationDomain/`. * Extend the inductions to any `NormalizationMonoid` with unique factorization. -/ open Nat Finset List Finsupp namespace Nat variable {a b m n p : ℕ} /-- `n.factorization` is the finitely supported function `ℕ →₀ ℕ` mapping each prime factor of `n` to its multiplicity in `n`. -/ def factorization (n : ℕ) : ℕ →₀ ℕ where support := n.primeFactors toFun p := if p.Prime then padicValNat p n else 0 mem_support_toFun := by simp [not_or]; aesop /-- The support of `n.factorization` is exactly `n.primeFactors`. -/ @[simp] lemma support_factorization (n : ℕ) : (factorization n).support = n.primeFactors := rfl theorem factorization_def (n : ℕ) {p : ℕ} (pp : p.Prime) : n.factorization p = padicValNat p n := by simpa [factorization] using absurd pp /-- We can write both `n.factorization p` and `n.factors.count p` to represent the power of `p` in the factorization of `n`: we declare the former to be the simp-normal form. -/ @[simp] theorem primeFactorsList_count_eq {n p : ℕ} : n.primeFactorsList.count p = n.factorization p := by rcases n.eq_zero_or_pos with (rfl | hn0) · simp [factorization, count] if pp : p.Prime then ?_ else rw [count_eq_zero_of_not_mem (mt prime_of_mem_primeFactorsList pp)] simp [factorization, pp] simp only [factorization_def _ pp] apply _root_.le_antisymm · rw [le_padicValNat_iff_replicate_subperm_primeFactorsList pp hn0.ne'] exact List.replicate_sublist_iff.mpr le_rfl |>.subperm · rw [← Nat.lt_add_one_iff, lt_iff_not_ge, le_padicValNat_iff_replicate_subperm_primeFactorsList pp hn0.ne'] intro h have := h.count_le p simp at this theorem factorization_eq_primeFactorsList_multiset (n : ℕ) : n.factorization = Multiset.toFinsupp (n.primeFactorsList : Multiset ℕ) := by ext p simp theorem Prime.factorization_pos_of_dvd {n p : ℕ} (hp : p.Prime) (hn : n ≠ 0) (h : p ∣ n) : 0 < n.factorization p := by rwa [← primeFactorsList_count_eq, count_pos_iff, mem_primeFactorsList_iff_dvd hn hp] theorem multiplicity_eq_factorization {n p : ℕ} (pp : p.Prime) (hn : n ≠ 0) : multiplicity p n = n.factorization p := by simp [factorization, pp, padicValNat_def' pp.ne_one hn] /-! ### Basic facts about factorization -/ @[simp] theorem factorization_prod_pow_eq_self {n : ℕ} (hn : n ≠ 0) : n.factorization.prod (· ^ ·) = n := by rw [factorization_eq_primeFactorsList_multiset n] simp only [← prod_toMultiset, Multiset.prod_coe, Multiset.toFinsupp_toMultiset] exact prod_primeFactorsList hn theorem eq_of_factorization_eq {a b : ℕ} (ha : a ≠ 0) (hb : b ≠ 0) (h : ∀ p : ℕ, a.factorization p = b.factorization p) : a = b := eq_of_perm_primeFactorsList ha hb (by simpa only [List.perm_iff_count, primeFactorsList_count_eq] using h) /-- Every nonzero natural number has a unique prime factorization -/ theorem factorization_inj : Set.InjOn factorization { x : ℕ | x ≠ 0 } := fun a ha b hb h => eq_of_factorization_eq ha hb fun p => by simp [h] @[simp] theorem factorization_zero : factorization 0 = 0 := by ext; simp [factorization] @[simp] theorem factorization_one : factorization 1 = 0 := by ext; simp [factorization] /-! ## Lemmas characterising when `n.factorization p = 0` -/ theorem factorization_eq_zero_iff (n p : ℕ) : n.factorization p = 0 ↔ ¬p.Prime ∨ ¬p ∣ n ∨ n = 0 := by simp_rw [← notMem_support_iff, support_factorization, mem_primeFactors, not_and_or, not_ne_iff] @[simp] theorem factorization_eq_zero_of_not_prime (n : ℕ) {p : ℕ} (hp : ¬p.Prime) : n.factorization p = 0 := by simp [factorization_eq_zero_iff, hp] @[deprecated (since := "2025-10-24")] alias factorization_eq_zero_of_non_prime := factorization_eq_zero_of_not_prime @[simp] theorem factorization_zero_right (n : ℕ) : n.factorization 0 = 0 := factorization_eq_zero_of_not_prime _ not_prime_zero @[simp] theorem factorization_one_right (n : ℕ) : n.factorization 1 = 0 := factorization_eq_zero_of_not_prime _ not_prime_one theorem factorization_eq_zero_of_not_dvd {n p : ℕ} (h : ¬p ∣ n) : n.factorization p = 0 := by simp [factorization_eq_zero_iff, h] theorem factorization_eq_zero_of_remainder {p r : ℕ} (i : ℕ) (hr : ¬p ∣ r) : (p * i + r).factorization p = 0 := by apply factorization_eq_zero_of_not_dvd rwa [← Nat.dvd_add_iff_right (Dvd.intro i rfl)] /-! ## Lemmas about factorizations of products and powers -/ /-- For nonzero `a` and `b`, the power of `p` in `a * b` is the sum of the powers in `a` and `b` -/ @[simp] theorem factorization_mul {a b : ℕ} (ha : a ≠ 0) (hb : b ≠ 0) : (a * b).factorization = a.factorization + b.factorization := by ext p simp only [add_apply, ← primeFactorsList_count_eq, perm_iff_count.mp (perm_primeFactorsList_mul ha hb) p, count_append] theorem factorization_le_iff_dvd {d n : ℕ} (hd : d ≠ 0) (hn : n ≠ 0) : d.factorization ≤ n.factorization ↔ d ∣ n := by constructor · intro hdn set K := n.factorization - d.factorization with hK use K.prod (· ^ ·) rw [← factorization_prod_pow_eq_self hn, ← factorization_prod_pow_eq_self hd, ← Finsupp.prod_add_index' pow_zero pow_add, hK, add_tsub_cancel_of_le hdn] · rintro ⟨c, rfl⟩ rw [factorization_mul hd (right_ne_zero_of_mul hn)] simp /-- For any `p : ℕ` and any function `g : α → ℕ` that's non-zero on `S : Finset α`, the power of `p` in `S.prod g` equals the sum over `x ∈ S` of the powers of `p` in `g x`. Generalises `factorization_mul`, which is the special case where `#S = 2` and `g = id`. -/ theorem factorization_prod {α : Type*} {S : Finset α} {g : α → ℕ} (hS : ∀ x ∈ S, g x ≠ 0) : (S.prod g).factorization = S.sum fun x => (g x).factorization := by classical ext p refine Finset.induction_on' S ?_ ?_ · simp · intro x T hxS hTS hxT IH have hT : T.prod g ≠ 0 := prod_ne_zero_iff.mpr fun x hx => hS x (hTS hx) simp [prod_insert hxT, sum_insert hxT, IH, factorization_mul (hS x hxS) hT] /-- For any `p`, the power of `p` in `n^k` is `k` times the power in `n` -/ @[simp] theorem factorization_pow (n k : ℕ) : factorization (n ^ k) = k • n.factorization := by induction k with | zero => simp | succ k ih => rcases eq_or_ne n 0 with (rfl | hn) · simp rw [Nat.pow_succ, mul_comm, factorization_mul hn (pow_ne_zero _ hn), ih, add_smul, one_smul, add_comm] /-! ## Lemmas about factorizations of primes and prime powers -/ /-- The only prime factor of prime `p` is `p` itself, with multiplicity `1` -/ @[simp] protected theorem Prime.factorization {p : ℕ} (hp : Prime p) : p.factorization = single p 1 := by ext q rw [← primeFactorsList_count_eq, primeFactorsList_prime hp, single_apply, count_singleton', if_congr eq_comm] <;> rfl /-- For prime `p` the only prime factor of `p^k` is `p` with multiplicity `k` -/ theorem Prime.factorization_pow {p k : ℕ} (hp : Prime p) : (p ^ k).factorization = single p k := by simp [hp] theorem pow_succ_factorization_not_dvd {n p : ℕ} (hn : n ≠ 0) (hp : p.Prime) : ¬p ^ (n.factorization p + 1) ∣ n := by intro h rw [← factorization_le_iff_dvd (pow_ne_zero _ hp.ne_zero) hn] at h simpa [hp.factorization] using h p lemma factorization_minFac_ne_zero {n : ℕ} (hn : 1 < n) : n.factorization n.minFac ≠ 0 := by refine mt (factorization_eq_zero_iff _ _).mp ?_ push_neg exact ⟨minFac_prime (by cutsat), minFac_dvd n, Nat.ne_zero_of_lt hn⟩ /-! ### Equivalence between `ℕ+` and `ℕ →₀ ℕ` with support in the primes. -/ /-- Any Finsupp `f : ℕ →₀ ℕ` whose support is in the primes is equal to the factorization of the product `∏ (a : ℕ) ∈ f.support, a ^ f a`. -/ theorem prod_pow_factorization_eq_self {f : ℕ →₀ ℕ} (hf : ∀ p : ℕ, p ∈ f.support → Prime p) : (f.prod (· ^ ·)).factorization = f := by have h : ∀ x : ℕ, x ∈ f.support → x ^ f x ≠ 0 := fun p hp => pow_ne_zero _ (Prime.ne_zero (hf p hp)) simp only [Finsupp.prod, factorization_prod h] conv => rhs rw [(sum_single f).symm] exact sum_congr rfl fun p hp => Prime.factorization_pow (hf p hp) /-- The equiv between `ℕ+` and `ℕ →₀ ℕ` with support in the primes. -/ def factorizationEquiv : ℕ+ ≃ { f : ℕ →₀ ℕ | ∀ p ∈ f.support, Prime p } where toFun := fun ⟨n, _⟩ => ⟨n.factorization, fun _ => prime_of_mem_primeFactors⟩ invFun := fun ⟨f, hf⟩ => ⟨f.prod _, prod_pow_pos_of_zero_notMem_support fun H => not_prime_zero (hf 0 H)⟩ left_inv := fun ⟨_, hx⟩ => Subtype.ext <| factorization_prod_pow_eq_self hx.ne.symm right_inv := fun ⟨_, hf⟩ => Subtype.ext <| prod_pow_factorization_eq_self hf /-! ### Factorization and coprimes -/ /-- For coprime `a` and `b`, the power of `p` in `a * b` is the sum of the powers in `a` and `b` -/ theorem factorization_mul_apply_of_coprime {p a b : ℕ} (hab : Coprime a b) : (a * b).factorization p = a.factorization p + b.factorization p := by simp only [← primeFactorsList_count_eq, perm_iff_count.mp (perm_primeFactorsList_mul_of_coprime hab), count_append] /-- For coprime `a` and `b`, the power of `p` in `a * b` is the sum of the powers in `a` and `b` -/ theorem factorization_mul_of_coprime {a b : ℕ} (hab : Coprime a b) : (a * b).factorization = a.factorization + b.factorization := by ext q rw [Finsupp.add_apply, factorization_mul_apply_of_coprime hab] /-! ### Generalisation of the "even part" and "odd part" of a natural number -/ /-- We introduce the notations `ordProj[p] n` for the largest power of the prime `p` that divides `n` and `ordCompl[p] n` for the complementary part. The `ord` naming comes from the $p$-adic order/valuation of a number, and `proj` and `compl` are for the projection and complementary projection. The term `n.factorization p` is the $p$-adic order itself. For example, `ordProj[2] n` is the even part of `n` and `ordCompl[2] n` is the odd part. -/ notation "ordProj[" p "] " n:arg => p ^ Nat.factorization n p @[inherit_doc «termOrdProj[_]_»] notation "ordCompl[" p "] " n:arg => n / ordProj[p] n theorem ordProj_dvd (n p : ℕ) : ordProj[p] n ∣ n := by if hp : p.Prime then ?_ else simp [hp] rw [← primeFactorsList_count_eq] apply dvd_of_primeFactorsList_subperm (pow_ne_zero _ hp.ne_zero) rw [hp.primeFactorsList_pow, List.subperm_ext_iff] intro q hq simp [List.eq_of_mem_replicate hq] lemma ordProj_dvd_ordProj_iff_dvd (ha : a ≠ 0) (hb : b ≠ 0) : (∀ p : ℕ, ordProj[p] a ∣ ordProj[p] b) ↔ a ∣ b := by rw [← factorization_le_iff_dvd ha hb, Finsupp.le_def] congr! 1 with p obtain _ | _ | p := p <;> simp [Nat.pow_dvd_pow_iff_le_right] /-! ### Factorization LCM definitions -/ /-- If `a = ∏ pᵢ ^ nᵢ` and `b = ∏ pᵢ ^ mᵢ`, then `factorizationLCMLeft = ∏ pᵢ ^ kᵢ`, where `kᵢ = nᵢ` if `mᵢ ≤ nᵢ` and `0` otherwise. Note that the product is over the divisors of `lcm a b`, so if one of `a` or `b` is `0` then the result is `1`. -/ def factorizationLCMLeft (a b : ℕ) : ℕ := (Nat.lcm a b).factorization.prod fun p n ↦ if b.factorization p ≤ a.factorization p then p ^ n else 1 /-- If `a = ∏ pᵢ ^ nᵢ` and `b = ∏ pᵢ ^ mᵢ`, then `factorizationLCMRight = ∏ pᵢ ^ kᵢ`, where `kᵢ = mᵢ` if `nᵢ < mᵢ` and `0` otherwise. Note that the product is over the divisors of `lcm a b`, so if one of `a` or `b` is `0` then the result is `1`. Note that `factorizationLCMRight a b` is *not* `factorizationLCMLeft b a`: the difference is that in `factorizationLCMLeft a b` there are the primes whose exponent in `a` is bigger or equal than the exponent in `b`, while in `factorizationLCMRight a b` there are the primes whose exponent in `b` is strictly bigger than in `a`. For example `factorizationLCMLeft 2 2 = 2`, but `factorizationLCMRight 2 2 = 1`. -/ def factorizationLCMRight (a b : ℕ) := (Nat.lcm a b).factorization.prod fun p n ↦ if b.factorization p ≤ a.factorization p then 1 else p ^ n end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Factorization/Induction.lean
import Mathlib.Data.Nat.Factorization.Defs /-! # Induction principles involving factorizations -/ open Nat Finset List Finsupp namespace Nat variable {a b m n p : ℕ} /-! ## Definitions -/ /-- Given `P 0, P 1` and a way to extend `P a` to `P (p ^ n * a)` for prime `p` not dividing `a`, we can define `P` for all natural numbers. -/ @[elab_as_elim] def recOnPrimePow {motive : ℕ → Sort*} (zero : motive 0) (one : motive 1) (prime_pow_mul : ∀ a p n : ℕ, p.Prime → ¬p ∣ a → 0 < n → motive a → motive (p ^ n * a)) (a : ℕ) : motive a := Nat.strongRecOn' a fun n => match n with | 0 => fun _ => zero | 1 => fun _ => one | k + 2 => fun hk => by letI p := (k + 2).minFac haveI hp : Prime p := minFac_prime (succ_succ_ne_one k) letI t := (k + 2).factorization p haveI hpt : p ^ t ∣ k + 2 := ordProj_dvd _ _ haveI htp : 0 < t := hp.factorization_pos_of_dvd (k + 1).succ_ne_zero (k + 2).minFac_dvd convert prime_pow_mul ((k + 2) / p ^ t) p t hp _ htp (hk _ (Nat.div_lt_of_lt_mul _)) using 1 · rw [Nat.mul_div_cancel' hpt] · rw [Nat.dvd_div_iff_mul_dvd hpt, ← Nat.pow_succ] exact pow_succ_factorization_not_dvd (k + 1).succ_ne_zero hp · simp [htp.ne', hp.one_lt] /-- Given `P 0`, `P 1`, and `P (p ^ n)` for positive prime powers, and a way to extend `P a` and `P b` to `P (a * b)` when `a, b` are positive coprime, we can define `P` for all natural numbers. -/ @[elab_as_elim] def recOnPosPrimePosCoprime {motive : ℕ → Sort*} (prime_pow : ∀ p n : ℕ, Prime p → 0 < n → motive (p ^ n)) (zero : motive 0) (one : motive 1) (coprime : ∀ a b, 1 < a → 1 < b → Coprime a b → motive a → motive b → motive (a * b)) : ∀ a, motive a := recOnPrimePow zero one <| by intro a p n hp' hpa hn hPa by_cases ha1 : a = 1 · rw [ha1, mul_one] exact prime_pow p n hp' hn refine coprime (p ^ n) a (hp'.one_lt.trans_le (le_self_pow hn.ne' _)) ?_ ?_ (prime_pow _ _ hp' hn) hPa · contrapose! hpa simp [lt_one_iff.1 (lt_of_le_of_ne hpa ha1)] · simpa [hn, Prime.coprime_iff_not_dvd hp'] /-- Given `P 0`, `P (p ^ n)` for all prime powers, and a way to extend `P a` and `P b` to `P (a * b)` when `a, b` are positive coprime, we can define `P` for all natural numbers. -/ @[elab_as_elim] def recOnPrimeCoprime {motive : ℕ → Sort*} (zero : motive 0) (prime_pow : ∀ p n : ℕ, Prime p → motive (p ^ n)) (coprime : ∀ a b, 1 < a → 1 < b → Coprime a b → motive a → motive b → motive (a * b)) : ∀ a, motive a := recOnPosPrimePosCoprime (fun p n h _ => prime_pow p n h) zero (prime_pow 2 0 prime_two) coprime /-- Given `P 0`, `P 1`, `P p` for all primes, and a way to extend `P a` and `P b` to `P (a * b)`, we can define `P` for all natural numbers. -/ @[elab_as_elim] def recOnMul {motive : ℕ → Sort*} (zero : motive 0) (one : motive 1) (prime : ∀ p, Prime p → motive p) (mul : ∀ a b, motive a → motive b → motive (a * b)) : ∀ a, motive a := recOnPrimeCoprime zero (fun p n hp' => Nat.rec one (fun _ ih => mul _ _ ih (prime p hp')) n) (fun a b _ _ _ => mul a b) lemma _root_.induction_on_primes {motive : ℕ → Prop} (zero : motive 0) (one : motive 1) (prime_mul : ∀ p a : ℕ, p.Prime → motive a → motive (p * a)) : ∀ n, motive n := by refine recOnPrimePow zero one ?_ rintro a p n hp - - ha induction n with | zero => simpa using ha | succ n ih => rw [pow_succ', mul_assoc] exact prime_mul _ _ hp ih lemma prime_composite_induction {motive : ℕ → Prop} (zero : motive 0) (one : motive 1) (prime : ∀ p : ℕ, p.Prime → motive p) (composite : ∀ a, 2 ≤ a → motive a → ∀ b, 2 ≤ b → motive b → motive (a * b)) (n : ℕ) : motive n := by refine induction_on_primes zero one ?_ _ rintro p (_ | _ | a) hp ha · simpa · simpa using prime _ hp · exact composite _ hp.two_le (prime _ hp) _ a.one_lt_succ_succ ha /-! ## Lemmas on multiplicative functions -/ /-- For any multiplicative function `f` with `f 1 = 1` and any `n ≠ 0`, we can evaluate `f n` by evaluating `f` at `p ^ k` over the factorization of `n` -/ theorem multiplicative_factorization {β : Type*} [CommMonoid β] (f : ℕ → β) (h_mult : ∀ x y : ℕ, Coprime x y → f (x * y) = f x * f y) (hf : f 1 = 1) : ∀ {n : ℕ}, n ≠ 0 → f n = n.factorization.prod fun p k => f (p ^ k) := by apply Nat.recOnPosPrimePosCoprime · rintro p k hp - - simp [Prime.factorization_pow hp, Finsupp.prod_single_index _, hf] · simp · rintro - rw [factorization_one, hf] simp · intro a b _ _ hab ha hb hab_pos rw [h_mult a b hab, ha (left_ne_zero_of_mul hab_pos), hb (right_ne_zero_of_mul hab_pos), factorization_mul_of_coprime hab, ← prod_add_index_of_disjoint] exact hab.disjoint_primeFactors /-- For any multiplicative function `f` with `f 1 = 1` and `f 0 = 1`, we can evaluate `f n` by evaluating `f` at `p ^ k` over the factorization of `n` -/ theorem multiplicative_factorization' {β : Type*} [CommMonoid β] (f : ℕ → β) (h_mult : ∀ x y : ℕ, Coprime x y → f (x * y) = f x * f y) (hf0 : f 0 = 1) (hf1 : f 1 = 1) : f n = n.factorization.prod fun p k => f (p ^ k) := by obtain rfl | hn := eq_or_ne n 0 · simpa · exact multiplicative_factorization _ h_mult hf1 hn end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Factorial/Basic.lean
import Mathlib.Data.Nat.Basic import Mathlib.Tactic.Common import Mathlib.Tactic.Monotonicity.Attr /-! # Factorial and variants This file defines the factorial, along with the ascending and descending variants. For the proof that the factorial of `n` counts the permutations of an `n`-element set, see `Fintype.card_perm`. ## Main declarations * `Nat.factorial`: The factorial. * `Nat.ascFactorial`: The ascending factorial. It is the product of natural numbers from `n` to `n + k - 1`. * `Nat.descFactorial`: The descending factorial. It is the product of natural numbers from `n - k + 1` to `n`. -/ namespace Nat /-- `Nat.factorial n` is the factorial of `n`. -/ def factorial : ℕ → ℕ | 0 => 1 | succ n => succ n * factorial n /-- factorial notation `(n)!` for `Nat.factorial n`. In Lean, names can end with exclamation marks (e.g. `List.get!`), so you cannot write `n!` in Lean, but must write `(n)!` or `n !` instead. The former is preferred, since Lean can confuse the `!` in `n !` as the (prefix) Boolean negation operation in some cases. For numerals the parentheses are not required, so e.g. `0!` or `1!` work fine. Todo: replace occurrences of `n !` with `(n)!` in Mathlib. -/ scoped notation:10000 n "!" => Nat.factorial n section Factorial variable {m n : ℕ} @[simp] theorem factorial_zero : 0! = 1 := rfl theorem factorial_succ (n : ℕ) : (n + 1)! = (n + 1) * n ! := rfl @[simp] theorem factorial_one : 1! = 1 := rfl @[simp] theorem factorial_two : 2! = 2 := rfl theorem mul_factorial_pred (hn : n ≠ 0) : n * (n - 1)! = n ! := Nat.sub_add_cancel (one_le_iff_ne_zero.mpr hn) ▸ rfl theorem factorial_pos : ∀ n, 0 < n ! | 0 => Nat.zero_lt_one | succ n => Nat.mul_pos (succ_pos _) (factorial_pos n) theorem factorial_ne_zero (n : ℕ) : n ! ≠ 0 := ne_of_gt (factorial_pos _) @[gcongr] theorem factorial_dvd_factorial {m n} (h : m ≤ n) : m ! ∣ n ! := by induction h with | refl => exact Nat.dvd_refl _ | step _ ih => exact Nat.dvd_trans ih (Nat.dvd_mul_left _ _) theorem dvd_factorial : ∀ {m n}, 0 < m → m ≤ n → m ∣ n ! | succ _, _, _, h => Nat.dvd_trans (Nat.dvd_mul_right _ _) (factorial_dvd_factorial h) @[mono, gcongr] theorem factorial_le {m n} (h : m ≤ n) : m ! ≤ n ! := le_of_dvd (factorial_pos _) (factorial_dvd_factorial h) theorem factorial_mul_pow_le_factorial : ∀ {m n : ℕ}, m ! * (m + 1) ^ n ≤ (m + n)! | m, 0 => by simp | m, n + 1 => by rw [← Nat.add_assoc, factorial_succ, Nat.mul_comm (_ + 1), Nat.pow_succ, ← Nat.mul_assoc] exact Nat.mul_le_mul factorial_mul_pow_le_factorial (succ_le_succ (le_add_right _ _)) theorem factorial_lt (hn : 0 < n) : n ! < m ! ↔ n < m := by refine ⟨fun h => not_le.mp fun hmn => Nat.not_le_of_gt h (factorial_le hmn), fun h => ?_⟩ have : ∀ {n}, 0 < n → n ! < (n + 1)! := by intro k hk rw [factorial_succ, succ_mul, Nat.lt_add_left_iff_pos] exact Nat.mul_pos hk k.factorial_pos induction h generalizing hn with | refl => exact this hn | step hnk ih => exact lt_trans (ih hn) <| this <| lt_trans hn <| lt_of_succ_le hnk @[gcongr] lemma factorial_lt_of_lt {m n : ℕ} (hn : 0 < n) (h : n < m) : n ! < m ! := (factorial_lt hn).mpr h @[simp] lemma one_lt_factorial : 1 < n ! ↔ 1 < n := factorial_lt Nat.one_pos @[simp] theorem factorial_eq_one : n ! = 1 ↔ n ≤ 1 := by constructor · intro h rw [← not_lt, ← one_lt_factorial, h] apply lt_irrefl · rintro (_ | _ | _) <;> rfl theorem factorial_inj (hn : 1 < n) : n ! = m ! ↔ n = m := by refine ⟨fun h => ?_, congr_arg _⟩ obtain hnm | rfl | hnm := lt_trichotomy n m · rw [← factorial_lt <| lt_of_succ_lt hn, h] at hnm cases lt_irrefl _ hnm · rfl rw [← one_lt_factorial, h, one_lt_factorial] at hn rw [← factorial_lt <| lt_of_succ_lt hn, h] at hnm cases lt_irrefl _ hnm theorem factorial_inj' (h : 1 < n ∨ 1 < m) : n ! = m ! ↔ n = m := by obtain hn | hm := h · exact factorial_inj hn · rw [eq_comm, factorial_inj hm, eq_comm] theorem self_le_factorial : ∀ n : ℕ, n ≤ n ! | 0 => Nat.zero_le _ | k + 1 => Nat.le_mul_of_pos_right _ (Nat.one_le_of_lt k.factorial_pos) theorem lt_factorial_self {n : ℕ} (hi : 3 ≤ n) : n < n ! := by have : 0 < n := by omega have hn : 1 < pred n := le_pred_of_lt (succ_le_iff.mp hi) rw [← succ_pred_eq_of_pos ‹0 < n›, factorial_succ] exact (Nat.lt_mul_iff_one_lt_right (pred n).succ_pos).2 ((Nat.lt_of_lt_of_le hn (self_le_factorial _))) theorem add_factorial_succ_lt_factorial_add_succ {i : ℕ} (n : ℕ) (hi : 2 ≤ i) : i + (n + 1)! < (i + n + 1)! := by rw [factorial_succ (i + _), Nat.add_mul, Nat.one_mul] have := (i + n).self_le_factorial refine Nat.add_lt_add_of_lt_of_le (Nat.lt_of_le_of_lt ?_ ((Nat.lt_mul_iff_one_lt_right ?_).2 ?_)) (factorial_le ?_) <;> omega theorem add_factorial_lt_factorial_add {i n : ℕ} (hi : 2 ≤ i) (hn : 1 ≤ n) : i + n ! < (i + n)! := by cases hn · rw [factorial_one] exact lt_factorial_self (succ_le_succ hi) exact add_factorial_succ_lt_factorial_add_succ _ hi theorem add_factorial_succ_le_factorial_add_succ (i : ℕ) (n : ℕ) : i + (n + 1)! ≤ (i + (n + 1))! := by cases (le_or_gt (2 : ℕ) i) · rw [← Nat.add_assoc] apply Nat.le_of_lt apply add_factorial_succ_lt_factorial_add_succ assumption · match i with | 0 => simp | 1 => rw [← Nat.add_assoc, factorial_succ (1 + n), Nat.add_mul, Nat.one_mul, Nat.add_comm 1 n, Nat.add_le_add_iff_right] exact Nat.mul_pos n.succ_pos n.succ.factorial_pos | succ (succ n) => contradiction theorem add_factorial_le_factorial_add (i : ℕ) {n : ℕ} (n1 : 1 ≤ n) : i + n ! ≤ (i + n)! := by rcases n1 with - | @h · exact self_le_factorial _ exact add_factorial_succ_le_factorial_add_succ i h theorem factorial_mul_pow_sub_le_factorial {n m : ℕ} (hnm : n ≤ m) : n ! * n ^ (m - n) ≤ m ! := by calc _ ≤ n ! * (n + 1) ^ (m - n) := Nat.mul_le_mul_left _ (Nat.pow_le_pow_left n.le_succ _) _ ≤ _ := by simpa [hnm] using @Nat.factorial_mul_pow_le_factorial n (m - n) lemma factorial_le_pow : ∀ n, n ! ≤ n ^ n | 0 => le_refl _ | n + 1 => calc _ ≤ (n + 1) * n ^ n := Nat.mul_le_mul_left _ n.factorial_le_pow _ ≤ (n + 1) * (n + 1) ^ n := Nat.mul_le_mul_left _ (Nat.pow_le_pow_left n.le_succ _) _ = _ := by rw [pow_succ'] end Factorial /-! ### Ascending and descending factorials -/ section AscFactorial /-- `n.ascFactorial k = n (n + 1) ⋯ (n + k - 1)`. This is closely related to `ascPochhammer`, but much less general. -/ def ascFactorial (n : ℕ) : ℕ → ℕ | 0 => 1 | k + 1 => (n + k) * ascFactorial n k @[simp] theorem ascFactorial_zero (n : ℕ) : n.ascFactorial 0 = 1 := rfl theorem ascFactorial_succ {n k : ℕ} : n.ascFactorial k.succ = (n + k) * n.ascFactorial k := rfl theorem zero_ascFactorial : ∀ (k : ℕ), (0 : ℕ).ascFactorial k.succ = 0 | 0 => by rw [ascFactorial_succ, ascFactorial_zero, Nat.zero_add, Nat.zero_mul] | (k + 1) => by rw [ascFactorial_succ, zero_ascFactorial k, Nat.mul_zero] @[simp] theorem one_ascFactorial : ∀ (k : ℕ), (1 : ℕ).ascFactorial k = k.factorial | 0 => ascFactorial_zero 1 | (k + 1) => by rw [ascFactorial_succ, one_ascFactorial k, Nat.add_comm, factorial_succ] theorem succ_ascFactorial (n : ℕ) : ∀ k, n * n.succ.ascFactorial k = (n + k) * n.ascFactorial k | 0 => by rw [Nat.add_zero, ascFactorial_zero, ascFactorial_zero] | k + 1 => by rw [ascFactorial, Nat.mul_left_comm, succ_ascFactorial n k, ascFactorial, succ_add, ← Nat.add_assoc] /-- `(n + 1).ascFactorial k = (n + k) ! / n !` but without ℕ-division. See `Nat.ascFactorial_eq_div` for the version with ℕ-division. -/ theorem factorial_mul_ascFactorial (n : ℕ) : ∀ k, n ! * (n + 1).ascFactorial k = (n + k)! | 0 => by rw [ascFactorial_zero, Nat.add_zero, Nat.mul_one] | k + 1 => by rw [ascFactorial_succ, ← Nat.add_assoc, factorial_succ, Nat.mul_comm (n + 1 + k), ← Nat.mul_assoc, factorial_mul_ascFactorial n k, Nat.mul_comm, Nat.add_right_comm] /-- `n.ascFactorial k = (n + k - 1)! / (n - 1)!` for `n > 0` but without ℕ-division. See `Nat.ascFactorial_eq_div` for the version with ℕ-division. Consider using `factorial_mul_ascFactorial` to avoid complications of ℕ-subtraction. -/ theorem factorial_mul_ascFactorial' (n k : ℕ) (h : 0 < n) : (n - 1)! * n.ascFactorial k = (n + k - 1)! := by rw [Nat.sub_add_comm h, Nat.sub_one] nth_rw 2 [Nat.eq_add_of_sub_eq h rfl] rw [Nat.sub_one, factorial_mul_ascFactorial] theorem ascFactorial_mul_ascFactorial (n l k : ℕ) : n.ascFactorial l * (n + l).ascFactorial k = n.ascFactorial (l + k) := by cases n with | zero => cases l · simp only [ascFactorial_zero, Nat.add_zero, Nat.one_mul, Nat.zero_add] · simp only [Nat.add_right_comm, zero_ascFactorial, Nat.zero_add, Nat.zero_mul] | succ n' => apply Nat.mul_left_cancel (factorial_pos n') simp only [Nat.add_assoc, ← Nat.mul_assoc, factorial_mul_ascFactorial] rw [Nat.add_comm 1 l, ← Nat.add_assoc, factorial_mul_ascFactorial, Nat.add_assoc] /-- Avoid in favor of `Nat.factorial_mul_ascFactorial` if you can. ℕ-division isn't worth it. -/ theorem ascFactorial_eq_div (n k : ℕ) : (n + 1).ascFactorial k = (n + k)! / n ! := Nat.eq_div_of_mul_eq_right n.factorial_ne_zero (factorial_mul_ascFactorial _ _) /-- Avoid in favor of `Nat.factorial_mul_ascFactorial'` if you can. ℕ-division isn't worth it. -/ theorem ascFactorial_eq_div' (n k : ℕ) (h : 0 < n) : n.ascFactorial k = (n + k - 1)! / (n - 1)! := Nat.eq_div_of_mul_eq_right (n - 1).factorial_ne_zero (factorial_mul_ascFactorial' _ _ h) theorem ascFactorial_of_sub {n k : ℕ} : (n - k) * (n - k + 1).ascFactorial k = (n - k).ascFactorial (k + 1) := by rw [succ_ascFactorial, ascFactorial_succ] theorem pow_succ_le_ascFactorial (n : ℕ) : ∀ k : ℕ, n ^ k ≤ n.ascFactorial k | 0 => by rw [ascFactorial_zero, Nat.pow_zero] | k + 1 => by rw [Nat.pow_succ, Nat.mul_comm, ascFactorial_succ, ← succ_ascFactorial] exact Nat.mul_le_mul (Nat.le_refl n) (Nat.le_trans (Nat.pow_le_pow_left (le_succ n) k) (pow_succ_le_ascFactorial n.succ k)) theorem pow_lt_ascFactorial' (n k : ℕ) : (n + 1) ^ (k + 2) < (n + 1).ascFactorial (k + 2) := by rw [Nat.pow_succ, ascFactorial, Nat.mul_comm] exact Nat.mul_lt_mul_of_lt_of_le' (Nat.lt_add_of_pos_right k.succ_pos) (pow_succ_le_ascFactorial n.succ _) (Nat.pow_pos n.succ_pos) theorem pow_lt_ascFactorial (n : ℕ) : ∀ {k : ℕ}, 2 ≤ k → (n + 1) ^ k < (n + 1).ascFactorial k | 0 => by rintro ⟨⟩ | 1 => by intro; contradiction | k + 2 => fun _ => pow_lt_ascFactorial' n k theorem ascFactorial_le_pow_add (n : ℕ) : ∀ k : ℕ, (n + 1).ascFactorial k ≤ (n + k) ^ k | 0 => by rw [ascFactorial_zero, Nat.pow_zero] | k + 1 => by rw [ascFactorial_succ, Nat.pow_succ, Nat.mul_comm, ← Nat.add_assoc, Nat.add_right_comm n 1 k] exact Nat.mul_le_mul_right _ (Nat.le_trans (ascFactorial_le_pow_add _ k) (Nat.pow_le_pow_left (le_succ _) _)) theorem ascFactorial_lt_pow_add (n : ℕ) : ∀ {k : ℕ}, 2 ≤ k → (n + 1).ascFactorial k < (n + k) ^ k | 0 => by rintro ⟨⟩ | 1 => by intro; contradiction | k + 2 => fun _ => by rw [Nat.pow_succ, Nat.mul_comm, ascFactorial_succ, succ_add_eq_add_succ n (k + 1)] exact Nat.mul_lt_mul_of_le_of_lt (le_refl _) (Nat.lt_of_le_of_lt (ascFactorial_le_pow_add n _) (Nat.pow_lt_pow_left (Nat.lt_succ_self _) k.succ_ne_zero)) (succ_pos _) theorem ascFactorial_pos (n k : ℕ) : 0 < (n + 1).ascFactorial k := Nat.lt_of_lt_of_le (Nat.pow_pos n.succ_pos) (pow_succ_le_ascFactorial (n + 1) k) end AscFactorial section DescFactorial /-- `n.descFactorial k = n! / (n - k)!` (as seen in `Nat.descFactorial_eq_div`), but implemented recursively to allow for "quick" computation when using `norm_num`. This is closely related to `descPochhammer`, but much less general. -/ def descFactorial (n : ℕ) : ℕ → ℕ | 0 => 1 | k + 1 => (n - k) * descFactorial n k @[simp] theorem descFactorial_zero (n : ℕ) : n.descFactorial 0 = 1 := rfl @[simp] theorem descFactorial_succ (n k : ℕ) : n.descFactorial (k + 1) = (n - k) * n.descFactorial k := rfl theorem zero_descFactorial_succ (k : ℕ) : (0 : ℕ).descFactorial (k + 1) = 0 := by rw [descFactorial_succ, Nat.zero_sub, Nat.zero_mul] theorem descFactorial_one (n : ℕ) : n.descFactorial 1 = n := by simp theorem succ_descFactorial_succ (n : ℕ) : ∀ k : ℕ, (n + 1).descFactorial (k + 1) = (n + 1) * n.descFactorial k | 0 => by rw [descFactorial_zero, descFactorial_one, Nat.mul_one] | succ k => by rw [descFactorial_succ, succ_descFactorial_succ _ k, descFactorial_succ, succ_sub_succ, Nat.mul_left_comm] theorem succ_descFactorial (n : ℕ) : ∀ k, (n + 1 - k) * (n + 1).descFactorial k = (n + 1) * n.descFactorial k | 0 => by rw [Nat.sub_zero, descFactorial_zero, descFactorial_zero] | k + 1 => by rw [descFactorial, succ_descFactorial _ k, descFactorial_succ, succ_sub_succ, Nat.mul_left_comm] theorem descFactorial_self : ∀ n : ℕ, n.descFactorial n = n ! | 0 => by rw [descFactorial_zero, factorial_zero] | succ n => by rw [succ_descFactorial_succ, descFactorial_self n, factorial_succ] @[simp] theorem descFactorial_eq_zero_iff_lt {n : ℕ} : ∀ {k : ℕ}, n.descFactorial k = 0 ↔ n < k | 0 => by simp only [descFactorial_zero, Nat.one_ne_zero, Nat.not_lt_zero] | succ k => by rw [descFactorial_succ, mul_eq_zero, descFactorial_eq_zero_iff_lt, Nat.lt_succ_iff, Nat.sub_eq_zero_iff_le, Nat.lt_iff_le_and_ne, or_iff_left_iff_imp, and_imp] exact fun h _ => h @[simp] lemma descFactorial_pos {n k : ℕ} : 0 < n.descFactorial k ↔ k ≤ n := by simp [Nat.pos_iff_ne_zero] alias ⟨_, descFactorial_of_lt⟩ := descFactorial_eq_zero_iff_lt theorem add_descFactorial_eq_ascFactorial (n : ℕ) : ∀ k : ℕ, (n + k).descFactorial k = (n + 1).ascFactorial k | 0 => by rw [ascFactorial_zero, descFactorial_zero] | succ k => by rw [Nat.add_succ, succ_descFactorial_succ, ascFactorial_succ, add_descFactorial_eq_ascFactorial _ k, Nat.add_right_comm] theorem add_descFactorial_eq_ascFactorial' (n : ℕ) : ∀ k : ℕ, (n + k - 1).descFactorial k = n.ascFactorial k | 0 => by rw [ascFactorial_zero, descFactorial_zero] | succ k => by rw [descFactorial_succ, ascFactorial_succ, ← succ_add_eq_add_succ, add_descFactorial_eq_ascFactorial' _ k, ← succ_ascFactorial, succ_add_sub_one, Nat.add_sub_cancel] /-- `n.descFactorial k = n! / (n - k)!` but without ℕ-division. See `Nat.descFactorial_eq_div` for the version using ℕ-division. -/ theorem factorial_mul_descFactorial : ∀ {n k : ℕ}, k ≤ n → (n - k)! * n.descFactorial k = n ! | n, 0 => fun _ => by rw [descFactorial_zero, Nat.mul_one, Nat.sub_zero] | 0, succ k => fun h => by exfalso exact not_succ_le_zero k h | succ n, succ k => fun h => by rw [succ_descFactorial_succ, succ_sub_succ, ← Nat.mul_assoc, Nat.mul_comm (n - k)!, Nat.mul_assoc, factorial_mul_descFactorial (Nat.succ_le_succ_iff.1 h), factorial_succ] theorem descFactorial_mul_descFactorial {k m n : ℕ} (hkm : k ≤ m) : (n - k).descFactorial (m - k) * n.descFactorial k = n.descFactorial m := by by_cases hmn : m ≤ n · apply Nat.mul_left_cancel (n - m).factorial_pos rw [factorial_mul_descFactorial hmn, show n - m = (n - k) - (m - k) by cutsat, ← Nat.mul_assoc, factorial_mul_descFactorial (show m - k ≤ n - k by cutsat), factorial_mul_descFactorial (le_trans hkm hmn)] · rw [descFactorial_eq_zero_iff_lt.mpr (show n < m by cutsat)] by_cases hkn : k ≤ n · rw [descFactorial_eq_zero_iff_lt.mpr (show n - k < m - k by cutsat), Nat.zero_mul] · rw [descFactorial_eq_zero_iff_lt.mpr (show n < k by cutsat), Nat.mul_zero] /-- Avoid in favor of `Nat.factorial_mul_descFactorial` if you can. ℕ-division isn't worth it. -/ theorem descFactorial_eq_div {n k : ℕ} (h : k ≤ n) : n.descFactorial k = n ! / (n - k)! := by apply Nat.mul_left_cancel (n - k).factorial_pos rw [factorial_mul_descFactorial h] exact (Nat.mul_div_cancel' <| factorial_dvd_factorial <| Nat.sub_le n k).symm theorem descFactorial_le (n : ℕ) {k m : ℕ} (h : k ≤ m) : k.descFactorial n ≤ m.descFactorial n := by induction n with | zero => rfl | succ n ih => rw [descFactorial_succ, descFactorial_succ] exact Nat.mul_le_mul (Nat.sub_le_sub_right h n) ih theorem pow_sub_le_descFactorial (n : ℕ) : ∀ k : ℕ, (n + 1 - k) ^ k ≤ n.descFactorial k | 0 => by rw [descFactorial_zero, Nat.pow_zero] | k + 1 => by rw [descFactorial_succ, Nat.pow_succ, succ_sub_succ, Nat.mul_comm] apply Nat.mul_le_mul_left exact (le_trans (Nat.pow_le_pow_left (Nat.sub_le_sub_right n.le_succ _) k) (pow_sub_le_descFactorial n k)) theorem pow_sub_lt_descFactorial' {n : ℕ} : ∀ {k : ℕ}, k + 2 ≤ n → (n - (k + 1)) ^ (k + 2) < n.descFactorial (k + 2) | 0, h => by rw [descFactorial_succ, Nat.pow_succ, Nat.pow_one, descFactorial_one] exact Nat.mul_lt_mul_of_pos_left (by cutsat) (Nat.sub_pos_of_lt h) | k + 1, h => by rw [descFactorial_succ, Nat.pow_succ, Nat.mul_comm] refine Nat.mul_lt_mul_of_pos_left ?_ (Nat.sub_pos_of_lt h) refine Nat.lt_of_le_of_lt (Nat.pow_le_pow_left (Nat.sub_le_sub_right n.le_succ _) _) ?_ rw [succ_sub_succ] exact pow_sub_lt_descFactorial' (Nat.le_trans (le_succ _) h) theorem pow_sub_lt_descFactorial {n : ℕ} : ∀ {k : ℕ}, 2 ≤ k → k ≤ n → (n + 1 - k) ^ k < n.descFactorial k | 0 => by rintro ⟨⟩ | 1 => by intro; contradiction | k + 2 => fun _ h => by rw [succ_sub_succ] exact pow_sub_lt_descFactorial' h theorem descFactorial_le_pow (n : ℕ) : ∀ k : ℕ, n.descFactorial k ≤ n ^ k | 0 => by rw [descFactorial_zero, Nat.pow_zero] | k + 1 => by rw [descFactorial_succ, Nat.pow_succ, Nat.mul_comm _ n] exact Nat.mul_le_mul (Nat.sub_le _ _) (descFactorial_le_pow _ k) theorem descFactorial_lt_pow {n : ℕ} (hn : n ≠ 0) : ∀ {k : ℕ}, 2 ≤ k → n.descFactorial k < n ^ k | 0 => by rintro ⟨⟩ | 1 => by intro; contradiction | k + 2 => fun _ => by rw [descFactorial_succ, pow_succ', Nat.mul_comm, Nat.mul_comm n] exact Nat.mul_lt_mul_of_le_of_lt (descFactorial_le_pow _ _) (by omega) (Nat.pow_pos <| by omega) end DescFactorial lemma factorial_two_mul_le (n : ℕ) : (2 * n)! ≤ (2 * n) ^ n * n ! := by rw [Nat.two_mul, ← factorial_mul_ascFactorial, Nat.mul_comm] exact Nat.mul_le_mul_right _ (ascFactorial_le_pow_add _ _) lemma two_pow_mul_factorial_le_factorial_two_mul (n : ℕ) : 2 ^ n * n ! ≤ (2 * n)! := by obtain _ | n := n · simp rw [Nat.mul_comm, Nat.two_mul] calc _ ≤ (n + 1)! * (n + 2) ^ (n + 1) := Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (le_add_left _ _) _) _ ≤ _ := Nat.factorial_mul_pow_le_factorial /-! ### Factorial via binary splitting. We prove this is equal to the standard factorial and mark it `@[csimp]`. We could proceed further, with either Legendre or Luschny methods. -/ /-! This is the highest factorial I can `#eval` using the naive implementation without a stack overflow: ``` /-- info: 114716 -/ #guard_msgs in #eval 9718 ! |>.log2 ``` We could implement a tail-recursive version (or just use `Nat.fold`), but instead let's jump straight to binary splitting. -/ /-- Factorial implemented using binary splitting. While this still performs the same number of multiplications, the big-integer operands to each are much smaller. -/ def factorialBinarySplitting (n : Nat) : Nat := if _ : n = 0 then 1 else prodRange 1 (n + 1) where /-- `prodRange lo hi` is the product of the range `lo` to `hi` (exclusive), computed by binary splitting. -/ prodRange (lo hi : Nat) (h : lo < hi := by grind) : Nat := if _ : hi = lo + 1 then lo else let mid := (lo + hi) / 2 prodRange lo mid * prodRange mid hi theorem factorialBinarySplitting.factorial_mul_prodRange (lo hi : Nat) (h : lo < hi) : lo ! * prodRange (lo + 1) (hi + 1) = hi ! := by rw [prodRange] split · grind [factorial_succ] · dsimp only rw [← Nat.mul_assoc] simp_rw [show (lo + 1 + (hi + 1)) / 2 = (lo + hi) / 2 + 1 by grind] rw [factorial_mul_prodRange, factorial_mul_prodRange] all_goals grind @[csimp] theorem factorialBinarySplitting_eq_factorial : @factorial = @factorialBinarySplitting := by ext n by_cases h : n = 0 · simp [h, factorialBinarySplitting] · rw [factorialBinarySplitting, ← factorialBinarySplitting.factorial_mul_prodRange 0 n (by grind)] simp [h] /-! We are now limited by time, not stack space, and this is much faster than even the tail-recursive version. ``` #time -- Less than 1s. (Tail-recursive version takes longer for `(10^5) !`.) #eval (10^6) ! |>.log2 ``` -/ end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Factorial/SuperFactorial.lean
import Mathlib.Algebra.BigOperators.Intervals import Mathlib.Tactic.Ring /-! # Superfactorial This file defines the [superfactorial](https://en.wikipedia.org/wiki/Superfactorial) `sf n = 1! * 2! * 3! * ... * n!`. ## Main declarations * `Nat.superFactorial`: The superfactorial, denoted by `sf`. -/ namespace Nat /-- `Nat.superFactorial n` is the superfactorial of `n`. -/ def superFactorial : ℕ → ℕ | 0 => 1 | succ n => factorial n.succ * superFactorial n /-- `sf` notation for superfactorial -/ scoped notation "sf " n:60 => Nat.superFactorial n section SuperFactorial @[simp] theorem superFactorial_zero : sf 0 = 1 := rfl theorem superFactorial_succ (n : ℕ) : (sf n.succ) = (n + 1)! * sf n := rfl @[simp] theorem superFactorial_one : sf 1 = 1 := rfl @[simp] theorem superFactorial_two : sf 2 = 2 := rfl open Finset @[simp] theorem prod_Icc_factorial : ∀ n : ℕ, ∏ x ∈ Icc 1 n, x ! = sf n | 0 => rfl | n + 1 => by rw [← Ico_add_one_right_eq_Icc 1, prod_Ico_succ_top le_add_self, Nat.factorial_succ, Ico_add_one_right_eq_Icc 1 n, prod_Icc_factorial n, superFactorial, factorial, mul_comm] @[simp] theorem prod_range_factorial_succ (n : ℕ) : ∏ x ∈ range n, (x + 1)! = sf n := (prod_Icc_factorial n) ▸ range_eq_Ico ▸ Finset.prod_Ico_add' _ _ _ _ @[simp] theorem prod_range_succ_factorial : ∀ n : ℕ, ∏ x ∈ range (n + 1), x ! = sf n | 0 => rfl | n + 1 => by rw [prod_range_succ, prod_range_succ_factorial n, mul_comm, superFactorial] theorem superFactorial_two_mul : ∀ n : ℕ, sf (2 * n) = (∏ i ∈ range n, (2 * i + 1) !) ^ 2 * 2 ^ n * n ! | 0 => rfl | (n + 1) => by simp only [prod_range_succ, mul_pow, mul_add, mul_one, superFactorial_succ, superFactorial_two_mul n, factorial_succ] ring theorem superFactorial_four_mul (n : ℕ) : sf (4 * n) = ((∏ i ∈ range (2 * n), (2 * i + 1) !) * 2 ^ n) ^ 2 * (2 * n) ! := calc sf (4 * n) = (∏ i ∈ range (2 * n), (2 * i + 1) !) ^ 2 * 2 ^ (2 * n) * (2 * n) ! := by rw [← superFactorial_two_mul, ← mul_assoc, Nat.mul_two] _ = ((∏ i ∈ range (2 * n), (2 * i + 1) !) * 2 ^ n) ^ 2 * (2 * n) ! := by rw [pow_mul', mul_pow] end SuperFactorial end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Factorial/NatCast.lean
import Mathlib.Algebra.Algebra.Defs import Mathlib.Algebra.CharP.Invertible import Mathlib.Data.Finset.NatAntidiagonal import Mathlib.RingTheory.Nilpotent.Defs /-! # Invertibility of factorials This file contains lemmas providing sufficient conditions for the cast of `n!` to a (semi)ring `A` to be a unit. -/ namespace IsUnit open Nat section Semiring variable {A : Type*} [Semiring A] theorem natCast_factorial_of_le {n : ℕ} (hn_fac : IsUnit (n ! : A)) {m : ℕ} (hmn : m ≤ n) : IsUnit (m ! : A) := by obtain ⟨k, rfl⟩ := exists_add_of_le hmn clear hmn induction k generalizing m with | zero => simpa using hn_fac | succ k ih => rw [← add_assoc, add_right_comm] at hn_fac have := ih hn_fac rw [Nat.factorial_succ, Nat.cast_mul, Nat.cast_commute _ _ |>.isUnit_mul_iff] at this exact this.2 theorem natCast_factorial_of_lt {n : ℕ} (hn_fac : IsUnit ((n - 1)! : A)) {m : ℕ} (hmn : m < n) : IsUnit (m ! : A) := hn_fac.natCast_factorial_of_le <| le_sub_one_of_lt hmn /-- If `A` is an algebra over a characteristic-zero (semi)field, then `n!` is a unit. -/ theorem natCast_factorial_of_algebra (K : Type*) [Semifield K] [CharZero K] [Algebra K A] (n : ℕ) : IsUnit (n ! : A) := by suffices IsUnit (n ! : K) by simpa using this.map (algebraMap K A) simp [isUnit_iff_ne_zero, n.factorial_ne_zero] end Semiring section CharP variable {A : Type*} [Ring A] (p : ℕ) [Fact (Nat.Prime p)] [CharP A p] theorem natCast_factorial_iff_of_charP {n : ℕ} : IsUnit (n ! : A) ↔ n < p := by have hp : p.Prime := Fact.out induction n with | zero => simp [hp.pos] | succ n ih => -- TODO: why is `.symm.symm` needed here!? rw [factorial_succ, cast_mul, Nat.cast_commute _ _ |>.isUnit_mul_iff, ih.symm.symm, ← Nat.add_one_le_iff, CharP.isUnit_natCast_iff hp] exact ⟨fun ⟨h1, h2⟩ ↦ lt_of_le_of_ne h2 (mt (· ▸ dvd_rfl) h1), fun h ↦ ⟨not_dvd_of_pos_of_lt (Nat.succ_pos _) h, h.le⟩⟩ end CharP section Nilpotent variable {A : Type*} [CommRing A] {n p : ℕ} (hp : IsNilpotent (p : A)) include hp lemma natCast_of_isNilpotent_of_coprime (h : p.Coprime n) : IsUnit (n : A) := by obtain ⟨m, hm⟩ := hp suffices ∃ a b : A, p ^ m * a + n * b = 1 by obtain ⟨a, b, h⟩ := this refine .of_mul_eq_one b ?_ simpa [hm] using h refine ⟨(p ^ m).gcdA n, (p ^ m).gcdB n, ?_⟩ norm_cast rw [← Nat.cast_one, ← Int.cast_natCast 1, ← (h.pow_left m).gcd_eq_one, Nat.gcd_eq_gcd_ab] theorem natCast_factorial_of_isNilpotent [Fact p.Prime] (h : n < p) : IsUnit (n ! : A) := by induction n with | zero => simp | succ n ih => simp only [factorial_succ, cast_mul, IsUnit.mul_iff] refine ⟨.natCast_of_isNilpotent_of_coprime hp ?_, ih (by cutsat)⟩ rw [Nat.Prime.coprime_iff_not_dvd Fact.out] exact Nat.not_dvd_of_pos_of_lt (by cutsat) h end Nilpotent end IsUnit open Nat Ring lemma Nat.castChoose_eq {A : Type*} [CommSemiring A] {m : ℕ} {k : ℕ × ℕ} (hm : IsUnit (m ! : A)) (hk : k ∈ Finset.antidiagonal m) : (choose m k.1 : A) = ↑m ! * inverse ↑k.1! * inverse ↑k.2! := by rw [Finset.mem_antidiagonal] at hk subst hk rw [eq_mul_inverse_iff_mul_eq, eq_mul_inverse_iff_mul_eq, ← Nat.cast_mul, ← Nat.cast_mul, add_comm, Nat.add_choose_mul_factorial_mul_factorial] <;> apply hm.natCast_factorial_of_le exacts [Nat.le_add_right k.1 k.2, Nat.le_add_left k.2 k.1]
.lake/packages/mathlib/Mathlib/Data/Nat/Factorial/BigOperators.lean
import Mathlib.Algebra.Order.BigOperators.Ring.Finset import Mathlib.Tactic.Zify /-! # Factorial with big operators This file contains some lemmas on factorials in combination with big operators. While in terms of semantics they could be in the `Basic.lean` file, importing `Algebra.BigOperators.Group.Finset` leads to a cyclic import. -/ open Finset Nat namespace Nat lemma monotone_factorial : Monotone factorial := fun _ _ => factorial_le variable {α : Type*} (s : Finset α) (f : α → ℕ) theorem prod_factorial_pos : 0 < ∏ i ∈ s, (f i)! := prod_pos fun _ _ ↦ factorial_pos _ theorem prod_factorial_dvd_factorial_sum : (∏ i ∈ s, (f i)!) ∣ (∑ i ∈ s, f i)! := by induction s using Finset.cons_induction_on with | empty => simp | cons a s has ih => rw [prod_cons, Finset.sum_cons] exact (mul_dvd_mul_left _ ih).trans (Nat.factorial_mul_factorial_dvd_factorial_add _ _) theorem factorial_eq_prod_range_add_one : ∀ n, (n)! = ∏ i ∈ range n, (i + 1) | 0 => rfl | n + 1 => by rw [factorial, prod_range_succ_comm, factorial_eq_prod_range_add_one n] @[simp] theorem _root_.Finset.prod_range_add_one_eq_factorial (n : ℕ) : ∏ i ∈ range n, (i + 1) = (n)! := factorial_eq_prod_range_add_one _ |>.symm theorem ascFactorial_eq_prod_range (n : ℕ) : ∀ k, n.ascFactorial k = ∏ i ∈ range k, (n + i) | 0 => rfl | k + 1 => by rw [ascFactorial, prod_range_succ_comm, ascFactorial_eq_prod_range n k] theorem descFactorial_eq_prod_range (n : ℕ) : ∀ k, n.descFactorial k = ∏ i ∈ range k, (n - i) | 0 => rfl | k + 1 => by rw [descFactorial, prod_range_succ_comm, descFactorial_eq_prod_range n k] /-- `k!` divides the product of any `k` consecutive integers. -/ lemma factorial_coe_dvd_prod (k : ℕ) (n : ℤ) : (k ! : ℤ) ∣ ∏ i ∈ range k, (n + i) := by rw [Int.dvd_iff_emod_eq_zero, Finset.prod_int_mod] simp_rw [← Int.emod_add_emod n] have hn : 0 ≤ n % k ! := Int.emod_nonneg n <| Int.natCast_ne_zero.mpr k.factorial_ne_zero obtain ⟨x, hx⟩ := Int.eq_ofNat_of_zero_le hn have hdivk := x.factorial_dvd_ascFactorial k zify [x.ascFactorial_eq_prod_range k] at hdivk rwa [← Finset.prod_int_mod, ← Int.dvd_iff_emod_eq_zero, hx] end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Factorial/DoubleFactorial.lean
import Mathlib.Data.Nat.Factorial.Basic import Mathlib.Tactic.Ring import Mathlib.Tactic.Positivity.Core import Mathlib.Algebra.BigOperators.Group.Finset.Basic /-! # Double factorials This file defines the double factorial, `n‼ := n * (n - 2) * (n - 4) * ...`. ## Main declarations * `Nat.doubleFactorial`: The double factorial. -/ open Nat namespace Nat /-- `Nat.doubleFactorial n` is the double factorial of `n`. -/ @[simp] def doubleFactorial : ℕ → ℕ | 0 => 1 | 1 => 1 | k + 2 => (k + 2) * doubleFactorial k -- This notation is `\!!` not two !'s @[inherit_doc] scoped notation:10000 n "‼" => Nat.doubleFactorial n lemma doubleFactorial_pos : ∀ n, 0 < n‼ | 0 | 1 => zero_lt_one | _n + 2 => mul_pos (succ_pos _) (doubleFactorial_pos _) theorem doubleFactorial_add_two (n : ℕ) : (n + 2)‼ = (n + 2) * n‼ := rfl theorem doubleFactorial_add_one (n : ℕ) : (n + 1)‼ = (n + 1) * (n - 1)‼ := by cases n <;> rfl theorem factorial_eq_mul_doubleFactorial : ∀ n : ℕ, (n + 1)! = (n + 1)‼ * n‼ | 0 => rfl | k + 1 => by rw [doubleFactorial_add_two, factorial, factorial_eq_mul_doubleFactorial _, mul_comm _ k‼, mul_assoc] lemma doubleFactorial_le_factorial : ∀ n, n‼ ≤ n ! | 0 => le_rfl | n + 1 => by rw [factorial_eq_mul_doubleFactorial]; exact Nat.le_mul_of_pos_right _ n.doubleFactorial_pos theorem doubleFactorial_two_mul : ∀ n : ℕ, (2 * n)‼ = 2 ^ n * n ! | 0 => rfl | n + 1 => by rw [mul_add, mul_one, doubleFactorial_add_two, factorial, pow_succ, doubleFactorial_two_mul _, succ_eq_add_one] ring theorem doubleFactorial_eq_prod_even : ∀ n : ℕ, (2 * n)‼ = ∏ i ∈ Finset.range n, 2 * (i + 1) | 0 => rfl | n + 1 => by rw [Finset.prod_range_succ, ← doubleFactorial_eq_prod_even _, mul_comm (2 * n)‼, (by ring : 2 * (n + 1) = 2 * n + 2)] rfl theorem doubleFactorial_eq_prod_odd : ∀ n : ℕ, (2 * n + 1)‼ = ∏ i ∈ Finset.range n, (2 * (i + 1) + 1) | 0 => rfl | n + 1 => by rw [Finset.prod_range_succ, ← doubleFactorial_eq_prod_odd _, mul_comm (2 * n + 1)‼, (by ring : 2 * (n + 1) + 1 = 2 * n + 1 + 2)] rfl end Nat namespace Mathlib.Meta.Positivity open Lean Meta Qq /-- Extension for `Nat.doubleFactorial`. -/ @[positivity Nat.doubleFactorial _] def evalDoubleFactorial : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℕ), ~q(Nat.doubleFactorial $n) => assumeInstancesCommute return .positive q(Nat.doubleFactorial_pos $n) | _, _ => throwError "not Nat.doubleFactorial" example (n : ℕ) : 0 < n‼ := by positivity end Mathlib.Meta.Positivity
.lake/packages/mathlib/Mathlib/Data/Nat/Factorial/Cast.lean
import Mathlib.Data.Nat.Cast.Basic import Mathlib.Data.Nat.Factorial.Basic /-! # Cast of factorials This file allows calculating factorials (including ascending and descending ones) as elements of a semiring. This is particularly crucial for `Nat.descFactorial` as subtraction on `ℕ` does **not** correspond to subtraction on a general semiring. For example, we can't rely on existing cast lemmas to prove `↑(a.descFactorial 2) = ↑a * (↑a - 1)`. We must use the fact that, whenever `↑(a - 1)` is not equal to `↑a - 1`, the other factor is `0` anyway. -/ open Nat variable (S : Type*) namespace Nat section Ring variable [Ring S] (a b : ℕ) /-- Convenience lemma. The `a - 1` is not using truncated subtraction, as opposed to the definition of `Nat.descFactorial` as a natural. -/ theorem cast_descFactorial_two : (a.descFactorial 2 : S) = a * (a - 1) := by rw [descFactorial] cases a · simp · simp [mul_add, add_mul] end Ring end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/GCD/Basic.lean
import Mathlib.Algebra.Group.Nat.Units import Mathlib.Algebra.GroupWithZero.Divisibility import Mathlib.Algebra.GroupWithZero.Nat /-! # Properties of `Nat.gcd`, `Nat.lcm`, and `Nat.Coprime` Definitions are provided in batteries. Generalizations of these are provided in a later file as `GCDMonoid.gcd` and `GCDMonoid.lcm`. Note that the global `IsCoprime` is not a straightforward generalization of `Nat.Coprime`, see `Nat.isCoprime_iff_coprime` for the connection between the two. Most of this file could be moved to batteries as well. -/ assert_not_exists IsOrderedMonoid namespace Nat variable {a a₁ a₂ b b₁ b₂ c : ℕ} /-! ### `gcd` -/ theorem gcd_greatest {a b d : ℕ} (hda : d ∣ a) (hdb : d ∣ b) (hd : ∀ e : ℕ, e ∣ a → e ∣ b → e ∣ d) : d = a.gcd b := (dvd_antisymm (hd _ (gcd_dvd_left a b) (gcd_dvd_right a b)) (dvd_gcd hda hdb)).symm /-! Lemmas where one argument consists of addition of a multiple of the other -/ @[simp] theorem pow_sub_one_mod_pow_sub_one (a b c : ℕ) : (a ^ c - 1) % (a ^ b - 1) = a ^ (c % b) - 1 := by rcases eq_zero_or_pos a with rfl | ha0 · simp [zero_pow_eq]; split_ifs <;> simp rcases Nat.eq_or_lt_of_le ha0 with rfl | ha1 · simp rcases eq_zero_or_pos b with rfl | hb0 · simp rcases lt_or_ge c b with h | h · rw [mod_eq_of_lt, mod_eq_of_lt h] rwa [Nat.sub_lt_sub_iff_right (one_le_pow c a ha0), Nat.pow_lt_pow_iff_right ha1] · suffices a ^ (c - b + b) - 1 = a ^ (c - b) * (a ^ b - 1) + (a ^ (c - b) - 1) by rw [← Nat.sub_add_cancel h, add_mod_right, this, add_mod, mul_mod, mod_self, mul_zero, zero_mod, zero_add, mod_mod, pow_sub_one_mod_pow_sub_one] rw [← Nat.add_sub_assoc (one_le_pow (c - b) a ha0), ← mul_add_one, pow_add, Nat.sub_add_cancel (one_le_pow b a ha0)] @[simp] theorem pow_sub_one_gcd_pow_sub_one (a b c : ℕ) : gcd (a ^ b - 1) (a ^ c - 1) = a ^ gcd b c - 1 := by rcases eq_zero_or_pos b with rfl | hb · simp replace hb : c % b < b := mod_lt c hb rw [gcd_rec, pow_sub_one_mod_pow_sub_one, pow_sub_one_gcd_pow_sub_one, ← gcd_rec] /-! ### `lcm` and divisibility -/ theorem dvd_lcm_of_dvd_left (h : a ∣ b) (c : ℕ) : a ∣ lcm b c := h.trans (dvd_lcm_left b c) alias Dvd.dvd.nat_lcm_right := dvd_lcm_of_dvd_left theorem dvd_of_lcm_right_dvd {a b c : ℕ} (h : lcm a b ∣ c) : a ∣ c := (dvd_lcm_left a b).trans h theorem dvd_lcm_of_dvd_right {a b : ℕ} (h : a ∣ b) (c : ℕ) : a ∣ lcm c b := h.trans (dvd_lcm_right c b) alias Dvd.dvd.nat_lcm_left := dvd_lcm_of_dvd_right theorem dvd_of_lcm_left_dvd {a b c : ℕ} (h : lcm a b ∣ c) : b ∣ c := (dvd_lcm_right a b).trans h /-! ### `Coprime` See also `Nat.coprime_of_dvd` and `Nat.coprime_of_dvd'` to prove `Nat.Coprime m n`. -/ theorem Coprime.lcm_eq_mul {m n : ℕ} (h : Coprime m n) : lcm m n = m * n := by rw [← one_mul (lcm m n), ← h.gcd_eq_one, gcd_mul_lcm] theorem Coprime.symmetric : Symmetric Coprime := fun _ _ => Coprime.symm theorem Coprime.dvd_mul_right {m n k : ℕ} (H : Coprime k n) : k ∣ m * n ↔ k ∣ m := ⟨H.dvd_of_dvd_mul_right, fun h => dvd_mul_of_dvd_left h n⟩ theorem Coprime.dvd_mul_left {m n k : ℕ} (H : Coprime k m) : k ∣ m * n ↔ k ∣ n := ⟨H.dvd_of_dvd_mul_left, fun h => dvd_mul_of_dvd_right h m⟩ @[simp] theorem coprime_add_self_right {m n : ℕ} : Coprime m (n + m) ↔ Coprime m n := by rw [Coprime, Coprime, gcd_add_self_right] @[simp] theorem coprime_self_add_right {m n : ℕ} : Coprime m (m + n) ↔ Coprime m n := by rw [add_comm, coprime_add_self_right] @[simp] theorem coprime_add_self_left {m n : ℕ} : Coprime (m + n) n ↔ Coprime m n := by rw [Coprime, Coprime, gcd_add_self_left] @[simp] theorem coprime_self_add_left {m n : ℕ} : Coprime (m + n) m ↔ Coprime n m := by rw [Coprime, Coprime, gcd_self_add_left] @[simp] theorem coprime_add_mul_right_right (m n k : ℕ) : Coprime m (n + k * m) ↔ Coprime m n := by rw [Coprime, Coprime, gcd_add_mul_right_right] @[simp] theorem coprime_add_mul_left_right (m n k : ℕ) : Coprime m (n + m * k) ↔ Coprime m n := by rw [Coprime, Coprime, gcd_add_mul_left_right] @[simp] theorem coprime_mul_right_add_right (m n k : ℕ) : Coprime m (k * m + n) ↔ Coprime m n := by rw [Coprime, Coprime, gcd_mul_right_add_right] @[simp] theorem coprime_mul_left_add_right (m n k : ℕ) : Coprime m (m * k + n) ↔ Coprime m n := by rw [Coprime, Coprime, gcd_mul_left_add_right] @[simp] theorem coprime_add_mul_right_left (m n k : ℕ) : Coprime (m + k * n) n ↔ Coprime m n := by rw [Coprime, Coprime, gcd_add_mul_right_left] @[simp] theorem coprime_add_mul_left_left (m n k : ℕ) : Coprime (m + n * k) n ↔ Coprime m n := by rw [Coprime, Coprime, gcd_add_mul_left_left] @[simp] theorem coprime_mul_right_add_left (m n k : ℕ) : Coprime (k * n + m) n ↔ Coprime m n := by rw [Coprime, Coprime, gcd_mul_right_add_left] @[simp] theorem coprime_mul_left_add_left (m n k : ℕ) : Coprime (n * k + m) n ↔ Coprime m n := by rw [Coprime, Coprime, gcd_mul_left_add_left] lemma add_coprime_iff_left (h : c ∣ b) : Coprime (a + b) c ↔ Coprime a c := by obtain ⟨n, rfl⟩ := h; simp lemma add_coprime_iff_right (h : c ∣ a) : Coprime (a + b) c ↔ Coprime b c := by obtain ⟨n, rfl⟩ := h; simp lemma coprime_add_iff_left (h : a ∣ c) : Coprime a (b + c) ↔ Coprime a b := by obtain ⟨n, rfl⟩ := h; simp lemma coprime_add_iff_right (h : a ∣ b) : Coprime a (b + c) ↔ Coprime a c := by obtain ⟨n, rfl⟩ := h; simp -- TODO: Replace `Nat.Coprime.coprime_dvd_left` lemma Coprime.of_dvd_left (ha : a₁ ∣ a₂) (h : Coprime a₂ b) : Coprime a₁ b := h.coprime_dvd_left ha -- TODO: Replace `Nat.Coprime.coprime_dvd_right` lemma Coprime.of_dvd_right (hb : b₁ ∣ b₂) (h : Coprime a b₂) : Coprime a b₁ := h.coprime_dvd_right hb lemma Coprime.of_dvd (ha : a₁ ∣ a₂) (hb : b₁ ∣ b₂) (h : Coprime a₂ b₂) : Coprime a₁ b₁ := (h.of_dvd_left ha).of_dvd_right hb @[simp] theorem coprime_sub_self_left {m n : ℕ} (h : m ≤ n) : Coprime (n - m) m ↔ Coprime n m := by rw [Coprime, Coprime, gcd_sub_self_left h] @[simp] theorem coprime_sub_self_right {m n : ℕ} (h : m ≤ n) : Coprime m (n - m) ↔ Coprime m n := by rw [Coprime, Coprime, gcd_sub_self_right h] @[simp] theorem coprime_self_sub_left {m n : ℕ} (h : m ≤ n) : Coprime (n - m) n ↔ Coprime m n := by rw [Coprime, Coprime, gcd_self_sub_left h] @[simp] theorem coprime_self_sub_right {m n : ℕ} (h : m ≤ n) : Coprime n (n - m) ↔ Coprime n m := by rw [Coprime, Coprime, gcd_self_sub_right h] @[simp] theorem coprime_pow_left_iff {n : ℕ} (hn : 0 < n) (a b : ℕ) : Nat.Coprime (a ^ n) b ↔ Nat.Coprime a b := by obtain ⟨n, rfl⟩ := exists_eq_succ_of_ne_zero (Nat.ne_of_gt hn) rw [Nat.pow_succ, Nat.coprime_mul_iff_left] exact ⟨And.right, fun hab => ⟨hab.pow_left _, hab⟩⟩ @[simp] theorem coprime_pow_right_iff {n : ℕ} (hn : 0 < n) (a b : ℕ) : Nat.Coprime a (b ^ n) ↔ Nat.Coprime a b := by rw [Nat.coprime_comm, coprime_pow_left_iff hn, Nat.coprime_comm] theorem not_coprime_zero_zero : ¬Coprime 0 0 := by simp theorem coprime_one_left_iff (n : ℕ) : Coprime 1 n ↔ True := by simp [Coprime] theorem coprime_one_right_iff (n : ℕ) : Coprime n 1 ↔ True := by simp [Coprime] theorem gcd_mul_of_coprime_of_dvd {a b c : ℕ} (hac : Coprime a c) (b_dvd_c : b ∣ c) : gcd (a * b) c = b := by rcases exists_eq_mul_left_of_dvd b_dvd_c with ⟨d, rfl⟩ rw [gcd_mul_right] convert one_mul b exact Coprime.coprime_mul_right_right hac theorem Coprime.eq_of_mul_eq_zero {m n : ℕ} (h : m.Coprime n) (hmn : m * n = 0) : m = 0 ∧ n = 1 ∨ m = 1 ∧ n = 0 := (Nat.mul_eq_zero.mp hmn).imp (fun hm => ⟨hm, n.coprime_zero_left.mp <| hm ▸ h⟩) fun hn => let eq := hn ▸ h.symm ⟨m.coprime_zero_left.mp <| eq, hn⟩ theorem coprime_iff_isRelPrime {m n : ℕ} : m.Coprime n ↔ IsRelPrime m n := by simp_rw [coprime_iff_gcd_eq_one, IsRelPrime, ← and_imp, ← dvd_gcd_iff, isUnit_iff_dvd_one] exact ⟨fun h _ ↦ (h ▸ ·), (dvd_one.mp <| · dvd_rfl)⟩ /-- If `k:ℕ` divides coprime `a` and `b` then `k = 1` -/ theorem eq_one_of_dvd_coprimes {a b k : ℕ} (h_ab_coprime : Coprime a b) (hka : k ∣ a) (hkb : k ∣ b) : k = 1 := dvd_one.mp (isUnit_iff_dvd_one.mp <| coprime_iff_isRelPrime.mp h_ab_coprime hka hkb) theorem Coprime.mul_add_mul_ne_mul {m n a b : ℕ} (cop : Coprime m n) (ha : a ≠ 0) (hb : b ≠ 0) : a * m + b * n ≠ m * n := by intro h obtain ⟨x, rfl⟩ : n ∣ a := cop.symm.dvd_of_dvd_mul_right ((Nat.dvd_add_iff_left (Nat.dvd_mul_left n b)).mpr ((congr_arg _ h).mpr (Nat.dvd_mul_left n m))) obtain ⟨y, rfl⟩ : m ∣ b := cop.dvd_of_dvd_mul_right ((Nat.dvd_add_iff_right (Nat.dvd_mul_left m (n * x))).mpr ((congr_arg _ h).mpr (Nat.dvd_mul_right m n))) rw [mul_comm, mul_ne_zero_iff, ← one_le_iff_ne_zero] at ha hb refine mul_ne_zero hb.2 ha.2 (eq_zero_of_mul_eq_self_left (ne_of_gt (add_le_add ha.1 hb.1)) ?_) rw [← mul_assoc, ← h, Nat.add_mul, Nat.add_mul, mul_comm _ n, ← mul_assoc, mul_comm y] variable {x n m k : ℕ} theorem gcd_mul_gcd_eq_iff_dvd_mul_of_coprime (hcop : Coprime n m) : gcd x n * gcd x m = x ↔ x ∣ n * m := by refine ⟨fun h ↦ ?_, (dvd_antisymm ?_ <| dvd_gcd_mul_gcd_iff_dvd_mul.mpr ·)⟩ refine h ▸ Nat.mul_dvd_mul ?_ ?_ <;> exact x.gcd_dvd_right _ refine (hcop.gcd_both x x).mul_dvd_of_dvd_of_dvd ?_ ?_ <;> exact x.gcd_dvd_left _ lemma div_mul_div (hkm : m ∣ k) (hkn : n ∣ m) : (k / m) * (m / n) = k / n := by rcases n.eq_zero_or_pos with hn | hn · simp [hn] refine (Nat.div_eq_of_eq_mul_left hn ?_).symm rw [mul_assoc, Nat.div_mul_cancel hkn, Nat.div_mul_cancel hkm] lemma div_dvd_div_left (hkm : m ∣ k) (hkn : n ∣ m) : k / m ∣ k / n := ⟨_, (div_mul_div hkm hkn).symm⟩ lemma div_lcm_eq_div_gcd (hkm : m ∣ k) (hkn : n ∣ k) : (k / m).lcm (k / n) = k / (m.gcd n) := by rw [Nat.lcm_eq_iff] refine ⟨div_dvd_div_left hkm (Nat.gcd_dvd_left m n), div_dvd_div_left hkn (Nat.gcd_dvd_right m n), fun c hmc hnc ↦ ?_⟩ rcases m.eq_zero_or_pos with hm | hm · simp_all rcases n.eq_zero_or_pos with hn | hn · simp_all rw [Nat.div_dvd_iff_dvd_mul hkm hm] at hmc rw [Nat.div_dvd_iff_dvd_mul hkn hn] at hnc simpa [Nat.div_dvd_iff_dvd_mul (Nat.dvd_trans (Nat.gcd_dvd_left m n) hkm) (gcd_pos_of_pos_left n hm), Nat.gcd_mul_right m c n] using (Nat.dvd_gcd hmc hnc) end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/GCD/BigOperators.lean
import Mathlib.Algebra.BigOperators.Group.Finset.Defs /-! # Lemmas about coprimality with big products. These lemmas are kept separate from `Data.Nat.GCD.Basic` in order to minimize imports. -/ namespace Nat variable {ι : Type*} theorem coprime_list_prod_left_iff {l : List ℕ} {k : ℕ} : Coprime l.prod k ↔ ∀ n ∈ l, Coprime n k := by induction l <;> simp [Nat.coprime_mul_iff_left, *] theorem coprime_list_prod_right_iff {k : ℕ} {l : List ℕ} : Coprime k l.prod ↔ ∀ n ∈ l, Coprime k n := by simp_rw [coprime_comm (n := k), coprime_list_prod_left_iff] theorem coprime_multiset_prod_left_iff {m : Multiset ℕ} {k : ℕ} : Coprime m.prod k ↔ ∀ n ∈ m, Coprime n k := by induction m using Quotient.inductionOn; simpa using coprime_list_prod_left_iff theorem coprime_multiset_prod_right_iff {k : ℕ} {m : Multiset ℕ} : Coprime k m.prod ↔ ∀ n ∈ m, Coprime k n := by induction m using Quotient.inductionOn; simpa using coprime_list_prod_right_iff theorem coprime_prod_left_iff {t : Finset ι} {s : ι → ℕ} {x : ℕ} : Coprime (∏ i ∈ t, s i) x ↔ ∀ i ∈ t, Coprime (s i) x := by simpa using coprime_multiset_prod_left_iff (m := t.val.map s) theorem coprime_prod_right_iff {x : ℕ} {t : Finset ι} {s : ι → ℕ} : Coprime x (∏ i ∈ t, s i) ↔ ∀ i ∈ t, Coprime x (s i) := by simpa using coprime_multiset_prod_right_iff (m := t.val.map s) /-- See `IsCoprime.prod_left` for the corresponding lemma about `IsCoprime` -/ alias ⟨_, Coprime.prod_left⟩ := coprime_prod_left_iff /-- See `IsCoprime.prod_right` for the corresponding lemma about `IsCoprime` -/ alias ⟨_, Coprime.prod_right⟩ := coprime_prod_right_iff theorem coprime_fintype_prod_left_iff [Fintype ι] {s : ι → ℕ} {x : ℕ} : Coprime (∏ i, s i) x ↔ ∀ i, Coprime (s i) x := by simp [coprime_prod_left_iff] theorem coprime_fintype_prod_right_iff [Fintype ι] {x : ℕ} {s : ι → ℕ} : Coprime x (∏ i, s i) ↔ ∀ i, Coprime x (s i) := by simp [coprime_prod_right_iff] end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/GCD/Prime.lean
import Mathlib.Data.Nat.GCD.Basic import Mathlib.Data.Nat.Prime.Defs /-! # Lemmas related to `Nat.Prime` and `lcm` This file contains lemmas related to `Nat.Prime`. These lemmas are kept separate from `Mathlib/Data/Nat/GCD/Basic.lean` in order to minimize imports. ## Main results - `Nat.Prime.dvd_or_dvd_of_dvd_lcm`: If `p ∣ lcm a b`, then `p ∣ a ∨ p ∣ b`. - `Nat.Prime.dvd_lcm`: `p ∣ lcm a b ↔ p ∣ a ∨ p ∣ b`. - `Nat.Prime.not_dvd_lcm`: If `p ∤ a` and `p ∤ b`, then `p ∤ lcm a b`. -/ namespace Nat namespace Prime variable {p a b : ℕ} (hp : Prime p) include hp theorem dvd_or_dvd_of_dvd_lcm (h : p ∣ lcm a b) : p ∣ a ∨ p ∣ b := dvd_or_dvd hp (h.trans (lcm_dvd_mul a b)) theorem dvd_lcm : p ∣ lcm a b ↔ p ∣ a ∨ p ∣ b := ⟨hp.dvd_or_dvd_of_dvd_lcm, (Or.elim · (dvd_lcm_of_dvd_left · _) (dvd_lcm_of_dvd_right · _))⟩ theorem not_dvd_lcm (ha : ¬ p ∣ a) (hb : ¬ p ∣ b) : ¬ p ∣ lcm a b := hp.dvd_lcm.not.mpr <| not_or.mpr ⟨ha, hb⟩ end Prime end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Digits/Div.lean
import Mathlib.Data.List.Palindrome import Mathlib.Data.Nat.Digits.Lemmas /-! # Divisibility tests for natural numbers in terms of digits. We prove some divisibility tests based on digits, in particular completing Theorem #85 from https://www.cs.ru.nl/~freek/100/. -/ namespace Nat variable {n : ℕ} theorem modEq_three_digits_sum (n : ℕ) : n ≡ (digits 10 n).sum [MOD 3] := modEq_digits_sum 3 10 (by simp) n theorem modEq_nine_digits_sum (n : ℕ) : n ≡ (digits 10 n).sum [MOD 9] := modEq_digits_sum 9 10 (by simp) n theorem modEq_eleven_digits_sum (n : ℕ) : n ≡ ((digits 10 n).map fun n : ℕ => (n : ℤ)).alternatingSum [ZMOD 11] := by have t := zmodeq_ofDigits_digits 11 10 (-1 : ℤ) (by unfold Int.ModEq; rfl) n rwa [ofDigits_neg_one] at t /-! ## Divisibility -/ theorem dvd_iff_dvd_digits_sum (b b' : ℕ) (h : b' % b = 1) (n : ℕ) : b ∣ n ↔ b ∣ (digits b' n).sum := by rw [← ofDigits_one] conv_lhs => rw [← ofDigits_digits b' n] rw [Nat.dvd_iff_mod_eq_zero, Nat.dvd_iff_mod_eq_zero, ofDigits_mod, h] /-- **Divisibility by 3 Rule** -/ theorem three_dvd_iff (n : ℕ) : 3 ∣ n ↔ 3 ∣ (digits 10 n).sum := dvd_iff_dvd_digits_sum 3 10 (by simp) n theorem nine_dvd_iff (n : ℕ) : 9 ∣ n ↔ 9 ∣ (digits 10 n).sum := dvd_iff_dvd_digits_sum 9 10 (by simp) n theorem dvd_iff_dvd_ofDigits (b b' : ℕ) (c : ℤ) (h : (b : ℤ) ∣ (b' : ℤ) - c) (n : ℕ) : b ∣ n ↔ (b : ℤ) ∣ ofDigits c (digits b' n) := by rw [← Int.natCast_dvd_natCast] exact dvd_iff_dvd_of_dvd_sub (zmodeq_ofDigits_digits b b' c (Int.modEq_iff_dvd.2 h).symm _).symm.dvd theorem eleven_dvd_iff : 11 ∣ n ↔ (11 : ℤ) ∣ ((digits 10 n).map fun n : ℕ => (n : ℤ)).alternatingSum := by have t := dvd_iff_dvd_ofDigits 11 10 (-1 : ℤ) (by simp) n rw [ofDigits_neg_one] at t exact t theorem eleven_dvd_of_palindrome (p : (digits 10 n).Palindrome) (h : Even (digits 10 n).length) : 11 ∣ n := by let dig := (digits 10 n).map fun n : ℕ => (n : ℤ) replace h : Even dig.length := by rwa [List.length_map] refine eleven_dvd_iff.2 ⟨0, (?_ : dig.alternatingSum = 0)⟩ have := dig.alternatingSum_reverse rw [(p.map _).reverse_eq, _root_.pow_succ', h.neg_one_pow, mul_one, neg_one_zsmul] at this exact eq_zero_of_neg_eq this.symm end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Digits/Lemmas.lean
import Mathlib.Algebra.BigOperators.Intervals import Mathlib.Algebra.BigOperators.Ring.List import Mathlib.Data.Int.ModEq import Mathlib.Data.Nat.Bits import Mathlib.Data.Nat.Log import Mathlib.Tactic.IntervalCases import Mathlib.Data.Nat.Digits.Defs /-! # Digits of a natural number This provides lemma about the digits of natural numbers. -/ namespace Nat variable {n : ℕ} theorem ofDigits_eq_sum_mapIdx_aux (b : ℕ) (l : List ℕ) : (l.zipWith ((fun a i : ℕ => a * b ^ (i + 1))) (List.range l.length)).sum = b * (l.zipWith (fun a i => a * b ^ i) (List.range l.length)).sum := by suffices l.zipWith (fun a i : ℕ => a * b ^ (i + 1)) (List.range l.length) = l.zipWith (fun a i=> b * (a * b ^ i)) (List.range l.length) by simp [this] congr; ext; ring theorem ofDigits_eq_sum_mapIdx (b : ℕ) (L : List ℕ) : ofDigits b L = (L.mapIdx fun i a => a * b ^ i).sum := by rw [List.mapIdx_eq_zipIdx_map, List.zipIdx_eq_zip_range', List.map_zip_eq_zipWith, ofDigits_eq_foldr, ← List.range_eq_range'] induction L with | nil => simp | cons hd tl hl => simpa [List.range_succ_eq_map, List.zipWith_map_right, ofDigits_eq_sum_mapIdx_aux] using Or.inl hl /-! ### Properties This section contains various lemmas of properties relating to `digits` and `ofDigits`. -/ theorem digits_len (b n : ℕ) (hb : 1 < b) (hn : n ≠ 0) : (b.digits n).length = b.log n + 1 := by induction n using Nat.strong_induction_on with | _ n IH rw [digits_eq_cons_digits_div hb hn, List.length] by_cases h : n / b = 0 · simp [h] aesop · have : n / b < n := div_lt_self (Nat.pos_of_ne_zero hn) hb rw [IH _ this h, log_div_base, tsub_add_cancel_of_le] refine Nat.succ_le_of_lt (log_pos hb ?_) contrapose! h exact div_eq_of_lt h theorem digits_length_le_iff {b k : ℕ} (hb : 1 < b) (n : ℕ) : (b.digits n).length ≤ k ↔ n < b ^ k := by by_cases h : n = 0 · have : 0 < b ^ k := by positivity simpa [h] rw [digits_len b n hb h, ← log_lt_iff_lt_pow hb h] exact add_one_le_iff theorem lt_digits_length_iff {b k : ℕ} (hb : 1 < b) (n : ℕ) : k < (b.digits n).length ↔ b ^ k ≤ n := by rw [← not_iff_not] push_neg exact digits_length_le_iff hb n theorem getLast_digit_ne_zero (b : ℕ) {m : ℕ} (hm : m ≠ 0) : (digits b m).getLast (digits_ne_nil_iff_ne_zero.mpr hm) ≠ 0 := by rcases b with (_ | _ | b) · cases m · cases hm rfl · simp · cases m · cases hm rfl simp only [zero_add, digits_one, List.getLast_replicate_succ] exact Nat.one_ne_zero revert hm induction m using Nat.strongRecOn with | ind n IH => ?_ intro hn by_cases! hnb : n < b + 2 · simpa only [digits_of_lt (b + 2) n hn hnb] · rw [digits_getLast n (le_add_left 2 b)] refine IH _ (Nat.div_lt_self hn.bot_lt (one_lt_succ_succ b)) ?_ rw [← pos_iff_ne_zero] exact Nat.div_pos hnb (zero_lt_succ (succ b)) theorem digits_append_digits {b m n : ℕ} (hb : 0 < b) : digits b n ++ digits b m = digits b (n + b ^ (digits b n).length * m) := by rcases eq_or_lt_of_le (Nat.succ_le_of_lt hb) with (rfl | hb) · simp rw [← ofDigits_digits_append_digits] refine (digits_ofDigits b hb _ (fun l hl => ?_) (fun h_append => ?_)).symm · rcases (List.mem_append.mp hl) with (h | h) <;> exact digits_lt_base hb h · by_cases h : digits b m = [] · simp only [h, List.append_nil] at h_append ⊢ exact getLast_digit_ne_zero b <| digits_ne_nil_iff_ne_zero.mp h_append · exact (List.getLast_append_of_right_ne_nil _ _ h) ▸ (getLast_digit_ne_zero _ <| digits_ne_nil_iff_ne_zero.mp h) theorem digits_append_zeroes_append_digits {b k m n : ℕ} (hb : 1 < b) (hm : 0 < m) : digits b n ++ List.replicate k 0 ++ digits b m = digits b (n + b ^ ((digits b n).length + k) * m) := by rw [List.append_assoc, ← digits_base_pow_mul hb hm] simp only [digits_append_digits (zero_lt_of_lt hb), digits_inj_iff, add_right_inj] ring theorem digits_len_le_digits_len_succ (b n : ℕ) : (digits b n).length ≤ (digits b (n + 1)).length := by rcases Decidable.eq_or_ne n 0 with (rfl | hn) · simp rcases le_or_gt b 1 with hb | hb · interval_cases b <;> simp +arith [digits_zero_succ', hn] simpa [digits_len, hb, hn] using log_mono_right (le_succ _) theorem le_digits_len_le (b n m : ℕ) (h : n ≤ m) : (digits b n).length ≤ (digits b m).length := monotone_nat_of_le_succ (digits_len_le_digits_len_succ b) h theorem pow_length_le_mul_ofDigits {b : ℕ} {l : List ℕ} (hl : l ≠ []) (hl2 : l.getLast hl ≠ 0) : (b + 2) ^ l.length ≤ (b + 2) * ofDigits (b + 2) l := by rw [← List.dropLast_append_getLast hl] simp only [List.length_append, List.length, zero_add, List.length_dropLast, ofDigits_append, List.length_dropLast, ofDigits_singleton, add_comm (l.length - 1), pow_add, pow_one] apply Nat.mul_le_mul_left refine le_trans ?_ (Nat.le_add_left _ _) have : 0 < l.getLast hl := by rwa [pos_iff_ne_zero] convert Nat.mul_le_mul_left ((b + 2) ^ (l.length - 1)) this using 1 rw [Nat.mul_one] /-- Any non-zero natural number `m` is greater than (b+2)^((number of digits in the base (b+2) representation of m) - 1) -/ theorem base_pow_length_digits_le' (b m : ℕ) (hm : m ≠ 0) : (b + 2) ^ (digits (b + 2) m).length ≤ (b + 2) * m := by have : digits (b + 2) m ≠ [] := digits_ne_nil_iff_ne_zero.mpr hm convert @pow_length_le_mul_ofDigits b (digits (b+2) m) this (getLast_digit_ne_zero _ hm) rw [ofDigits_digits] /-- Any non-zero natural number `m` is greater than b^((number of digits in the base b representation of m) - 1) -/ theorem base_pow_length_digits_le (b m : ℕ) (hb : 1 < b) : m ≠ 0 → b ^ (digits b m).length ≤ b * m := by rcases b with (_ | _ | b) <;> try simp_all exact base_pow_length_digits_le' b m open Finset theorem sub_one_mul_sum_div_pow_eq_sub_sum_digits {p : ℕ} (L : List ℕ) {h_nonempty} (h_ne_zero : L.getLast h_nonempty ≠ 0) (h_lt : ∀ l ∈ L, l < p) : (p - 1) * ∑ i ∈ range L.length, (ofDigits p L) / p ^ i.succ = (ofDigits p L) - L.sum := by obtain h | rfl | h : 1 < p ∨ 1 = p ∨ p < 1 := trichotomous 1 p · induction L with | nil => simp [ofDigits] | cons hd tl ih => simp only [List.length_cons, List.sum_cons, self_div_pow_eq_ofDigits_drop _ _ h, digits_ofDigits p h (hd :: tl) h_lt (fun _ => h_ne_zero)] simp only [ofDigits] rw [sum_range_succ, Nat.cast_id] simp only [List.drop, List.drop_length] obtain rfl | h' := em <| tl = [] · simp [ofDigits] · have w₁' := fun l hl ↦ h_lt l <| List.mem_cons_of_mem hd hl have w₂' := fun (h : tl ≠ []) ↦ (List.getLast_cons h) ▸ h_ne_zero have ih := ih (w₂' h') w₁' simp only [self_div_pow_eq_ofDigits_drop _ _ h, digits_ofDigits p h tl w₁' w₂', ← Nat.one_add] at ih have := sum_singleton (fun x ↦ ofDigits p <| tl.drop x) tl.length rw [← Ico_succ_singleton, List.drop_length, ofDigits] at this have h₁ : 1 ≤ tl.length := List.length_pos_iff.mpr h' rw [← sum_range_add_sum_Ico _ <| h₁, ← add_zero (∑ x ∈ Ico _ _, ofDigits p (tl.drop x)), ← this, sum_Ico_consecutive _ h₁ <| (le_add_right tl.length 1), ← sum_Ico_add _ 0 tl.length 1, Ico_zero_eq_range, mul_add, mul_add, ih, range_one, sum_singleton, List.drop, ofDigits, mul_zero, add_zero, ← Nat.add_sub_assoc <| sum_le_ofDigits _ <| Nat.le_of_lt h] nth_rw 2 [← one_mul <| ofDigits p tl] rw [← add_mul, Nat.sub_add_cancel (one_le_of_lt h), Nat.add_sub_add_left] · simp [ofDigits_one] · simp [lt_one_iff.mp h] cases L · rfl · simp [ofDigits] theorem sub_one_mul_sum_log_div_pow_eq_sub_sum_digits {p : ℕ} (n : ℕ) : (p - 1) * ∑ i ∈ range (log p n).succ, n / p ^ i.succ = n - (p.digits n).sum := by obtain h | rfl | h : 1 < p ∨ 1 = p ∨ p < 1 := trichotomous 1 p · rcases eq_or_ne n 0 with rfl | hn · simp · convert sub_one_mul_sum_div_pow_eq_sub_sum_digits (p.digits n) (getLast_digit_ne_zero p hn) <| (fun l a ↦ digits_lt_base h a) · refine (digits_len p n h hn).symm all_goals exact (ofDigits_digits p n).symm · simp · simp [lt_one_iff.mp h] cases n all_goals simp /-! ### Binary -/ theorem digits_two_eq_bits (n : ℕ) : digits 2 n = n.bits.map fun b => cond b 1 0 := by induction n using Nat.binaryRecFromOne with | zero => simp | one => simp | bit b n h ih => rw [bits_append_bit _ _ fun hn => absurd hn h] cases b · rw [digits_def' one_lt_two] · simpa [Nat.bit] · simpa [Nat.bit, pos_iff_ne_zero] · simpa [Nat.bit, add_comm, digits_add 2 one_lt_two 1 n, Nat.add_mul_div_left] /-! ### Modular Arithmetic -/ -- This is really a theorem about polynomials. theorem dvd_ofDigits_sub_ofDigits {α : Type*} [CommRing α] {a b k : α} (h : k ∣ a - b) (L : List ℕ) : k ∣ ofDigits a L - ofDigits b L := by induction L with | nil => change k ∣ 0 - 0; simp | cons d L ih => simp only [ofDigits, add_sub_add_left_eq_sub] exact dvd_mul_sub_mul h ih theorem ofDigits_modEq' (b b' : ℕ) (k : ℕ) (h : b ≡ b' [MOD k]) (L : List ℕ) : ofDigits b L ≡ ofDigits b' L [MOD k] := by induction L with | nil => rfl | cons d L ih => dsimp [ofDigits] dsimp [Nat.ModEq] at * conv_lhs => rw [Nat.add_mod, Nat.mul_mod, h, ih] conv_rhs => rw [Nat.add_mod, Nat.mul_mod] theorem ofDigits_modEq (b k : ℕ) (L : List ℕ) : ofDigits b L ≡ ofDigits (b % k) L [MOD k] := ofDigits_modEq' b (b % k) k (b.mod_modEq k).symm L theorem ofDigits_mod (b k : ℕ) (L : List ℕ) : ofDigits b L % k = ofDigits (b % k) L % k := ofDigits_modEq b k L theorem ofDigits_mod_eq_head! (b : ℕ) (l : List ℕ) : ofDigits b l % b = l.head! % b := by induction l <;> simp [Nat.ofDigits] theorem head!_digits {b n : ℕ} (h : b ≠ 1) : (Nat.digits b n).head! = n % b := by by_cases hb : 1 < b · rcases n with _ | n · simp · nth_rw 2 [← Nat.ofDigits_digits b (n + 1)] rw [Nat.ofDigits_mod_eq_head! _ _] exact (Nat.mod_eq_of_lt (Nat.digits_lt_base hb <| List.head!_mem_self <| Nat.digits_ne_nil_iff_ne_zero.mpr <| Nat.succ_ne_zero n)).symm · rcases n with _ | _ <;> simp_all [show b = 0 by cutsat] theorem ofDigits_zmodeq' (b b' : ℤ) (k : ℕ) (h : b ≡ b' [ZMOD k]) (L : List ℕ) : ofDigits b L ≡ ofDigits b' L [ZMOD k] := by induction L with | nil => rfl | cons d L ih => dsimp [ofDigits] dsimp [Int.ModEq] at * conv_lhs => rw [Int.add_emod, Int.mul_emod, h, ih] conv_rhs => rw [Int.add_emod, Int.mul_emod] theorem ofDigits_zmodeq (b : ℤ) (k : ℕ) (L : List ℕ) : ofDigits b L ≡ ofDigits (b % k) L [ZMOD k] := ofDigits_zmodeq' b (b % k) k (b.mod_modEq ↑k).symm L theorem ofDigits_zmod (b : ℤ) (k : ℕ) (L : List ℕ) : ofDigits b L % k = ofDigits (b % k) L % k := ofDigits_zmodeq b k L theorem modEq_digits_sum (b b' : ℕ) (h : b' % b = 1) (n : ℕ) : n ≡ (digits b' n).sum [MOD b] := by rw [← ofDigits_one] conv => congr · skip · rw [← ofDigits_digits b' n] convert ofDigits_modEq b' b (digits b' n) exact h.symm theorem zmodeq_ofDigits_digits (b b' : ℕ) (c : ℤ) (h : b' ≡ c [ZMOD b]) (n : ℕ) : n ≡ ofDigits c (digits b' n) [ZMOD b] := by conv => congr · skip · rw [← ofDigits_digits b' n] rw [coe_ofDigits] apply ofDigits_zmodeq' _ _ _ h theorem ofDigits_neg_one : ∀ L : List ℕ, ofDigits (-1 : ℤ) L = (L.map fun n : ℕ => (n : ℤ)).alternatingSum | [] => rfl | [n] => by simp [ofDigits, List.alternatingSum] | a :: b :: t => by simp only [ofDigits, List.alternatingSum, List.map_cons, ofDigits_neg_one t] ring end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Digits/Defs.lean
import Mathlib.Tactic.NormNum import Mathlib.Tactic.Ring import Mathlib.Tactic.Linarith import Mathlib.Algebra.Order.Group.Nat /-! # Digits of a natural number This provides a basic API for extracting the digits of a natural number in a given base, and reconstructing numbers from their digits. We also prove some divisibility tests based on digits, in particular completing Theorem #85 from https://www.cs.ru.nl/~freek/100/. Also included is a bound on the length of `Nat.toDigits` from core. ## TODO A basic `norm_digits` tactic for proving goals of the form `Nat.digits a b = l` where `a` and `b` are numerals is not yet ported. -/ assert_not_exists Finset namespace Nat variable {n : ℕ} /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digitsAux0 : ℕ → List ℕ | 0 => [] | n + 1 => [n+1] /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digitsAux1 (n : ℕ) : List ℕ := List.replicate n 1 /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digitsAux (b : ℕ) (h : 2 ≤ b) (n : ℕ) : List ℕ := go n (n + 2) init where init : (if n = 0 then 0 else n + 1) < n + 2 := by split_ifs <;> simp decreasing (n f : ℕ) (hf : (if n + 1 = 0 then 0 else n + 2) < f + 1) : (if (n + 1) / b = 0 then 0 else ((n + 1) / b) + 1) < f := by rw [if_neg n.add_one_ne_zero] at hf split_ifs with hn · exact zero_lt_of_lt (lt_of_succ_lt_succ hf) · rw [Nat.div_eq_zero_iff, or_iff_right (by omega), not_lt] at hn refine Nat.lt_of_le_of_lt (succ_le_succ ?_) (succ_lt_succ_iff.1 hf) refine Nat.div_le_of_le_mul (Nat.le_trans ?_ (Nat.mul_le_mul_right n h)) omega /-- Auxiliary function performing recursion for `Nat.digitsAux`. -/ go (n fuel : ℕ) (hfuel : (if n = 0 then 0 else n + 1) < fuel) : List ℕ := match n, fuel, hfuel with | 0, _, _ => [] | n + 1, f + 1, hf => ((n + 1) % b) :: go ((n + 1) / b) f (decreasing n f hf) theorem digitsAux.go_zero (b : ℕ) (h : 2 ≤ b) (fuel : ℕ) (hfuel : (if 0 = 0 then 0 else n + 1) < fuel) : digitsAux.go b h 0 fuel hfuel = [] := by rw [digitsAux.go] theorem digitsAux.go_succ (b : ℕ) (h : 2 ≤ b) (n fuel : ℕ) (hfuel : (if n + 1 = 0 then 0 else n + 2) < fuel + 1) : digitsAux.go b h (n + 1) (fuel + 1) hfuel = ((n + 1) % b) :: digitsAux.go b h ((n + 1) / b) fuel (decreasing b h n fuel hfuel) := rfl theorem digitsAux.go_fuel_irrel (b : ℕ) (h : 2 ≤ b) (n fuel fuel' : ℕ) (hfuel : (if n = 0 then 0 else n + 1) < fuel) (hfuel' : (if n = 0 then 0 else n + 1) < fuel') : digitsAux.go b h n fuel hfuel = digitsAux.go b h n fuel' hfuel' := by fun_induction go b h n fuel hfuel generalizing fuel' · rw [go_zero] · cases fuel' · simp at hfuel' · rw [go_succ] solve_by_elim @[simp] theorem digitsAux_zero (b : ℕ) (h : 2 ≤ b) : digitsAux b h 0 = [] := by rw [digitsAux, digitsAux.go] theorem digitsAux_def (b : ℕ) (h : 2 ≤ b) (n : ℕ) (w : 0 < n) : digitsAux b h n = (n % b) :: digitsAux b h (n / b) := by cases n · cases w · rw [digitsAux, digitsAux.go, digitsAux, digitsAux.go_fuel_irrel] /-- `digits b n` gives the digits, in little-endian order, of a natural number `n` in a specified base `b`. In any base, we have `ofDigits b L = L.foldr (fun x y ↦ x + b * y) 0`. * For any `2 ≤ b`, we have `l < b` for any `l ∈ digits b n`, and the last digit is not zero. This uniquely specifies the behaviour of `digits b`. * For `b = 1`, we define `digits 1 n = List.replicate n 1`. * For `b = 0`, we define `digits 0 n = [n]`, except `digits 0 0 = []`. Note this differs from the existing `Nat.toDigits` in core, which is used for printing numerals. In particular, `Nat.toDigits b 0 = ['0']`, while `digits b 0 = []`. -/ def digits : ℕ → ℕ → List ℕ | 0 => digitsAux0 | 1 => digitsAux1 | b + 2 => digitsAux (b + 2) (by simp) @[simp] theorem digits_zero (b : ℕ) : digits b 0 = [] := by rcases b with (_ | ⟨_ | ⟨_⟩⟩) <;> simp [digits, digitsAux0, digitsAux1] theorem digits_zero_zero : digits 0 0 = [] := rfl @[simp] theorem digits_zero_succ (n : ℕ) : digits 0 n.succ = [n+1] := rfl theorem digits_zero_succ' : ∀ {n : ℕ}, n ≠ 0 → digits 0 n = [n] | 0, h => (h rfl).elim | _ + 1, _ => rfl @[simp] theorem digits_one (n : ℕ) : digits 1 n = List.replicate n 1 := rfl -- no `@[simp]`: dsimp can prove this theorem digits_one_succ (n : ℕ) : digits 1 (n + 1) = 1 :: digits 1 n := rfl theorem digits_add_two_add_one (b n : ℕ) : digits (b + 2) (n + 1) = ((n + 1) % (b + 2)) :: digits (b + 2) ((n + 1) / (b + 2)) := by simp [digits, digitsAux_def] @[simp] lemma digits_of_two_le_of_pos {b : ℕ} (hb : 2 ≤ b) (hn : 0 < n) : Nat.digits b n = n % b :: Nat.digits b (n / b) := by rw [Nat.eq_add_of_sub_eq hb rfl, Nat.eq_add_of_sub_eq hn rfl, Nat.digits_add_two_add_one] theorem digits_def' : ∀ {b : ℕ} (_ : 1 < b) {n : ℕ} (_ : 0 < n), digits b n = (n % b) :: digits b (n / b) | 0, h => absurd h (by decide) | 1, h => absurd h (by decide) | b + 2, _ => digitsAux_def _ (by simp) _ @[simp] theorem digits_of_lt (b x : ℕ) (hx : x ≠ 0) (hxb : x < b) : digits b x = [x] := by rcases exists_eq_succ_of_ne_zero hx with ⟨x, rfl⟩ rcases Nat.exists_eq_add_of_le' ((Nat.le_add_left 1 x).trans_lt hxb) with ⟨b, rfl⟩ rw [digits_add_two_add_one, div_eq_of_lt hxb, digits_zero, mod_eq_of_lt hxb] theorem digits_add (b : ℕ) (h : 1 < b) (x y : ℕ) (hxb : x < b) (hxy : x ≠ 0 ∨ y ≠ 0) : digits b (x + b * y) = x :: digits b y := by rcases Nat.exists_eq_add_of_le' h with ⟨b, rfl : _ = _ + 2⟩ cases y · simp [hxb, hxy.resolve_right (absurd rfl)] dsimp [digits] rw [digitsAux_def] · congr · simp [Nat.add_mod, mod_eq_of_lt hxb] · simp [add_mul_div_left, div_eq_of_lt hxb] · apply Nat.succ_pos -- If we had a function converting a list into a polynomial, -- and appropriate lemmas about that function, -- we could rewrite this in terms of that. /-- `ofDigits b L` takes a list `L` of natural numbers, and interprets them as a number in semiring, as the little-endian digits in base `b`. -/ def ofDigits {α : Type*} [Semiring α] (b : α) : List ℕ → α | [] => 0 | h :: t => h + b * ofDigits b t theorem ofDigits_eq_foldr {α : Type*} [Semiring α] (b : α) (L : List ℕ) : ofDigits b L = List.foldr (fun x y => ↑x + b * y) 0 L := by induction L with | nil => rfl | cons d L ih => dsimp [ofDigits]; rw [ih] @[simp] theorem ofDigits_nil {b : ℕ} : ofDigits b [] = 0 := rfl @[simp] theorem ofDigits_singleton {b n : ℕ} : ofDigits b [n] = n := by simp [ofDigits] @[simp] theorem ofDigits_one_cons {α : Type*} [Semiring α] (h : ℕ) (L : List ℕ) : ofDigits (1 : α) (h :: L) = h + ofDigits 1 L := by simp [ofDigits] theorem ofDigits_cons {b hd} {tl : List ℕ} : ofDigits b (hd :: tl) = hd + b * ofDigits b tl := rfl theorem ofDigits_append {b : ℕ} {l1 l2 : List ℕ} : ofDigits b (l1 ++ l2) = ofDigits b l1 + b ^ l1.length * ofDigits b l2 := by induction l1 with | nil => simp [ofDigits] | cons hd tl IH => rw [ofDigits, List.cons_append, ofDigits, IH, List.length_cons, pow_succ'] ring @[simp] theorem ofDigits_append_zero {b : ℕ} (l : List ℕ) : ofDigits b (l ++ [0]) = ofDigits b l := by rw [ofDigits_append, ofDigits_singleton, mul_zero, add_zero] @[simp] theorem ofDigits_replicate_zero {b k : ℕ} : ofDigits b (List.replicate k 0) = 0 := by induction k with | zero => rfl | succ k ih => simp [List.replicate, ofDigits_cons, ih] @[simp] theorem ofDigits_append_replicate_zero {b k : ℕ} (l : List ℕ) : ofDigits b (l ++ List.replicate k 0) = ofDigits b l := by rw [ofDigits_append] simp theorem ofDigits_reverse_cons {b : ℕ} (l : List ℕ) (d : ℕ) : ofDigits b (d :: l).reverse = ofDigits b l.reverse + b^l.length * d := by simp only [List.reverse_cons] rw [ofDigits_append] simp theorem ofDigits_reverse_zero_cons {b : ℕ} (l : List ℕ) : ofDigits b (0 :: l).reverse = ofDigits b l.reverse := by simp only [List.reverse_cons, ofDigits_append_zero] @[norm_cast] theorem coe_ofDigits (α : Type*) [Semiring α] (b : ℕ) (L : List ℕ) : ((ofDigits b L : ℕ) : α) = ofDigits (b : α) L := by induction L with | nil => simp [ofDigits] | cons d L ih => dsimp [ofDigits]; push_cast; rw [ih] @[deprecated (since := "2025-08-14")] alias coe_int_ofDigits := coe_ofDigits theorem digits_zero_of_eq_zero {b : ℕ} (h : b ≠ 0) : ∀ {L : List ℕ} (_ : ofDigits b L = 0), ∀ l ∈ L, l = 0 | _ :: _, h0, _, List.Mem.head .. => Nat.eq_zero_of_add_eq_zero_right h0 | _ :: _, h0, _, List.Mem.tail _ hL => digits_zero_of_eq_zero h (mul_right_injective₀ h (Nat.eq_zero_of_add_eq_zero_left h0)) _ hL theorem digits_ofDigits (b : ℕ) (h : 1 < b) (L : List ℕ) (w₁ : ∀ l ∈ L, l < b) (w₂ : ∀ h : L ≠ [], L.getLast h ≠ 0) : digits b (ofDigits b L) = L := by induction L with | nil => simp | cons d L ih => dsimp [ofDigits] replace w₂ := w₂ (by simp) rw [digits_add b h] · rw [ih] · intro l m apply w₁ exact List.mem_cons_of_mem _ m · intro h rw [List.getLast_cons h] at w₂ convert w₂ · exact w₁ d List.mem_cons_self · by_cases h' : L = [] · rcases h' with rfl left simpa using w₂ · right contrapose! w₂ refine digits_zero_of_eq_zero h.ne_bot w₂ _ ?_ rw [List.getLast_cons h'] exact List.getLast_mem h' theorem ofDigits_digits (b n : ℕ) : ofDigits b (digits b n) = n := by rcases b with - | b · rcases n with - | n · rfl · simp · rcases b with - | b · induction n with | zero => rfl | succ n ih => rw [Nat.zero_add] at ih ⊢ simp only [ih, add_comm 1, ofDigits_one_cons, Nat.cast_id, digits_one_succ] · induction n using Nat.strongRecOn with | ind n h => ?_ cases n · rw [digits_zero] rfl · simp only [digits_add_two_add_one] dsimp [ofDigits] rw [h _ (Nat.div_lt_self' _ b)] rw [Nat.mod_add_div] theorem ofDigits_one (L : List ℕ) : ofDigits 1 L = L.sum := by induction L with | nil => rfl | cons _ _ ih => simp [ofDigits, List.sum_cons, ih] /-! ### Properties This section contains various lemmas of properties relating to `digits` and `ofDigits`. -/ theorem digits_eq_nil_iff_eq_zero {b n : ℕ} : digits b n = [] ↔ n = 0 := by constructor · intro h have : ofDigits b (digits b n) = ofDigits b [] := by rw [h] convert this rw [ofDigits_digits] · rintro rfl simp theorem digits_ne_nil_iff_ne_zero {b n : ℕ} : digits b n ≠ [] ↔ n ≠ 0 := not_congr digits_eq_nil_iff_eq_zero theorem digits_eq_cons_digits_div {b n : ℕ} (h : 1 < b) (w : n ≠ 0) : digits b n = (n % b) :: digits b (n / b) := digits_def' h (Nat.pos_of_ne_zero w) theorem digits_getLast {b : ℕ} (m : ℕ) (h : 1 < b) (p q) : (digits b m).getLast p = (digits b (m / b)).getLast q := by by_cases hm : m = 0 · simp [hm] simp only [digits_eq_cons_digits_div h hm] rw [List.getLast_cons] theorem digits.injective (b : ℕ) : Function.Injective b.digits := Function.LeftInverse.injective (ofDigits_digits b) @[simp] theorem digits_inj_iff {b n m : ℕ} : b.digits n = b.digits m ↔ n = m := (digits.injective b).eq_iff theorem mul_ofDigits (n : ℕ) {b : ℕ} {l : List ℕ} : n * ofDigits b l = ofDigits b (l.map (n * ·)) := by induction l with | nil => rfl | cons hd tl ih => rw [List.map_cons, ofDigits_cons, ofDigits_cons, ← ih] ring lemma ofDigits_inj_of_len_eq {b : ℕ} (hb : 1 < b) {L1 L2 : List ℕ} (len : L1.length = L2.length) (w1 : ∀ l ∈ L1, l < b) (w2 : ∀ l ∈ L2, l < b) (h : ofDigits b L1 = ofDigits b L2) : L1 = L2 := by induction L1 generalizing L2 with | nil => simp only [List.length_nil] at len exact (List.length_eq_zero_iff.mp len.symm).symm | cons D L ih => ?_ obtain ⟨d, l, rfl⟩ := List.exists_cons_of_length_eq_add_one len.symm simp only [List.length_cons, add_left_inj] at len simp only [ofDigits_cons] at h have eqd : D = d := by have H : (D + b * ofDigits b L) % b = (d + b * ofDigits b l) % b := by rw [h] simpa [mod_eq_of_lt (w2 d List.mem_cons_self), mod_eq_of_lt (w1 D List.mem_cons_self)] using H simp only [eqd, add_right_inj, mul_left_cancel_iff_of_pos (zero_lt_of_lt hb)] at h have := ih len (fun a ha ↦ w1 a <| List.mem_cons_of_mem D ha) (fun a ha ↦ w2 a <| List.mem_cons_of_mem d ha) h rw [eqd, this] /-- The addition of ofDigits of two lists is equal to ofDigits of digit-wise addition of them -/ theorem ofDigits_add_ofDigits_eq_ofDigits_zipWith_of_length_eq {b : ℕ} {l1 l2 : List ℕ} (h : l1.length = l2.length) : ofDigits b l1 + ofDigits b l2 = ofDigits b (l1.zipWith (· + ·) l2) := by induction l1 generalizing l2 with | nil => simp_all [eq_comm, List.length_eq_zero_iff, ofDigits] | cons hd₁ tl₁ ih₁ => induction l2 generalizing tl₁ with | nil => simp_all | cons hd₂ tl₂ ih₂ => simp_all only [List.length_cons, ofDigits_cons, add_left_inj, eq_comm, List.zipWith_cons_cons] rw [← ih₁ h.symm, mul_add] ac_rfl /-- The digits in the base b+2 expansion of n are all less than b+2 -/ theorem digits_lt_base' {b m : ℕ} : ∀ {d}, d ∈ digits (b + 2) m → d < b + 2 := by induction m using Nat.strongRecOn with | ind n IH => ?_ intro d hd rcases n with - | n · rw [digits_zero] at hd cases hd -- base b+2 expansion of 0 has no digits rw [digits_add_two_add_one] at hd cases hd · exact n.succ.mod_lt (by linarith) · apply IH ((n + 1) / (b + 2)) · apply Nat.div_lt_self <;> omega · assumption /-- The digits in the base b expansion of n are all less than b, if b ≥ 2 -/ theorem digits_lt_base {b m d : ℕ} (hb : 1 < b) (hd : d ∈ digits b m) : d < b := by rcases b with (_ | _ | b) <;> try simp_all exact digits_lt_base' hd /-- an n-digit number in base b + 2 is less than (b + 2)^n -/ theorem ofDigits_lt_base_pow_length' {b : ℕ} {l : List ℕ} (hl : ∀ x ∈ l, x < b + 2) : ofDigits (b + 2) l < (b + 2) ^ l.length := by induction l with | nil => simp [ofDigits] | cons hd tl IH => rw [ofDigits, List.length_cons, pow_succ] have : (ofDigits (b + 2) tl + 1) * (b + 2) ≤ (b + 2) ^ tl.length * (b + 2) := mul_le_mul (IH fun x hx => hl _ (List.mem_cons_of_mem _ hx)) (by rfl) (by simp only [zero_le]) (Nat.zero_le _) suffices ↑hd < b + 2 by linarith exact hl hd List.mem_cons_self /-- an n-digit number in base b is less than b^n if b > 1 -/ theorem ofDigits_lt_base_pow_length {b : ℕ} {l : List ℕ} (hb : 1 < b) (hl : ∀ x ∈ l, x < b) : ofDigits b l < b ^ l.length := by rcases b with (_ | _ | b) <;> try simp_all exact ofDigits_lt_base_pow_length' hl /-- Any number m is less than (b+2)^(number of digits in the base b + 2 representation of m) -/ theorem lt_base_pow_length_digits' {b m : ℕ} : m < (b + 2) ^ (digits (b + 2) m).length := by convert @ofDigits_lt_base_pow_length' b (digits (b + 2) m) fun _ => digits_lt_base' rw [ofDigits_digits (b + 2) m] /-- Any number m is less than b^(number of digits in the base b representation of m) -/ theorem lt_base_pow_length_digits {b m : ℕ} (hb : 1 < b) : m < b ^ (digits b m).length := by rcases b with (_ | _ | b) <;> try simp_all exact lt_base_pow_length_digits' theorem digits_base_mul {b m : ℕ} (hb : 1 < b) (hm : 0 < m) : b.digits (b * m) = 0 :: b.digits m := by rw [digits_def' hb (by positivity)] simp [mul_div_right m (by positivity)] theorem digits_base_pow_mul {b k m : ℕ} (hb : 1 < b) (hm : 0 < m) : digits b (b ^ k * m) = List.replicate k 0 ++ digits b m := by induction k generalizing m with | zero => simp | succ k ih => rw [pow_succ', mul_assoc, digits_base_mul hb (by positivity), ih hm, List.replicate_succ, List.cons_append] theorem ofDigits_digits_append_digits {b m n : ℕ} : ofDigits b (digits b n ++ digits b m) = n + b ^ (digits b n).length * m := by rw [ofDigits_append, ofDigits_digits, ofDigits_digits] @[mono] theorem ofDigits_monotone {p q : ℕ} (L : List ℕ) (h : p ≤ q) : ofDigits p L ≤ ofDigits q L := by induction L with | nil => rfl | cons _ _ hi => simp only [ofDigits, cast_id, add_le_add_iff_left] exact Nat.mul_le_mul h hi theorem sum_le_ofDigits {p : ℕ} (L : List ℕ) (h : 1 ≤ p) : L.sum ≤ ofDigits p L := (ofDigits_one L).symm ▸ ofDigits_monotone L h theorem digit_sum_le (p n : ℕ) : List.sum (digits p n) ≤ n := by induction n with | zero => exact digits_zero _ ▸ Nat.le_refl (List.sum []) | succ n => induction p with | zero => rw [digits_zero_succ, List.sum_cons, List.sum_nil, add_zero] | succ p => nth_rw 2 [← ofDigits_digits p.succ (n + 1)] rw [← ofDigits_one <| digits p.succ n.succ] exact ofDigits_monotone (digits p.succ n.succ) <| Nat.succ_pos p /-- Interpreting as a base `p` number and dividing by `p` is the same as interpreting the tail. -/ lemma ofDigits_div_eq_ofDigits_tail {p : ℕ} (hpos : 0 < p) (digits : List ℕ) (w₁ : ∀ l ∈ digits, l < p) : ofDigits p digits / p = ofDigits p digits.tail := by induction digits with | nil => simp [ofDigits] | cons hd tl => refine Eq.trans (add_mul_div_left hd _ hpos) ?_ rw [Nat.div_eq_of_lt <| w₁ _ List.mem_cons_self, zero_add, List.tail_cons] /-- Interpreting as a base `p` number and dividing by `p^i` is the same as dropping `i`. -/ lemma ofDigits_div_pow_eq_ofDigits_drop {p : ℕ} (i : ℕ) (hpos : 0 < p) (digits : List ℕ) (w₁ : ∀ l ∈ digits, l < p) : ofDigits p digits / p ^ i = ofDigits p (digits.drop i) := by induction i with | zero => simp | succ i hi => rw [Nat.pow_succ, ← Nat.div_div_eq_div_mul, hi, ofDigits_div_eq_ofDigits_tail hpos (List.drop i digits) fun x hx ↦ w₁ x <| List.mem_of_mem_drop hx, ← List.drop_one, List.drop_drop, add_comm] /-- Dividing `n` by `p^i` is like truncating the first `i` digits of `n` in base `p`. -/ lemma self_div_pow_eq_ofDigits_drop {p : ℕ} (i n : ℕ) (h : 2 ≤ p) : n / p ^ i = ofDigits p ((p.digits n).drop i) := by convert ofDigits_div_pow_eq_ofDigits_drop i (zero_lt_of_lt h) (p.digits n) (fun l hl ↦ digits_lt_base h hl) exact (ofDigits_digits p n).symm /-- Interpreting as a base `p` number and modulo `p^i` is the same as taking the first `i` digits. -/ lemma ofDigits_mod_pow_eq_ofDigits_take {p : ℕ} (i : ℕ) (hpos : 0 < p) (digits : List ℕ) (w₁ : ∀ l ∈ digits, l < p) : ofDigits p digits % p ^ i = ofDigits p (digits.take i) := by induction i generalizing digits with | zero => simp [mod_one] | succ i ih => cases digits with | nil => simp | cons hd tl => rw [List.take_succ_cons, ofDigits_cons, ofDigits_cons, ← ih _ fun x hx ↦ w₁ x <| List.mem_cons_of_mem hd hx, add_mod, mod_eq_of_lt <| lt_of_lt_of_le (w₁ hd List.mem_cons_self) (le_pow <| add_one_pos i), pow_succ', mul_mod_mul_left, mod_eq_of_lt] apply add_lt_of_lt_sub apply lt_of_lt_of_le (b := p) · exact w₁ hd List.mem_cons_self · rw [← Nat.mul_sub] exact Nat.le_mul_of_pos_right _ <| Nat.sub_pos_of_lt <| mod_lt _ <| pow_pos hpos i /-- `n` modulo `p^i` is like taking the least significant `i` digits of `n` in base `p`. -/ lemma self_mod_pow_eq_ofDigits_take {p : ℕ} (i n : ℕ) (h : 2 ≤ p) : n % p ^ i = ofDigits p ((p.digits n).take i) := by convert ofDigits_mod_pow_eq_ofDigits_take i (zero_lt_of_lt h) (p.digits n) (fun l hl ↦ digits_lt_base h hl) exact (ofDigits_digits p n).symm /-! ### `Nat.toDigits` length -/ lemma toDigitsCore_lens_eq_aux (b f : Nat) : ∀ (n : Nat) (l1 l2 : List Char), l1.length = l2.length → (Nat.toDigitsCore b f n l1).length = (Nat.toDigitsCore b f n l2).length := by induction f with (simp only [Nat.toDigitsCore]; intro n l1 l2 hlen) | zero => assumption | succ f ih => if hx : n / b = 0 then simp only [hx, if_true, List.length, congrArg (fun l ↦ l + 1) hlen] else simp only [hx, if_false] specialize ih (n / b) (Nat.digitChar (n % b) :: l1) (Nat.digitChar (n % b) :: l2) simp only [List.length, congrArg (fun l ↦ l + 1) hlen] at ih exact ih trivial lemma toDigitsCore_lens_eq (b f : Nat) : ∀ (n : Nat) (c : Char) (tl : List Char), (Nat.toDigitsCore b f n (c :: tl)).length = (Nat.toDigitsCore b f n tl).length + 1 := by induction f with (intro n c tl; simp only [Nat.toDigitsCore, List.length]) | succ f ih => grind lemma nat_repr_len_aux (n b e : Nat) (h_b_pos : 0 < b) : n < b ^ e.succ → n / b < b ^ e := by simp only [Nat.pow_succ] exact (@Nat.div_lt_iff_lt_mul b n (b ^ e) h_b_pos).mpr /-- The String representation produced by toDigitsCore has the proper length relative to the number of digits in `n < e` for some base `b`. Since this works with any base, it can be used for binary, decimal, and hex. -/ lemma toDigitsCore_length (b f n e : Nat) (h_e_pos : 0 < e) (hlt : n < b ^ e) : (Nat.toDigitsCore b f n []).length ≤ e := by induction f generalizing n e hlt h_e_pos with | zero => simp only [toDigitsCore, List.length, zero_le] | succ f ih => simp only [toDigitsCore] cases e with | zero => exact False.elim (Nat.lt_irrefl 0 h_e_pos) | succ e => cases e with | zero => rw [zero_add, pow_one] at hlt simp [Nat.div_eq_of_lt hlt] | succ e => specialize ih (n / b) _ (add_one_pos e) (Nat.div_lt_of_lt_mul <| by rwa [← pow_add_one']) split_ifs · simp only [List.length_singleton, _root_.zero_le, succ_le_succ] · simp only [toDigitsCore_lens_eq b f (n / b) (Nat.digitChar <| n % b), Nat.succ_le_succ_iff, ih] /-- The core implementation of `Nat.toDigits` returns a String with length less than or equal to the number of digits in the base-`b` number (represented by `e`). For example, the string representation of any number less than `b ^ 3` has a length less than or equal to 3. -/ lemma toDigits_length (b n e : Nat) : 0 < e → n < b ^ e → (Nat.toDigits b n).length ≤ e := toDigitsCore_length _ _ _ _ /-- The core implementation of `Nat.repr` returns a String with length less than or equal to the number of digits in the decimal number (represented by `e`). For example, the decimal string representation of any number less than 1000 (10 ^ 3) has a length less than or equal to 3. -/ lemma repr_length (n e : Nat) : 0 < e → n < 10 ^ e → (Nat.repr n).length ≤ e := by simpa [Nat.repr] using toDigits_length _ _ _ /-! ### `norm_digits` tactic -/ namespace NormDigits theorem digits_succ (b n m r l) (e : r + b * m = n) (hr : r < b) (h : Nat.digits b m = l ∧ 1 < b ∧ 0 < m) : (Nat.digits b n = r :: l) ∧ 1 < b ∧ 0 < n := by rcases h with ⟨h, b2, m0⟩ have b0 : 0 < b := by omega have n0 : 0 < n := by linarith [mul_pos b0 m0] refine ⟨?_, b2, n0⟩ obtain ⟨rfl, rfl⟩ := (Nat.div_mod_unique b0).2 ⟨e, hr⟩ subst h; exact Nat.digits_def' b2 n0 theorem digits_one (b n) (n0 : 0 < n) (nb : n < b) : Nat.digits b n = [n] ∧ 1 < b ∧ 0 < n := by have b2 : 1 < b := by cutsat refine ⟨?_, b2, n0⟩ rw [Nat.digits_def' b2 n0, Nat.mod_eq_of_lt nb, Nat.div_eq_zero_iff.2 <| .inr nb, Nat.digits_zero] /- Porting note: this part of the file is tactic related. open Tactic -- failed to format: unknown constant 'term.pseudo.antiquot' /-- Helper function for the `norm_digits` tactic. -/ unsafe def eval_aux ( eb : expr ) ( b : ℕ ) : expr → ℕ → instance_cache → tactic ( instance_cache × expr × expr ) | en , n , ic => do let m := n / b let r := n % b let ( ic , er ) ← ic . ofNat r let ( ic , pr ) ← norm_num.prove_lt_nat ic er eb if m = 0 then do let ( _ , pn0 ) ← norm_num.prove_pos ic en return ( ic , q( ( [ $ ( en ) ] : List Nat ) ) , q( digits_one $ ( eb ) $ ( en ) $ ( pn0 ) $ ( pr ) ) ) else do let em ← expr.of_nat q( ℕ ) m let ( _ , pe ) ← norm_num.derive q( ( $ ( er ) + $ ( eb ) * $ ( em ) : ℕ ) ) let ( ic , el , p ) ← eval_aux em m ic return ( ic , q( @ List.cons ℕ $ ( er ) $ ( el ) ) , q( digits_succ $ ( eb ) $ ( en ) $ ( em ) $ ( er ) $ ( el ) $ ( pe ) $ ( pr ) $ ( p ) ) ) /-- A tactic for normalizing expressions of the form `Nat.digits a b = l` where `a` and `b` are numerals. ``` example : Nat.digits 10 123 = [3,2,1] := by norm_num ``` -/ @[norm_num] unsafe def eval : expr → tactic (expr × expr) | q(Nat.digits $(eb) $(en)) => do let b ← expr.to_nat eb let n ← expr.to_nat en if n = 0 then return (q(([] : List ℕ)), q(Nat.digits_zero $(eb))) else if b = 0 then do let ic ← mk_instance_cache q(ℕ) let (_, pn0) ← norm_num.prove_ne_zero' ic en return (q(([$(en)] : List ℕ)), q(@Nat.digits_zero_succ' $(en) $(pn0))) else if b = 1 then do let ic ← mk_instance_cache q(ℕ) let s ← simp_lemmas.add_simp simp_lemmas.mk `list.replicate let (rhs, p2, _) ← simplify s [] q(List.replicate $(en) 1) let p ← mk_eq_trans q(Nat.digits_one $(en)) p2 return (rhs, p) else do let ic ← mk_instance_cache q(ℕ) let (_, l, p) ← eval_aux eb b en n ic let p ← mk_app `` And.left [p] return (l, p) | _ => failed -/ end NormDigits end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Fib/Basic.lean
import Mathlib.Data.Finset.NatAntidiagonal import Mathlib.Data.Nat.GCD.Basic import Mathlib.Data.Nat.BinaryRec import Mathlib.Logic.Function.Iterate import Mathlib.Tactic.Ring import Mathlib.Tactic.Zify import Mathlib.Data.Nat.Choose.Basic import Mathlib.Algebra.BigOperators.Group.Finset.Basic /-! # Fibonacci numbers This file defines the Fibonacci sequence as `F₀ = 0, F₁ = 1, Fₙ₊₂ = Fₙ + Fₙ₊₁`. Furthermore, it proves results about the sequence and introduces methods to compute it quickly. ## Main definitions - `Nat.fib` returns the stream of Fibonacci numbers. ## Main statements - `Nat.fib_add_two`: shows that `fib` indeed satisfies the Fibonacci recurrence `Fₙ₊₂ = Fₙ + Fₙ₊₁`. - `Nat.fib_gcd`: `fib n` is a strong divisibility sequence. - `Nat.fib_succ_eq_sum_choose`: `fib` is given by the sum of `Nat.choose` along an antidiagonal. - `Nat.fib_succ_eq_succ_sum`: shows that `F₀ + F₁ + ⋯ + Fₙ = Fₙ₊₂ - 1`. - `Nat.fib_two_mul` and `Nat.fib_two_mul_add_one` are the basis for an efficient algorithm to compute `fib` (see `Nat.fastFib`). ## Implementation notes For efficiency purposes, the sequence is defined using `Stream.iterate`. ## Tags Fibonacci numbers, Fibonacci sequence -/ namespace Nat /-- Implementation of the Fibonacci sequence satisfying `fib 0 = 0, fib 1 = 1, fib (n + 2) = fib n + fib (n + 1)`. *Note:* We use a stream iterator for better performance when compared to the naive recursive implementation. -/ @[pp_nodot] def fib (n : ℕ) : ℕ := ((fun p : ℕ × ℕ => (p.snd, p.fst + p.snd))^[n] (0, 1)).fst @[simp] theorem fib_zero : fib 0 = 0 := rfl @[simp] theorem fib_one : fib 1 = 1 := rfl @[simp] theorem fib_two : fib 2 = 1 := rfl /-- Shows that `fib` indeed satisfies the Fibonacci recurrence `Fₙ₊₂ = Fₙ + Fₙ₊₁`. -/ theorem fib_add_two {n : ℕ} : fib (n + 2) = fib n + fib (n + 1) := by simp [fib, Function.iterate_succ_apply'] lemma fib_add_one : ∀ {n}, n ≠ 0 → fib (n + 1) = fib (n - 1) + fib n | _n + 1, _ => fib_add_two theorem fib_le_fib_succ {n : ℕ} : fib n ≤ fib (n + 1) := by cases n <;> simp [fib_add_two] @[mono] theorem fib_mono : Monotone fib := monotone_nat_of_le_succ fun _ => fib_le_fib_succ @[simp] lemma fib_eq_zero : ∀ {n}, fib n = 0 ↔ n = 0 | 0 => Iff.rfl | 1 => Iff.rfl | n + 2 => by simp [fib_add_two, fib_eq_zero] @[simp] lemma fib_pos {n : ℕ} : 0 < fib n ↔ 0 < n := by simp [pos_iff_ne_zero] theorem fib_add_two_sub_fib_add_one {n : ℕ} : fib (n + 2) - fib (n + 1) = fib n := by rw [fib_add_two, add_tsub_cancel_right] theorem fib_lt_fib_succ {n : ℕ} (hn : 2 ≤ n) : fib n < fib (n + 1) := by rcases exists_add_of_le hn with ⟨n, rfl⟩ rw [← tsub_pos_iff_lt, add_comm 2, add_right_comm, fib_add_two, add_tsub_cancel_right, fib_pos] exact succ_pos n /-- `fib (n + 2)` is strictly monotone. -/ theorem fib_add_two_strictMono : StrictMono fun n => fib (n + 2) := by refine strictMono_nat_of_lt_succ fun n => ?_ rw [add_right_comm] exact fib_lt_fib_succ (self_le_add_left _ _) lemma fib_strictMonoOn : StrictMonoOn fib (Set.Ici 2) | _m + 2, _, _n + 2, _, hmn => fib_add_two_strictMono <| lt_of_add_lt_add_right hmn lemma fib_lt_fib {m : ℕ} (hm : 2 ≤ m) : ∀ {n}, fib m < fib n ↔ m < n | 0 => by simp | 1 => by simp | n + 2 => fib_strictMonoOn.lt_iff_lt hm <| by simp theorem le_fib_self {n : ℕ} (five_le_n : 5 ≤ n) : n ≤ fib n := by induction five_le_n with | refl => rfl -- 5 ≤ fib 5 | @step n five_le_n IH => -- n + 1 ≤ fib (n + 1) for 5 ≤ n rw [succ_le_iff] calc n ≤ fib n := IH _ < fib (n + 1) := fib_lt_fib_succ (le_trans (by decide) five_le_n) lemma le_fib_add_one : ∀ n, n ≤ fib n + 1 | 0 => zero_le_one | 1 => one_le_two | 2 => le_rfl | 3 => le_rfl | 4 => le_rfl | _n + 5 => (le_fib_self le_add_self).trans <| le_succ _ /-- Subsequent Fibonacci numbers are coprime, see https://proofwiki.org/wiki/Consecutive_Fibonacci_Numbers_are_Coprime -/ theorem fib_coprime_fib_succ (n : ℕ) : Nat.Coprime (fib n) (fib (n + 1)) := by induction n with | zero => simp | succ n ih => simp only [fib_add_two, coprime_add_self_right, Coprime, ih.symm] /-- See https://proofwiki.org/wiki/Fibonacci_Number_in_terms_of_Smaller_Fibonacci_Numbers -/ theorem fib_add (m n : ℕ) : fib (m + n + 1) = fib m * fib n + fib (m + 1) * fib (n + 1) := by induction n generalizing m with | zero => simp | succ n ih => specialize ih (m + 1) rw [add_assoc m 1 n, add_comm 1 n] at ih simp only [fib_add_two, ih] ring theorem fib_two_mul (n : ℕ) : fib (2 * n) = fib n * (2 * fib (n + 1) - fib n) := by cases n · simp · rw [two_mul, ← add_assoc, fib_add, fib_add_two, two_mul] simp only [← add_assoc, add_tsub_cancel_right] ring theorem fib_two_mul_add_one (n : ℕ) : fib (2 * n + 1) = fib (n + 1) ^ 2 + fib n ^ 2 := by rw [two_mul, fib_add] ring theorem fib_two_mul_add_two (n : ℕ) : fib (2 * n + 2) = fib (n + 1) * (2 * fib n + fib (n + 1)) := by rw [fib_add_two, fib_two_mul, fib_two_mul_add_one] have : fib n ≤ 2 * fib (n + 1) := le_trans fib_le_fib_succ (mul_comm 2 _ ▸ Nat.le_mul_of_pos_right _ two_pos) zify [this] ring /-- Computes `(Nat.fib n, Nat.fib (n + 1))` using the binary representation of `n`. Supports `Nat.fastFib`. -/ def fastFibAux : ℕ → ℕ × ℕ := Nat.binaryRec (fib 0, fib 1) fun b _ p => if b then (p.2 ^ 2 + p.1 ^ 2, p.2 * (2 * p.1 + p.2)) else (p.1 * (2 * p.2 - p.1), p.2 ^ 2 + p.1 ^ 2) /-- Computes `Nat.fib n` using the binary representation of `n`. Proved to be equal to `Nat.fib` in `Nat.fast_fib_eq`. -/ def fastFib (n : ℕ) : ℕ := (fastFibAux n).1 theorem fast_fib_aux_bit_ff (n : ℕ) : fastFibAux (bit false n) = let p := fastFibAux n (p.1 * (2 * p.2 - p.1), p.2 ^ 2 + p.1 ^ 2) := by rw [fastFibAux, binaryRec_eq] · rfl · simp theorem fast_fib_aux_bit_tt (n : ℕ) : fastFibAux (bit true n) = let p := fastFibAux n (p.2 ^ 2 + p.1 ^ 2, p.2 * (2 * p.1 + p.2)) := by rw [fastFibAux, binaryRec_eq] · rfl · simp theorem fast_fib_aux_eq (n : ℕ) : fastFibAux n = (fib n, fib (n + 1)) := by refine Nat.binaryRec ?_ ?_ n · simp [fastFibAux] · rintro (_ | _) n' ih <;> simp only [fast_fib_aux_bit_ff, fast_fib_aux_bit_tt, congr_arg Prod.fst ih, congr_arg Prod.snd ih, Prod.mk_inj] <;> simp [bit, fib_two_mul, fib_two_mul_add_one, fib_two_mul_add_two] theorem fast_fib_eq (n : ℕ) : fastFib n = fib n := by rw [fastFib, fast_fib_aux_eq] theorem gcd_fib_add_self (m n : ℕ) : gcd (fib m) (fib (n + m)) = gcd (fib m) (fib n) := by rcases Nat.eq_zero_or_pos n with rfl | h · simp replace h := Nat.succ_pred_eq_of_pos h; rw [← h, succ_eq_add_one] calc gcd (fib m) (fib (n.pred + 1 + m)) = gcd (fib m) (fib n.pred * fib m + fib (n.pred + 1) * fib (m + 1)) := by rw [← fib_add n.pred _] ring_nf _ = gcd (fib m) (fib (n.pred + 1) * fib (m + 1)) := by rw [add_comm, gcd_add_mul_right_right (fib m) _ (fib n.pred)] _ = gcd (fib m) (fib (n.pred + 1)) := Coprime.gcd_mul_right_cancel_right (fib (n.pred + 1)) (Coprime.symm (fib_coprime_fib_succ m)) theorem gcd_fib_add_mul_self (m n : ℕ) : ∀ k, gcd (fib m) (fib (n + k * m)) = gcd (fib m) (fib n) | 0 => by simp | k + 1 => by rw [← gcd_fib_add_mul_self m n k, add_mul, ← add_assoc, one_mul, gcd_fib_add_self _ _] /-- `fib n` is a strong divisibility sequence, see https://proofwiki.org/wiki/GCD_of_Fibonacci_Numbers -/ theorem fib_gcd (m n : ℕ) : fib (gcd m n) = gcd (fib m) (fib n) := by induction m, n using Nat.gcd.induction with | H0 => simp | H1 m n _ h' => rw [← gcd_rec m n] at h' conv_rhs => rw [← mod_add_div' n m] rwa [gcd_fib_add_mul_self m (n % m) (n / m), gcd_comm (fib m) _] theorem fib_dvd (m n : ℕ) (h : m ∣ n) : fib m ∣ fib n := by rwa [← gcd_eq_left_iff_dvd, ← fib_gcd, gcd_eq_left_iff_dvd.mpr] theorem fib_succ_eq_sum_choose : ∀ n : ℕ, fib (n + 1) = ∑ p ∈ Finset.antidiagonal n, choose p.1 p.2 := twoStepInduction rfl rfl fun n h1 h2 => by rw [fib_add_two, h1, h2, Finset.Nat.antidiagonal_succ_succ', Finset.Nat.antidiagonal_succ'] simp [choose_succ_succ, Finset.sum_add_distrib, add_left_comm] theorem fib_succ_eq_succ_sum (n : ℕ) : fib (n + 1) = (∑ k ∈ Finset.range n, fib k) + 1 := by induction n with | zero => simp | succ n ih => calc fib (n + 2) = fib n + fib (n + 1) := fib_add_two _ = (fib n + ∑ k ∈ Finset.range n, fib k) + 1 := by rw [ih, add_assoc] _ = (∑ k ∈ Finset.range (n + 1), fib k) + 1 := by simp [Finset.range_add_one] end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Fib/Zeckendorf.lean
import Mathlib.Data.Nat.Fib.Basic /-! # Zeckendorf's Theorem This file proves Zeckendorf's theorem: Every natural number can be written uniquely as a sum of distinct non-consecutive Fibonacci numbers. ## Main declarations * `List.IsZeckendorfRep`: Predicate for a list to be an increasing sequence of non-consecutive natural numbers greater than or equal to `2`, namely a Zeckendorf representation. * `Nat.greatestFib`: Greatest index of a Fibonacci number less than or equal to some natural. * `Nat.zeckendorf`: Send a natural number to its Zeckendorf representation. * `Nat.zeckendorfEquiv`: Zeckendorf's theorem, in the form of an equivalence between natural numbers and Zeckendorf representations. ## TODO We could prove that the order induced by `zeckendorfEquiv` on Zeckendorf representations is exactly the lexicographic order. ## Tags fibonacci, zeckendorf, digit -/ open List Nat -- TODO: The `local` attribute makes this not considered as an instance by linters @[nolint defLemma docBlame] local instance : IsTrans ℕ fun a b ↦ b + 2 ≤ a where trans _a _b _c hba hcb := hcb.trans <| le_self_add.trans hba namespace List /-- A list of natural numbers is a Zeckendorf representation (of a natural number) if it is an increasing sequence of non-consecutive numbers greater than or equal to `2`. This is relevant for Zeckendorf's theorem, since if we write a natural `n` as a sum of Fibonacci numbers `(l.map fib).sum`, `IsZeckendorfRep l` exactly means that we can't simplify any expression of the form `fib n + fib (n + 1) = fib (n + 2)`, `fib 1 = fib 2` or `fib 0 = 0` in the sum. -/ def IsZeckendorfRep (l : List ℕ) : Prop := (l ++ [0]).IsChain (fun a b ↦ b + 2 ≤ a) @[simp] lemma IsZeckendorfRep_nil : IsZeckendorfRep [] := by simp [IsZeckendorfRep] lemma IsZeckendorfRep.sum_fib_lt : ∀ {n l}, IsZeckendorfRep l → (∀ a ∈ (l ++ [0]).head?, a < n) → (l.map fib).sum < fib n | _, [], _, hn => fib_pos.2 <| hn _ rfl | n, a :: l, hl, hn => by simp only [IsZeckendorfRep, cons_append, isChain_iff_pairwise, pairwise_cons] at hl have : ∀ b, b ∈ head? (l ++ [0]) → b < a - 1 := fun b hb ↦ lt_tsub_iff_right.2 <| hl.1 _ <| mem_of_mem_head? hb simp only [mem_append, mem_singleton, ← isChain_iff_pairwise, or_imp, forall_and, forall_eq, zero_add] at hl simp only [map, List.sum_cons] refine (add_lt_add_left (sum_fib_lt hl.2 this) _).trans_le ?_ rw [add_comm, ← fib_add_one (hl.1.2.trans_lt' zero_lt_two).ne'] exact fib_mono (hn _ rfl) end List namespace Nat variable {m n : ℕ} /-- The greatest index of a Fibonacci number less than or equal to `n`. -/ def greatestFib (n : ℕ) : ℕ := (n + 1).findGreatest (fun k ↦ fib k ≤ n) lemma fib_greatestFib_le (n : ℕ) : fib (greatestFib n) ≤ n := findGreatest_spec (P := (fun k ↦ fib k ≤ n)) (zero_le _) <| zero_le _ lemma greatestFib_mono : Monotone greatestFib := fun _a _b hab ↦ findGreatest_mono (fun _k ↦ hab.trans') <| by gcongr @[simp] lemma le_greatestFib : m ≤ greatestFib n ↔ fib m ≤ n := ⟨fun h ↦ (fib_mono h).trans <| fib_greatestFib_le _, fun h ↦ le_findGreatest (m.le_fib_add_one.trans <| by gcongr) h⟩ @[simp] lemma greatestFib_lt : greatestFib m < n ↔ m < fib n := lt_iff_lt_of_le_iff_le le_greatestFib lemma lt_fib_greatestFib_add_one (n : ℕ) : n < fib (greatestFib n + 1) := greatestFib_lt.1 <| lt_succ_self _ @[simp] lemma greatestFib_fib : ∀ {n}, n ≠ 1 → greatestFib (fib n) = n | 0, _ => rfl | _n + 2, _ => findGreatest_eq_iff.2 ⟨le_fib_add_one _, fun _ ↦ le_rfl, fun _m hnm _ ↦ ((fib_lt_fib le_add_self).2 hnm).not_ge⟩ @[simp] lemma greatestFib_eq_zero : greatestFib n = 0 ↔ n = 0 := ⟨fun h ↦ by simpa using findGreatest_eq_zero_iff.1 h zero_lt_one le_add_self, by rintro rfl; rfl⟩ lemma greatestFib_ne_zero : greatestFib n ≠ 0 ↔ n ≠ 0 := greatestFib_eq_zero.not @[simp] lemma greatestFib_pos : 0 < greatestFib n ↔ 0 < n := by simp [pos_iff_ne_zero] lemma greatestFib_sub_fib_greatestFib_le_greatestFib (hn : n ≠ 0) : greatestFib (n - fib (greatestFib n)) ≤ greatestFib n - 2 := by rw [← Nat.lt_succ_iff, greatestFib_lt, tsub_lt_iff_right n.fib_greatestFib_le, Nat.sub_succ, succ_pred, ← fib_add_one] · exact n.lt_fib_greatestFib_add_one · simpa · simpa [← succ_le_iff, tsub_eq_zero_iff_le] using hn.bot_lt private lemma zeckendorf_aux (hm : 0 < m) : m - fib (greatestFib m) < m := tsub_lt_self hm <| fib_pos.2 <| findGreatest_pos.2 ⟨1, zero_lt_one, le_add_self, hm⟩ /-- The Zeckendorf representation of a natural number. Note: For unfolding, you should use the equational lemmas `Nat.zeckendorf_zero` and `Nat.zeckendorf_of_pos` instead of the autogenerated one. -/ def zeckendorf : ℕ → List ℕ | 0 => [] | m@(_ + 1) => letI a := greatestFib m a :: zeckendorf (m - fib a) decreasing_by simp_wf; subst_vars; apply zeckendorf_aux (zero_lt_succ _) @[simp] lemma zeckendorf_zero : zeckendorf 0 = [] := zeckendorf.eq_1 .. @[simp] lemma zeckendorf_succ (n : ℕ) : zeckendorf (n + 1) = greatestFib (n + 1) :: zeckendorf (n + 1 - fib (greatestFib (n + 1))) := zeckendorf.eq_2 .. @[simp] lemma zeckendorf_of_pos : ∀ {n}, 0 < n → zeckendorf n = greatestFib n :: zeckendorf (n - fib (greatestFib n)) | _n + 1, _ => zeckendorf_succ _ lemma isZeckendorfRep_zeckendorf : ∀ n, (zeckendorf n).IsZeckendorfRep | 0 => by simp only [zeckendorf_zero, IsZeckendorfRep_nil] | n + 1 => by rw [zeckendorf_succ, IsZeckendorfRep, List.cons_append] refine (isZeckendorfRep_zeckendorf _).cons (fun a ha ↦ ?_) obtain h | h := eq_zero_or_pos (n + 1 - fib (greatestFib (n + 1))) · simp only [h, zeckendorf_zero, nil_append, head?_cons, Option.mem_some_iff] at ha subst ha exact le_greatestFib.2 le_add_self rw [zeckendorf_of_pos h, cons_append, head?_cons, Option.mem_some_iff] at ha subst a exact add_le_of_le_tsub_right_of_le (le_greatestFib.2 le_add_self) (greatestFib_sub_fib_greatestFib_le_greatestFib n.succ_ne_zero) lemma zeckendorf_sum_fib : ∀ {l}, IsZeckendorfRep l → zeckendorf (l.map fib).sum = l | [], _ => by simp only [map_nil, List.sum_nil, zeckendorf_zero] | a :: l, hl => by have hl' := hl simp only [IsZeckendorfRep, cons_append, isChain_iff_pairwise, pairwise_cons, mem_append, mem_singleton, or_imp, forall_and, forall_eq, zero_add] at hl rw [← isChain_iff_pairwise] at hl have ha : 0 < a := hl.1.2.trans_lt' zero_lt_two suffices h : greatestFib (fib a + sum (map fib l)) = a by simp only [map, List.sum_cons, add_pos_iff, fib_pos.2 ha, true_or, zeckendorf_of_pos, h, add_tsub_cancel_left, zeckendorf_sum_fib hl.2] simp only [add_comm, add_assoc, greatestFib, findGreatest_eq_iff, ne_eq, ha.ne', not_false_eq_true, le_add_iff_nonneg_left, _root_.zero_le, forall_true_left, not_le, true_and] refine ⟨le_add_of_le_right <| le_fib_add_one _, fun n hn _ ↦ ?_⟩ rw [add_comm, ← List.sum_cons, ← map_cons] exact hl'.sum_fib_lt (by simpa) @[simp] lemma sum_zeckendorf_fib (n : ℕ) : (n.zeckendorf.map fib).sum = n := by induction n using zeckendorf.induct <;> simp_all [fib_greatestFib_le] /-- **Zeckendorf's Theorem** as an equivalence between natural numbers and Zeckendorf representations. Every natural number can be written uniquely as a sum of non-consecutive Fibonacci numbers (if we forget about the first two terms `F₀ = 0`, `F₁ = 1`). -/ def zeckendorfEquiv : ℕ ≃ {l // IsZeckendorfRep l} where toFun n := ⟨zeckendorf n, isZeckendorfRep_zeckendorf _⟩ invFun l := (map fib l).sum left_inv := sum_zeckendorf_fib right_inv l := Subtype.ext <| zeckendorf_sum_fib l.2 end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Prime/Nth.lean
import Mathlib.Data.Nat.Prime.Defs import Mathlib.Data.Nat.Nth /-! # The Nth primes -/ namespace Nat @[simp] theorem nth_prime_zero_eq_two : nth Prime 0 = 2 := nth_count prime_two @[simp] theorem nth_prime_one_eq_three : nth Nat.Prime 1 = 3 := nth_count prime_three @[simp] theorem nth_prime_two_eq_five : nth Nat.Prime 2 = 5 := nth_count prime_five @[simp] theorem nth_prime_three_eq_seven : nth Nat.Prime 3 = 7 := nth_count prime_seven @[simp] theorem nth_prime_four_eq_eleven : nth Nat.Prime 4 = 11 := nth_count prime_eleven end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Prime/Pow.lean
import Mathlib.Algebra.Order.Monoid.Unbundled.Pow import Mathlib.Data.Nat.Prime.Basic /-! # Prime numbers This file develops the theory of prime numbers: natural numbers `p ≥ 2` whose only divisors are `p` and `1`. -/ namespace Nat theorem pow_minFac {n k : ℕ} (hk : k ≠ 0) : (n ^ k).minFac = n.minFac := by rcases eq_or_ne n 1 with (rfl | hn) · simp have hnk : n ^ k ≠ 1 := fun hk' => hn ((pow_eq_one_iff hk).1 hk') apply (minFac_le_of_dvd (minFac_prime hn).two_le ((minFac_dvd n).pow hk)).antisymm apply minFac_le_of_dvd (minFac_prime hnk).two_le ((minFac_prime hnk).dvd_of_dvd_pow (minFac_dvd _)) theorem Prime.pow_minFac {p k : ℕ} (hp : p.Prime) (hk : k ≠ 0) : (p ^ k).minFac = p := by rw [Nat.pow_minFac hk, hp.minFac_eq] end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Prime/Int.lean
import Mathlib.Algebra.Ring.Int.Defs import Mathlib.Data.Nat.Prime.Basic import Mathlib.Algebra.Group.Int.Units import Mathlib.Data.Int.Basic /-! # Prime numbers in the naturals and the integers TODO: This file can probably be merged with `Mathlib/Data/Int/NatPrime.lean`. -/ namespace Nat theorem prime_iff_prime_int {p : ℕ} : p.Prime ↔ _root_.Prime (p : ℤ) := ⟨fun hp => ⟨Int.natCast_ne_zero_iff_pos.2 hp.pos, mt Int.isUnit_iff_natAbs_eq.1 hp.ne_one, fun a b h => by rw [← Int.dvd_natAbs, Int.natCast_dvd_natCast, Int.natAbs_mul, hp.dvd_mul] at h rwa [← Int.dvd_natAbs, Int.natCast_dvd_natCast, ← Int.dvd_natAbs, Int.natCast_dvd_natCast]⟩, fun hp => Nat.prime_iff.2 ⟨Int.natCast_ne_zero.1 hp.1, (mt Nat.isUnit_iff.1) fun h => by simp [h] at hp, fun a b => by simpa only [Int.natCast_dvd_natCast, (Int.natCast_mul _ _).symm] using hp.2.2 a b⟩⟩ /-- Two prime powers with positive exponents are equal only when the primes and the exponents are equal. -/ lemma Prime.pow_inj {p q m n : ℕ} (hp : p.Prime) (hq : q.Prime) (h : p ^ (m + 1) = q ^ (n + 1)) : p = q ∧ m = n := by have H := dvd_antisymm (Prime.dvd_of_dvd_pow hp <| h ▸ dvd_pow_self p (succ_ne_zero m)) (Prime.dvd_of_dvd_pow hq <| h.symm ▸ dvd_pow_self q (succ_ne_zero n)) exact ⟨H, succ_inj.mp <| Nat.pow_right_injective hq.two_le (H ▸ h)⟩ end Nat namespace Int @[simp] theorem prime_ofNat_iff {n : ℕ} : Prime (ofNat(n) : ℤ) ↔ Nat.Prime (OfNat.ofNat n) := Nat.prime_iff_prime_int.symm theorem prime_two : Prime (2 : ℤ) := prime_ofNat_iff.mpr Nat.prime_two theorem prime_three : Prime (3 : ℤ) := prime_ofNat_iff.mpr Nat.prime_three end Int
.lake/packages/mathlib/Mathlib/Data/Nat/Prime/Basic.lean
import Mathlib.Algebra.GroupWithZero.Associated import Mathlib.Algebra.Ring.Parity import Mathlib.Data.Nat.Prime.Defs /-! # Prime numbers This file develops the theory of prime numbers: natural numbers `p ≥ 2` whose only divisors are `p` and `1`. -/ namespace Nat variable {n : ℕ} theorem prime_mul_iff {a b : ℕ} : Nat.Prime (a * b) ↔ a.Prime ∧ b = 1 ∨ b.Prime ∧ a = 1 := by simp only [irreducible_mul_iff, ← irreducible_iff_nat_prime, Nat.isUnit_iff] theorem not_prime_mul {a b : ℕ} (a1 : a ≠ 1) (b1 : b ≠ 1) : ¬Prime (a * b) := by simp [prime_mul_iff, *] theorem not_prime_of_mul_eq {a b n : ℕ} (h : a * b = n) (h₁ : a ≠ 1) (h₂ : b ≠ 1) : ¬Prime n := h ▸ not_prime_mul h₁ h₂ @[deprecated (since := "2025-05-24")] alias not_prime_mul' := not_prime_of_mul_eq theorem Prime.dvd_iff_eq {p a : ℕ} (hp : p.Prime) (a1 : a ≠ 1) : a ∣ p ↔ p = a := by refine ⟨?_, by rintro rfl; rfl⟩ rintro ⟨j, rfl⟩ rcases prime_mul_iff.mp hp with (⟨_, rfl⟩ | ⟨_, rfl⟩) · exact mul_one _ · exact (a1 rfl).elim theorem Prime.eq_two_or_odd {p : ℕ} (hp : Prime p) : p = 2 ∨ p % 2 = 1 := p.mod_two_eq_zero_or_one.imp_left fun h => ((hp.eq_one_or_self_of_dvd 2 (dvd_of_mod_eq_zero h)).resolve_left (by decide)).symm theorem Prime.eq_two_or_odd' {p : ℕ} (hp : Prime p) : p = 2 ∨ Odd p := Or.imp_right (fun h => ⟨p / 2, (div_add_mod p 2).symm.trans (congr_arg _ h)⟩) hp.eq_two_or_odd section theorem Prime.five_le_of_ne_two_of_ne_three {p : ℕ} (hp : p.Prime) (h_two : p ≠ 2) (h_three : p ≠ 3) : 5 ≤ p := by by_contra! h revert h_two h_three hp decide +revert end theorem Prime.pred_pos {p : ℕ} (pp : Prime p) : 0 < pred p := lt_pred_iff.2 pp.one_lt theorem succ_pred_prime {p : ℕ} (pp : Prime p) : succ (pred p) = p := succ_pred_eq_of_pos pp.pos theorem exists_dvd_of_not_prime {n : ℕ} (n2 : 2 ≤ n) (np : ¬Prime n) : ∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n := ⟨minFac n, minFac_dvd _, ne_of_gt (minFac_prime (ne_of_gt n2)).one_lt, ne_of_lt <| (not_prime_iff_minFac_lt n2).1 np⟩ theorem exists_dvd_of_not_prime2 {n : ℕ} (n2 : 2 ≤ n) (np : ¬Prime n) : ∃ m, m ∣ n ∧ 2 ≤ m ∧ m < n := ⟨minFac n, minFac_dvd _, (minFac_prime (ne_of_gt n2)).two_le, (not_prime_iff_minFac_lt n2).1 np⟩ theorem not_prime_of_dvd_of_ne {m n : ℕ} (h1 : m ∣ n) (h2 : m ≠ 1) (h3 : m ≠ n) : ¬Prime n := fun h => Or.elim (h.eq_one_or_self_of_dvd m h1) h2 h3 theorem not_prime_of_dvd_of_lt {m n : ℕ} (h1 : m ∣ n) (h2 : 2 ≤ m) (h3 : m < n) : ¬Prime n := not_prime_of_dvd_of_ne h1 (ne_of_gt h2) (ne_of_lt h3) theorem not_prime_iff_exists_dvd_ne {n : ℕ} (h : 2 ≤ n) : (¬Prime n) ↔ ∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n := ⟨exists_dvd_of_not_prime h, fun ⟨_, h1, h2, h3⟩ => not_prime_of_dvd_of_ne h1 h2 h3⟩ theorem not_prime_iff_exists_dvd_lt {n : ℕ} (h : 2 ≤ n) : (¬Prime n) ↔ ∃ m, m ∣ n ∧ 2 ≤ m ∧ m < n := ⟨exists_dvd_of_not_prime2 h, fun ⟨_, h1, h2, h3⟩ => not_prime_of_dvd_of_lt h1 h2 h3⟩ theorem not_prime_iff_exists_mul_eq {n : ℕ} (h : 2 ≤ n) : (¬Prime n) ↔ ∃ a b, a < n ∧ b < n ∧ a * b = n := by rw [prime_iff_not_exists_mul_eq, and_iff_right h, Classical.not_not] theorem dvd_of_forall_prime_mul_dvd {a b : ℕ} (hdvd : ∀ p : ℕ, p.Prime → p ∣ a → p * a ∣ b) : a ∣ b := by obtain rfl | ha := eq_or_ne a 1 · apply one_dvd obtain ⟨p, hp⟩ := exists_prime_and_dvd ha exact _root_.trans (dvd_mul_left a p) (hdvd p hp.1 hp.2) theorem Prime.even_iff {p : ℕ} (hp : Prime p) : Even p ↔ p = 2 := by rw [even_iff_two_dvd, prime_dvd_prime_iff_eq prime_two hp, eq_comm] theorem Prime.odd_of_ne_two {p : ℕ} (hp : p.Prime) (h_two : p ≠ 2) : Odd p := hp.eq_two_or_odd'.resolve_left h_two theorem Prime.even_sub_one {p : ℕ} (hp : p.Prime) (h2 : p ≠ 2) : Even (p - 1) := let ⟨n, hn⟩ := hp.odd_of_ne_two h2; ⟨n, by rw [hn, Nat.add_sub_cancel, two_mul]⟩ /-- A prime `p` satisfies `p % 2 = 1` if and only if `p ≠ 2`. -/ theorem Prime.mod_two_eq_one_iff_ne_two {p : ℕ} (hp : p.Prime) : p % 2 = 1 ↔ p ≠ 2 := by refine ⟨fun h hf => ?_, hp.eq_two_or_odd.resolve_left⟩ rw [hf] at h simp at h theorem coprime_of_dvd' {m n : ℕ} (H : ∀ k, Prime k → k ∣ m → k ∣ n → k ∣ 1) : Coprime m n := coprime_of_dvd fun k kp km kn => not_le_of_gt kp.one_lt <| le_of_dvd Nat.one_pos <| H k kp km kn theorem Prime.dvd_iff_not_coprime {p n : ℕ} (pp : Prime p) : p ∣ n ↔ ¬Coprime p n := iff_not_comm.2 pp.coprime_iff_not_dvd theorem Prime.not_coprime_iff_dvd {m n : ℕ} : ¬Coprime m n ↔ ∃ p, Prime p ∧ p ∣ m ∧ p ∣ n := by apply Iff.intro · intro h exact ⟨minFac (gcd m n), minFac_prime h, (minFac_dvd (gcd m n)).trans (gcd_dvd_left m n), (minFac_dvd (gcd m n)).trans (gcd_dvd_right m n)⟩ · intro h obtain ⟨p, hp⟩ := h apply Nat.not_coprime_of_dvd_of_dvd (Prime.one_lt hp.1) hp.2.1 hp.2.2 /-- If `0 < m < minFac n`, then `n` and `m` are coprime. -/ lemma coprime_of_lt_minFac {n m : ℕ} (h₀ : m ≠ 0) (h : m < minFac n) : Coprime n m := by rw [← not_not (a := n.Coprime m), Prime.not_coprime_iff_dvd] push_neg exact fun p hp hn hm ↦ ((le_of_dvd (by cutsat) hm).trans_lt <| h.trans_le <| minFac_le_of_dvd hp.two_le hn).false /-- If `0 < m < minFac n`, then `n` and `m` have gcd equal to `1`. -/ lemma gcd_eq_one_of_lt_minFac {n m : ℕ} (h₀ : m ≠ 0) (h : m < minFac n) : n.gcd m = 1 := coprime_iff_gcd_eq_one.mp <| coprime_of_lt_minFac h₀ h theorem Prime.not_dvd_mul {p m n : ℕ} (pp : Prime p) (Hm : ¬p ∣ m) (Hn : ¬p ∣ n) : ¬p ∣ m * n := mt pp.dvd_mul.1 <| by simp [Hm, Hn] @[simp] lemma coprime_two_left : Coprime 2 n ↔ Odd n := by rw [prime_two.coprime_iff_not_dvd, ← not_even_iff_odd, even_iff_two_dvd] @[simp] lemma coprime_two_right : n.Coprime 2 ↔ Odd n := coprime_comm.trans coprime_two_left protected alias ⟨Coprime.odd_of_left, _root_.Odd.coprime_two_left⟩ := coprime_two_left protected alias ⟨Coprime.odd_of_right, _root_.Odd.coprime_two_right⟩ := coprime_two_right theorem Prime.dvd_of_dvd_pow {p m n : ℕ} (pp : Prime p) (h : p ∣ m ^ n) : p ∣ m := pp.prime.dvd_of_dvd_pow h theorem Prime.not_prime_pow' {x n : ℕ} (hn : n ≠ 1) : ¬(x ^ n).Prime := not_irreducible_pow hn theorem Prime.not_prime_pow {x n : ℕ} (hn : 2 ≤ n) : ¬(x ^ n).Prime := not_prime_pow' ((two_le_iff _).mp hn).2 theorem Prime.eq_one_of_pow {x n : ℕ} (h : (x ^ n).Prime) : n = 1 := not_imp_not.mp Prime.not_prime_pow' h theorem Prime.pow_eq_iff {p a k : ℕ} (hp : p.Prime) : a ^ k = p ↔ a = p ∧ k = 1 := by refine ⟨fun h => ?_, fun h => by rw [h.1, h.2, pow_one]⟩ rw [← h] at hp rw [← h, hp.eq_one_of_pow, eq_self_iff_true, _root_.and_true, pow_one] theorem Prime.mul_eq_prime_sq_iff {x y p : ℕ} (hp : p.Prime) (hx : x ≠ 1) (hy : y ≠ 1) : x * y = p ^ 2 ↔ x = p ∧ y = p := by refine ⟨fun h => ?_, fun ⟨h₁, h₂⟩ => h₁.symm ▸ h₂.symm ▸ (sq _).symm⟩ have pdvdxy : p ∣ x * y := by rw [h]; simp [sq] -- Could be `wlog := hp.dvd_mul.1 pdvdxy using x y`, but that imports more than we want. suffices ∀ x' y' : ℕ, x' ≠ 1 → y' ≠ 1 → x' * y' = p ^ 2 → p ∣ x' → x' = p ∧ y' = p by obtain hx | hy := hp.dvd_mul.1 pdvdxy <;> [skip; rw [And.comm]] <;> [skip; rw [mul_comm] at h pdvdxy] <;> apply this <;> assumption rintro x y hx hy h ⟨a, ha⟩ have : a ∣ p := ⟨y, by rwa [ha, sq, mul_assoc, mul_right_inj' hp.ne_zero, eq_comm] at h⟩ obtain ha1 | hap := (Nat.dvd_prime hp).mp ‹a ∣ p› · subst ha1 rw [mul_one] at ha subst ha simp only [sq, mul_right_inj' hp.ne_zero] at h subst h exact ⟨rfl, rfl⟩ · refine (hy ?_).elim subst hap subst ha rw [sq, Nat.mul_eq_left (Nat.mul_ne_zero hp.ne_zero hp.ne_zero)] at h exact h theorem Prime.coprime_pow_of_not_dvd {p m a : ℕ} (pp : Prime p) (h : ¬p ∣ a) : Coprime a (p ^ m) := (pp.coprime_iff_not_dvd.2 h).symm.pow_right _ theorem coprime_primes {p q : ℕ} (pp : Prime p) (pq : Prime q) : Coprime p q ↔ p ≠ q := pp.coprime_iff_not_dvd.trans <| not_congr <| dvd_prime_two_le pq pp.two_le theorem coprime_pow_primes {p q : ℕ} (n m : ℕ) (pp : Prime p) (pq : Prime q) (h : p ≠ q) : Coprime (p ^ n) (q ^ m) := ((coprime_primes pp pq).2 h).pow _ _ theorem coprime_or_dvd_of_prime {p} (pp : Prime p) (i : ℕ) : Coprime p i ∨ p ∣ i := by rw [pp.dvd_iff_not_coprime]; apply em theorem coprime_of_lt_prime {n p} (ne_zero : n ≠ 0) (hlt : n < p) (pp : Prime p) : Coprime p n := (coprime_or_dvd_of_prime pp n).resolve_right fun h => Nat.lt_le_asymm hlt (le_of_dvd (Nat.pos_of_ne_zero ne_zero) h) theorem eq_or_coprime_of_le_prime {n p} (ne_zero : n ≠ 0) (hle : n ≤ p) (pp : Prime p) : p = n ∨ Coprime p n := hle.eq_or_lt.imp Eq.symm fun h => coprime_of_lt_prime ne_zero h pp theorem prime_eq_prime_of_dvd_pow {m p q} (pp : Prime p) (pq : Prime q) (h : p ∣ q ^ m) : p = q := (prime_dvd_prime_iff_eq pp pq).mp (pp.dvd_of_dvd_pow h) theorem dvd_prime_pow {p : ℕ} (pp : Prime p) {m i : ℕ} : i ∣ p ^ m ↔ ∃ k ≤ m, i = p ^ k := by simp_rw [_root_.dvd_prime_pow (prime_iff.mp pp) m, associated_eq_eq] theorem Prime.dvd_mul_of_dvd_ne {p1 p2 n : ℕ} (h_neq : p1 ≠ p2) (pp1 : Prime p1) (pp2 : Prime p2) (h1 : p1 ∣ n) (h2 : p2 ∣ n) : p1 * p2 ∣ n := Coprime.mul_dvd_of_dvd_of_dvd ((coprime_primes pp1 pp2).mpr h_neq) h1 h2 /-- If `p` is prime, and `a` doesn't divide `p^k`, but `a` does divide `p^(k+1)` then `a = p^(k+1)`. -/ theorem eq_prime_pow_of_dvd_least_prime_pow {a p k : ℕ} (pp : Prime p) (h₁ : ¬a ∣ p ^ k) (h₂ : a ∣ p ^ (k + 1)) : a = p ^ (k + 1) := by obtain ⟨l, ⟨h, rfl⟩⟩ := (dvd_prime_pow pp).1 h₂ congr exact le_antisymm h (not_le.1 ((not_congr (pow_dvd_pow_iff_le_right (Prime.one_lt pp))).1 h₁)) theorem ne_one_iff_exists_prime_dvd : ∀ {n}, n ≠ 1 ↔ ∃ p : ℕ, p.Prime ∧ p ∣ n | 0 => by simpa using Exists.intro 2 Nat.prime_two | 1 => by simp [Nat.not_prime_one] | n + 2 => by let a := n + 2 have ha : a ≠ 1 := Nat.succ_succ_ne_one n simp only [a, true_iff, Ne, not_false_iff, ha] exact ⟨a.minFac, Nat.minFac_prime ha, a.minFac_dvd⟩ theorem eq_one_iff_not_exists_prime_dvd {n : ℕ} : n = 1 ↔ ∀ p : ℕ, p.Prime → ¬p ∣ n := by simpa using not_iff_not.mpr ne_one_iff_exists_prime_dvd theorem succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : Prime p) {m n k l : ℕ} (hpm : p ^ k ∣ m) (hpn : p ^ l ∣ n) (hpmn : p ^ (k + l + 1) ∣ m * n) : p ^ (k + 1) ∣ m ∨ p ^ (l + 1) ∣ n := by have hpd : p ^ (k + l) * p ∣ m * n := by let hpmn' : p ^ (succ (k + l)) ∣ m * n := hpmn rwa [pow_succ'] at hpmn' have hpd2 : p ∣ m * n / p ^ (k + l) := dvd_div_of_mul_dvd hpd have hpd3 : p ∣ m * n / (p ^ k * p ^ l) := by simpa [pow_add] using hpd2 have hpd4 : p ∣ m / p ^ k * (n / p ^ l) := by simpa [Nat.div_mul_div_comm hpm hpn] using hpd3 have hpd5 : p ∣ m / p ^ k ∨ p ∣ n / p ^ l := (Prime.dvd_mul p_prime).1 hpd4 suffices p ^ k * p ∣ m ∨ p ^ l * p ∣ n by rwa [_root_.pow_succ, _root_.pow_succ] exact hpd5.elim (fun h : p ∣ m / p ^ k => Or.inl <| mul_dvd_of_dvd_div hpm h) fun h : p ∣ n / p ^ l => Or.inr <| mul_dvd_of_dvd_div hpn h end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Prime/Defs.lean
import Mathlib.Algebra.Group.Nat.Units import Mathlib.Algebra.GroupWithZero.Nat import Mathlib.Algebra.Prime.Defs import Mathlib.Data.Nat.Sqrt import Mathlib.Order.Basic /-! # Prime numbers This file deals with prime numbers: natural numbers `p ≥ 2` whose only divisors are `p` and `1`. ## Important declarations - `Nat.Prime`: the predicate that expresses that a natural number `p` is prime - `Nat.Primes`: the subtype of natural numbers that are prime - `Nat.minFac n`: the minimal prime factor of a natural number `n ≠ 1` - `Nat.prime_iff`: `Nat.Prime` coincides with the general definition of `Prime` - `Nat.irreducible_iff_nat_prime`: a non-unit natural number is only divisible by `1` iff it is prime -/ assert_not_exists Ring namespace Nat variable {n : ℕ} /-- `Nat.Prime p` means that `p` is a prime number, that is, a natural number at least 2 whose only divisors are `p` and `1`. The theorem `Nat.prime_def` witnesses this description of a prime number. -/ @[pp_nodot] def Prime (p : ℕ) := Irreducible p theorem irreducible_iff_nat_prime (a : ℕ) : Irreducible a ↔ Nat.Prime a := Iff.rfl theorem not_prime_zero : ¬ Prime 0 | h => h.ne_zero rfl /-- A copy of `not_prime_zero` stated in a way that works for `aesop`. See https://github.com/leanprover-community/aesop/issues/197 for an explanation. -/ @[aesop safe destruct] theorem prime_zero_false : Prime 0 → False := not_prime_zero theorem not_prime_one : ¬ Prime 1 | h => h.ne_one rfl /-- A copy of `not_prime_one` stated in a way that works for `aesop`. See https://github.com/leanprover-community/aesop/issues/197 for an explanation. -/ @[aesop safe destruct] theorem prime_one_false : Prime 1 → False := not_prime_one theorem Prime.ne_zero {n : ℕ} (h : Prime n) : n ≠ 0 := Irreducible.ne_zero h theorem Prime.pos {p : ℕ} (pp : Prime p) : 0 < p := Nat.pos_of_ne_zero pp.ne_zero theorem Prime.two_le : ∀ {p : ℕ}, Prime p → 2 ≤ p | 0, h => (not_prime_zero h).elim | 1, h => (not_prime_one h).elim | _ + 2, _ => le_add_left 2 _ theorem Prime.one_lt {p : ℕ} : Prime p → 1 < p := Prime.two_le lemma Prime.one_le {p : ℕ} (hp : p.Prime) : 1 ≤ p := hp.one_lt.le instance Prime.one_lt' (p : ℕ) [hp : Fact p.Prime] : Fact (1 < p) := ⟨hp.1.one_lt⟩ theorem Prime.ne_one {p : ℕ} (hp : p.Prime) : p ≠ 1 := hp.one_lt.ne' theorem Prime.eq_one_or_self_of_dvd {p : ℕ} (pp : p.Prime) (m : ℕ) (hm : m ∣ p) : m = 1 ∨ m = p := by obtain ⟨n, hn⟩ := hm have := pp.isUnit_or_isUnit hn rw [Nat.isUnit_iff, Nat.isUnit_iff] at this apply Or.imp_right _ this rintro rfl rw [hn, mul_one] @[inherit_doc Nat.Prime] theorem prime_def {p : ℕ} : Prime p ↔ 2 ≤ p ∧ ∀ m, m ∣ p → m = 1 ∨ m = p := by refine ⟨fun h => ⟨h.two_le, h.eq_one_or_self_of_dvd⟩, fun h => ?_⟩ have h1 := Nat.one_lt_two.trans_le h.1 refine ⟨mt Nat.isUnit_iff.mp h1.ne', ?_⟩ rintro a b rfl simp only [Nat.isUnit_iff] refine (h.2 a <| dvd_mul_right ..).imp_right fun hab ↦ ?_ rw [← mul_right_inj' (Nat.ne_zero_of_lt h1), ← hab, ← hab, mul_one] theorem prime_def_lt {p : ℕ} : Prime p ↔ 2 ≤ p ∧ ∀ m < p, m ∣ p → m = 1 := prime_def.trans <| and_congr_right fun p2 => forall_congr' fun _ => ⟨fun h l d => (h d).resolve_right (ne_of_lt l), fun h d => (le_of_dvd (le_of_succ_le p2) d).lt_or_eq_dec.imp_left fun l => h l d⟩ theorem prime_def_lt' {p : ℕ} : Prime p ↔ 2 ≤ p ∧ ∀ m, 2 ≤ m → m < p → ¬m ∣ p := prime_def_lt.trans <| and_congr_right fun p2 => forall_congr' fun m => ⟨fun h m2 l d => not_lt_of_ge m2 ((h l d).symm ▸ by decide), fun h l d => by rcases m with (_ | _ | m) · omega · rfl · exact (h (le_add_left 2 m) l).elim d⟩ theorem prime_def_le_sqrt {p : ℕ} : Prime p ↔ 2 ≤ p ∧ ∀ m, 2 ≤ m → m ≤ sqrt p → ¬m ∣ p := prime_def_lt'.trans <| and_congr_right fun p2 => ⟨fun a m m2 l => a m m2 <| lt_of_le_of_lt l <| sqrt_lt_self p2, fun a m m2 l mdvd@⟨k, e⟩ => by rcases le_sqrt_of_eq_mul e with hm | hk · exact a m m2 hm mdvd · rw [mul_comm] at e exact a k (Nat.lt_of_mul_lt_mul_right (a := m) (by rwa [one_mul, ← e])) hk ⟨m, e⟩⟩ theorem prime_iff_not_exists_mul_eq {p : ℕ} : p.Prime ↔ 2 ≤ p ∧ ¬ ∃ m n, m < p ∧ n < p ∧ m * n = p := by push_neg simp_rw [prime_def_lt, dvd_def, exists_imp] refine and_congr_right fun hp ↦ forall_congr' fun m ↦ (forall_congr' fun h ↦ ?_).trans forall_comm simp_rw [Ne, forall_comm (β := _ = _), eq_comm, imp_false, not_lt] refine forall₂_congr fun n hp ↦ ⟨by simp_all, fun hpn ↦ ?_⟩ have := mul_ne_zero_iff.mp (hp ▸ show p ≠ 0 by cutsat) exact (Nat.mul_eq_right (by cutsat)).mp (hp.symm.trans (hpn.antisymm (hp ▸ Nat.le_mul_of_pos_left _ (by cutsat)))) theorem prime_of_coprime (n : ℕ) (h1 : 1 < n) (h : ∀ m < n, m ≠ 0 → n.Coprime m) : Prime n := by refine prime_def_lt.mpr ⟨h1, fun m mlt mdvd => ?_⟩ have hm : m ≠ 0 := by rintro rfl rw [zero_dvd_iff] at mdvd exact mlt.ne' mdvd exact (h m mlt hm).symm.eq_one_of_dvd mdvd /-- This instance is set up to work in the kernel (`by decide`) for small values. Below (`decidablePrime'`) we will define a faster variant to be used by the compiler (e.g. in `#eval` or `by native_decide`). If you need to prove that a particular number is prime, in any case you should not use `by decide`, but rather `by norm_num`, which is much faster. -/ instance decidablePrime (p : ℕ) : Decidable (Prime p) := decidable_of_iff' _ prime_def_lt' theorem prime_two : Prime 2 := by decide theorem prime_three : Prime 3 := by decide theorem prime_five : Prime 5 := by decide theorem prime_seven : Prime 7 := by decide theorem prime_eleven : Prime 11 := by decide theorem dvd_prime {p m : ℕ} (pp : Prime p) : m ∣ p ↔ m = 1 ∨ m = p := ⟨fun d => pp.eq_one_or_self_of_dvd m d, fun h => h.elim (fun e => e.symm ▸ one_dvd _) fun e => e.symm ▸ dvd_rfl⟩ theorem dvd_prime_two_le {p m : ℕ} (pp : Prime p) (H : 2 ≤ m) : m ∣ p ↔ m = p := (dvd_prime pp).trans <| or_iff_right_of_imp <| Not.elim <| ne_of_gt H theorem prime_dvd_prime_iff_eq {p q : ℕ} (pp : p.Prime) (qp : q.Prime) : p ∣ q ↔ p = q := dvd_prime_two_le qp (Prime.two_le pp) theorem Prime.not_dvd_one {p : ℕ} (pp : Prime p) : ¬p ∣ 1 := Irreducible.not_dvd_one pp section MinFac theorem minFac_lemma (n k : ℕ) (h : ¬n < k * k) : sqrt n - k < sqrt n + 2 - k := (Nat.sub_lt_sub_right <| le_sqrt.2 <| le_of_not_gt h) <| Nat.lt_add_of_pos_right (by decide) /-- If `n < k * k`, then `minFacAux n k = n`, if `k | n`, then `minFacAux n k = k`. Otherwise, `minFacAux n k = minFacAux n (k+2)` using well-founded recursion. If `n` is odd and `1 < n`, then `minFacAux n 3` is the smallest prime factor of `n`. This definition is by well-founded recursion, so `rfl` or `decide` cannot be used. One can use `norm_num` to prove `Nat.prime n` for small `n`. -/ def minFacAux (n : ℕ) : ℕ → ℕ | k => if n < k * k then n else if k ∣ n then k else minFacAux n (k + 2) termination_by k => sqrt n + 2 - k decreasing_by simp_wf; apply minFac_lemma n k; assumption /-- Returns the smallest prime factor of `n ≠ 1`. -/ def minFac (n : ℕ) : ℕ := if 2 ∣ n then 2 else minFacAux n 3 @[simp] theorem minFac_zero : minFac 0 = 2 := rfl @[simp] theorem minFac_one : minFac 1 = 1 := by simp [minFac, minFacAux] @[simp] theorem minFac_two : minFac 2 = 2 := by simp [minFac] theorem minFac_eq (n : ℕ) : minFac n = if 2 ∣ n then 2 else minFacAux n 3 := rfl private def minFacProp (n k : ℕ) := 2 ≤ k ∧ k ∣ n ∧ ∀ m, 2 ≤ m → m ∣ n → k ≤ m theorem minFacAux_has_prop {n : ℕ} (n2 : 2 ≤ n) : ∀ k i, k = 2 * i + 3 → (∀ m, 2 ≤ m → m ∣ n → k ≤ m) → minFacProp n (minFacAux n k) | k => fun i e a => by rw [minFacAux] by_cases h : n < k * k · have pp : Prime n := prime_def_le_sqrt.2 ⟨n2, fun m m2 l d => not_lt_of_ge l <| lt_of_lt_of_le (sqrt_lt.2 h) (a m m2 d)⟩ simpa only [k, h] using ⟨n2, dvd_rfl, fun m m2 d => le_of_eq ((dvd_prime_two_le pp m2).1 d).symm⟩ have k2 : 2 ≤ k := by subst e apply Nat.le_add_left simp only [k, h, ↓reduceIte] by_cases dk : k ∣ n <;> simp only [k, dk, ↓reduceIte] · exact ⟨k2, dk, a⟩ · refine have := minFac_lemma n k h minFacAux_has_prop n2 (k + 2) (i + 1) (by simp [k, e, Nat.left_distrib, add_right_comm]) fun m m2 d => ?_ rcases Nat.eq_or_lt_of_le (a m m2 d) with me | ml · subst me contradiction apply (Nat.eq_or_lt_of_le ml).resolve_left intro me rw [← me, e] at d have d' : 2 * (i + 2) ∣ n := d have := a _ le_rfl (dvd_of_mul_right_dvd d') rw [e] at this exact absurd this (by contradiction) termination_by k => sqrt n + 2 - k theorem minFac_has_prop {n : ℕ} (n1 : n ≠ 1) : minFacProp n (minFac n) := by by_cases n0 : n = 0 · simp [n0, minFacProp] have n2 : 2 ≤ n := by revert n0 n1 rcases n with (_ | _ | _) <;> simp [succ_le_succ] simp only [minFac_eq] by_cases d2 : 2 ∣ n <;> simp only [d2, ↓reduceIte] · exact ⟨le_rfl, d2, fun k k2 _ => k2⟩ · refine minFacAux_has_prop n2 3 0 rfl fun m m2 d => (Nat.eq_or_lt_of_le m2).resolve_left (mt ?_ d2) exact fun e => e.symm ▸ d theorem minFac_dvd (n : ℕ) : minFac n ∣ n := if n1 : n = 1 then by simp [n1] else (minFac_has_prop n1).2.1 theorem minFac_prime {n : ℕ} (n1 : n ≠ 1) : Prime (minFac n) := let ⟨f2, fd, a⟩ := minFac_has_prop n1 prime_def_lt'.2 ⟨f2, fun m m2 l d => not_le_of_gt l (a m m2 (d.trans fd))⟩ @[simp] theorem minFac_prime_iff {n : ℕ} : Prime (minFac n) ↔ n ≠ 1 := by refine ⟨?_, minFac_prime⟩ rintro h rfl simp only [minFac_one, not_prime_one] at h theorem minFac_le_of_dvd {n : ℕ} : ∀ {m : ℕ}, 2 ≤ m → m ∣ n → minFac n ≤ m := by by_cases n1 : n = 1 · exact fun m2 _ => n1.symm ▸ le_trans (by simp) m2 · apply (minFac_has_prop n1).2.2 theorem minFac_pos (n : ℕ) : 0 < minFac n := by by_cases n1 : n = 1 · simp [n1] · exact (minFac_prime n1).pos theorem minFac_le {n : ℕ} (H : 0 < n) : minFac n ≤ n := le_of_dvd H (minFac_dvd n) theorem le_minFac {m n : ℕ} : n = 1 ∨ m ≤ minFac n ↔ ∀ p, Prime p → p ∣ n → m ≤ p := ⟨fun h p pp d => h.elim (by rintro rfl; cases pp.not_dvd_one d) fun h => le_trans h <| minFac_le_of_dvd pp.two_le d, fun H => or_iff_not_imp_left.2 fun n1 => H _ (minFac_prime n1) (minFac_dvd _)⟩ theorem le_minFac' {m n : ℕ} : n = 1 ∨ m ≤ minFac n ↔ ∀ p, 2 ≤ p → p ∣ n → m ≤ p := ⟨fun h p (pp : 1 < p) d => h.elim (by rintro rfl; cases not_le_of_gt pp (le_of_dvd (by decide) d)) fun h => le_trans h <| minFac_le_of_dvd pp d, fun H => le_minFac.2 fun p pp d => H p pp.two_le d⟩ theorem prime_def_minFac {p : ℕ} : Prime p ↔ 2 ≤ p ∧ minFac p = p := ⟨fun pp => ⟨pp.two_le, let ⟨f2, fd, _⟩ := minFac_has_prop <| ne_of_gt pp.one_lt ((dvd_prime pp).1 fd).resolve_left (ne_of_gt f2)⟩, fun ⟨p2, e⟩ => e ▸ minFac_prime (ne_of_gt p2)⟩ @[simp] theorem Prime.minFac_eq {p : ℕ} (hp : Prime p) : minFac p = p := (prime_def_minFac.1 hp).2 /-- This definition is faster in the virtual machine than `decidablePrime`, but slower in the kernel. -/ def decidablePrime' (p : ℕ) : Decidable (Prime p) := decidable_of_iff' _ prime_def_minFac @[csimp] theorem decidablePrime_csimp : @decidablePrime = @decidablePrime' := by subsingleton theorem not_prime_iff_minFac_lt {n : ℕ} (n2 : 2 ≤ n) : ¬Prime n ↔ minFac n < n := (not_congr <| prime_def_minFac.trans <| and_iff_right n2).trans <| (lt_iff_le_and_ne.trans <| and_iff_right <| minFac_le <| le_of_succ_le n2).symm theorem minFac_le_div {n : ℕ} (pos : 0 < n) (np : ¬Prime n) : minFac n ≤ n / minFac n := match minFac_dvd n with | ⟨0, h0⟩ => absurd pos <| by rw [h0, mul_zero]; decide | ⟨1, h1⟩ => by rw [mul_one] at h1 rw [prime_def_minFac, not_and_or, ← h1, eq_self_iff_true, _root_.not_true, _root_.or_false, not_le] at np rw [le_antisymm (le_of_lt_succ np) (succ_le_of_lt pos), minFac_one, Nat.div_one] | ⟨x + 2, hx⟩ => by conv_rhs => congr rw [hx] rw [Nat.mul_div_cancel_left _ (minFac_pos _)] exact minFac_le_of_dvd (le_add_left 2 x) ⟨minFac n, by rwa [mul_comm]⟩ /-- The square of the smallest prime factor of a composite number `n` is at most `n`. -/ theorem minFac_sq_le_self {n : ℕ} (w : 0 < n) (h : ¬Prime n) : minFac n ^ 2 ≤ n := have t : minFac n ≤ n / minFac n := minFac_le_div w h calc minFac n ^ 2 = minFac n * minFac n := sq (minFac n) _ ≤ n / minFac n * minFac n := Nat.mul_le_mul_right (minFac n) t _ ≤ n := div_mul_le_self n (minFac n) @[simp] theorem minFac_eq_one_iff {n : ℕ} : minFac n = 1 ↔ n = 1 := by constructor · intro h by_contra hn have := minFac_prime hn rw [h] at this exact not_prime_one this · rintro rfl simp [minFac, minFacAux] @[simp] theorem minFac_eq_two_iff (n : ℕ) : minFac n = 2 ↔ 2 ∣ n := by constructor · intro h rw [← h] exact minFac_dvd n · intro h have ub := minFac_le_of_dvd (le_refl 2) h have lb := minFac_pos n refine ub.eq_or_lt.resolve_right fun h' => ?_ suffices n.minFac = 1 by simp_all exact (le_antisymm (Nat.succ_le_of_lt lb) (Nat.lt_succ_iff.mp h')).symm theorem factors_lemma {k} : (k + 2) / minFac (k + 2) < k + 2 := div_lt_self (Nat.zero_lt_succ _) (minFac_prime (by apply Nat.ne_of_gt apply Nat.succ_lt_succ apply Nat.zero_lt_succ )).one_lt end MinFac theorem exists_prime_and_dvd {n : ℕ} (hn : n ≠ 1) : ∃ p, Prime p ∧ p ∣ n := ⟨minFac n, minFac_prime hn, minFac_dvd _⟩ theorem coprime_of_dvd {m n : ℕ} (H : ∀ k, Prime k → k ∣ m → ¬k ∣ n) : Coprime m n := by rw [coprime_iff_gcd_eq_one] by_contra g2 obtain ⟨p, hp, hpdvd⟩ := exists_prime_and_dvd g2 apply H p hp <;> apply dvd_trans hpdvd · exact gcd_dvd_left _ _ · exact gcd_dvd_right _ _ theorem Prime.coprime_iff_not_dvd {p n : ℕ} (pp : Prime p) : Coprime p n ↔ ¬p ∣ n := ⟨fun co d => pp.not_dvd_one <| co.dvd_of_dvd_mul_left (by simp [d]), fun nd => coprime_of_dvd fun _ m2 mp => ((prime_dvd_prime_iff_eq m2 pp).1 mp).symm ▸ nd⟩ theorem Prime.dvd_mul {p m n : ℕ} (pp : Prime p) : p ∣ m * n ↔ p ∣ m ∨ p ∣ n := ⟨fun H => or_iff_not_imp_left.2 fun h => (pp.coprime_iff_not_dvd.2 h).dvd_of_dvd_mul_left H, Or.rec (fun h : p ∣ m => h.mul_right _) fun h : p ∣ n => h.mul_left _⟩ alias ⟨Prime.dvd_or_dvd, _⟩ := Prime.dvd_mul theorem prime_iff {p : ℕ} : p.Prime ↔ _root_.Prime p := ⟨fun h => ⟨h.ne_zero, h.not_isUnit, fun _ _ => h.dvd_mul.mp⟩, Prime.irreducible⟩ alias ⟨Prime.prime, _root_.Prime.nat_prime⟩ := prime_iff instance instDecidablePredPrime : DecidablePred (_root_.Prime : ℕ → Prop) := fun n ↦ decidable_of_iff (Nat.Prime n) Nat.prime_iff theorem irreducible_iff_prime {p : ℕ} : Irreducible p ↔ _root_.Prime p := prime_iff instance instDecidablePredIrreducible : DecidablePred (Irreducible : ℕ → Prop) := decidablePrime /-- The type of prime numbers -/ def Primes := { p : ℕ // p.Prime } deriving DecidableEq namespace Primes instance : Repr Nat.Primes := ⟨fun p _ => repr p.val⟩ instance inhabitedPrimes : Inhabited Primes := ⟨⟨2, prime_two⟩⟩ instance coeNat : Coe Nat.Primes ℕ := ⟨Subtype.val⟩ theorem coe_nat_injective : Function.Injective ((↑) : Nat.Primes → ℕ) := Subtype.coe_injective theorem coe_nat_inj (p q : Nat.Primes) : (p : ℕ) = (q : ℕ) ↔ p = q := Subtype.ext_iff.symm end Primes instance monoid.primePow {α : Type*} [Monoid α] : Pow α Primes := ⟨fun x p => x ^ (p : ℕ)⟩ instance fact_prime_two : Fact (Prime 2) := ⟨prime_two⟩ instance fact_prime_three : Fact (Prime 3) := ⟨prime_three⟩ end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Prime/Infinite.lean
import Mathlib.Data.Nat.Factorial.Basic import Mathlib.Data.Nat.Prime.Defs import Mathlib.Order.Bounds.Basic /-! ## Notable Theorems - `Nat.exists_infinite_primes`: Euclid's theorem that there exist infinitely many prime numbers. This also appears as `Nat.not_bddAbove_setOf_prime` and `Nat.infinite_setOf_prime` (the latter in `Data.Nat.PrimeFin`). -/ open Bool Subtype open Nat namespace Nat section Infinite /-- Euclid's theorem on the **infinitude of primes**. Here given in the form: for every `n`, there exists a prime number `p ≥ n`. -/ theorem exists_infinite_primes (n : ℕ) : ∃ p, n ≤ p ∧ Prime p := let p := minFac (n ! + 1) have f1 : n ! + 1 ≠ 1 := ne_of_gt <| succ_lt_succ <| factorial_pos _ have pp : Prime p := minFac_prime f1 have np : n ≤ p := le_of_not_ge fun h => have h₁ : p ∣ n ! := dvd_factorial (minFac_pos _) h have h₂ : p ∣ 1 := (Nat.dvd_add_iff_right h₁).2 (minFac_dvd _) pp.not_dvd_one h₂ ⟨p, np, pp⟩ /-- A version of `Nat.exists_infinite_primes` using the `BddAbove` predicate. -/ theorem not_bddAbove_setOf_prime : ¬BddAbove { p | Prime p } := by rw [not_bddAbove_iff] intro n obtain ⟨p, hi, hp⟩ := exists_infinite_primes n.succ exact ⟨p, hp, hi⟩ end Infinite end Nat
.lake/packages/mathlib/Mathlib/Data/Nat/Prime/Factorial.lean
import Mathlib.Data.Nat.Factorial.Basic import Mathlib.Data.Nat.Prime.Basic /-! # Prime natural numbers and the factorial operator -/ open Bool Subtype open Nat namespace Nat theorem Prime.dvd_factorial : ∀ {n p : ℕ} (_ : Prime p), p ∣ n ! ↔ p ≤ n | 0, _, hp => iff_of_false hp.not_dvd_one (not_le_of_gt hp.pos) | n + 1, p, hp => by rw [factorial_succ, hp.dvd_mul, Prime.dvd_factorial hp] exact ⟨fun h => h.elim (le_of_dvd (succ_pos _)) le_succ_of_le, fun h => (_root_.lt_or_eq_of_le h).elim (Or.inr ∘ le_of_lt_succ) fun h => Or.inl <| by rw [h]⟩ theorem coprime_factorial_iff {m n : ℕ} (hm : m ≠ 1) : m.Coprime n ! ↔ n < m.minFac := by rw [← not_le, iff_not_comm, Nat.Prime.not_coprime_iff_dvd] constructor · intro h exact ⟨m.minFac, minFac_prime hm, minFac_dvd m, Nat.dvd_factorial (minFac_pos m) h⟩ · rintro ⟨p, hp, hdvd, hdvd'⟩ exact le_trans (minFac_le_of_dvd hp.two_le hdvd) (hp.dvd_factorial.mp hdvd') lemma Prime.coprime_factorial_of_lt {p n : ℕ} (hp : p.Prime) (hn : n < p) : p.Coprime n.factorial := by rwa [hp.coprime_iff_not_dvd, hp.dvd_factorial, not_le] lemma Prime.coprime_descFactorial_of_lt_of_le {p n k : ℕ} (hp : p.Prime) (hn : n < p) (hk : k ≤ n) : p.Coprime (n.descFactorial k) := by rw [Nat.descFactorial_eq_div hk] refine (hp.coprime_factorial_of_lt hn).coprime_div_right ?_ simp [Nat.factorial_dvd_factorial] end Nat
.lake/packages/mathlib/Mathlib/Data/Stream/Init.lean
import Mathlib.Data.Stream.Defs import Mathlib.Logic.Function.Basic import Mathlib.Data.Nat.Basic import Mathlib.Tactic.Common /-! # Streams a.k.a. infinite lists a.k.a. infinite sequences -/ open Nat Function Option namespace Stream' universe u v w variable {α : Type u} {β : Type v} {δ : Type w} variable (m n : ℕ) (x y : List α) (a b : Stream' α) instance [Inhabited α] : Inhabited (Stream' α) := ⟨Stream'.const default⟩ @[simp] protected theorem eta (s : Stream' α) : head s :: tail s = s := funext fun i => by cases i <;> rfl /-- Alias for `Stream'.eta` to match `List` API. -/ alias cons_head_tail := Stream'.eta @[ext] protected theorem ext {s₁ s₂ : Stream' α} : (∀ n, get s₁ n = get s₂ n) → s₁ = s₂ := fun h => funext h @[simp] theorem get_zero_cons (a : α) (s : Stream' α) : get (a::s) 0 = a := rfl @[simp] theorem head_cons (a : α) (s : Stream' α) : head (a::s) = a := rfl @[simp] theorem tail_cons (a : α) (s : Stream' α) : tail (a::s) = s := rfl @[simp] theorem get_drop (n m : ℕ) (s : Stream' α) : get (drop m s) n = get s (m + n) := by rw [Nat.add_comm] rfl theorem tail_eq_drop (s : Stream' α) : tail s = drop 1 s := rfl @[simp] theorem drop_drop (n m : ℕ) (s : Stream' α) : drop n (drop m s) = drop (m + n) s := by ext; simp [Nat.add_assoc] @[simp] theorem get_tail {n : ℕ} {s : Stream' α} : s.tail.get n = s.get (n + 1) := rfl @[simp] theorem tail_drop' {i : ℕ} {s : Stream' α} : tail (drop i s) = s.drop (i + 1) := by ext; simp [Nat.add_comm, Nat.add_left_comm] @[simp] theorem drop_tail' {i : ℕ} {s : Stream' α} : drop i (tail s) = s.drop (i + 1) := rfl theorem tail_drop (n : ℕ) (s : Stream' α) : tail (drop n s) = drop n (tail s) := by simp theorem get_succ (n : ℕ) (s : Stream' α) : get s (succ n) = get (tail s) n := rfl @[simp] theorem get_succ_cons (n : ℕ) (s : Stream' α) (x : α) : get (x :: s) n.succ = get s n := rfl @[simp] lemma get_cons_append_zero {a : α} {x : List α} {s : Stream' α} : (a :: x ++ₛ s).get 0 = a := rfl @[simp] lemma append_eq_cons {a : α} {as : Stream' α} : [a] ++ₛ as = a :: as := rfl @[simp] theorem drop_zero {s : Stream' α} : s.drop 0 = s := rfl theorem drop_succ (n : ℕ) (s : Stream' α) : drop (succ n) s = drop n (tail s) := rfl theorem head_drop (a : Stream' α) (n : ℕ) : (a.drop n).head = a.get n := by simp theorem cons_injective2 : Function.Injective2 (cons : α → Stream' α → Stream' α) := fun x y s t h => ⟨by rw [← get_zero_cons x s, h, get_zero_cons], Stream'.ext fun n => by rw [← get_succ_cons n _ x, h, get_succ_cons]⟩ theorem cons_injective_left (s : Stream' α) : Function.Injective fun x => cons x s := cons_injective2.left _ theorem cons_injective_right (x : α) : Function.Injective (cons x) := cons_injective2.right _ theorem all_def (p : α → Prop) (s : Stream' α) : All p s = ∀ n, p (get s n) := rfl theorem any_def (p : α → Prop) (s : Stream' α) : Any p s = ∃ n, p (get s n) := rfl @[simp] theorem mem_cons (a : α) (s : Stream' α) : a ∈ a::s := Exists.intro 0 rfl theorem mem_cons_of_mem {a : α} {s : Stream' α} (b : α) : a ∈ s → a ∈ b::s := fun ⟨n, h⟩ => Exists.intro (succ n) (by rw [get_succ, tail_cons, h]) theorem eq_or_mem_of_mem_cons {a b : α} {s : Stream' α} : (a ∈ b::s) → a = b ∨ a ∈ s := fun ⟨n, h⟩ => by rcases n with - | n' · left exact h · right rw [get_succ, tail_cons] at h exact ⟨n', h⟩ theorem mem_of_get_eq {n : ℕ} {s : Stream' α} {a : α} : a = get s n → a ∈ s := fun h => Exists.intro n h theorem mem_iff_exists_get_eq {s : Stream' α} {a : α} : a ∈ s ↔ ∃ n, a = s.get n where mp := by simp [Membership.mem, any_def] mpr h := mem_of_get_eq h.choose_spec section Map variable (f : α → β) theorem drop_map (n : ℕ) (s : Stream' α) : drop n (map f s) = map f (drop n s) := Stream'.ext fun _ => rfl @[simp] theorem get_map (n : ℕ) (s : Stream' α) : get (map f s) n = f (get s n) := rfl theorem tail_map (s : Stream' α) : tail (map f s) = map f (tail s) := rfl @[simp] theorem head_map (s : Stream' α) : head (map f s) = f (head s) := rfl theorem map_eq (s : Stream' α) : map f s = f (head s)::map f (tail s) := by rw [← Stream'.eta (map f s), tail_map, head_map] theorem map_cons (a : α) (s : Stream' α) : map f (a::s) = f a::map f s := by rw [← Stream'.eta (map f (a::s)), map_eq]; rfl @[simp] theorem map_id (s : Stream' α) : map id s = s := rfl @[simp] theorem map_map (g : β → δ) (f : α → β) (s : Stream' α) : map g (map f s) = map (g ∘ f) s := rfl @[simp] theorem map_tail (s : Stream' α) : map f (tail s) = tail (map f s) := rfl theorem mem_map {a : α} {s : Stream' α} : a ∈ s → f a ∈ map f s := fun ⟨n, h⟩ => Exists.intro n (by rw [get_map, h]) theorem exists_of_mem_map {f} {b : β} {s : Stream' α} : b ∈ map f s → ∃ a, a ∈ s ∧ f a = b := fun ⟨n, h⟩ => ⟨get s n, ⟨n, rfl⟩, h.symm⟩ end Map section Zip variable (f : α → β → δ) theorem drop_zip (n : ℕ) (s₁ : Stream' α) (s₂ : Stream' β) : drop n (zip f s₁ s₂) = zip f (drop n s₁) (drop n s₂) := Stream'.ext fun _ => rfl @[simp] theorem get_zip (n : ℕ) (s₁ : Stream' α) (s₂ : Stream' β) : get (zip f s₁ s₂) n = f (get s₁ n) (get s₂ n) := rfl theorem head_zip (s₁ : Stream' α) (s₂ : Stream' β) : head (zip f s₁ s₂) = f (head s₁) (head s₂) := rfl theorem tail_zip (s₁ : Stream' α) (s₂ : Stream' β) : tail (zip f s₁ s₂) = zip f (tail s₁) (tail s₂) := rfl theorem zip_eq (s₁ : Stream' α) (s₂ : Stream' β) : zip f s₁ s₂ = f (head s₁) (head s₂)::zip f (tail s₁) (tail s₂) := by rw [← Stream'.eta (zip f s₁ s₂)]; rfl @[simp] theorem get_enum (s : Stream' α) (n : ℕ) : get (enum s) n = (n, s.get n) := rfl theorem enum_eq_zip (s : Stream' α) : enum s = zip Prod.mk nats s := rfl end Zip @[simp] theorem mem_const (a : α) : a ∈ const a := Exists.intro 0 rfl theorem const_eq (a : α) : const a = a::const a := by apply Stream'.ext; intro n cases n <;> rfl @[simp] theorem tail_const (a : α) : tail (const a) = const a := suffices tail (a::const a) = const a by rwa [← const_eq] at this rfl @[simp] theorem map_const (f : α → β) (a : α) : map f (const a) = const (f a) := rfl @[simp] theorem get_const (n : ℕ) (a : α) : get (const a) n = a := rfl @[simp] theorem drop_const (n : ℕ) (a : α) : drop n (const a) = const a := Stream'.ext fun _ => rfl @[simp] theorem head_iterate (f : α → α) (a : α) : head (iterate f a) = a := rfl theorem get_succ_iterate' (n : ℕ) (f : α → α) (a : α) : get (iterate f a) (succ n) = f (get (iterate f a) n) := rfl theorem tail_iterate (f : α → α) (a : α) : tail (iterate f a) = iterate f (f a) := by ext n rw [get_tail] induction n with | zero => rfl | succ n ih => rw [get_succ_iterate', ih, get_succ_iterate'] theorem iterate_eq (f : α → α) (a : α) : iterate f a = a::iterate f (f a) := by rw [← Stream'.eta (iterate f a)] rw [tail_iterate]; rfl @[simp] theorem get_zero_iterate (f : α → α) (a : α) : get (iterate f a) 0 = a := rfl theorem get_succ_iterate (n : ℕ) (f : α → α) (a : α) : get (iterate f a) (succ n) = get (iterate f (f a)) n := by rw [get_succ, tail_iterate] section Bisim variable (R : Stream' α → Stream' α → Prop) /-- equivalence relation -/ local infixl:50 " ~ " => R /-- Streams `s₁` and `s₂` are defined to be bisimulations if their heads are equal and tails are bisimulations. -/ def IsBisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → head s₁ = head s₂ ∧ tail s₁ ~ tail s₂ theorem get_of_bisim (bisim : IsBisimulation R) {s₁ s₂} : ∀ n, s₁ ~ s₂ → get s₁ n = get s₂ n ∧ drop (n + 1) s₁ ~ drop (n + 1) s₂ | 0, h => bisim h | n + 1, h => match bisim h with | ⟨_, trel⟩ => get_of_bisim bisim n trel -- If two streams are bisimilar, then they are equal theorem eq_of_bisim (bisim : IsBisimulation R) {s₁ s₂} : s₁ ~ s₂ → s₁ = s₂ := fun r => Stream'.ext fun n => And.left (get_of_bisim R bisim n r) end Bisim theorem bisim_simple (s₁ s₂ : Stream' α) : head s₁ = head s₂ → s₁ = tail s₁ → s₂ = tail s₂ → s₁ = s₂ := fun hh ht₁ ht₂ => eq_of_bisim (fun s₁ s₂ => head s₁ = head s₂ ∧ s₁ = tail s₁ ∧ s₂ = tail s₂) (fun s₁ s₂ ⟨h₁, h₂, h₃⟩ => by grind) (And.intro hh (And.intro ht₁ ht₂)) theorem coinduction {s₁ s₂ : Stream' α} : head s₁ = head s₂ → (∀ (β : Type u) (fr : Stream' α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) → s₁ = s₂ := fun hh ht => eq_of_bisim (fun s₁ s₂ => head s₁ = head s₂ ∧ ∀ (β : Type u) (fr : Stream' α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) (fun s₁ s₂ h => have h₁ : head s₁ = head s₂ := And.left h have h₂ : head (tail s₁) = head (tail s₂) := And.right h α (@head α) h₁ have h₃ : ∀ (β : Type u) (fr : Stream' α → β), fr (tail s₁) = fr (tail s₂) → fr (tail (tail s₁)) = fr (tail (tail s₂)) := fun β fr => And.right h β fun s => fr (tail s) And.intro h₁ (And.intro h₂ h₃)) (And.intro hh ht) @[simp] theorem iterate_id (a : α) : iterate id a = const a := coinduction rfl fun β fr ch => by rw [tail_iterate, tail_const]; exact ch theorem map_iterate (f : α → α) (a : α) : iterate f (f a) = map f (iterate f a) := by funext n induction n with | zero => rfl | succ n ih => unfold map iterate get rw [map, get] at ih rw [iterate] exact congrArg f ih section Corec theorem corec_def (f : α → β) (g : α → α) (a : α) : corec f g a = map f (iterate g a) := rfl theorem corec_eq (f : α → β) (g : α → α) (a : α) : corec f g a = f a :: corec f g (g a) := by rw [corec_def, map_eq, head_iterate, tail_iterate]; rfl theorem corec_id_id_eq_const (a : α) : corec id id a = const a := by rw [corec_def, map_id, iterate_id] theorem corec_id_f_eq_iterate (f : α → α) (a : α) : corec id f a = iterate f a := rfl end Corec section Corec' theorem corec'_eq (f : α → β × α) (a : α) : corec' f a = (f a).1 :: corec' f (f a).2 := corec_eq _ _ _ end Corec' theorem unfolds_eq (g : α → β) (f : α → α) (a : α) : unfolds g f a = g a :: unfolds g f (f a) := by unfold unfolds; rw [corec_eq] theorem get_unfolds_head_tail (n : ℕ) (s : Stream' α) : get (unfolds head tail s) n = get s n := by induction n generalizing s with | zero => rfl | succ n ih => rw [get_succ, get_succ, unfolds_eq, tail_cons, ih] theorem unfolds_head_eq : ∀ s : Stream' α, unfolds head tail s = s := fun s => Stream'.ext fun n => get_unfolds_head_tail n s theorem interleave_eq (s₁ s₂ : Stream' α) : s₁ ⋈ s₂ = head s₁::head s₂::(tail s₁ ⋈ tail s₂) := by let t := tail s₁ ⋈ tail s₂ change s₁ ⋈ s₂ = head s₁::head s₂::t unfold interleave; unfold corecOn; rw [corec_eq]; dsimp; rw [corec_eq]; rfl theorem tail_interleave (s₁ s₂ : Stream' α) : tail (s₁ ⋈ s₂) = s₂ ⋈ tail s₁ := by unfold interleave corecOn; rw [corec_eq]; rfl theorem interleave_tail_tail (s₁ s₂ : Stream' α) : tail s₁ ⋈ tail s₂ = tail (tail (s₁ ⋈ s₂)) := by rw [interleave_eq s₁ s₂]; rfl theorem get_interleave_left : ∀ (n : ℕ) (s₁ s₂ : Stream' α), get (s₁ ⋈ s₂) (2 * n) = get s₁ n | 0, _, _ => rfl | n + 1, s₁, s₂ => by change get (s₁ ⋈ s₂) (succ (succ (2 * n))) = get s₁ (succ n) rw [get_succ, get_succ, interleave_eq, tail_cons, tail_cons] rw [get_interleave_left n (tail s₁) (tail s₂)] rfl theorem get_interleave_right : ∀ (n : ℕ) (s₁ s₂ : Stream' α), get (s₁ ⋈ s₂) (2 * n + 1) = get s₂ n | 0, _, _ => rfl | n + 1, s₁, s₂ => by change get (s₁ ⋈ s₂) (succ (succ (2 * n + 1))) = get s₂ (succ n) rw [get_succ, get_succ, interleave_eq, tail_cons, tail_cons, get_interleave_right n (tail s₁) (tail s₂)] rfl theorem mem_interleave_left {a : α} {s₁ : Stream' α} (s₂ : Stream' α) : a ∈ s₁ → a ∈ s₁ ⋈ s₂ := fun ⟨n, h⟩ => Exists.intro (2 * n) (by rw [h, get_interleave_left]) theorem mem_interleave_right {a : α} {s₁ : Stream' α} (s₂ : Stream' α) : a ∈ s₂ → a ∈ s₁ ⋈ s₂ := fun ⟨n, h⟩ => Exists.intro (2 * n + 1) (by rw [h, get_interleave_right]) theorem odd_eq (s : Stream' α) : odd s = even (tail s) := rfl @[simp] theorem head_even (s : Stream' α) : head (even s) = head s := rfl theorem tail_even (s : Stream' α) : tail (even s) = even (tail (tail s)) := by unfold even rw [corec_eq] rfl theorem even_cons_cons (a₁ a₂ : α) (s : Stream' α) : even (a₁::a₂::s) = a₁::even s := by unfold even rw [corec_eq]; rfl theorem even_tail (s : Stream' α) : even (tail s) = odd s := rfl theorem even_interleave (s₁ s₂ : Stream' α) : even (s₁ ⋈ s₂) = s₁ := eq_of_bisim (fun s₁' s₁ => ∃ s₂, s₁' = even (s₁ ⋈ s₂)) (fun s₁' s₁ ⟨s₂, h₁⟩ => by rw [h₁] constructor · rfl · exact ⟨tail s₂, by rw [interleave_eq, even_cons_cons, tail_cons]⟩) (Exists.intro s₂ rfl) theorem interleave_even_odd (s₁ : Stream' α) : even s₁ ⋈ odd s₁ = s₁ := eq_of_bisim (fun s' s => s' = even s ⋈ odd s) (fun s' s (h : s' = even s ⋈ odd s) => by rw [h]; constructor · rfl · simp [odd_eq, odd_eq, tail_interleave, tail_even]) rfl theorem get_even : ∀ (n : ℕ) (s : Stream' α), get (even s) n = get s (2 * n) | 0, _ => rfl | succ n, s => by change get (even s) (succ n) = get s (succ (succ (2 * n))) rw [get_succ, get_succ, tail_even, get_even n]; rfl theorem get_odd : ∀ (n : ℕ) (s : Stream' α), get (odd s) n = get s (2 * n + 1) := fun n s => by rw [odd_eq, get_even]; rfl theorem mem_of_mem_even (a : α) (s : Stream' α) : a ∈ even s → a ∈ s := fun ⟨n, h⟩ => Exists.intro (2 * n) (by rw [h, get_even]) theorem mem_of_mem_odd (a : α) (s : Stream' α) : a ∈ odd s → a ∈ s := fun ⟨n, h⟩ => Exists.intro (2 * n + 1) (by rw [h, get_odd]) @[simp] theorem nil_append_stream (s : Stream' α) : appendStream' [] s = s := rfl theorem cons_append_stream (a : α) (l : List α) (s : Stream' α) : appendStream' (a::l) s = a::appendStream' l s := rfl @[simp] theorem append_append_stream : ∀ (l₁ l₂ : List α) (s : Stream' α), l₁ ++ l₂ ++ₛ s = l₁ ++ₛ (l₂ ++ₛ s) | [], _, _ => rfl | List.cons a l₁, l₂, s => by rw [List.cons_append, cons_append_stream, cons_append_stream, append_append_stream l₁] lemma get_append_left (h : n < x.length) : (x ++ₛ a).get n = x[n] := by induction x generalizing n with | nil => simp at h | cons b x ih => rcases n with (_ | n) · simp · simp [ih n (by simpa using h), cons_append_stream] @[simp] lemma get_append_right : (x ++ₛ a).get (x.length + n) = a.get n := by induction x <;> simp [Nat.succ_add, *, cons_append_stream] @[simp] lemma get_append_length : (x ++ₛ a).get x.length = a.get 0 := get_append_right 0 x a lemma append_right_injective (h : x ++ₛ a = x ++ₛ b) : a = b := by ext n; replace h := congr_arg (fun a ↦ a.get (x.length + n)) h; simpa using h @[simp] lemma append_right_inj : x ++ₛ a = x ++ₛ b ↔ a = b := ⟨append_right_injective x a b, by simp +contextual⟩ lemma append_left_injective (h : x ++ₛ a = y ++ₛ b) (hl : x.length = y.length) : x = y := by apply List.ext_getElem hl intros rw [← get_append_left, ← get_append_left, h] theorem map_append_stream (f : α → β) : ∀ (l : List α) (s : Stream' α), map f (l ++ₛ s) = List.map f l ++ₛ map f s | [], _ => rfl | List.cons a l, s => by rw [cons_append_stream, List.map_cons, map_cons, cons_append_stream, map_append_stream f l] theorem drop_append_stream : ∀ (l : List α) (s : Stream' α), drop l.length (l ++ₛ s) = s | [], s => rfl | List.cons a l, s => by rw [List.length_cons, drop_succ, cons_append_stream, tail_cons, drop_append_stream l s] theorem append_stream_head_tail (s : Stream' α) : [head s] ++ₛ tail s = s := by simp theorem mem_append_stream_right : ∀ {a : α} (l : List α) {s : Stream' α}, a ∈ s → a ∈ l ++ₛ s | _, [], _, h => h | a, List.cons _ l, s, h => have ih : a ∈ l ++ₛ s := mem_append_stream_right l h mem_cons_of_mem _ ih theorem mem_append_stream_left : ∀ {a : α} {l : List α} (s : Stream' α), a ∈ l → a ∈ l ++ₛ s | _, [], _, h => absurd h List.not_mem_nil | a, List.cons b l, s, h => Or.elim (List.eq_or_mem_of_mem_cons h) (fun aeqb : a = b => Exists.intro 0 aeqb) fun ainl : a ∈ l => mem_cons_of_mem b (mem_append_stream_left s ainl) @[simp] theorem take_zero (s : Stream' α) : take 0 s = [] := rfl -- This lemma used to be simp, but we removed it from the simp set because: -- 1) It duplicates the (often large) `s` term, resulting in large tactic states. -- 2) It conflicts with the very useful `dropLast_take` lemma below (causing nonconfluence). theorem take_succ (n : ℕ) (s : Stream' α) : take (succ n) s = head s::take n (tail s) := rfl @[simp] theorem take_succ_cons {a : α} (n : ℕ) (s : Stream' α) : take (n + 1) (a::s) = a :: take n s := rfl theorem take_succ' {s : Stream' α} : ∀ n, s.take (n + 1) = s.take n ++ [s.get n] | 0 => rfl | n + 1 => by rw [take_succ, take_succ' n, ← List.cons_append, ← take_succ, get_tail] @[simp] theorem length_take (n : ℕ) (s : Stream' α) : (take n s).length = n := by induction n generalizing s <;> simp [*, take_succ] @[simp] theorem take_take {s : Stream' α} : ∀ {m n}, (s.take n).take m = s.take (min n m) | 0, n => by rw [Nat.min_zero, List.take_zero, take_zero] | m, 0 => by rw [Nat.zero_min, take_zero, List.take_nil] | m + 1, n + 1 => by rw [take_succ, List.take_succ_cons, Nat.succ_min_succ, take_succ, take_take] @[simp] theorem concat_take_get {n : ℕ} {s : Stream' α} : s.take n ++ [s.get n] = s.take (n + 1) := (take_succ' n).symm theorem getElem?_take {s : Stream' α} : ∀ {k n}, k < n → (s.take n)[k]? = s.get k | 0, _ + 1, _ => by simp only [length_take, zero_lt_succ, List.getElem?_eq_getElem]; rfl | k + 1, n + 1, h => by rw [take_succ, List.getElem?_cons_succ, getElem?_take (Nat.lt_of_succ_lt_succ h), get_succ] theorem getElem?_take_succ (n : ℕ) (s : Stream' α) : (take (succ n) s)[n]? = some (get s n) := getElem?_take (Nat.lt_succ_self n) @[simp] theorem dropLast_take {n : ℕ} {xs : Stream' α} : (Stream'.take n xs).dropLast = Stream'.take (n - 1) xs := by cases n with | zero => simp | succ n => rw [take_succ', List.dropLast_concat, Nat.add_one_sub_one] @[simp] theorem append_take_drop (n : ℕ) (s : Stream' α) : appendStream' (take n s) (drop n s) = s := by induction n generalizing s with | zero => rfl | succ n ih =>rw [take_succ, drop_succ, cons_append_stream, ih (tail s), Stream'.eta] lemma append_take : x ++ (a.take n) = (x ++ₛ a).take (x.length + n) := by induction x <;> simp [take, Nat.add_comm, cons_append_stream, *] @[simp] lemma take_get (h : m < (a.take n).length) : (a.take n)[m] = a.get m := by nth_rw 2 [← append_take_drop n a]; rw [get_append_left] theorem take_append_of_le_length (h : n ≤ x.length) : (x ++ₛ a).take n = x.take n := by apply List.ext_getElem (by simp [h]) intro _ _ _; rw [List.getElem_take, take_get, get_append_left] lemma take_add : a.take (m + n) = a.take m ++ (a.drop m).take n := by apply append_left_injective _ _ (a.drop (m + n)) ((a.drop m).drop n) <;> simp [-drop_drop] @[gcongr] lemma take_prefix_take_left (h : m ≤ n) : a.take m <+: a.take n := by rw [(by simp [h] : a.take m = (a.take n).take m)] apply List.take_prefix @[simp] lemma take_prefix : a.take m <+: a.take n ↔ m ≤ n := ⟨fun h ↦ by simpa using h.length_le, take_prefix_take_left m n a⟩ lemma map_take (f : α → β) : (a.take n).map f = (a.map f).take n := by apply List.ext_getElem <;> simp lemma take_drop : (a.drop m).take n = (a.take (m + n)).drop m := by apply List.ext_getElem <;> simp lemma drop_append_of_le_length (h : n ≤ x.length) : (x ++ₛ a).drop n = x.drop n ++ₛ a := by obtain ⟨m, hm⟩ := Nat.exists_eq_add_of_le h ext k; rcases lt_or_ge k m with _ | hk · rw [get_drop, get_append_left, get_append_left, List.getElem_drop]; simpa [hm] · obtain ⟨p, rfl⟩ := Nat.exists_eq_add_of_le hk have hm' : m = (x.drop n).length := by simp [hm] simp_rw [get_drop, ← Nat.add_assoc, ← hm, get_append_right, hm', get_append_right] -- Take theorem reduces a proof of equality of infinite streams to an -- induction over all their finite approximations. theorem take_theorem (s₁ s₂ : Stream' α) (h : ∀ n : ℕ, take n s₁ = take n s₂) : s₁ = s₂ := by ext n induction n with | zero => simpa [take] using h 1 | succ n => have h₁ : some (get s₁ (succ n)) = some (get s₂ (succ n)) := by rw [← getElem?_take_succ, ← getElem?_take_succ, h (succ (succ n))] injection h₁ protected theorem cycle_g_cons (a : α) (a₁ : α) (l₁ : List α) (a₀ : α) (l₀ : List α) : Stream'.cycleG (a, a₁::l₁, a₀, l₀) = (a₁, l₁, a₀, l₀) := rfl theorem cycle_eq : ∀ (l : List α) (h : l ≠ []), cycle l h = l ++ₛ cycle l h | [], h => absurd rfl h | List.cons a l, _ => have gen (l' a') : corec Stream'.cycleF Stream'.cycleG (a', l', a, l) = (a'::l') ++ₛ corec Stream'.cycleF Stream'.cycleG (a, l, a, l) := by induction l' generalizing a' with | nil => rw [corec_eq]; rfl | cons a₁ l₁ ih => rw [corec_eq, Stream'.cycle_g_cons, ih a₁]; rfl gen l a theorem mem_cycle {a : α} {l : List α} : ∀ h : l ≠ [], a ∈ l → a ∈ cycle l h := fun h ainl => by rw [cycle_eq]; exact mem_append_stream_left _ ainl @[simp] theorem cycle_singleton (a : α) : cycle [a] (by simp) = const a := coinduction rfl fun β fr ch => by rwa [cycle_eq, const_eq] theorem tails_eq (s : Stream' α) : tails s = tail s::tails (tail s) := by unfold tails; rw [corec_eq]; rfl @[simp] theorem get_tails (n : ℕ) (s : Stream' α) : get (tails s) n = drop n (tail s) := by induction n generalizing s with | zero => rfl | succ n ih => rw [get_succ, drop_succ, tails_eq, tail_cons, ih] theorem tails_eq_iterate (s : Stream' α) : tails s = iterate tail (tail s) := rfl theorem inits_core_eq (l : List α) (s : Stream' α) : initsCore l s = l::initsCore (l ++ [head s]) (tail s) := by unfold initsCore corecOn rw [corec_eq] theorem tail_inits (s : Stream' α) : tail (inits s) = initsCore [head s, head (tail s)] (tail (tail s)) := by unfold inits rw [inits_core_eq]; rfl theorem inits_tail (s : Stream' α) : inits (tail s) = initsCore [head (tail s)] (tail (tail s)) := rfl theorem cons_get_inits_core (a : α) (n : ℕ) (l : List α) (s : Stream' α) : (a :: get (initsCore l s) n) = get (initsCore (a :: l) s) n := by induction n generalizing l s with | zero => rfl | succ n ih => rw [get_succ, inits_core_eq, tail_cons, ih, inits_core_eq (a :: l) s] rfl @[simp] theorem get_inits (n : ℕ) (s : Stream' α) : get (inits s) n = take (succ n) s := by induction n generalizing s with | zero => rfl | succ n ih => rw [get_succ, take_succ, ← ih, tail_inits, inits_tail, cons_get_inits_core] theorem inits_eq (s : Stream' α) : inits s = [head s]::map (List.cons (head s)) (inits (tail s)) := by apply Stream'.ext; intro n cases n · rfl · rw [get_inits, get_succ, tail_cons, get_map, get_inits] rfl theorem zip_inits_tails (s : Stream' α) : zip appendStream' (inits s) (tails s) = const s := by ext simp theorem identity (s : Stream' α) : pure id ⊛ s = s := rfl theorem composition (g : Stream' (β → δ)) (f : Stream' (α → β)) (s : Stream' α) : pure comp ⊛ g ⊛ f ⊛ s = g ⊛ (f ⊛ s) := rfl theorem homomorphism (f : α → β) (a : α) : pure f ⊛ pure a = pure (f a) := rfl theorem interchange (fs : Stream' (α → β)) (a : α) : fs ⊛ pure a = (pure fun f : α → β => f a) ⊛ fs := rfl theorem map_eq_apply (f : α → β) (s : Stream' α) : map f s = pure f ⊛ s := rfl theorem get_nats (n : ℕ) : get nats n = n := rfl theorem nats_eq : nats = cons 0 (map succ nats) := by apply Stream'.ext; intro n cases n · rfl rw [get_succ]; rfl end Stream'
.lake/packages/mathlib/Mathlib/Data/Stream/Defs.lean
import Mathlib.Data.Nat.Notation /-! # Definition of `Stream'` and functions on streams A stream `Stream' α` is an infinite sequence of elements of `α`. One can also think about it as an infinite list. In this file we define `Stream'` and some functions that take and/or return streams. Note that we already have `Stream` to represent a similar object, hence the awkward naming. -/ universe u v w variable {α : Type u} {β : Type v} {δ : Type w} /-- A stream `Stream' α` is an infinite sequence of elements of `α`. -/ def Stream' (α : Type u) := ℕ → α namespace Stream' /-- Prepend an element to a stream. -/ def cons (a : α) (s : Stream' α) : Stream' α | 0 => a | n + 1 => s n @[inherit_doc] scoped infixr:67 " :: " => cons /-- Get the `n`-th element of a stream. -/ def get (s : Stream' α) (n : ℕ) : α := s n /-- Head of a stream: `Stream'.head s = Stream'.get s 0`. -/ abbrev head (s : Stream' α) : α := s.get 0 /-- Tail of a stream: `Stream'.tail (h :: t) = t`. -/ def tail (s : Stream' α) : Stream' α := fun i => s.get (i + 1) /-- Drop first `n` elements of a stream. -/ def drop (n : ℕ) (s : Stream' α) : Stream' α := fun i => s.get (i + n) /-- Proposition saying that all elements of a stream satisfy a predicate. -/ def All (p : α → Prop) (s : Stream' α) := ∀ n, p (get s n) /-- Proposition saying that at least one element of a stream satisfies a predicate. -/ def Any (p : α → Prop) (s : Stream' α) := ∃ n, p (get s n) /-- `a ∈ s` means that `a = Stream'.get n s` for some `n`. -/ instance : Membership α (Stream' α) := ⟨fun s a => Any (fun b => a = b) s⟩ /-- Apply a function `f` to all elements of a stream `s`. -/ def map (f : α → β) (s : Stream' α) : Stream' β := fun n => f (get s n) /-- Zip two streams using a binary operation: `Stream'.get n (Stream'.zip f s₁ s₂) = f (Stream'.get s₁) (Stream'.get s₂)`. -/ def zip (f : α → β → δ) (s₁ : Stream' α) (s₂ : Stream' β) : Stream' δ := fun n => f (get s₁ n) (get s₂ n) /-- Enumerate a stream by tagging each element with its index. -/ def enum (s : Stream' α) : Stream' (ℕ × α) := fun n => (n, s.get n) /-- The constant stream: `Stream'.get n (Stream'.const a) = a`. -/ def const (a : α) : Stream' α := fun _ => a /-- Iterates of a function as a stream. -/ def iterate (f : α → α) (a : α) : Stream' α | 0 => a | n + 1 => f (iterate f a n) /-- Given functions `f : α → β` and `g : α → α`, `corec f g` creates a stream by: 1. Starting with an initial value `a : α` 2. Applying `g` repeatedly to get a stream of α values 3. Applying `f` to each value to convert them to β -/ def corec (f : α → β) (g : α → α) : α → Stream' β := fun a => map f (iterate g a) /-- Given an initial value `a : α` and functions `f : α → β` and `g : α → α`, `corecOn a f g` creates a stream by repeatedly: 1. Applying `f` to the current value to get the next stream element 2. Applying `g` to get the next value to process This is equivalent to `corec f g a`. -/ def corecOn (a : α) (f : α → β) (g : α → α) : Stream' β := corec f g a /-- Given a function `f : α → β × α`, `corec' f` creates a stream by repeatedly: 1. Starting with an initial value `a : α` 2. Applying `f` to get both the next stream element (β) and next state value (α) This is a more convenient form when the next element and state are computed together. -/ def corec' (f : α → β × α) : α → Stream' β := corec (Prod.fst ∘ f) (Prod.snd ∘ f) /-- Use a state monad to generate a stream through corecursion -/ def corecState {σ α} (cmd : StateM σ α) (s : σ) : Stream' α := corec Prod.fst (cmd.run ∘ Prod.snd) (cmd.run s) -- corec is also known as unfolds abbrev unfolds (g : α → β) (f : α → α) (a : α) : Stream' β := corec g f a /-- Interleave two streams. -/ def interleave (s₁ s₂ : Stream' α) : Stream' α := corecOn (s₁, s₂) (fun ⟨s₁, _⟩ => head s₁) fun ⟨s₁, s₂⟩ => (s₂, tail s₁) @[inherit_doc] infixl:65 " ⋈ " => interleave /-- Elements of a stream with even indices. -/ def even (s : Stream' α) : Stream' α := corec head (fun s => tail (tail s)) s /-- Elements of a stream with odd indices. -/ def odd (s : Stream' α) : Stream' α := even (tail s) /-- Append a stream to a list. -/ def appendStream' : List α → Stream' α → Stream' α | [], s => s | List.cons a l, s => a::appendStream' l s @[inherit_doc] infixl:65 " ++ₛ " => appendStream' /-- `take n s` returns a list of the `n` first elements of stream `s` -/ def take : ℕ → Stream' α → List α | 0, _ => [] | n + 1, s => List.cons (head s) (take n (tail s)) /-- An auxiliary definition for `Stream'.cycle` corecursive def -/ protected def cycleF : α × List α × α × List α → α | (v, _, _, _) => v /-- An auxiliary definition for `Stream'.cycle` corecursive def -/ protected def cycleG : α × List α × α × List α → α × List α × α × List α | (_, [], v₀, l₀) => (v₀, l₀, v₀, l₀) | (_, List.cons v₂ l₂, v₀, l₀) => (v₂, l₂, v₀, l₀) /-- Interpret a nonempty list as a cyclic stream. -/ def cycle : ∀ l : List α, l ≠ [] → Stream' α | [], h => absurd rfl h | List.cons a l, _ => corec Stream'.cycleF Stream'.cycleG (a, l, a, l) /-- Tails of a stream, starting with `Stream'.tail s`. -/ def tails (s : Stream' α) : Stream' (Stream' α) := corec id tail (tail s) /-- An auxiliary definition for `Stream'.inits`. -/ def initsCore (l : List α) (s : Stream' α) : Stream' (List α) := corecOn (l, s) (fun ⟨a, _⟩ => a) fun p => match p with | (l', s') => (l' ++ [head s'], tail s') /-- Nonempty initial segments of a stream. -/ def inits (s : Stream' α) : Stream' (List α) := initsCore [head s] (tail s) /-- A constant stream, same as `Stream'.const`. -/ def pure (a : α) : Stream' α := const a /-- Given a stream of functions and a stream of values, apply `n`-th function to `n`-th value. -/ def apply (f : Stream' (α → β)) (s : Stream' α) : Stream' β := fun n => (get f n) (get s n) @[inherit_doc] infixl:75 " ⊛ " => apply -- input as `\circledast` /-- The stream of natural numbers: `Stream'.get n Stream'.nats = n`. -/ def nats : Stream' ℕ := fun n => n end Stream'
.lake/packages/mathlib/Mathlib/Data/FP/Basic.lean
import Mathlib.Data.Semiquot import Mathlib.Data.Nat.Size import Mathlib.Data.PNat.Defs import Mathlib.Data.Rat.Init import Mathlib.Algebra.Ring.Int.Defs import Mathlib.Algebra.Order.Group.Unbundled.Basic /-! # Implementation of floating-point numbers (experimental). -/ -- TODO add docs and remove `@[nolint docBlame]` @[nolint docBlame] def Int.shift2 (a b : ℕ) : ℤ → ℕ × ℕ | Int.ofNat e => (a <<< e, b) | Int.negSucc e => (a, b <<< e.succ) namespace FP @[nolint docBlame] inductive RMode | NE -- round to nearest even deriving Inhabited @[nolint docBlame] class FloatCfg where (prec emax : ℕ) precPos : 0 < prec precMax : prec ≤ emax attribute [nolint docBlame] FloatCfg.prec FloatCfg.emax FloatCfg.precPos FloatCfg.precMax variable [C : FloatCfg] @[nolint docBlame] def prec := C.prec @[nolint docBlame] def emax := C.emax @[nolint docBlame] def emin : ℤ := 1 - C.emax @[nolint docBlame] def ValidFinite (e : ℤ) (m : ℕ) : Prop := emin ≤ e + prec - 1 ∧ e + prec - 1 ≤ emax ∧ e = max (e + m.size - prec) emin instance decValidFinite (e m) : Decidable (ValidFinite e m) := by (unfold ValidFinite; infer_instance) @[nolint docBlame] inductive Float | inf : Bool → Float | nan : Float | finite : Bool → ∀ e m, ValidFinite e m → Float @[nolint docBlame] def Float.isFinite : Float → Bool | Float.finite _ _ _ _ => true | _ => false @[nolint docBlame] def toRat : ∀ f : Float, f.isFinite → ℚ | Float.finite s e m _, _ => let (n, d) := Int.shift2 m 1 e let r := mkRat n d if s then -r else r theorem Float.Zero.valid : ValidFinite emin 0 := ⟨by rw [add_sub_assoc] apply le_add_of_nonneg_right apply sub_nonneg_of_le apply Int.ofNat_le_ofNat_of_le exact C.precPos, suffices prec ≤ 2 * emax by rw [← Int.ofNat_le] at this rw [← sub_nonneg] at * simp only [emin, emax] at * cutsat le_trans C.precMax (Nat.le_mul_of_pos_left _ Nat.zero_lt_two), by (simp [sub_eq_add_neg, Int.ofNat_zero_le])⟩ @[nolint docBlame] def Float.zero (s : Bool) : Float := Float.finite s emin 0 Float.Zero.valid instance : Inhabited Float := ⟨Float.zero true⟩ @[nolint docBlame] protected def Float.sign' : Float → Semiquot Bool | Float.inf s => pure s | Float.nan => ⊤ | Float.finite s _ _ _ => pure s @[nolint docBlame] protected def Float.sign : Float → Bool | Float.inf s => s | Float.nan => false | Float.finite s _ _ _ => s @[nolint docBlame] protected def Float.isZero : Float → Bool | Float.finite _ _ 0 _ => true | _ => false @[nolint docBlame] protected def Float.neg : Float → Float | Float.inf s => Float.inf (not s) | Float.nan => Float.nan | Float.finite s e m f => Float.finite (not s) e m f @[nolint docBlame] def divNatLtTwoPow (n d : ℕ) : ℤ → Bool | Int.ofNat e => n < d <<< e | Int.negSucc e => n <<< e.succ < d -- TODO(Mario): Prove these and drop 'unsafe' @[nolint docBlame] unsafe def ofPosRatDn (n : ℕ+) (d : ℕ+) : Float × Bool := by let e₁ : ℤ := n.1.size - d.1.size - prec obtain ⟨d₁, n₁⟩ := Int.shift2 d.1 n.1 (e₁ + prec) let e₂ := if n₁ < d₁ then e₁ - 1 else e₁ let e₃ := max e₂ emin obtain ⟨d₂, n₂⟩ := Int.shift2 d.1 n.1 (e₃ + prec) let r := mkRat n₂ d₂ let m := r.floor refine (Float.finite Bool.false e₃ (Int.toNat m) ?_, r.den = 1) exact lcProof @[nolint docBlame] unsafe def nextUpPos (e m) (v : ValidFinite e m) : Float := let m' := m.succ if ss : m'.size = m.size then Float.finite false e m' (by unfold ValidFinite at *; rw [ss]; exact v) else if h : e = emax then Float.inf false else Float.finite false e.succ (Nat.div2 m') lcProof @[nolint docBlame] unsafe def nextDnPos (e m) (v : ValidFinite e m) : Float := match h : m with | 0 => nextUpPos _ _ Float.Zero.valid | Nat.succ m' => if ss : m'.size = m.size then Float.finite false e m' (by subst h; unfold ValidFinite at *; rw [ss]; exact v) else if h : e = emin then Float.finite false emin m' lcProof else Float.finite false e.pred (2 * m' + 1) lcProof @[nolint docBlame] unsafe def nextUp : Float → Float | Float.finite Bool.false e m f => nextUpPos e m f | Float.finite Bool.true e m f => Float.neg <| nextDnPos e m f | f => f @[nolint docBlame] unsafe def nextDn : Float → Float | Float.finite Bool.false e m f => nextDnPos e m f | Float.finite Bool.true e m f => Float.neg <| nextUpPos e m f | f => f @[nolint docBlame] unsafe def ofRatUp : ℚ → Float | ⟨0, _, _, _⟩ => Float.zero false | ⟨Nat.succ n, d, h, _⟩ => let (f, exact) := ofPosRatDn n.succPNat ⟨d, Nat.pos_of_ne_zero h⟩ if exact then f else nextUp f | ⟨Int.negSucc n, d, h, _⟩ => Float.neg (ofPosRatDn n.succPNat ⟨d, Nat.pos_of_ne_zero h⟩).1 @[nolint docBlame] unsafe def ofRatDn (r : ℚ) : Float := Float.neg <| ofRatUp (-r) @[nolint docBlame] unsafe def ofRat : RMode → ℚ → Float | RMode.NE, r => let low := ofRatDn r let high := ofRatUp r if hf : high.isFinite then if r = toRat _ hf then high else if lf : low.isFinite then if r - toRat _ lf > toRat _ hf - r then high else if r - toRat _ lf < toRat _ hf - r then low else match low, lf with | Float.finite _ _ m _, _ => if 2 ∣ m then low else high else Float.inf true else Float.inf false namespace Float instance : Neg Float := ⟨Float.neg⟩ @[nolint docBlame] unsafe def add (mode : RMode) : Float → Float → Float | nan, _ => nan | _, nan => nan | inf Bool.true, inf Bool.false => nan | inf Bool.false, inf Bool.true => nan | inf s₁, _ => inf s₁ | _, inf s₂ => inf s₂ | finite s₁ e₁ m₁ v₁, finite s₂ e₂ m₂ v₂ => let f₁ := finite s₁ e₁ m₁ v₁ let f₂ := finite s₂ e₂ m₂ v₂ ofRat mode (toRat f₁ rfl + toRat f₂ rfl) unsafe instance : Add Float := ⟨Float.add RMode.NE⟩ @[nolint docBlame] unsafe def sub (mode : RMode) (f1 f2 : Float) : Float := add mode f1 (-f2) unsafe instance : Sub Float := ⟨Float.sub RMode.NE⟩ @[nolint docBlame] unsafe def mul (mode : RMode) : Float → Float → Float | nan, _ => nan | _, nan => nan | inf s₁, f₂ => if f₂.isZero then nan else inf (xor s₁ f₂.sign) | f₁, inf s₂ => if f₁.isZero then nan else inf (xor f₁.sign s₂) | finite s₁ e₁ m₁ v₁, finite s₂ e₂ m₂ v₂ => let f₁ := finite s₁ e₁ m₁ v₁ let f₂ := finite s₂ e₂ m₂ v₂ ofRat mode (toRat f₁ rfl * toRat f₂ rfl) @[nolint docBlame] unsafe def div (mode : RMode) : Float → Float → Float | nan, _ => nan | _, nan => nan | inf _, inf _ => nan | inf s₁, f₂ => inf (xor s₁ f₂.sign) | f₁, inf s₂ => zero (xor f₁.sign s₂) | finite s₁ e₁ m₁ v₁, finite s₂ e₂ m₂ v₂ => let f₁ := finite s₁ e₁ m₁ v₁ let f₂ := finite s₂ e₂ m₂ v₂ if f₂.isZero then inf (xor s₁ s₂) else ofRat mode (toRat f₁ rfl / toRat f₂ rfl) end Float end FP
.lake/packages/mathlib/Mathlib/Data/Setoid/Basic.lean
import Mathlib.Logic.Relation import Mathlib.Order.CompleteLattice.Basic import Mathlib.Order.GaloisConnection.Defs /-! # Equivalence relations This file defines the complete lattice of equivalence relations on a type, results about the inductively defined equivalence closure of a binary relation, and the analogues of some isomorphism theorems for quotients of arbitrary types. ## Implementation notes The complete lattice instance for equivalence relations could have been defined by lifting the Galois insertion of equivalence relations on α into binary relations on α, and then using `CompleteLattice.copy` to define a complete lattice instance with more appropriate definitional equalities (a similar example is `Filter.CompleteLattice` in `Mathlib/Order/Filter/Basic.lean`). This does not save space, however, and is less clear. Partitions are not defined as a separate structure here; users are encouraged to reason about them using the existing `Setoid` and its infrastructure. ## Tags setoid, equivalence, iseqv, relation, equivalence relation -/ attribute [refl, simp] Setoid.refl attribute [symm] Setoid.symm attribute [trans] Setoid.trans variable {α : Type*} {β : Type*} namespace Setoid attribute [ext] ext /-- Two equivalence relations are equal iff their underlying binary operations are equal. -/ theorem eq_iff_rel_eq {r₁ r₂ : Setoid α} : r₁ = r₂ ↔ ⇑r₁ = ⇑r₂ := ⟨fun h => h ▸ rfl, fun h => Setoid.ext fun _ _ => h ▸ Iff.rfl⟩ /-- Defining `≤` for equivalence relations. -/ instance : LE (Setoid α) := ⟨fun r s => ∀ ⦃x y⦄, r x y → s x y⟩ theorem le_def {r s : Setoid α} : r ≤ s ↔ ∀ {x y}, r x y → s x y := Iff.rfl @[refl] theorem refl' (r : Setoid α) (x) : r x x := r.iseqv.refl x @[symm] theorem symm' (r : Setoid α) : ∀ {x y}, r x y → r y x := r.iseqv.symm @[trans] theorem trans' (r : Setoid α) : ∀ {x y z}, r x y → r y z → r x z := r.iseqv.trans theorem comm' (s : Setoid α) {x y} : s x y ↔ s y x := ⟨s.symm', s.symm'⟩ open scoped Function -- required for scoped `on` notation /-- The kernel of a function is an equivalence relation. -/ def ker (f : α → β) : Setoid α := ⟨(· = ·) on f, eq_equivalence.comap f⟩ /-- The kernel of the quotient map induced by an equivalence relation r equals r. -/ @[simp] theorem ker_mk_eq (r : Setoid α) : ker (@Quotient.mk'' _ r) = r := ext fun _ _ => Quotient.eq theorem ker_apply_mk_out {f : α → β} (a : α) : f (⟦a⟧ : Quotient (Setoid.ker f)).out = f a := @Quotient.mk_out _ (Setoid.ker f) a @[simp] theorem ker_def {f : α → β} {x y : α} : ker f x y ↔ f x = f y := Iff.rfl /-- Given types `α`, `β`, the product of two equivalence relations `r` on `α` and `s` on `β`: `(x₁, x₂), (y₁, y₂) ∈ α × β` are related by `r.prod s` iff `x₁` is related to `y₁` by `r` and `x₂` is related to `y₂` by `s`. -/ protected def prod (r : Setoid α) (s : Setoid β) : Setoid (α × β) where r x y := r x.1 y.1 ∧ s x.2 y.2 iseqv := ⟨fun x => ⟨r.refl' x.1, s.refl' x.2⟩, fun h => ⟨r.symm' h.1, s.symm' h.2⟩, fun h₁ h₂ => ⟨r.trans' h₁.1 h₂.1, s.trans' h₁.2 h₂.2⟩⟩ lemma prod_apply {r : Setoid α} {s : Setoid β} {x₁ x₂ : α} {y₁ y₂ : β} : @Setoid.r _ (r.prod s) (x₁, y₁) (x₂, y₂) ↔ (@Setoid.r _ r x₁ x₂ ∧ @Setoid.r _ s y₁ y₂) := Iff.rfl lemma piSetoid_apply {ι : Sort*} {α : ι → Sort*} {r : ∀ i, Setoid (α i)} {x y : ∀ i, α i} : @Setoid.r _ (@piSetoid _ _ r) x y ↔ ∀ i, @Setoid.r _ (r i) (x i) (y i) := Iff.rfl /-- A bijection between the product of two quotients and the quotient by the product of the equivalence relations. -/ @[simps] def prodQuotientEquiv (r : Setoid α) (s : Setoid β) : Quotient r × Quotient s ≃ Quotient (r.prod s) where toFun | (x, y) => Quotient.map₂ Prod.mk (fun _ _ hx _ _ hy ↦ ⟨hx, hy⟩) x y invFun q := Quotient.liftOn' q (fun xy ↦ (Quotient.mk'' xy.1, Quotient.mk'' xy.2)) fun x y hxy ↦ Prod.ext (by simpa using hxy.1) (by simpa using hxy.2) left_inv q := by rcases q with ⟨qa, qb⟩ exact Quotient.inductionOn₂' qa qb fun _ _ ↦ rfl right_inv q := by simp only refine Quotient.inductionOn' q fun _ ↦ rfl /-- A bijection between an indexed product of quotients and the quotient by the product of the equivalence relations. -/ @[simps] noncomputable def piQuotientEquiv {ι : Sort*} {α : ι → Sort*} (r : ∀ i, Setoid (α i)) : (∀ i, Quotient (r i)) ≃ Quotient (@piSetoid _ _ r) where toFun x := Quotient.mk'' fun i ↦ (x i).out invFun q := Quotient.liftOn' q (fun x i ↦ Quotient.mk'' (x i)) fun x y hxy ↦ by ext i simpa using hxy i left_inv q := by ext i simp right_inv q := by refine Quotient.inductionOn' q fun _ ↦ ?_ simp only [Quotient.liftOn'_mk'', Quotient.eq''] intro i change Setoid.r _ _ rw [← Quotient.eq''] simp /-- The infimum of two equivalence relations. -/ instance : Min (Setoid α) := ⟨fun r s => ⟨fun x y => r x y ∧ s x y, ⟨fun x => ⟨r.refl' x, s.refl' x⟩, fun h => ⟨r.symm' h.1, s.symm' h.2⟩, fun h1 h2 => ⟨r.trans' h1.1 h2.1, s.trans' h1.2 h2.2⟩⟩⟩⟩ /-- The infimum of 2 equivalence relations r and s is the same relation as the infimum of the underlying binary operations. -/ theorem inf_def {r s : Setoid α} : ⇑(r ⊓ s) = ⇑r ⊓ ⇑s := rfl theorem inf_iff_and {r s : Setoid α} {x y} : (r ⊓ s) x y ↔ r x y ∧ s x y := Iff.rfl /-- The infimum of a set of equivalence relations. -/ instance : InfSet (Setoid α) := ⟨fun S => { r := fun x y => ∀ r ∈ S, r x y iseqv := ⟨fun x r _ => r.refl' x, fun h r hr => r.symm' <| h r hr, fun h1 h2 r hr => r.trans' (h1 r hr) <| h2 r hr⟩ }⟩ /-- The underlying binary operation of the infimum of a set of equivalence relations is the infimum of the set's image under the map to the underlying binary operation. -/ theorem sInf_def {s : Set (Setoid α)} : ⇑(sInf s) = sInf ((⇑) '' s) := by ext simp only [sInf_image, iInf_apply, iInf_Prop_eq] rfl instance : PartialOrder (Setoid α) where lt r s := r ≤ s ∧ ¬s ≤ r le_refl _ _ _ := id le_trans _ _ _ hr hs _ _ h := hs <| hr h lt_iff_le_not_ge _ _ := Iff.rfl le_antisymm _ _ h1 h2 := Setoid.ext fun _ _ => ⟨fun h => h1 h, fun h => h2 h⟩ /-- The complete lattice of equivalence relations on a type, with bottom element `=` and top element the trivial equivalence relation. -/ instance completeLattice : CompleteLattice (Setoid α) := { (completeLatticeOfInf (Setoid α)) fun _ => ⟨fun _ hr _ _ h => h _ hr, fun _ hr _ _ h _ hr' => hr hr' h⟩ with inf := Min.min inf_le_left := fun _ _ _ _ h => h.1 inf_le_right := fun _ _ _ _ h => h.2 le_inf := fun _ _ _ h1 h2 _ _ h => ⟨h1 h, h2 h⟩ top := ⟨fun _ _ => True, ⟨fun _ => trivial, fun h => h, fun h1 _ => h1⟩⟩ le_top := fun _ _ _ _ => trivial bot := ⟨(· = ·), ⟨fun _ => rfl, fun h => h.symm, fun h1 h2 => h1.trans h2⟩⟩ bot_le := fun r x _ h => h ▸ r.2.1 x } @[simp] theorem top_def : ⇑(⊤ : Setoid α) = ⊤ := rfl @[simp] theorem bot_def : ⇑(⊥ : Setoid α) = (· = ·) := rfl theorem eq_top_iff {s : Setoid α} : s = (⊤ : Setoid α) ↔ ∀ x y : α, s x y := by rw [_root_.eq_top_iff, Setoid.le_def, Setoid.top_def] simp only [Pi.top_apply, Prop.top_eq_true, forall_true_left] lemma sInf_equiv {S : Set (Setoid α)} {x y : α} : letI := sInf S x ≈ y ↔ ∀ s ∈ S, s x y := Iff.rfl lemma sInf_iff {S : Set (Setoid α)} {x y : α} : sInf S x y ↔ ∀ s ∈ S, s x y := Iff.rfl lemma quotient_mk_sInf_eq {S : Set (Setoid α)} {x y : α} : Quotient.mk (sInf S) x = Quotient.mk (sInf S) y ↔ ∀ s ∈ S, s x y := by simp [sInf_iff] /-- The map induced between quotients by a setoid inequality. -/ def map_of_le {s t : Setoid α} (h : s ≤ t) : Quotient s → Quotient t := Quotient.map' id h /-- The map from the quotient of the infimum of a set of setoids into the quotient by an element of this set. -/ def map_sInf {S : Set (Setoid α)} {s : Setoid α} (h : s ∈ S) : Quotient (sInf S) → Quotient s := Setoid.map_of_le fun _ _ a ↦ a s h section EqvGen open Relation /-- The inductively defined equivalence closure of a binary relation r is the infimum of the set of all equivalence relations containing r. -/ theorem eqvGen_eq (r : α → α → Prop) : EqvGen.setoid r = sInf { s : Setoid α | ∀ ⦃x y⦄, r x y → s x y } := le_antisymm (fun _ _ H => EqvGen.rec (fun _ _ h _ hs => hs h) (refl' _) (fun _ _ _ => symm' _) (fun _ _ _ _ _ => trans' _) H) (sInf_le fun _ _ h => EqvGen.rel _ _ h) /-- The supremum of two equivalence relations r and s is the equivalence closure of the binary relation `x is related to y by r or s`. -/ theorem sup_eq_eqvGen (r s : Setoid α) : r ⊔ s = EqvGen.setoid fun x y => r x y ∨ s x y := by rw [eqvGen_eq] apply congr_arg sInf simp only [le_def, or_imp, ← forall_and] /-- The supremum of 2 equivalence relations r and s is the equivalence closure of the supremum of the underlying binary operations. -/ theorem sup_def {r s : Setoid α} : r ⊔ s = EqvGen.setoid (⇑r ⊔ ⇑s) := by rw [sup_eq_eqvGen]; rfl /-- The supremum of a set S of equivalence relations is the equivalence closure of the binary relation `there exists r ∈ S relating x and y`. -/ theorem sSup_eq_eqvGen (S : Set (Setoid α)) : sSup S = EqvGen.setoid fun x y => ∃ r : Setoid α, r ∈ S ∧ r x y := by rw [eqvGen_eq] apply congr_arg sInf simp only [upperBounds, le_def, and_imp, exists_imp] ext exact ⟨fun H x y r hr => H hr, fun H r hr x y => H r hr⟩ /-- The supremum of a set of equivalence relations is the equivalence closure of the supremum of the set's image under the map to the underlying binary operation. -/ theorem sSup_def {s : Set (Setoid α)} : sSup s = EqvGen.setoid (sSup ((⇑) '' s)) := by rw [sSup_eq_eqvGen, sSup_image] congr with (x y) simp only [iSup_apply, iSup_Prop_eq, exists_prop] /-- The equivalence closure of an equivalence relation r is r. -/ @[simp] theorem eqvGen_of_setoid (r : Setoid α) : EqvGen.setoid r.r = r := le_antisymm (by rw [eqvGen_eq]; exact sInf_le fun _ _ => id) EqvGen.rel /-- Equivalence closure is idempotent. -/ theorem eqvGen_idem (r : α → α → Prop) : EqvGen.setoid (EqvGen.setoid r) = EqvGen.setoid r := eqvGen_of_setoid _ /-- The equivalence closure of a binary relation r is contained in any equivalence relation containing r. -/ theorem eqvGen_le {r : α → α → Prop} {s : Setoid α} (h : ∀ x y, r x y → s x y) : EqvGen.setoid r ≤ s := by rw [eqvGen_eq]; exact sInf_le h /-- Equivalence closure of binary relations is monotone. -/ theorem eqvGen_mono {r s : α → α → Prop} (h : ∀ x y, r x y → s x y) : EqvGen.setoid r ≤ EqvGen.setoid s := eqvGen_le fun _ _ hr => EqvGen.rel _ _ <| h _ _ hr /-- There is a Galois insertion of equivalence relations on α into binary relations on α, with equivalence closure the lower adjoint. -/ def gi : @GaloisInsertion (α → α → Prop) (Setoid α) _ _ EqvGen.setoid (⇑) where choice r _ := EqvGen.setoid r gc _ s := ⟨fun H _ _ h => H <| EqvGen.rel _ _ h, fun H => eqvGen_of_setoid s ▸ eqvGen_mono H⟩ le_l_u x := (eqvGen_of_setoid x).symm ▸ le_refl x choice_eq _ _ := rfl end EqvGen open Function /-- A function from α to β is injective iff its kernel is the bottom element of the complete lattice of equivalence relations on α. -/ theorem injective_iff_ker_bot (f : α → β) : Injective f ↔ ker f = ⊥ := (@eq_bot_iff (Setoid α) _ _ (ker f)).symm /-- The elements related to x ∈ α by the kernel of f are those in the preimage of f(x) under f. -/ theorem ker_iff_mem_preimage {f : α → β} {x y} : ker f x y ↔ x ∈ f ⁻¹' {f y} := Iff.rfl /-- Equivalence between functions `α → β` such that `r x y → f x = f y` and functions `quotient r → β`. -/ def liftEquiv (r : Setoid α) : { f : α → β // r ≤ ker f } ≃ (Quotient r → β) where toFun f := Quotient.lift (f : α → β) f.2 invFun f := ⟨f ∘ Quotient.mk'', fun x y h => by simp [ker_def, Quotient.sound' h]⟩ right_inv _ := funext fun x => Quotient.inductionOn' x fun _ => rfl /-- The uniqueness part of the universal property for quotients of an arbitrary type. -/ theorem lift_unique {r : Setoid α} {f : α → β} (H : r ≤ ker f) (g : Quotient r → β) (Hg : f = g ∘ Quotient.mk'') : Quotient.lift f H = g := by ext ⟨x⟩ rw [← Quotient.mk, Quotient.lift_mk f H, Hg, Function.comp_apply, Quotient.mk''_eq_mk] /-- Given a function `f`, lift it to the quotient by its kernel. -/ def kerLift (f : α → β) : Quotient (ker f) → β := Quotient.lift f fun _ _ ↦ id @[simp] theorem kerLift_mk (f : α → β) (x : α) : kerLift f ⟦x⟧ = f x := rfl /-- Given a map f from α to β, the natural map from the quotient of α by the kernel of f is injective. -/ theorem kerLift_injective (f : α → β) : Injective <| kerLift f := fun x y => Quotient.inductionOn₂' x y fun _ _ h => Quotient.sound' h @[deprecated (since := "2025-10-11")] alias ker_lift_injective := kerLift_injective /-- Given a map f from α to β, the kernel of f is the unique equivalence relation on α whose induced map from the quotient of α to β is injective. -/ theorem ker_eq_lift_of_injective {r : Setoid α} (f : α → β) (H : r ≤ ker f) (h : Injective (Quotient.lift f H)) : ker f = r := le_antisymm (fun x y hk => Quotient.exact <| h <| show Quotient.lift f H ⟦x⟧ = Quotient.lift f H ⟦y⟧ from hk) H theorem lift_injective_iff_ker_eq_of_le {r : Setoid α} {f : α → β} (hle : r ≤ ker f) : Injective (Quotient.lift f hle) ↔ ker f = r := ⟨ker_eq_lift_of_injective f hle, fun h ↦ h ▸ kerLift_injective _⟩ variable (r : Setoid α) (f : α → β) /-- The image of `f` lifted to the quotient by its kernel is equal to the image of `f` itself. -/ @[simp] theorem range_kerLift_eq_range : Set.range (kerLift f) = Set.range f := Set.range_quotient_lift (s := ker f) _ /-- The quotient of `α` by the kernel of a function `f` bijects with the image of `f` lifted to the quotient. -/ noncomputable def quotientKerEquivRangeKerLift : Quotient (ker f) ≃ Set.range (kerLift f) := .ofInjective _ <| kerLift_injective _ /-- The first isomorphism theorem for sets: the quotient of α by the kernel of a function f bijects with f's image. -/ noncomputable def quotientKerEquivRange : Quotient (ker f) ≃ Set.range f := quotientKerEquivRangeKerLift _ |>.trans <| .setCongr <| range_kerLift_eq_range _ /-- If `f` has a computable right-inverse, then the quotient by its kernel is equivalent to its domain. -/ @[simps] def quotientKerEquivOfRightInverse (g : β → α) (hf : Function.RightInverse g f) : Quotient (ker f) ≃ β where toFun := kerLift f invFun b := Quotient.mk'' (g b) left_inv a := Quotient.inductionOn' a fun a => Quotient.sound' <| hf (f a) right_inv := hf /-- The quotient of α by the kernel of a surjective function f bijects with f's codomain. If a specific right-inverse of `f` is known, `Setoid.quotientKerEquivOfRightInverse` can be definitionally more useful. -/ noncomputable def quotientKerEquivOfSurjective (hf : Surjective f) : Quotient (ker f) ≃ β := quotientKerEquivOfRightInverse _ (Function.surjInv hf) (rightInverse_surjInv hf) variable {r f} /-- Given a function `f : α → β` and equivalence relation `r` on `α`, the equivalence closure of the relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `r`.' -/ def map (r : Setoid α) (f : α → β) : Setoid β := Relation.EqvGen.setoid (Relation.Map r f f) /-- Given a surjective function f whose kernel is contained in an equivalence relation r, the equivalence relation on f's codomain defined by x ≈ y ↔ the elements of f⁻¹(x) are related to the elements of f⁻¹(y) by r. -/ def mapOfSurjective (r : Setoid α) (f : α → β) (h : ker f ≤ r) (hf : Surjective f) : Setoid β := ⟨Relation.Map r f f, Relation.map_equivalence r.iseqv f hf h⟩ /-- A special case of the equivalence closure of an equivalence relation r equaling r. -/ theorem mapOfSurjective_eq_map (h : ker f ≤ r) (hf : Surjective f) : map r f = mapOfSurjective r f h hf := by rw [← eqvGen_of_setoid (mapOfSurjective r f h hf)]; rfl /-- Given a function `f : α → β`, an equivalence relation `r` on `β` induces an equivalence relation on `α` defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `r`'. See note [reducible non-instances]. -/ abbrev comap (f : α → β) (r : Setoid β) : Setoid α := ⟨r on f, r.iseqv.comap _⟩ theorem comap_rel (f : α → β) (r : Setoid β) (x y : α) : comap f r x y ↔ r (f x) (f y) := Iff.rfl /-- Given a map `f : N → M` and an equivalence relation `r` on `β`, the equivalence relation induced on `α` by `f` equals the kernel of `r`'s quotient map composed with `f`. -/ theorem comap_eq {f : α → β} {r : Setoid β} : comap f r = ker (@Quotient.mk'' _ r ∘ f) := ext fun x y => show _ ↔ ⟦_⟧ = ⟦_⟧ by rw [Quotient.eq]; rfl /-- The second isomorphism theorem for sets. -/ noncomputable def comapQuotientEquiv (f : α → β) (r : Setoid β) : Quotient (comap f r) ≃ Set.range (@Quotient.mk'' _ r ∘ f) := (Quotient.congrRight <| Setoid.ext_iff.1 comap_eq).trans <| quotientKerEquivRange <| Quotient.mk'' ∘ f variable (r f) /-- The third isomorphism theorem for sets. -/ def quotientQuotientEquivQuotient (s : Setoid α) (h : r ≤ s) : Quotient (ker (Quot.mapRight h)) ≃ Quotient s where toFun x := (Quotient.liftOn' x fun w => (Quotient.liftOn' w (@Quotient.mk'' _ s)) fun _ _ H => Quotient.sound <| h H) fun x y => Quotient.inductionOn₂' x y fun _ _ H => show @Quot.mk _ _ _ = @Quot.mk _ _ _ from H invFun x := (Quotient.liftOn' x fun w => @Quotient.mk'' _ (ker <| Quot.mapRight h) <| @Quotient.mk'' _ r w) fun _ _ H => Quotient.sound' <| show @Quot.mk _ _ _ = @Quot.mk _ _ _ from Quotient.sound H left_inv x := Quotient.inductionOn' x fun y => Quotient.inductionOn' y fun w => by change ⟦_⟧ = _; rfl right_inv x := Quotient.inductionOn' x fun y => by change ⟦_⟧ = _; rfl variable {r f} open Quotient /-- Given an equivalence relation `r` on `α`, the order-preserving bijection between the set of equivalence relations containing `r` and the equivalence relations on the quotient of `α` by `r`. -/ def correspondence (r : Setoid α) : { s // r ≤ s } ≃o Setoid (Quotient r) where toFun s := ⟨Quotient.lift₂ s.1.1 fun _ _ _ _ h₁ h₂ ↦ Eq.propIntro (fun h ↦ s.1.trans' (s.1.trans' (s.1.symm' (s.2 h₁)) h) (s.2 h₂)) (fun h ↦ s.1.trans' (s.1.trans' (s.2 h₁) h) (s.1.symm' (s.2 h₂))), ⟨Quotient.ind s.1.2.1, fun {x y} ↦ Quotient.inductionOn₂ x y fun _ _ ↦ s.1.2.2, fun {x y z} ↦ Quotient.inductionOn₃ x y z fun _ _ _ ↦ s.1.2.3⟩⟩ invFun s := ⟨comap Quotient.mk' s, fun x y h => by rw [comap_rel, Quotient.eq'.2 h]⟩ right_inv _ := ext fun x y ↦ Quotient.inductionOn₂ x y fun _ _ ↦ Iff.rfl map_rel_iff' := ⟨fun h x y hs ↦ @h ⟦x⟧ ⟦y⟧ hs, fun h x y ↦ Quotient.inductionOn₂ x y fun _ _ hs ↦ h hs⟩ /-- Given two equivalence relations with `r ≤ s`, a bijection between the sum of the quotients by `r` on each equivalence class by `s` and the quotient by `r`. -/ def sigmaQuotientEquivOfLe {r s : Setoid α} (hle : r ≤ s) : (Σ q : Quotient s, Quotient (r.comap (Subtype.val : Quotient.mk s ⁻¹' {q} → α))) ≃ Quotient r := .trans (.symm <| .sigmaCongrRight fun _ ↦ .subtypeQuotientEquivQuotientSubtype (s₁ := r) (s₂ := r.comap Subtype.val) _ _ (fun _ ↦ Iff.rfl) fun _ _ ↦ Iff.rfl) (.sigmaFiberEquiv fun a ↦ a.lift (Quotient.mk s) fun _ _ h ↦ Quotient.sound <| hle h) end Setoid @[simp] theorem Quotient.subsingleton_iff {s : Setoid α} : Subsingleton (Quotient s) ↔ s = ⊤ := by simp only [_root_.subsingleton_iff, eq_top_iff, Setoid.le_def, Setoid.top_def, Pi.top_apply] refine Quotient.mk'_surjective.forall.trans (forall_congr' fun a => ?_) refine Quotient.mk'_surjective.forall.trans (forall_congr' fun b => ?_) simp_rw [Prop.top_eq_true, true_implies, Quotient.eq'] theorem Quot.subsingleton_iff (r : α → α → Prop) : Subsingleton (Quot r) ↔ Relation.EqvGen r = ⊤ := by simp only [_root_.subsingleton_iff, _root_.eq_top_iff, Pi.le_def, Pi.top_apply] refine Quot.mk_surjective.forall.trans (forall_congr' fun a => ?_) refine Quot.mk_surjective.forall.trans (forall_congr' fun b => ?_) rw [Quot.eq] simp only [forall_const, le_Prop_eq, Prop.top_eq_true]
.lake/packages/mathlib/Mathlib/Data/Setoid/Partition.lean
import Mathlib.Data.Set.Finite.Range import Mathlib.Order.Partition.Finpartition /-! # Equivalence relations: partitions This file comprises properties of equivalence relations viewed as partitions. There are two implementations of partitions here: * A collection `c : Set (Set α)` of sets is a partition of `α` if `∅ ∉ c` and each element `a : α` belongs to a unique set `b ∈ c`. This is expressed as `IsPartition c` * An indexed partition is a map `s : ι → α` whose image is a partition. This is expressed as `IndexedPartition s`. Of course both implementations are related to `Quotient` and `Setoid`. `Setoid.isPartition.partition` and `Finpartition.isPartition_parts` furnish a link between `Setoid.IsPartition` and `Finpartition`. ## TODO Could the design of `Finpartition` inform the one of `Setoid.IsPartition`? Maybe bundling it and changing it from `Set (Set α)` to `Set α` where `[Lattice α] [OrderBot α]` would make it more usable. ## Tags setoid, equivalence, iseqv, relation, equivalence relation, partition, equivalence class -/ namespace Setoid variable {α : Type*} /-- If x ∈ α is in 2 elements of a set of sets partitioning α, those 2 sets are equal. -/ theorem eq_of_mem_eqv_class {c : Set (Set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {x b b'} (hc : b ∈ c) (hb : x ∈ b) (hc' : b' ∈ c) (hb' : x ∈ b') : b = b' := (H x).unique ⟨hc, hb⟩ ⟨hc', hb'⟩ /-- Makes an equivalence relation from a set of sets partitioning α. -/ def mkClasses (c : Set (Set α)) (H : ∀ a, ∃! b ∈ c, a ∈ b) : Setoid α where r x y := ∀ s ∈ c, x ∈ s → y ∈ s iseqv.refl := fun _ _ _ hx => hx iseqv.symm := fun {x _y} h s hs hy => by obtain ⟨t, ⟨ht, hx⟩, _⟩ := H x rwa [eq_of_mem_eqv_class H hs hy ht (h t ht hx)] iseqv.trans := fun {_x _ _} h1 h2 s hs hx => h2 s hs (h1 s hs hx) /-- Makes the equivalence classes of an equivalence relation. -/ def classes (r : Setoid α) : Set (Set α) := { s | ∃ y, s = { x | r x y } } theorem mem_classes (r : Setoid α) (y) : { x | r x y } ∈ r.classes := ⟨y, rfl⟩ theorem classes_ker_subset_fiber_set {β : Type*} (f : α → β) : (Setoid.ker f).classes ⊆ Set.range fun y => { x | f x = y } := by rintro s ⟨x, rfl⟩ rw [Set.mem_range] exact ⟨f x, rfl⟩ theorem finite_classes_ker {α β : Type*} [Finite β] (f : α → β) : (Setoid.ker f).classes.Finite := (Set.finite_range _).subset <| classes_ker_subset_fiber_set f theorem card_classes_ker_le {α β : Type*} [Fintype β] (f : α → β) [Fintype (Setoid.ker f).classes] : Fintype.card (Setoid.ker f).classes ≤ Fintype.card β := by classical exact le_trans (Set.card_le_card (classes_ker_subset_fiber_set f)) (Fintype.card_range_le _) /-- Two equivalence relations are equal iff all their equivalence classes are equal. -/ theorem eq_iff_classes_eq {r₁ r₂ : Setoid α} : r₁ = r₂ ↔ ∀ x, { y | r₁ x y } = { y | r₂ x y } := ⟨fun h _x => h ▸ rfl, fun h => ext fun x => Set.ext_iff.1 <| h x⟩ theorem rel_iff_exists_classes (r : Setoid α) {x y} : r x y ↔ ∃ c ∈ r.classes, x ∈ c ∧ y ∈ c := ⟨fun h => ⟨_, r.mem_classes y, h, r.refl' y⟩, fun ⟨c, ⟨z, hz⟩, hx, hy⟩ => by subst c exact r.trans' hx (r.symm' hy)⟩ /-- Two equivalence relations are equal iff their equivalence classes are equal. -/ theorem classes_inj {r₁ r₂ : Setoid α} : r₁ = r₂ ↔ r₁.classes = r₂.classes := ⟨fun h => h ▸ rfl, fun h => ext fun a b => by simp only [rel_iff_exists_classes, h]⟩ /-- The empty set is not an equivalence class. -/ theorem empty_notMem_classes {r : Setoid α} : ∅ ∉ r.classes := fun ⟨y, hy⟩ => Set.notMem_empty y <| hy.symm ▸ r.refl' y @[deprecated (since := "2025-05-23")] alias empty_not_mem_classes := empty_notMem_classes /-- Equivalence classes partition the type. -/ theorem classes_eqv_classes {r : Setoid α} (a) : ∃! b ∈ r.classes, a ∈ b := ExistsUnique.intro { x | r x a } ⟨r.mem_classes a, r.refl' _⟩ <| by rintro y ⟨⟨_, rfl⟩, ha⟩ ext x exact ⟨fun hx => r.trans' hx (r.symm' ha), fun hx => r.trans' hx ha⟩ /-- If x ∈ α is in 2 equivalence classes, the equivalence classes are equal. -/ theorem eq_of_mem_classes {r : Setoid α} {x b} (hc : b ∈ r.classes) (hb : x ∈ b) {b'} (hc' : b' ∈ r.classes) (hb' : x ∈ b') : b = b' := eq_of_mem_eqv_class classes_eqv_classes hc hb hc' hb' /-- The elements of a set of sets partitioning α are the equivalence classes of the equivalence relation defined by the set of sets. -/ theorem eq_eqv_class_of_mem {c : Set (Set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {s y} (hs : s ∈ c) (hy : y ∈ s) : s = { x | mkClasses c H x y } := by ext x constructor · intro hx _s' hs' hx' rwa [eq_of_mem_eqv_class H hs' hx' hs hx] · intro hx obtain ⟨b', ⟨hc, hb'⟩, _⟩ := H x rwa [eq_of_mem_eqv_class H hs hy hc (hx b' hc hb')] /-- The equivalence classes of the equivalence relation defined by a set of sets partitioning α are elements of the set of sets. -/ theorem eqv_class_mem {c : Set (Set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {y} : { x | mkClasses c H x y } ∈ c := (H y).elim fun _ hc _ => eq_eqv_class_of_mem H hc.1 hc.2 ▸ hc.1 theorem eqv_class_mem' {c : Set (Set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {x} : { y : α | mkClasses c H x y } ∈ c := by convert @Setoid.eqv_class_mem _ _ H x using 3 rw [Setoid.comm'] /-- Distinct elements of a set of sets partitioning α are disjoint. -/ theorem eqv_classes_disjoint {c : Set (Set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) : c.PairwiseDisjoint id := fun _b₁ h₁ _b₂ h₂ h => Set.disjoint_left.2 fun x hx1 hx2 => (H x).elim fun _b _hc _hx => h <| eq_of_mem_eqv_class H h₁ hx1 h₂ hx2 /-- A set of disjoint sets covering α partition α (classical). -/ theorem eqv_classes_of_disjoint_union {c : Set (Set α)} (hu : Set.sUnion c = @Set.univ α) (H : c.PairwiseDisjoint id) (a) : ∃! b ∈ c, a ∈ b := let ⟨b, hc, ha⟩ := Set.mem_sUnion.1 <| show a ∈ _ by rw [hu]; exact Set.mem_univ a ExistsUnique.intro b ⟨hc, ha⟩ fun _ hc' => H.elim_set hc'.1 hc _ hc'.2 ha /-- Makes an equivalence relation from a set of disjoints sets covering α. -/ def setoidOfDisjointUnion {c : Set (Set α)} (hu : Set.sUnion c = @Set.univ α) (H : c.PairwiseDisjoint id) : Setoid α := Setoid.mkClasses c <| eqv_classes_of_disjoint_union hu H /-- The equivalence relation made from the equivalence classes of an equivalence relation `r` equals `r`. -/ theorem mkClasses_classes (r : Setoid α) : mkClasses r.classes classes_eqv_classes = r := ext fun x _y => ⟨fun h => r.symm' (h { z | r z x } (r.mem_classes x) <| r.refl' x), fun h _b hb hx => eq_of_mem_classes (r.mem_classes x) (r.refl' x) hb hx ▸ r.symm' h⟩ @[simp] theorem sUnion_classes (r : Setoid α) : ⋃₀ r.classes = Set.univ := Set.eq_univ_of_forall fun x => Set.mem_sUnion.2 ⟨{ y | r y x }, ⟨x, rfl⟩, Setoid.refl _⟩ /-- The equivalence between the quotient by an equivalence relation and its type of equivalence classes. -/ noncomputable def quotientEquivClasses (r : Setoid α) : Quotient r ≃ Setoid.classes r := by let f (a : α) : Setoid.classes r := ⟨{ x | r x a }, Setoid.mem_classes r a⟩ have f_respects_relation (a b : α) (a_rel_b : r a b) : f a = f b := by rw [Subtype.mk.injEq] exact Setoid.eq_of_mem_classes (Setoid.mem_classes r a) (Setoid.symm a_rel_b) (Setoid.mem_classes r b) (Setoid.refl b) apply Equiv.ofBijective (Quot.lift f f_respects_relation) constructor · intro (q_a : Quotient r) (q_b : Quotient r) h_eq induction q_a using Quotient.ind with | _ a induction q_b using Quotient.ind with | _ b simp only [f, Quotient.lift_mk, Subtype.ext_iff] at h_eq apply Quotient.sound change a ∈ { x | r x b } rw [← h_eq] exact Setoid.refl a · rw [Quot.surjective_lift] intro ⟨c, a, hc⟩ exact ⟨a, Subtype.ext hc.symm⟩ @[simp] lemma quotientEquivClasses_mk_eq (r : Setoid α) (a : α) : (quotientEquivClasses r (Quotient.mk r a) : Set α) = { x | r x a } := (@Subtype.ext_iff _ _ _ ⟨{ x | r x a }, Setoid.mem_classes r a⟩).mp rfl section Partition /-- A collection `c : Set (Set α)` of sets is a partition of `α` into pairwise disjoint sets if `∅ ∉ c` and each element `a : α` belongs to a unique set `b ∈ c`. -/ def IsPartition (c : Set (Set α)) := ∅ ∉ c ∧ ∀ a, ∃! b ∈ c, a ∈ b /-- A partition of `α` does not contain the empty set. -/ theorem nonempty_of_mem_partition {c : Set (Set α)} (hc : IsPartition c) {s} (h : s ∈ c) : s.Nonempty := Set.nonempty_iff_ne_empty.2 fun hs0 => hc.1 <| hs0 ▸ h theorem isPartition_classes (r : Setoid α) : IsPartition r.classes := ⟨empty_notMem_classes, classes_eqv_classes⟩ theorem IsPartition.pairwiseDisjoint {c : Set (Set α)} (hc : IsPartition c) : c.PairwiseDisjoint id := eqv_classes_disjoint hc.2 lemma _root_.Set.PairwiseDisjoint.isPartition_of_exists_of_ne_empty {α : Type*} {s : Set (Set α)} (h₁ : s.PairwiseDisjoint id) (h₂ : ∀ a : α, ∃ x ∈ s, a ∈ x) (h₃ : ∅ ∉ s) : Setoid.IsPartition s := by refine ⟨h₃, fun a ↦ existsUnique_of_exists_of_unique (h₂ a) ?_⟩ intro b₁ b₂ hb₁ hb₂ apply h₁.elim hb₁.1 hb₂.1 simp only [Set.not_disjoint_iff] exact ⟨a, hb₁.2, hb₂.2⟩ theorem IsPartition.sUnion_eq_univ {c : Set (Set α)} (hc : IsPartition c) : ⋃₀ c = Set.univ := Set.eq_univ_of_forall fun x => Set.mem_sUnion.2 <| let ⟨t, ht⟩ := hc.2 x ⟨t, by simp only at ht tauto⟩ /-- All elements of a partition of α are the equivalence class of some y ∈ α. -/ theorem exists_of_mem_partition {c : Set (Set α)} (hc : IsPartition c) {s} (hs : s ∈ c) : ∃ y, s = { x | mkClasses c hc.2 x y } := let ⟨y, hy⟩ := nonempty_of_mem_partition hc hs ⟨y, eq_eqv_class_of_mem hc.2 hs hy⟩ /-- The equivalence classes of the equivalence relation defined by a partition of α equal the original partition. -/ theorem classes_mkClasses (c : Set (Set α)) (hc : IsPartition c) : (mkClasses c hc.2).classes = c := by ext s constructor · rintro ⟨y, rfl⟩ obtain ⟨b, ⟨hb, hy⟩, _⟩ := hc.2 y rwa [← eq_eqv_class_of_mem _ hb hy] · exact exists_of_mem_partition hc /-- Defining `≤` on partitions as the `≤` defined on their induced equivalence relations. -/ instance Partition.le : LE (Subtype (@IsPartition α)) := ⟨fun x y => mkClasses x.1 x.2.2 ≤ mkClasses y.1 y.2.2⟩ /-- Defining a partial order on partitions as the partial order on their induced equivalence relations. -/ instance Partition.partialOrder : PartialOrder (Subtype (@IsPartition α)) where lt x y := x ≤ y ∧ ¬y ≤ x le_refl _ := @le_refl (Setoid α) _ _ le_trans _ _ _ := @le_trans (Setoid α) _ _ _ _ lt_iff_le_not_ge _ _ := Iff.rfl le_antisymm x y hx hy := by let h := @le_antisymm (Setoid α) _ _ _ hx hy rw [Subtype.ext_iff, ← classes_mkClasses x.1 x.2, ← classes_mkClasses y.1 y.2, h] variable (α) in /-- The order-preserving bijection between equivalence relations on a type `α`, and partitions of `α` into subsets. -/ protected def Partition.orderIso : Setoid α ≃o { C : Set (Set α) // IsPartition C } where toFun r := ⟨r.classes, empty_notMem_classes, classes_eqv_classes⟩ invFun C := mkClasses C.1 C.2.2 left_inv := mkClasses_classes right_inv C := by rw [Subtype.ext_iff, ← classes_mkClasses C.1 C.2] map_rel_iff' {r s} := by conv_rhs => rw [← mkClasses_classes r, ← mkClasses_classes s] rfl /-- A complete lattice instance for partitions; there is more infrastructure for the equivalent complete lattice on equivalence relations. -/ instance Partition.completeLattice : CompleteLattice (Subtype (@IsPartition α)) := GaloisInsertion.liftCompleteLattice <| @OrderIso.toGaloisInsertion _ (Subtype (@IsPartition α)) _ (PartialOrder.toPreorder) <| Partition.orderIso α end Partition /-- A finite setoid partition furnishes a finpartition -/ @[simps] def IsPartition.finpartition {c : Finset (Set α)} (hc : Setoid.IsPartition (c : Set (Set α))) : Finpartition (Set.univ : Set α) where parts := c supIndep := Finset.supIndep_iff_pairwiseDisjoint.mpr <| eqv_classes_disjoint hc.2 sup_parts := c.sup_id_set_eq_sUnion.trans hc.sUnion_eq_univ bot_notMem := hc.left end Setoid /-- A finpartition gives rise to a setoid partition -/ theorem Finpartition.isPartition_parts {α} (f : Finpartition (Set.univ : Set α)) : Setoid.IsPartition (f.parts : Set (Set α)) := ⟨f.bot_notMem, Setoid.eqv_classes_of_disjoint_union (f.parts.sup_id_set_eq_sUnion.symm.trans f.sup_parts) f.supIndep.pairwiseDisjoint⟩ /-- Constructive information associated with a partition of a type `α` indexed by another type `ι`, `s : ι → Set α`. `IndexedPartition.index` sends an element to its index, while `IndexedPartition.some` sends an index to an element of the corresponding set. This type is primarily useful for definitional control of `s` - if this is not needed, then `Setoid.ker index` by itself may be sufficient. -/ structure IndexedPartition {ι α : Type*} (s : ι → Set α) where /-- two indexes are equal if they are equal in membership -/ eq_of_mem : ∀ {x i j}, x ∈ s i → x ∈ s j → i = j /-- sends an index to an element of the corresponding set -/ some : ι → α /-- membership invariance for `some` -/ some_mem : ∀ i, some i ∈ s i /-- index for type `α` -/ index : α → ι /-- membership invariance for `index` -/ mem_index : ∀ x, x ∈ s (index x) open scoped Function -- required for scoped `on` notation /-- The non-constructive constructor for `IndexedPartition`. -/ noncomputable def IndexedPartition.mk' {ι α : Type*} (s : ι → Set α) (dis : Pairwise (Disjoint on s)) (nonempty : ∀ i, (s i).Nonempty) (ex : ∀ x, ∃ i, x ∈ s i) : IndexedPartition s where eq_of_mem {_x _i _j} hxi hxj := by_contradiction fun h => (dis h).le_bot ⟨hxi, hxj⟩ some i := (nonempty i).some some_mem i := (nonempty i).choose_spec index x := (ex x).choose mem_index x := (ex x).choose_spec namespace IndexedPartition open Set variable {ι α : Type*} {s : ι → Set α} /-- On a unique index set there is the obvious trivial partition -/ instance [Unique ι] [Inhabited α] : Inhabited (IndexedPartition fun _i : ι => (Set.univ : Set α)) := ⟨{ eq_of_mem := fun {_x _i _j} _hi _hj => Subsingleton.elim _ _ some := default some_mem := Set.mem_univ index := default mem_index := Set.mem_univ }⟩ attribute [simp] some_mem variable (hs : IndexedPartition s) include hs in theorem exists_mem (x : α) : ∃ i, x ∈ s i := ⟨hs.index x, hs.mem_index x⟩ include hs in theorem iUnion : ⋃ i, s i = univ := by ext x simp [hs.exists_mem x] include hs in theorem disjoint : Pairwise (Disjoint on s) := fun {_i _j} h => disjoint_left.mpr fun {_x} hxi hxj => h (hs.eq_of_mem hxi hxj) theorem mem_iff_index_eq {x i} : x ∈ s i ↔ hs.index x = i := ⟨fun hxi => (hs.eq_of_mem hxi (hs.mem_index x)).symm, fun h => h ▸ hs.mem_index _⟩ theorem eq (i) : s i = { x | hs.index x = i } := Set.ext fun _ => hs.mem_iff_index_eq /-- The equivalence relation associated to an indexed partition. Two elements are equivalent if they belong to the same set of the partition. -/ protected abbrev setoid (hs : IndexedPartition s) : Setoid α := Setoid.ker hs.index @[simp] theorem index_some (i : ι) : hs.index (hs.some i) = i := (mem_iff_index_eq _).1 <| hs.some_mem i theorem some_index (x : α) : hs.setoid (hs.some (hs.index x)) x := hs.index_some (hs.index x) /-- The quotient associated to an indexed partition. -/ protected def Quotient := Quotient hs.setoid /-- The projection onto the quotient associated to an indexed partition. -/ def proj : α → hs.Quotient := Quotient.mk'' instance [Inhabited α] : Inhabited hs.Quotient := ⟨hs.proj default⟩ theorem proj_eq_iff {x y : α} : hs.proj x = hs.proj y ↔ hs.index x = hs.index y := Quotient.eq'' @[simp] theorem proj_some_index (x : α) : hs.proj (hs.some (hs.index x)) = hs.proj x := Quotient.eq''.2 (hs.some_index x) /-- The obvious equivalence between the quotient associated to an indexed partition and the indexing type. -/ def equivQuotient : ι ≃ hs.Quotient := (Setoid.quotientKerEquivOfRightInverse hs.index hs.some <| hs.index_some).symm @[simp] theorem equivQuotient_index_apply (x : α) : hs.equivQuotient (hs.index x) = hs.proj x := hs.proj_eq_iff.mpr (some_index hs x) @[simp] theorem equivQuotient_symm_proj_apply (x : α) : hs.equivQuotient.symm (hs.proj x) = hs.index x := rfl theorem equivQuotient_index : hs.equivQuotient ∘ hs.index = hs.proj := funext hs.equivQuotient_index_apply /-- A map choosing a representative for each element of the quotient associated to an indexed partition. This is a computable version of `Quotient.out` using `IndexedPartition.some`. -/ def out : hs.Quotient ↪ α := hs.equivQuotient.symm.toEmbedding.trans ⟨hs.some, Function.LeftInverse.injective hs.index_some⟩ /-- This lemma is analogous to `Quotient.mk_out'`. -/ @[simp] theorem out_proj (x : α) : hs.out (hs.proj x) = hs.some (hs.index x) := rfl /-- The indices of `Quotient.out` and `IndexedPartition.out` are equal. -/ theorem index_out (x : hs.Quotient) : hs.index x.out = hs.index (hs.out x) := Quotient.inductionOn' x fun x => (Setoid.ker_apply_mk_out x).trans (hs.index_some _).symm /-- This lemma is analogous to `Quotient.out_eq'`. -/ @[simp] theorem proj_out (x : hs.Quotient) : hs.proj (hs.out x) = x := Quotient.inductionOn' x fun x => Quotient.sound' <| hs.some_index x theorem class_of {x : α} : setOf (hs.setoid x) = s (hs.index x) := Set.ext fun _y => eq_comm.trans hs.mem_iff_index_eq.symm theorem proj_fiber (x : hs.Quotient) : hs.proj ⁻¹' {x} = s (hs.equivQuotient.symm x) := Quotient.inductionOn' x fun x => by ext y simp only [Set.mem_preimage, Set.mem_singleton_iff, hs.mem_iff_index_eq] exact Quotient.eq'' /-- Combine functions with disjoint domains into a new function. You can use the regular expression `def.*piecewise` to search for other ways to define piecewise functions in mathlib4. -/ def piecewise {β : Type*} (f : ι → α → β) : α → β := fun x => f (hs.index x) x lemma piecewise_apply {β : Type*} {f : ι → α → β} (x : α) : hs.piecewise f x = f (hs.index x) x := rfl open Function /-- A family of injective functions with pairwise disjoint domains and pairwise disjoint ranges can be glued together to form an injective function. -/ theorem piecewise_inj {β : Type*} {f : ι → α → β} (h_injOn : ∀ i, InjOn (f i) (s i)) (h_disjoint : PairwiseDisjoint (univ : Set ι) fun i => (f i) '' (s i)) : Injective (piecewise hs f) := by intro x y h suffices hs.index x = hs.index y by apply h_injOn (hs.index x) (hs.mem_index x) (this ▸ hs.mem_index y) simpa only [piecewise_apply, this] using h apply h_disjoint.elim trivial trivial contrapose! h exact h.ne_of_mem (mem_image_of_mem _ (hs.mem_index x)) (mem_image_of_mem _ (hs.mem_index y)) /-- A family of bijective functions with pairwise disjoint domains and pairwise disjoint ranges can be glued together to form a bijective function. -/ theorem piecewise_bij {β : Type*} {f : ι → α → β} {t : ι → Set β} (ht : IndexedPartition t) (hf : ∀ i, BijOn (f i) (s i) (t i)) : Bijective (piecewise hs f) := by set g := piecewise hs f with hg have hg_bij : ∀ i, BijOn g (s i) (t i) := by intro i refine BijOn.congr (hf i) ?_ intro x hx rw [hg, piecewise_apply, hs.mem_iff_index_eq.mp hx] have hg_inj : InjOn g (⋃ i, s i) := by refine injOn_of_injective ?_ refine piecewise_inj hs (fun i ↦ BijOn.injOn (hf i)) ?h_disjoint simp only [fun i ↦ BijOn.image_eq (hf i)] rintro i - j - hij exact ht.disjoint hij rw [← bijOn_univ, ← hs.iUnion, ← ht.iUnion] exact bijOn_iUnion hg_bij hg_inj end IndexedPartition
.lake/packages/mathlib/Mathlib/Data/Setoid/Partition/Card.lean
import Mathlib.Algebra.BigOperators.Finprod import Mathlib.Data.Set.Card import Mathlib.Data.Setoid.Partition /-! # Cardinality of parts of partitions * `Setoid.IsPartition.ncard_eq_finsum` on an ambient finite type, the cardinal of a set is the sum of the cardinalities of its trace on the parts of the partition -/ section Finite open scoped BigOperators /-- Given a partition of the ambient type, the cardinal of a finite set is the `finsum` of the cardinalities of its traces on the parts of the partition -/ theorem Setoid.IsPartition.ncard_eq_finsum {α : Type*} {P : Set (Set α)} (hP : Setoid.IsPartition P) (s : Set α) (hs : s.Finite := by toFinite_tac) : s.ncard = finsum fun t : P => (s ∩ t).ncard := by classical have hst (t : Set α) : (s ∩ t).Finite := hs.inter_of_left t have hst' (t : Set α) : Nat.card ↑(s ∩ t) = (hst t).toFinset.card := Nat.card_eq_card_finite_toFinset (hst t) suffices hs' : _ by rw [finsum_def, dif_pos hs'] simp only [← Nat.card_coe_set_eq, Nat.card_eq_card_finite_toFinset hs] rw [Finset.sum_congr rfl (fun t ht ↦ by exact hst' ↑t)] rw [← Finset.card_sigma, eq_comm] apply Finset.card_nbij' (fun ⟨t, x⟩ ↦ x) (fun x ↦ ⟨⟨(hP.2 x).exists.choose, (hP.2 x).exists.choose_spec.1⟩, x⟩) · rintro ⟨t, x⟩ simp +contextual · intro x simp only [Set.Finite.mem_toFinset, Finset.mem_sigma, Function.mem_support, Set.mem_inter_iff, Finset.mem_coe] intro hx refine ⟨Nat.card_ne_zero.mpr ⟨?_, hst (hP.right x).exists.choose⟩, hx, (hP.2 x).exists.choose_spec.2⟩ simp only [nonempty_subtype, Set.mem_inter_iff] use x, hx, (hP.2 x).exists.choose_spec.2 · rintro ⟨t, x⟩ simp only [Finset.mem_sigma, Set.Finite.mem_toFinset, Function.mem_support, Nat.card_ne_zero, Set.mem_inter_iff, Sigma.mk.inj_iff, heq_eq_eq, and_true, and_imp, Finset.mem_coe] simp only [nonempty_subtype, Set.mem_inter_iff, forall_exists_index, and_imp] intro y hy hyt _ hxs hxt rw [← Subtype.coe_inj] exact (hP.2 x).unique (hP.2 x).exists.choose_spec ⟨t.prop, hxt⟩ · intro t simp only [implies_true] let f : Function.support (fun (t : P) ↦ (s ∩ (t : Set α)).ncard) → s := fun ⟨t, ht⟩ ↦ ⟨(Set.nonempty_of_ncard_ne_zero ht).choose, (Set.nonempty_of_ncard_ne_zero ht).choose_spec.1⟩ have hf (t : Function.support (fun (t : P) ↦ (s ∩ (t : Set α)).ncard)) : ↑↑t ∈ P ∧ (f t : α) ∈ (t : Set α) := ⟨(↑t : P).prop, (Set.nonempty_of_ncard_ne_zero t.prop).choose_spec.2⟩ have : Finite ↑s := hs apply Finite.of_injective f intro t t' h simp only [← Subtype.coe_inj] exact (hP.2 (f t)).unique (hf t) (h ▸ hf t') end Finite
.lake/packages/mathlib/Mathlib/Data/ENat/Pow.lean
import Mathlib.Algebra.Order.Monoid.Unbundled.Pow import Mathlib.Data.ENat.Basic /-! # Powers of extended natural numbers We define the power of an extended natural `x : ℕ∞` by another extended natural `y : ℕ∞`. The definition is chosen such that `x ^ y` is the cardinality of `α → β`, when `β` has cardinality `x` and `α` has cardinality `y`: * When `y` is finite, it coincides with the exponentiation by natural numbers (e.g. `⊤ ^ 0 = 1`). * We set `0 ^ ⊤ = 0`, `1 ^ ⊤ = 1` and `x ^ ⊤ = ⊤` for `x > 1`. ## Naming convention The quantity `x ^ y` for `x`, `y : ℕ∞` is defined as a `Pow` instance. It is called `epow` in lemmas' names. -/ namespace ENat variable {x y z : ℕ∞} instance : Pow ℕ∞ ℕ∞ where pow | x, some y => x ^ y | x, ⊤ => if x = 0 then 0 else if x = 1 then 1 else ⊤ @[simp, norm_cast] lemma epow_natCast {y : ℕ} : x ^ (y : ℕ∞) = x ^ y := rfl @[simp] lemma zero_epow_top : (0 : ℕ∞) ^ (⊤ : ℕ∞) = 0 := rfl lemma zero_epow (h : y ≠ 0) : (0 : ℕ∞) ^ y = 0 := by induction y with | top => exact zero_epow_top | coe y => rwa [epow_natCast, pow_eq_zero_iff', eq_self 0, true_and, ← y.cast_ne_zero (R := ℕ∞)] @[simp] lemma one_epow : (1 : ℕ∞) ^ y = 1 := by induction y with | top => rfl | coe y => rw [epow_natCast, one_pow] @[simp] lemma top_epow_top : (⊤ : ℕ∞) ^ (⊤ : ℕ∞) = ⊤ := rfl lemma top_epow (h : y ≠ 0) : (⊤ : ℕ∞) ^ y = ⊤ := by induction y with | top => exact top_epow_top | coe y => rwa [epow_natCast, pow_eq_top_iff, eq_self ⊤, true_and, ← y.cast_ne_zero (R := ℕ∞)] @[simp] lemma epow_zero : x ^ (0 : ℕ∞) = 1 := by rw [← coe_zero, epow_natCast, pow_zero] @[simp] lemma epow_one : x ^ (1 : ℕ∞) = x := by rw [← coe_one, epow_natCast, pow_one] lemma epow_top (h : 1 < x) : x ^ (⊤ : ℕ∞) = ⊤ := by simp only [instHPow, instPow, (zero_le_one.trans_lt h).ne.symm, ↓reduceIte, h.ne.symm] lemma epow_right_mono (h : x ≠ 0) : Monotone (fun y : ℕ∞ ↦ x ^ y) := by intro y z y_z induction y · rw [top_le_iff.1 y_z] induction z · rcases lt_trichotomy x 1 with x_0 | rfl | x_2 · exact (h (lt_one_iff_eq_zero.1 x_0)).rec · simp only [one_epow, le_refl] · simp only [epow_top x_2, le_top] · exact pow_right_mono₀ (one_le_iff_ne_zero.2 h) (Nat.cast_le.1 y_z) lemma one_le_epow (h : x ≠ 0) : 1 ≤ x ^ y := le_of_eq_of_le (by simp) (epow_right_mono h (zero_le y)) lemma epow_left_mono : Monotone (fun x : ℕ∞ ↦ x ^ y) := by intro x z x_z simp only induction y · rcases lt_trichotomy x 1 with x_0 | rfl | x_2 · rw [lt_one_iff_eq_zero.1 x_0, zero_epow_top]; exact bot_le · rw [one_epow]; exact one_le_epow (one_le_iff_ne_zero.1 x_z) · rw [epow_top (x_2.trans_le x_z)]; exact le_top · simp only [epow_natCast, (pow_left_mono _) x_z] lemma epow_eq_zero_iff : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by refine ⟨fun h ↦ ⟨?_, fun y_0 ↦ ?_⟩, fun h ↦ h.1.symm ▸ zero_epow h.2⟩ · by_contra x_0 exact (one_le_iff_ne_zero.1 (one_le_epow (y := y) x_0) h).rec · rw [y_0, epow_zero] at h; contradiction lemma epow_eq_one_iff : x ^ y = 1 ↔ x = 1 ∨ y = 0 := by refine ⟨fun h ↦ or_iff_not_imp_right.2 fun y_0 ↦ ?_, fun h ↦ by rcases h with h | h <;> simp [h]⟩ rcases lt_trichotomy x 1 with x_0 | rfl | x_2 · rw [lt_one_iff_eq_zero.1 x_0, zero_epow y_0] at h; contradiction · rfl · have := epow_right_mono (one_le_iff_ne_zero.1 x_2.le) (one_le_iff_ne_zero.2 y_0) simp only [epow_one, h] at this exact (not_lt_of_ge this x_2).rec lemma epow_add : x ^ (y + z) = x ^ y * x ^ z := by rcases lt_trichotomy x 1 with x_0 | rfl | x_2 · rw [lt_one_iff_eq_zero.1 x_0] rcases eq_zero_or_pos y with rfl | y_0 · simp only [zero_add, epow_zero, one_mul] · rw [zero_epow y_0.ne.symm, zero_mul] exact zero_epow (add_pos_of_pos_of_nonneg y_0 bot_le).ne.symm · simp only [one_epow, mul_one] · induction y · rw [top_add, epow_top x_2, top_mul] exact one_le_iff_ne_zero.1 (one_le_epow (one_le_iff_ne_zero.1 x_2.le)) induction z · rw [add_top, epow_top x_2, mul_top] exact one_le_iff_ne_zero.1 (one_le_epow (one_le_iff_ne_zero.1 x_2.le)) simp only [← Nat.cast_add, epow_natCast, pow_add x] lemma mul_epow : (x * y) ^ z = x ^ z * y ^ z := by induction z · rcases lt_trichotomy x 1 with x_0 | rfl | x_2 · simp only [lt_one_iff_eq_zero.1 x_0, zero_mul, zero_epow_top] · simp only [one_mul, one_epow] · rcases lt_trichotomy y 1 with y_0 | rfl | y_2 · simp only [lt_one_iff_eq_zero.1 y_0, mul_zero, zero_epow_top] · simp only [mul_one, one_epow, epow_top x_2] · rw [epow_top x_2, epow_top y_2, WithTop.top_mul_top] exact epow_top (one_lt_mul x_2.le y_2) · simp only [epow_natCast, mul_pow x y] lemma epow_mul : x ^ (y * z) = (x ^ y) ^ z := by rcases eq_or_ne y 0 with y_0 | y_0 · simp [y_0] rcases eq_or_ne z 0 with z_0 | z_0 · simp [z_0] rcases lt_trichotomy x 1 with x_0 | rfl | x_2 · rw [lt_one_iff_eq_zero.1 x_0, zero_epow y_0, zero_epow z_0, zero_epow (mul_ne_zero y_0 z_0)] · simp only [one_epow] · induction y · rw [top_mul z_0, epow_top x_2, top_epow z_0] induction z · rw [mul_top y_0, epow_top x_2] apply (epow_top _).symm apply (epow_right_mono (one_le_iff_ne_zero.1 x_2.le) (one_le_iff_ne_zero.2 y_0)).trans_lt' simp only [x_2, epow_one] · simp only [← Nat.cast_mul, epow_natCast, pow_mul x] end ENat
.lake/packages/mathlib/Mathlib/Data/ENat/Basic.lean
import Mathlib.Algebra.Group.Nat.Units import Mathlib.Algebra.Order.AddGroupWithTop import Mathlib.Algebra.Order.Ring.Nat import Mathlib.Algebra.Order.Ring.WithTop import Mathlib.Algebra.Order.Sub.WithTop import Mathlib.Data.ENat.Defs import Mathlib.Data.Nat.Cast.Order.Basic import Mathlib.Data.Nat.SuccPred /-! # Definition and basic properties of extended natural numbers In this file we define `ENat` (notation: `ℕ∞`) to be `WithTop ℕ` and prove some basic lemmas about this type. ## Implementation details There are two natural coercions from `ℕ` to `WithTop ℕ = ENat`: `WithTop.some` and `Nat.cast`. In Lean 3, this difference was hidden in typeclass instances. Since these instances were definitionally equal, we did not duplicate generic lemmas about `WithTop α` and `WithTop.some` coercion for `ENat` and `Nat.cast` coercion. If you need to apply a lemma about `WithTop`, you may either rewrite back and forth using `ENat.some_eq_coe`, or restate the lemma for `ENat`. ## TODO Unify `ENat.add_iSup`/`ENat.iSup_add` with `ENNReal.add_iSup`/`ENNReal.iSup_add`. The key property of `ENat` and `ENNReal` we are using is that all `a` are either absorbing for addition (`a + b = a` for all `b`), or that it's order-cancellable (`a + b ≤ a + c → b ≤ c` for all `b`, `c`), and similarly for multiplication. -/ open Function assert_not_exists Field deriving instance Zero, CommSemiring, Nontrivial, LinearOrder, Bot, Sub, LinearOrderedAddCommMonoidWithTop, IsOrderedRing, CanonicallyOrderedAdd, OrderBot, OrderTop, OrderedSub, SuccOrder, WellFoundedLT, CharZero, NoZeroDivisors for ENat namespace ENat variable {a b c m n : ℕ∞} /-- Lemmas about `WithTop` expect (and can output) `WithTop.some` but the normal form for coercion `ℕ → ℕ∞` is `Nat.cast`. -/ @[simp] theorem some_eq_coe : (WithTop.some : ℕ → ℕ∞) = Nat.cast := rfl theorem coe_inj {a b : ℕ} : (a : ℕ∞) = b ↔ a = b := WithTop.coe_inj instance : SuccAddOrder ℕ∞ where succ_eq_add_one x := by cases x <;> simp [SuccOrder.succ] theorem coe_zero : ((0 : ℕ) : ℕ∞) = 0 := rfl theorem coe_one : ((1 : ℕ) : ℕ∞) = 1 := rfl theorem coe_add (m n : ℕ) : ↑(m + n) = (m + n : ℕ∞) := rfl @[simp, norm_cast] theorem coe_sub (m n : ℕ) : ↑(m - n) = (m - n : ℕ∞) := rfl @[simp] lemma coe_mul (m n : ℕ) : ↑(m * n) = (m * n : ℕ∞) := rfl @[simp] theorem mul_top (hm : m ≠ 0) : m * ⊤ = ⊤ := WithTop.mul_top hm @[simp] theorem top_mul (hm : m ≠ 0) : ⊤ * m = ⊤ := WithTop.top_mul hm /-- A version of `mul_top` where the RHS is stated as an `ite` -/ theorem mul_top' : m * ⊤ = if m = 0 then 0 else ⊤ := WithTop.mul_top' m /-- A version of `top_mul` where the RHS is stated as an `ite` -/ theorem top_mul' : ⊤ * m = if m = 0 then 0 else ⊤ := WithTop.top_mul' m @[simp] lemma top_pow {n : ℕ} (hn : n ≠ 0) : (⊤ : ℕ∞) ^ n = ⊤ := WithTop.top_pow hn @[simp] lemma pow_eq_top_iff {n : ℕ} : a ^ n = ⊤ ↔ a = ⊤ ∧ n ≠ 0 := WithTop.pow_eq_top_iff lemma pow_ne_top_iff {n : ℕ} : a ^ n ≠ ⊤ ↔ a ≠ ⊤ ∨ n = 0 := WithTop.pow_ne_top_iff @[simp] lemma pow_lt_top_iff {n : ℕ} : a ^ n < ⊤ ↔ a < ⊤ ∨ n = 0 := WithTop.pow_lt_top_iff lemma eq_top_of_pow (n : ℕ) (ha : a ^ n = ⊤) : a = ⊤ := WithTop.eq_top_of_pow n ha /-- Convert a `ℕ∞` to a `ℕ` using a proof that it is not infinite. -/ def lift (x : ℕ∞) (h : x < ⊤) : ℕ := WithTop.untop x (WithTop.lt_top_iff_ne_top.mp h) @[simp] theorem coe_lift (x : ℕ∞) (h : x < ⊤) : (lift x h : ℕ∞) = x := WithTop.coe_untop x (WithTop.lt_top_iff_ne_top.mp h) @[simp] theorem lift_coe (n : ℕ) : lift (n : ℕ∞) (WithTop.coe_lt_top n) = n := rfl @[simp] theorem lift_lt_iff {x : ℕ∞} {h} {n : ℕ} : lift x h < n ↔ x < n := WithTop.untop_lt_iff _ @[simp] theorem lift_le_iff {x : ℕ∞} {h} {n : ℕ} : lift x h ≤ n ↔ x ≤ n := WithTop.untop_le_iff _ @[simp] theorem lt_lift_iff {x : ℕ} {n : ℕ∞} {h} : x < lift n h ↔ x < n := WithTop.lt_untop_iff _ @[simp] theorem le_lift_iff {x : ℕ} {n : ℕ∞} {h} : x ≤ lift n h ↔ x ≤ n := WithTop.le_untop_iff _ @[simp] theorem lift_zero : lift 0 (WithTop.coe_lt_top 0) = 0 := rfl @[simp] theorem lift_one : lift 1 (WithTop.coe_lt_top 1) = 1 := rfl @[simp] theorem lift_ofNat (n : ℕ) [n.AtLeastTwo] : lift ofNat(n) (WithTop.coe_lt_top n) = OfNat.ofNat n := rfl @[simp] theorem add_lt_top {a b : ℕ∞} : a + b < ⊤ ↔ a < ⊤ ∧ b < ⊤ := WithTop.add_lt_top @[simp] theorem lift_add (a b : ℕ∞) (h : a + b < ⊤) : lift (a + b) h = lift a (add_lt_top.1 h).1 + lift b (add_lt_top.1 h).2 := by apply coe_inj.1 simp instance canLift : CanLift ℕ∞ ℕ (↑) (· ≠ ⊤) := WithTop.canLift instance : WellFoundedRelation ℕ∞ where rel := (· < ·) wf := IsWellFounded.wf /-- Conversion of `ℕ∞` to `ℕ` sending `∞` to `0`. -/ def toNat : ℕ∞ → ℕ := WithTop.untopD 0 /-- Homomorphism from `ℕ∞` to `ℕ` sending `∞` to `0`. -/ def toNatHom : MonoidWithZeroHom ℕ∞ ℕ where toFun := toNat map_one' := rfl map_zero' := rfl map_mul' := WithTop.untopD_zero_mul @[simp, norm_cast] lemma coe_toNatHom : toNatHom = toNat := rfl lemma toNatHom_apply (n : ℕ) : toNatHom n = toNat n := rfl @[simp] theorem toNat_coe (n : ℕ) : toNat n = n := rfl @[simp] theorem toNat_zero : toNat 0 = 0 := rfl @[simp] theorem toNat_one : toNat 1 = 1 := rfl @[simp] theorem toNat_ofNat (n : ℕ) [n.AtLeastTwo] : toNat ofNat(n) = n := rfl @[simp] theorem toNat_top : toNat ⊤ = 0 := rfl @[simp] theorem toNat_eq_zero : toNat n = 0 ↔ n = 0 ∨ n = ⊤ := WithTop.untopD_eq_self_iff theorem lift_eq_toNat_of_lt_top {x : ℕ∞} (hx : x < ⊤) : x.lift hx = x.toNat := by rcases x with ⟨⟩ | x · contradiction · rfl @[simp] theorem recTopCoe_zero {C : ℕ∞ → Sort*} (d : C ⊤) (f : ∀ a : ℕ, C a) : @recTopCoe C d f 0 = f 0 := rfl @[simp] theorem recTopCoe_one {C : ℕ∞ → Sort*} (d : C ⊤) (f : ∀ a : ℕ, C a) : @recTopCoe C d f 1 = f 1 := rfl @[simp] theorem recTopCoe_ofNat {C : ℕ∞ → Sort*} (d : C ⊤) (f : ∀ a : ℕ, C a) (x : ℕ) [x.AtLeastTwo] : @recTopCoe C d f ofNat(x) = f (OfNat.ofNat x) := rfl @[simp] theorem top_ne_coe (a : ℕ) : ⊤ ≠ (a : ℕ∞) := nofun @[simp] theorem top_ne_ofNat (a : ℕ) [a.AtLeastTwo] : ⊤ ≠ (ofNat(a) : ℕ∞) := nofun @[simp] lemma top_ne_zero : (⊤ : ℕ∞) ≠ 0 := nofun @[simp] lemma top_ne_one : (⊤ : ℕ∞) ≠ 1 := nofun @[simp] theorem coe_ne_top (a : ℕ) : (a : ℕ∞) ≠ ⊤ := nofun @[simp] theorem ofNat_ne_top (a : ℕ) [a.AtLeastTwo] : (ofNat(a) : ℕ∞) ≠ ⊤ := nofun @[simp] lemma zero_ne_top : 0 ≠ (⊤ : ℕ∞) := nofun @[simp] lemma one_ne_top : 1 ≠ (⊤ : ℕ∞) := nofun @[simp] theorem top_sub_coe (a : ℕ) : (⊤ : ℕ∞) - a = ⊤ := rfl @[simp] theorem top_sub_one : (⊤ : ℕ∞) - 1 = ⊤ := rfl @[simp] theorem top_sub_ofNat (a : ℕ) [a.AtLeastTwo] : (⊤ : ℕ∞) - ofNat(a) = ⊤ := rfl @[simp] theorem top_pos : (0 : ℕ∞) < ⊤ := WithTop.top_pos @[simp] theorem one_lt_top : (1 : ℕ∞) < ⊤ := WithTop.one_lt_top @[simp] theorem sub_top (a : ℕ∞) : a - ⊤ = 0 := WithTop.sub_top @[simp] theorem coe_toNat_eq_self : ENat.toNat n = n ↔ n ≠ ⊤ := ENat.recTopCoe (by decide) (fun _ => by simp [toNat_coe]) n alias ⟨_, coe_toNat⟩ := coe_toNat_eq_self @[simp] lemma toNat_eq_iff_eq_coe (n : ℕ∞) (m : ℕ) [NeZero m] : n.toNat = m ↔ n = m := by cases n · simpa using NeZero.ne' m · simp theorem coe_toNat_le_self (n : ℕ∞) : ↑(toNat n) ≤ n := ENat.recTopCoe le_top (fun _ => le_rfl) n theorem toNat_add {m n : ℕ∞} (hm : m ≠ ⊤) (hn : n ≠ ⊤) : toNat (m + n) = toNat m + toNat n := by lift m to ℕ using hm lift n to ℕ using hn rfl theorem toNat_sub {n : ℕ∞} (hn : n ≠ ⊤) (m : ℕ∞) : toNat (m - n) = toNat m - toNat n := by lift n to ℕ using hn induction m · rw [top_sub_coe, toNat_top, zero_tsub] · rw [← coe_sub, toNat_coe, toNat_coe, toNat_coe] @[simp] theorem toNat_mul (a b : ℕ∞) : (a * b).toNat = a.toNat * b.toNat := by cases a <;> cases b · simp · rename_i b; cases b <;> simp · rename_i a; cases a <;> simp · simp only [toNat_coe]; rw [← coe_mul, toNat_coe] theorem toNat_eq_iff {m : ℕ∞} {n : ℕ} (hn : n ≠ 0) : toNat m = n ↔ m = n := by induction m <;> simp [hn.symm] lemma toNat_le_of_le_coe {m : ℕ∞} {n : ℕ} (h : m ≤ n) : toNat m ≤ n := by lift m to ℕ using ne_top_of_le_ne_top (coe_ne_top n) h simpa using h @[gcongr] lemma toNat_le_toNat {m n : ℕ∞} (h : m ≤ n) (hn : n ≠ ⊤) : toNat m ≤ toNat n := toNat_le_of_le_coe <| h.trans_eq (coe_toNat hn).symm @[simp] theorem succ_def (m : ℕ∞) : Order.succ m = m + 1 := Order.succ_eq_add_one m theorem add_one_le_iff (hm : m ≠ ⊤) : m + 1 ≤ n ↔ m < n := Order.add_one_le_iff_of_not_isMax (not_isMax_iff_ne_top.mpr hm) theorem one_le_iff_ne_zero : 1 ≤ n ↔ n ≠ 0 := Order.one_le_iff_pos.trans pos_iff_ne_zero lemma lt_one_iff_eq_zero : n < 1 ↔ n = 0 := not_le.symm.trans one_le_iff_ne_zero.not_left theorem lt_add_one_iff (hm : n ≠ ⊤) : m < n + 1 ↔ m ≤ n := Order.lt_add_one_iff_of_not_isMax (not_isMax_iff_ne_top.mpr hm) theorem lt_coe_add_one_iff {m : ℕ∞} {n : ℕ} : m < n + 1 ↔ m ≤ n := lt_add_one_iff (coe_ne_top n) theorem le_coe_iff {n : ℕ∞} {k : ℕ} : n ≤ ↑k ↔ ∃ (n₀ : ℕ), n = n₀ ∧ n₀ ≤ k := WithTop.le_coe_iff @[simp] lemma not_lt_zero (n : ℕ∞) : ¬ n < 0 := by cases n <;> simp @[simp] lemma coe_lt_top (n : ℕ) : (n : ℕ∞) < ⊤ := WithTop.coe_lt_top n lemma coe_lt_coe {n m : ℕ} : (n : ℕ∞) < (m : ℕ∞) ↔ n < m := by simp lemma coe_le_coe {n m : ℕ} : (n : ℕ∞) ≤ (m : ℕ∞) ↔ n ≤ m := by simp @[elab_as_elim] theorem nat_induction {motive : ℕ∞ → Prop} (a : ℕ∞) (zero : motive 0) (succ : ∀ n : ℕ, motive n → motive n.succ) (top : (∀ n : ℕ, motive n) → motive ⊤) : motive a := by have A : ∀ n : ℕ, motive n := fun n => Nat.recOn n zero succ cases a · exact top A · exact A _ lemma add_one_pos : 0 < n + 1 := succ_def n ▸ Order.bot_lt_succ n lemma natCast_lt_succ {n : ℕ} : (n : ℕ∞) < (n : ℕ∞) + 1 := by rw [← Nat.cast_one, ← Nat.cast_add, coe_lt_coe] exact lt_add_one n lemma add_lt_add_iff_right {k : ℕ∞} (h : k ≠ ⊤) : n + k < m + k ↔ n < m := WithTop.add_lt_add_iff_right h lemma add_lt_add_iff_left {k : ℕ∞} (h : k ≠ ⊤) : k + n < k + m ↔ n < m := WithTop.add_lt_add_iff_left h lemma ne_top_iff_exists : n ≠ ⊤ ↔ ∃ m : ℕ, ↑m = n := WithTop.ne_top_iff_exists lemma eq_top_iff_forall_ne : n = ⊤ ↔ ∀ m : ℕ, ↑m ≠ n := WithTop.eq_top_iff_forall_ne lemma forall_ne_top {p : ℕ∞ → Prop} : (∀ x, x ≠ ⊤ → p x) ↔ ∀ x : ℕ, p x := WithTop.forall_ne_top lemma exists_ne_top {p : ℕ∞ → Prop} : (∃ x ≠ ⊤, p x) ↔ ∃ x : ℕ, p x := WithTop.exists_ne_top lemma eq_top_iff_forall_gt : n = ⊤ ↔ ∀ m : ℕ, m < n := WithTop.eq_top_iff_forall_gt lemma eq_top_iff_forall_ge : n = ⊤ ↔ ∀ m : ℕ, m ≤ n := WithTop.eq_top_iff_forall_ge /-- Version of `WithTop.forall_coe_le_iff_le` using `Nat.cast` rather than `WithTop.some`. -/ lemma forall_natCast_le_iff_le : (∀ a : ℕ, a ≤ m → a ≤ n) ↔ m ≤ n := WithTop.forall_coe_le_iff_le /-- Version of `WithTop.eq_of_forall_coe_le_iff` using `Nat.cast` rather than `WithTop.some`. -/ lemma eq_of_forall_natCast_le_iff (hm : ∀ a : ℕ, a ≤ m ↔ a ≤ n) : m = n := WithTop.eq_of_forall_coe_le_iff hm protected lemma exists_nat_gt (hn : n ≠ ⊤) : ∃ m : ℕ, n < m := by simp_rw [lt_iff_not_ge] exact not_forall.mp <| eq_top_iff_forall_ge.2.mt hn @[simp] lemma sub_eq_top_iff : a - b = ⊤ ↔ a = ⊤ ∧ b ≠ ⊤ := WithTop.sub_eq_top_iff lemma sub_ne_top_iff : a - b ≠ ⊤ ↔ a ≠ ⊤ ∨ b = ⊤ := WithTop.sub_ne_top_iff lemma addLECancellable_of_ne_top : a ≠ ⊤ → AddLECancellable a := WithTop.addLECancellable_of_ne_top lemma addLECancellable_of_lt_top : a < ⊤ → AddLECancellable a := WithTop.addLECancellable_of_lt_top lemma addLECancellable_coe (a : ℕ) : AddLECancellable (a : ℕ∞) := WithTop.addLECancellable_coe _ protected lemma le_sub_of_add_le_left (ha : a ≠ ⊤) : a + b ≤ c → b ≤ c - a := (addLECancellable_of_ne_top ha).le_tsub_of_add_le_left protected lemma le_sub_of_add_le_right (hb : b ≠ ⊤) : a + b ≤ c → a ≤ c - b := (addLECancellable_of_ne_top hb).le_tsub_of_add_le_right protected lemma le_sub_one_of_lt (h : a < b) : a ≤ b - 1 := by cases b · simp · exact ENat.le_sub_of_add_le_right one_ne_top <| lt_coe_add_one_iff.mp <| lt_tsub_iff_right.mp h protected lemma sub_sub_cancel (h : a ≠ ⊤) (h2 : b ≤ a) : a - (a - b) = b := (addLECancellable_of_ne_top <| ne_top_of_le_ne_top h tsub_le_self).tsub_tsub_cancel_of_le h2 lemma add_left_injective_of_ne_top {n : ℕ∞} (hn : n ≠ ⊤) : Function.Injective (· + n) := by intro a b e exact le_antisymm ((WithTop.add_le_add_iff_right hn).mp e.le) ((WithTop.add_le_add_iff_right hn).mp e.ge) lemma add_right_injective_of_ne_top {n : ℕ∞} (hn : n ≠ ⊤) : Function.Injective (n + ·) := by simp_rw [add_comm n _] exact add_left_injective_of_ne_top hn lemma mul_right_strictMono (ha : a ≠ 0) (h_top : a ≠ ⊤) : StrictMono (a * ·) := WithTop.mul_right_strictMono (pos_iff_ne_zero.2 ha) h_top lemma mul_left_strictMono (ha : a ≠ 0) (h_top : a ≠ ⊤) : StrictMono (· * a) := WithTop.mul_left_strictMono (pos_iff_ne_zero.2 ha) h_top @[simp] lemma mul_le_mul_left_iff {x y : ℕ∞} (ha : a ≠ 0) (h_top : a ≠ ⊤) : a * x ≤ a * y ↔ x ≤ y := (ENat.mul_right_strictMono ha h_top).le_iff_le @[simp] lemma mul_le_mul_right_iff {x y : ℕ∞} (ha : a ≠ 0) (h_top : a ≠ ⊤) : x * a ≤ y * a ↔ x ≤ y := (ENat.mul_left_strictMono ha h_top).le_iff_le @[gcongr] lemma mul_le_mul_of_le_right {x y : ℕ∞} (hxy : x ≤ y) (ha : a ≠ 0) (h_top : a ≠ ⊤) : x * a ≤ y * a := by simpa [ha, h_top] lemma self_le_mul_right (a : ℕ∞) (hc : c ≠ 0) : a ≤ a * c := by obtain rfl | hne := eq_or_ne a ⊤ · simp [top_mul hc] obtain rfl | h0 := eq_or_ne a 0 · simp nth_rewrite 1 [← mul_one a, ENat.mul_le_mul_left_iff h0 hne, ENat.one_le_iff_ne_zero] assumption lemma self_le_mul_left (a : ℕ∞) (hc : c ≠ 0) : a ≤ c * a := by rw [mul_comm] exact ENat.self_le_mul_right a hc instance : Unique ℕ∞ˣ where uniq x := by have := x.val_inv have x_top : x.val ≠ ⊤ := by intro h simp [h] at this have x_inv_top : x.inv ≠ ⊤ := by intro h simp only [h, ne_eq, x.ne_zero, not_false_eq_true, mul_top, top_ne_one] at this obtain ⟨y, x_y⟩ := ne_top_iff_exists.1 x_top obtain ⟨z, x_z⟩ := ne_top_iff_exists.1 x_inv_top replace x_y := x_y.symm rw [x_y, ← x_z, ← coe_mul, ← coe_one, coe_inj, _root_.mul_eq_one] at this rwa [this.1, Nat.cast_one, Units.val_eq_one] at x_y section withTop_enat lemma add_one_natCast_le_withTop_of_lt {m : ℕ} {n : WithTop ℕ∞} (h : m < n) : (m + 1 : ℕ) ≤ n := by match n with | ⊤ => exact le_top | (⊤ : ℕ∞) => exact WithTop.coe_le_coe.2 (OrderTop.le_top _) | (n : ℕ) => simpa only [Nat.cast_le, ge_iff_le, Nat.cast_lt] using h @[simp] lemma coe_top_add_one : ((⊤ : ℕ∞) : WithTop ℕ∞) + 1 = (⊤ : ℕ∞) := rfl @[simp] lemma add_one_eq_coe_top_iff {n : WithTop ℕ∞} : n + 1 = (⊤ : ℕ∞) ↔ n = (⊤ : ℕ∞) := by match n with | ⊤ => exact Iff.rfl | (⊤ : ℕ∞) => simp | (n : ℕ) => norm_cast simp only [coe_ne_top] @[simp] lemma natCast_ne_coe_top (n : ℕ) : (n : WithTop ℕ∞) ≠ (⊤ : ℕ∞) := nofun lemma one_le_iff_ne_zero_withTop {n : WithTop ℕ∞} : 1 ≤ n ↔ n ≠ 0 := ⟨fun h ↦ (zero_lt_one.trans_le h).ne', fun h ↦ add_one_natCast_le_withTop_of_lt (pos_iff_ne_zero.mpr h)⟩ lemma natCast_le_of_coe_top_le_withTop {N : WithTop ℕ∞} (hN : (⊤ : ℕ∞) ≤ N) (n : ℕ) : n ≤ N := le_trans (mod_cast le_top) hN lemma natCast_lt_of_coe_top_le_withTop {N : WithTop ℕ∞} (hN : (⊤ : ℕ∞) ≤ N) (n : ℕ) : n < N := lt_of_lt_of_le (mod_cast lt_add_one n) (natCast_le_of_coe_top_le_withTop hN (n + 1)) end withTop_enat variable {α : Type*} /-- Specialization of `WithTop.map` to `ENat`. -/ def map (f : ℕ → α) (k : ℕ∞) : WithTop α := WithTop.map f k @[simp] theorem map_top (f : ℕ → α) : map f ⊤ = ⊤ := rfl @[simp] theorem map_coe (f : ℕ → α) (a : ℕ) : map f a = f a := rfl @[simp] protected theorem map_zero (f : ℕ → α) : map f 0 = f 0 := rfl @[simp] protected theorem map_one (f : ℕ → α) : map f 1 = f 1 := rfl @[simp] theorem map_ofNat (f : ℕ → α) (n : ℕ) [n.AtLeastTwo] : map f ofNat(n) = f n := rfl @[simp] lemma map_eq_top_iff {f : ℕ → α} : map f n = ⊤ ↔ n = ⊤ := WithTop.map_eq_top_iff @[simp] theorem strictMono_map_iff {f : ℕ → α} [Preorder α] : StrictMono (ENat.map f) ↔ StrictMono f := WithTop.strictMono_map_iff @[simp] theorem monotone_map_iff {f : ℕ → α} [Preorder α] : Monotone (ENat.map f) ↔ Monotone f := WithTop.monotone_map_iff section AddMonoidWithOne variable [AddMonoidWithOne α] [PartialOrder α] [AddLeftMono α] [ZeroLEOneClass α] @[simp] lemma map_natCast_nonneg : 0 ≤ n.map (Nat.cast : ℕ → α) := by cases n <;> simp variable [CharZero α] lemma map_natCast_strictMono : StrictMono (map (Nat.cast : ℕ → α)) := strictMono_map_iff.2 Nat.strictMono_cast lemma map_natCast_injective : Injective (map (Nat.cast : ℕ → α)) := map_natCast_strictMono.injective @[simp] lemma map_natCast_inj : m.map (Nat.cast : ℕ → α) = n.map Nat.cast ↔ m = n := map_natCast_injective.eq_iff @[simp] lemma map_natCast_eq_zero : n.map (Nat.cast : ℕ → α) = 0 ↔ n = 0 := by simp [← map_natCast_inj (α := α)] end AddMonoidWithOne @[simp] protected theorem map_add {β F} [Add β] [FunLike F ℕ β] [AddHomClass F ℕ β] (f : F) (a b : ℕ∞) : (a + b).map f = a.map f + b.map f := WithTop.map_add f a b /-- A version of `ENat.map` for `OneHom`s. -/ -- @[to_additive (attr := simps -fullyApplied) -- "A version of `ENat.map` for `ZeroHom`s"] protected def _root_.OneHom.ENatMap {N : Type*} [One N] (f : OneHom ℕ N) : OneHom ℕ∞ (WithTop N) where toFun := ENat.map f map_one' := by simp /-- A version of `ENat.map` for `ZeroHom`s. -/ protected def _root_.ZeroHom.ENatMap {N : Type*} [Zero N] (f : ZeroHom ℕ N) : ZeroHom ℕ∞ (WithTop N) where toFun := ENat.map f map_zero' := by simp /-- A version of `WithTop.map` for `AddHom`s. -/ @[simps -fullyApplied] protected def _root_.AddHom.ENatMap {N : Type*} [Add N] (f : AddHom ℕ N) : AddHom ℕ∞ (WithTop N) where toFun := ENat.map f map_add' := ENat.map_add f /-- A version of `WithTop.map` for `AddMonoidHom`s. -/ @[simps -fullyApplied] protected def _root_.AddMonoidHom.ENatMap {N : Type*} [AddZeroClass N] (f : ℕ →+ N) : ℕ∞ →+ WithTop N := { ZeroHom.ENatMap f.toZeroHom, AddHom.ENatMap f.toAddHom with toFun := ENat.map f } /-- A version of `ENat.map` for `MonoidWithZeroHom`s. -/ @[simps -fullyApplied] protected def _root_.MonoidWithZeroHom.ENatMap {S : Type*} [MulZeroOneClass S] [DecidableEq S] [Nontrivial S] (f : ℕ →*₀ S) (hf : Function.Injective f) : ℕ∞ →*₀ WithTop S := { f.toZeroHom.ENatMap, f.toMonoidHom.toOneHom.ENatMap with toFun := ENat.map f map_mul' := fun x y => by have : ∀ z, map f z = 0 ↔ z = 0 := fun z => (WithTop.map_injective hf).eq_iff' f.toZeroHom.ENatMap.map_zero rcases Decidable.eq_or_ne x 0 with (rfl | hx) · simp rcases Decidable.eq_or_ne y 0 with (rfl | hy) · simp induction x with | top => simp [hy, this] | coe x => induction y with | top => have : (f x : WithTop S) ≠ 0 := by simpa [hf.eq_iff' (map_zero f)] using hx simp [mul_top hx, WithTop.mul_top this] | coe y => simp [← Nat.cast_mul, - coe_mul] } /-- A version of `ENat.map` for `RingHom`s. -/ @[simps -fullyApplied] protected def _root_.RingHom.ENatMap {S : Type*} [CommSemiring S] [PartialOrder S] [CanonicallyOrderedAdd S] [DecidableEq S] [Nontrivial S] (f : ℕ →+* S) (hf : Function.Injective f) : ℕ∞ →+* WithTop S := {MonoidWithZeroHom.ENatMap f.toMonoidWithZeroHom hf, f.toAddMonoidHom.ENatMap with} end ENat lemma WithBot.lt_add_one_iff {n : WithBot ℕ∞} {m : ℕ} : n < m + 1 ↔ n ≤ m := by rw [← WithBot.coe_one, ← ENat.coe_one, WithBot.coe_natCast, ← Nat.cast_add, ← WithBot.coe_natCast] cases n · simp only [bot_le, WithBot.bot_lt_coe] · rw [WithBot.coe_lt_coe, Nat.cast_add, ENat.coe_one, ENat.lt_add_one_iff (ENat.coe_ne_top _), ← WithBot.coe_le_coe, WithBot.coe_natCast] lemma WithBot.add_one_le_iff {n : ℕ} {m : WithBot ℕ∞} : n + 1 ≤ m ↔ n < m := by rw [← WithBot.coe_one, ← ENat.coe_one, WithBot.coe_natCast, ← Nat.cast_add, ← WithBot.coe_natCast] cases m · simp · rw [WithBot.coe_le_coe, ENat.coe_add, ENat.coe_one, ENat.add_one_le_iff (ENat.coe_ne_top n), ← WithBot.coe_lt_coe, WithBot.coe_natCast]
.lake/packages/mathlib/Mathlib/Data/ENat/Defs.lean
import Mathlib.Data.Nat.Notation import Mathlib.Order.TypeTags /-! # Definition and notation for extended natural numbers -/ /-- Extended natural numbers `ℕ∞ = WithTop ℕ`. -/ def ENat : Type := WithTop ℕ deriving Top, Inhabited @[inherit_doc] notation "ℕ∞" => ENat namespace ENat instance instNatCast : NatCast ℕ∞ := ⟨WithTop.some⟩ /-- Recursor for `ENat` using the preferred forms `⊤` and `↑a`. -/ @[elab_as_elim, induction_eliminator, cases_eliminator] def recTopCoe {C : ℕ∞ → Sort*} (top : C ⊤) (coe : ∀ a : ℕ, C a) : ∀ n : ℕ∞, C n | none => top | Option.some a => coe a @[simp] theorem recTopCoe_top {C : ℕ∞ → Sort*} (d : C ⊤) (f : ∀ a : ℕ, C a) : @recTopCoe C d f ⊤ = d := rfl @[simp] theorem recTopCoe_coe {C : ℕ∞ → Sort*} (d : C ⊤) (f : ∀ a : ℕ, C a) (x : ℕ) : @recTopCoe C d f ↑x = f x := rfl end ENat
.lake/packages/mathlib/Mathlib/Data/ENat/BigOperators.lean
import Mathlib.Algebra.Order.BigOperators.Group.Finset import Mathlib.Data.ENat.Lattice /-! # Sum of suprema in `ENat` -/ assert_not_exists Field namespace ENat lemma sum_iSup {α ι : Type*} {s : Finset α} {f : α → ι → ℕ∞} (hf : ∀ i j, ∃ k, ∀ a, f a i ≤ f a k ∧ f a j ≤ f a k) : ∑ a ∈ s, ⨆ i, f a i = ⨆ i, ∑ a ∈ s, f a i := by induction s using Finset.cons_induction with | empty => simp | cons a s ha ihs => simp_rw [Finset.sum_cons, ihs] refine iSup_add_iSup fun i j ↦ (hf i j).imp fun k hk ↦ ?_ gcongr exacts [(hk a).1, (hk _).2] lemma sum_iSup_of_monotone {α ι : Type*} [Preorder ι] [IsDirected ι (· ≤ ·)] {s : Finset α} {f : α → ι → ℕ∞} (hf : ∀ a, Monotone (f a)) : (∑ a ∈ s, iSup (f a)) = ⨆ n, ∑ a ∈ s, f a n := sum_iSup fun i j ↦ (exists_ge_ge i j).imp fun _k ⟨hi, hj⟩ a ↦ ⟨hf a hi, hf a hj⟩ end ENat
.lake/packages/mathlib/Mathlib/Data/ENat/Lattice.lean
import Mathlib.Algebra.Group.Action.Defs import Mathlib.Data.Nat.Lattice import Mathlib.Data.ENat.Basic /-! # Extended natural numbers form a complete linear order This instance is not in `Data.ENat.Basic` to avoid dependency on `Finset`s. We also restate some lemmas about `WithTop` for `ENat` to have versions that use `Nat.cast` instead of `WithTop.some`. -/ assert_not_exists Field open Set noncomputable section deriving instance CompleteLinearOrder for ℕ∞ end noncomputable instance : CompleteLinearOrder (WithBot ENat) := inferInstanceAs (CompleteLinearOrder (WithBot (WithTop ℕ))) namespace ENat variable {ι : Sort*} {f : ι → ℕ} {s : Set ℕ} lemma iSup_coe_eq_top : ⨆ i, (f i : ℕ∞) = ⊤ ↔ ¬ BddAbove (range f) := WithTop.iSup_coe_eq_top lemma iSup_coe_ne_top : ⨆ i, (f i : ℕ∞) ≠ ⊤ ↔ BddAbove (range f) := iSup_coe_eq_top.not_left lemma iSup_coe_lt_top : ⨆ i, (f i : ℕ∞) < ⊤ ↔ BddAbove (range f) := WithTop.iSup_coe_lt_top lemma iInf_coe_eq_top : ⨅ i, (f i : ℕ∞) = ⊤ ↔ IsEmpty ι := WithTop.iInf_coe_eq_top lemma iInf_coe_ne_top : ⨅ i, (f i : ℕ∞) ≠ ⊤ ↔ Nonempty ι := by rw [Ne, iInf_coe_eq_top, not_isEmpty_iff] lemma iInf_coe_lt_top : ⨅ i, (f i : ℕ∞) < ⊤ ↔ Nonempty ι := WithTop.iInf_coe_lt_top lemma coe_sSup : BddAbove s → ↑(sSup s) = ⨆ a ∈ s, (a : ℕ∞) := WithTop.coe_sSup lemma coe_sInf (hs : s.Nonempty) : ↑(sInf s) = ⨅ a ∈ s, (a : ℕ∞) := WithTop.coe_sInf hs (OrderBot.bddBelow s) lemma coe_iSup : BddAbove (range f) → ↑(⨆ i, f i) = ⨆ i, (f i : ℕ∞) := WithTop.coe_iSup _ @[norm_cast] lemma coe_iInf [Nonempty ι] : ↑(⨅ i, f i) = ⨅ i, (f i : ℕ∞) := WithTop.coe_iInf (OrderBot.bddBelow _) @[simp] lemma iInf_eq_top_of_isEmpty [IsEmpty ι] : ⨅ i, (f i : ℕ∞) = ⊤ := iInf_coe_eq_top.mpr ‹_› lemma iInf_toNat : (⨅ i, (f i : ℕ∞)).toNat = ⨅ i, f i := by cases isEmpty_or_nonempty ι · simp · norm_cast @[simp] lemma iInf_eq_zero {f : ι → ℕ∞} : ⨅ i, f i = 0 ↔ ∃ i, f i = 0 := by simpa [lt_one_iff_eq_zero] using iInf_lt_iff (α := ℕ∞) (a := 1) variable {f : ι → ℕ∞} {s : Set ℕ∞} lemma sSup_eq_zero : sSup s = 0 ↔ ∀ a ∈ s, a = 0 := sSup_eq_bot lemma sInf_eq_zero : sInf s = 0 ↔ 0 ∈ s := by rw [← lt_one_iff_eq_zero] simp only [sInf_lt_iff, lt_one_iff_eq_zero, exists_eq_right] lemma sSup_eq_zero' : sSup s = 0 ↔ s = ∅ ∨ s = {0} := sSup_eq_bot' @[simp] lemma iSup_eq_zero : iSup f = 0 ↔ ∀ i, f i = 0 := iSup_eq_bot @[simp] lemma iSup_zero : ⨆ _ : ι, (0 : ℕ∞) = 0 := by simp lemma sSup_eq_top_of_infinite (h : s.Infinite) : sSup s = ⊤ := by apply (sSup_eq_top ..).mpr intro x hx cases x with | top => simp at hx | coe x => contrapose! h simp only [not_infinite] apply Finite.subset <| Finite.Set.finite_image {n : ℕ | n ≤ x} (fun (n : ℕ) => (n : ℕ∞)) intro y hy specialize h y hy have hxt : y < ⊤ := lt_of_le_of_lt h hx use y.toNat simp [toNat_le_of_le_coe h, LT.lt.ne_top hxt] lemma finite_of_sSup_lt_top (h : sSup s < ⊤) : s.Finite := by contrapose! h simp only [top_le_iff] exact sSup_eq_top_of_infinite h lemma sSup_mem_of_nonempty_of_lt_top [Nonempty s] (hs' : sSup s < ⊤) : sSup s ∈ s := Nonempty.csSup_mem .of_subtype (finite_of_sSup_lt_top hs') lemma exists_eq_iSup_of_lt_top [Nonempty ι] (h : ⨆ i, f i < ⊤) : ∃ i, f i = ⨆ i, f i := sSup_mem_of_nonempty_of_lt_top h lemma exists_eq_iInf [Nonempty ι] (f : ι → ℕ∞) : ∃ a, f a = ⨅ x, f x := csInf_mem (range_nonempty fun i ↦ f i) lemma exists_eq_iSup₂_of_lt_top {ι₁ ι₂ : Type*} {f : ι₁ → ι₂ → ℕ∞} [Nonempty ι₁] [Nonempty ι₂] (h : ⨆ i, ⨆ j, f i j < ⊤) : ∃ i j, f i j = ⨆ i, ⨆ j, f i j := by rw [iSup_prod'] at h ⊢ exact Prod.exists'.mp (exists_eq_iSup_of_lt_top h) variable {ι κ : Sort*} {f g : ι → ℕ∞} {s : Set ℕ∞} {a : ℕ∞} lemma iSup_natCast : ⨆ n : ℕ, (n : ℕ∞) = ⊤ := (iSup_eq_top _).2 fun _b hb ↦ ENat.exists_nat_gt (lt_top_iff_ne_top.1 hb) lemma mul_iSup (a : ℕ∞) (f : ι → ℕ∞) : a * ⨆ i, f i = ⨆ i, a * f i := by refine (iSup_le fun i ↦ mul_le_mul' rfl.le <| le_iSup_iff.2 fun _ a ↦ a i).antisymm' <| le_iSup_iff.2 fun d h ↦ ?_ obtain rfl | hne := eq_or_ne a 0 · simp obtain hι | hι := isEmpty_or_nonempty ι · simp cases d with | top => simp | coe d => have hlt : ⨆ i, f i < ⊤ := by rw [lt_top_iff_ne_top] intro htop obtain ⟨i, hi : d < f i⟩ := (iSup_eq_top ..).1 htop d (by simp) exact (((h i).trans_lt hi).trans_le (ENat.self_le_mul_left _ hne)).false obtain ⟨j, hj⟩ := exists_eq_iSup_of_lt_top hlt rw [← hj] apply h lemma iSup_mul (f : ι → ℕ∞) (a : ℕ∞) : (⨆ i, f i) * a = ⨆ i, f i * a := by simp_rw [mul_comm, ENat.mul_iSup] lemma mul_sSup : a * sSup s = ⨆ b ∈ s, a * b := by simp_rw [sSup_eq_iSup, mul_iSup] lemma sSup_mul : sSup s * a = ⨆ b ∈ s, b * a := by simp_rw [mul_comm, mul_sSup] lemma mul_iInf [Nonempty ι] : a * ⨅ i, f i = ⨅ i, a * f i := by refine (le_iInf fun x ↦ by grw [iInf_le]).antisymm ?_ obtain ⟨b, hb⟩ := ENat.exists_eq_iInf f rw [← hb, iInf_le_iff] exact fun x h ↦ h _ lemma iInf_mul [Nonempty ι] : (⨅ i, f i) * a = ⨅ i, f i * a := by simp_rw [mul_comm, mul_iInf] /-- A version of `mul_iInf` with a slightly more general hypothesis. -/ lemma mul_iInf' (h₀ : a = 0 → Nonempty ι) : a * ⨅ i, f i = ⨅ i, a * f i := by obtain hι | hι := isEmpty_or_nonempty ι · suffices a ≠ 0 by simpa [iInf_of_empty, ite_eq_right_iff, mul_top'] aesop rw [mul_iInf] /-- A version of `iInf_mul` with a slightly more general hypothesis. -/ lemma iInf_mul' (h₀ : a = 0 → Nonempty ι) : (⨅ i, f i) * a = ⨅ i, f i * a := by simp_rw [mul_comm, mul_iInf' h₀] /-- If `a ≠ 0`, then right multiplication by `a` maps infimum to infimum. See also `ENat.iInf_mul` that assumes `[Nonempty ι]` but does not require `a ≠ 0`. -/ lemma mul_iInf_of_ne (ha₀ : a ≠ 0) : a * ⨅ i, f i = ⨅ i, a * f i := mul_iInf' <| by simp [ha₀] /-- If `a ≠ 0`, then right multiplication by `a` maps infimum to infimum. See also `ENat.iInf_mul` that assumes `[Nonempty ι]` but does not require `a ≠ 0`. -/ lemma iInf_mul_of_ne (ha₀ : a ≠ 0) : (⨅ i, f i) * a = ⨅ i, f i * a := iInf_mul' <| by simp [ha₀] lemma add_iSup [Nonempty ι] (f : ι → ℕ∞) : a + ⨆ i, f i = ⨆ i, a + f i := by obtain rfl | ha := eq_or_ne a ⊤ · simp refine le_antisymm ?_ <| iSup_le fun i ↦ by grw [← le_iSup] refine add_le_of_le_tsub_left_of_le (le_iSup_of_le (Classical.arbitrary _) le_self_add) ?_ exact iSup_le fun i ↦ ENat.le_sub_of_add_le_left ha <| le_iSup (a + f ·) i lemma iSup_add [Nonempty ι] (f : ι → ℕ∞) : (⨆ i, f i) + a = ⨆ i, f i + a := by simp [add_comm, add_iSup] lemma add_biSup' {p : ι → Prop} (h : ∃ i, p i) (f : ι → ℕ∞) : a + ⨆ i, ⨆ _ : p i, f i = ⨆ i, ⨆ _ : p i, a + f i := by haveI : Nonempty {i // p i} := nonempty_subtype.2 h simp only [iSup_subtype', add_iSup] lemma biSup_add' {p : ι → Prop} (h : ∃ i, p i) (f : ι → ℕ∞) : (⨆ i, ⨆ _ : p i, f i) + a = ⨆ i, ⨆ _ : p i, f i + a := by simp only [add_comm, add_biSup' h] lemma add_biSup {ι : Type*} {s : Set ι} (hs : s.Nonempty) (f : ι → ℕ∞) : a + ⨆ i ∈ s, f i = ⨆ i ∈ s, a + f i := add_biSup' hs _ lemma biSup_add {ι : Type*} {s : Set ι} (hs : s.Nonempty) (f : ι → ℕ∞) : (⨆ i ∈ s, f i) + a = ⨆ i ∈ s, f i + a := biSup_add' hs _ lemma add_sSup (hs : s.Nonempty) : a + sSup s = ⨆ b ∈ s, a + b := by rw [sSup_eq_iSup, add_biSup hs] lemma sSup_add (hs : s.Nonempty) : sSup s + a = ⨆ b ∈ s, b + a := by rw [sSup_eq_iSup, biSup_add hs] lemma iSup_add_iSup_le [Nonempty ι] [Nonempty κ] {g : κ → ℕ∞} (h : ∀ i j, f i + g j ≤ a) : iSup f + iSup g ≤ a := by simp_rw [iSup_add, add_iSup]; exact iSup₂_le h lemma biSup_add_biSup_le' {p : ι → Prop} {q : κ → Prop} (hp : ∃ i, p i) (hq : ∃ j, q j) {g : κ → ℕ∞} (h : ∀ i, p i → ∀ j, q j → f i + g j ≤ a) : (⨆ i, ⨆ _ : p i, f i) + ⨆ j, ⨆ _ : q j, g j ≤ a := by simp_rw [biSup_add' hp, add_biSup' hq] exact iSup₂_le fun i hi => iSup₂_le (h i hi) lemma biSup_add_biSup_le {ι κ : Type*} {s : Set ι} {t : Set κ} (hs : s.Nonempty) (ht : t.Nonempty) {f : ι → ℕ∞} {g : κ → ℕ∞} {a : ℕ∞} (h : ∀ i ∈ s, ∀ j ∈ t, f i + g j ≤ a) : (⨆ i ∈ s, f i) + ⨆ j ∈ t, g j ≤ a := biSup_add_biSup_le' hs ht h lemma iSup_add_iSup (h : ∀ i j, ∃ k, f i + g j ≤ f k + g k) : iSup f + iSup g = ⨆ i, f i + g i := by cases isEmpty_or_nonempty ι · simp only [iSup_of_empty, bot_eq_zero, zero_add] · refine le_antisymm ?_ (iSup_le fun a => add_le_add (le_iSup _ _) (le_iSup _ _)) refine iSup_add_iSup_le fun i j => ?_ rcases h i j with ⟨k, hk⟩ exact le_iSup_of_le k hk lemma iSup_add_iSup_of_monotone {ι : Type*} [Preorder ι] [IsDirected ι (· ≤ ·)] {f g : ι → ℕ∞} (hf : Monotone f) (hg : Monotone g) : iSup f + iSup g = ⨆ a, f a + g a := iSup_add_iSup fun i j ↦ (exists_ge_ge i j).imp fun _k ⟨hi, hj⟩ ↦ by gcongr <;> apply_rules lemma smul_iSup {R} [SMul R ℕ∞] [IsScalarTower R ℕ∞ ℕ∞] (f : ι → ℕ∞) (c : R) : c • ⨆ i, f i = ⨆ i, c • f i := by simpa using mul_iSup (c • 1) f lemma smul_sSup {R} [SMul R ℕ∞] [IsScalarTower R ℕ∞ ℕ∞] (s : Set ℕ∞) (c : R) : c • sSup s = ⨆ a ∈ s, c • a := by simp_rw [sSup_eq_iSup, smul_iSup] lemma sub_iSup [Nonempty ι] (ha : a ≠ ⊤) : a - ⨆ i, f i = ⨅ i, a - f i := by obtain ⟨i, hi⟩ | h := em (∃ i, a < f i) · rw [tsub_eq_zero_iff_le.2 <| le_iSup_of_le _ hi.le, (iInf_eq_bot _).2, bot_eq_zero] exact fun x hx ↦ ⟨i, by simpa [hi.le, tsub_eq_zero_of_le]⟩ simp_rw [not_exists, not_lt] at h refine le_antisymm (le_iInf fun i ↦ tsub_le_tsub_left (le_iSup ..) _) <| ENat.le_sub_of_add_le_left (ne_top_of_le_ne_top ha <| iSup_le h) <| add_le_of_le_tsub_right_of_le (iInf_le_of_le (Classical.arbitrary _) tsub_le_self) <| iSup_le fun i ↦ ?_ rw [← ENat.sub_sub_cancel ha (h _)] exact tsub_le_tsub_left (iInf_le (a - f ·) i) _ end ENat
.lake/packages/mathlib/Mathlib/Data/Rat/Sqrt.lean
import Mathlib.Algebra.Order.Ring.Abs import Mathlib.Algebra.Order.Ring.Unbundled.Rat import Mathlib.Data.Rat.Lemmas import Mathlib.Data.Int.Sqrt /-! # Square root on rational numbers This file defines the square root function on rational numbers `Rat.sqrt` and proves several theorems about it. -/ namespace Rat /-- Square root function on rational numbers, defined by taking the (integer) square root of the numerator and the square root (on natural numbers) of the denominator. -/ @[pp_nodot] def sqrt (q : ℚ) : ℚ := mkRat (Int.sqrt q.num) (Nat.sqrt q.den) theorem sqrt_eq (q : ℚ) : Rat.sqrt (q * q) = |q| := by rw [sqrt, mul_self_num, mul_self_den, Int.sqrt_eq, Nat.sqrt_eq, abs_def, divInt_ofNat] theorem exists_mul_self (x : ℚ) : (∃ q, q * q = x) ↔ Rat.sqrt x * Rat.sqrt x = x := ⟨fun ⟨n, hn⟩ => by rw [← hn, sqrt_eq, abs_mul_abs_self], fun h => ⟨Rat.sqrt x, h⟩⟩ lemma sqrt_nonneg (q : ℚ) : 0 ≤ Rat.sqrt q := mkRat_nonneg (Int.sqrt_nonneg _) _ /-- `IsSquare` can be decided on `ℚ` by checking against the square root. -/ instance : DecidablePred (IsSquare : ℚ → Prop) := fun m => decidable_of_iff' (sqrt m * sqrt m = m) <| by simp_rw [← exists_mul_self m, IsSquare, eq_comm] @[simp, norm_cast] theorem sqrt_intCast (z : ℤ) : Rat.sqrt (z : ℚ) = Int.sqrt z := by simp only [sqrt, num_intCast, den_intCast, Nat.sqrt_one, mkRat_one] @[simp, norm_cast] theorem sqrt_natCast (n : ℕ) : Rat.sqrt (n : ℚ) = Nat.sqrt n := by rw [← Int.cast_natCast, sqrt_intCast, Int.sqrt_natCast, Int.cast_natCast] @[simp] theorem sqrt_ofNat (n : ℕ) : Rat.sqrt (ofNat(n) : ℚ) = Nat.sqrt (OfNat.ofNat n) := sqrt_natCast _ end Rat
.lake/packages/mathlib/Mathlib/Data/Rat/Lemmas.lean
import Mathlib.Algebra.GroupWithZero.Divisibility import Mathlib.Algebra.Ring.Rat import Mathlib.Algebra.Ring.Int.Parity import Mathlib.Data.PNat.Defs /-! # Further lemmas for the Rational Numbers -/ namespace Rat -- TODO: move this to Lean attribute [norm_cast] num_intCast den_intCast theorem num_dvd (a) {b : ℤ} (b0 : b ≠ 0) : (a /. b).num ∣ a := by rcases e : a /. b with ⟨n, d, h, c⟩ rw [Rat.mk'_eq_divInt, divInt_eq_divInt_iff b0 (mod_cast h)] at e refine Int.natAbs_dvd.1 <| Int.dvd_natAbs.1 <| Int.natCast_dvd_natCast.2 <| c.dvd_of_dvd_mul_right ?_ have := congr_arg Int.natAbs e simp only [Int.natAbs_mul, Int.natAbs_natCast] at this; simp [this] theorem den_dvd (a b : ℤ) : ((a /. b).den : ℤ) ∣ b := by by_cases b0 : b = 0; · simp [b0] rcases e : a /. b with ⟨n, d, h, c⟩ rw [mk'_eq_divInt, divInt_eq_divInt_iff b0 (ne_of_gt (Int.natCast_pos.2 (Nat.pos_of_ne_zero h)))] at e refine Int.dvd_natAbs.1 <| Int.natCast_dvd_natCast.2 <| c.symm.dvd_of_dvd_mul_left ?_ rw [← Int.natAbs_mul, ← Int.natCast_dvd_natCast, Int.dvd_natAbs, ← e]; simp theorem num_den_mk {q : ℚ} {n d : ℤ} (hd : d ≠ 0) (qdf : q = n /. d) : ∃ c : ℤ, n = c * q.num ∧ d = c * q.den := by obtain rfl | hn := eq_or_ne n 0 · simp [qdf] have : q.num * d = n * ↑q.den := by refine (divInt_eq_divInt_iff ?_ hd).mp ?_ · exact Int.natCast_ne_zero.mpr (Rat.den_nz _) · rwa [num_divInt_den] have hqdn : q.num ∣ n := by rw [qdf] exact Rat.num_dvd _ hd refine ⟨n / q.num, ?_, ?_⟩ · rw [Int.ediv_mul_cancel hqdn] · refine Int.eq_mul_div_of_mul_eq_mul_of_dvd_left ?_ hqdn this rw [qdf] exact Rat.num_ne_zero.2 ((divInt_ne_zero hd).mpr hn) theorem num_mk (n d : ℤ) : (n /. d).num = d.sign * n / n.gcd d := by have (m : ℕ) : Int.natAbs (m + 1) = m + 1 := by rw [← Nat.cast_one, ← Nat.cast_add, Int.natAbs_cast] rcases d with ((_ | _) | _) <;> simp [divInt, mkRat, Rat.normalize_eq, Int.sign, Int.gcd, Int.zero_ediv, this] theorem den_mk (n d : ℤ) : (n /. d).den = if d = 0 then 1 else d.natAbs / n.gcd d := by have (m : ℕ) : Int.natAbs (m + 1) = m + 1 := by rw [← Nat.cast_one, ← Nat.cast_add, Int.natAbs_cast] rcases d with ((_ | _) | _) <;> simp [divInt, mkRat, Rat.normalize_eq, Int.gcd, if_neg (Nat.cast_add_one_ne_zero _), this] theorem add_den_dvd_lcm (q₁ q₂ : ℚ) : (q₁ + q₂).den ∣ q₁.den.lcm q₂.den := by rw [add_def, normalize_eq, Nat.div_dvd_iff_dvd_mul (Nat.gcd_dvd_right _ _) (Nat.gcd_pos_of_pos_right _ (by simp [Nat.pos_iff_ne_zero])), ← Nat.gcd_mul_lcm, mul_dvd_mul_iff_right (Nat.lcm_ne_zero (by simp) (by simp)), Nat.dvd_gcd_iff] refine ⟨?_, dvd_mul_right _ _⟩ rw [← Int.natCast_dvd_natCast, Int.dvd_natAbs] apply Int.dvd_add <;> apply dvd_mul_of_dvd_right <;> rw [Int.natCast_dvd_natCast] <;> [exact Nat.gcd_dvd_right _ _; exact Nat.gcd_dvd_left _ _] theorem sub_den_dvd_lcm (q₁ q₂ : ℚ) : (q₁ - q₂).den ∣ q₁.den.lcm q₂.den := by simpa only [sub_eq_add_neg, neg_den] using add_den_dvd_lcm q₁ (-q₂) theorem add_den_dvd (q₁ q₂ : ℚ) : (q₁ + q₂).den ∣ q₁.den * q₂.den := (add_den_dvd_lcm _ _).trans (Nat.lcm_dvd_mul _ _) theorem sub_den_dvd (q₁ q₂ : ℚ) : (q₁ - q₂).den ∣ q₁.den * q₂.den := (sub_den_dvd_lcm _ _).trans (Nat.lcm_dvd_mul _ _) theorem mul_den_dvd (q₁ q₂ : ℚ) : (q₁ * q₂).den ∣ q₁.den * q₂.den := by rw [mul_def, normalize_eq] apply Nat.div_dvd_of_dvd apply Nat.gcd_dvd_right theorem mul_num (q₁ q₂ : ℚ) : (q₁ * q₂).num = q₁.num * q₂.num / Nat.gcd (q₁.num * q₂.num).natAbs (q₁.den * q₂.den) := by rw [mul_def, normalize_eq] theorem mul_den (q₁ q₂ : ℚ) : (q₁ * q₂).den = q₁.den * q₂.den / Nat.gcd (q₁.num * q₂.num).natAbs (q₁.den * q₂.den) := by rw [mul_def, normalize_eq] @[simp] theorem add_intCast_den (q : ℚ) (n : ℤ) : (q + n).den = q.den := by apply Nat.dvd_antisymm · simpa using add_den_dvd q n · simpa using add_den_dvd (q + n) (-n) @[simp] theorem intCast_add_den (n : ℤ) (q : ℚ) : (n + q).den = q.den := by rw [add_comm, add_intCast_den] @[simp] theorem sub_intCast_den (q : ℚ) (n : ℤ) : (q - n).den = q.den := by rw [sub_eq_add_neg, ← Int.cast_neg, add_intCast_den] @[simp] theorem intCast_sub_den (n : ℤ) (q : ℚ) : (n - q).den = q.den := by rw [sub_eq_add_neg, intCast_add_den, neg_den] @[simp] theorem add_natCast_den (q : ℚ) (n : ℕ) : (q + n).den = q.den := mod_cast add_intCast_den q n @[simp] theorem natCast_add_den (n : ℕ) (q : ℚ) : (n + q).den = q.den := mod_cast intCast_add_den n q @[simp] theorem sub_natCast_den (q : ℚ) (n : ℕ) : (q - n).den = q.den := mod_cast sub_intCast_den q n @[simp] theorem natCast_sub_den (n : ℕ) (q : ℚ) : (n - q).den = q.den := mod_cast intCast_sub_den n q @[simp] theorem add_ofNat_den (q : ℚ) (n : ℕ) : (q + ofNat(n)).den = q.den := add_natCast_den q n @[simp] theorem ofNat_add_den (n : ℕ) (q : ℚ) : (ofNat(n) + q).den = q.den := natCast_add_den n q @[simp] theorem sub_ofNat_den (q : ℚ) (n : ℕ) : (q - ofNat(n)).den = q.den := sub_natCast_den .. @[simp] theorem ofNat_sub_den (n : ℕ) (q : ℚ) : (ofNat(n) - q).den = q.den := natCast_sub_den .. /-- A version of `Rat.mul_den` without division. -/ theorem den_mul_den_eq_den_mul_gcd (q₁ q₂ : ℚ) : q₁.den * q₂.den = (q₁ * q₂).den * ((q₁.num * q₂.num).natAbs.gcd (q₁.den * q₂.den)) := by rw [mul_den] exact ((Nat.dvd_iff_div_mul_eq _ _).mp (Nat.gcd_dvd_right _ _)).symm /-- A version of `Rat.mul_num` without division. -/ theorem num_mul_num_eq_num_mul_gcd (q₁ q₂ : ℚ) : q₁.num * q₂.num = (q₁ * q₂).num * ((q₁.num * q₂.num).natAbs.gcd (q₁.den * q₂.den)) := by rw [mul_num] refine (Int.ediv_mul_cancel ?_).symm rw [← Int.dvd_natAbs] exact Int.ofNat_dvd.mpr (Nat.gcd_dvd_left _ _) theorem mul_self_num (q : ℚ) : (q * q).num = q.num * q.num := by rw [mul_num, Int.natAbs_mul, Nat.Coprime.gcd_eq_one, Int.ofNat_one, Int.ediv_one] exact (q.reduced.mul_right q.reduced).mul_left (q.reduced.mul_right q.reduced) theorem mul_self_den (q : ℚ) : (q * q).den = q.den * q.den := by rw [Rat.mul_den, Int.natAbs_mul, Nat.Coprime.gcd_eq_one, Nat.div_one] exact (q.reduced.mul_right q.reduced).mul_left (q.reduced.mul_right q.reduced) theorem add_num_den (q r : ℚ) : q + r = (q.num * r.den + q.den * r.num : ℤ) /. (↑q.den * ↑r.den : ℤ) := by have hqd : (q.den : ℤ) ≠ 0 := Int.natCast_ne_zero_iff_pos.2 q.den_pos have hrd : (r.den : ℤ) ≠ 0 := Int.natCast_ne_zero_iff_pos.2 r.den_pos conv_lhs => rw [← num_divInt_den q, ← num_divInt_den r, divInt_add_divInt _ _ hqd hrd] rw [mul_comm r.num q.den] theorem isSquare_iff {q : ℚ} : IsSquare q ↔ IsSquare q.num ∧ IsSquare q.den := by constructor · rintro ⟨qr, rfl⟩ rw [Rat.mul_self_num, mul_self_den] simp only [IsSquare.mul_self, and_self] · rintro ⟨⟨nr, hnr⟩, ⟨dr, hdr⟩⟩ refine ⟨nr / dr, ?_⟩ rw [div_mul_div_comm, ← Int.cast_mul, ← Nat.cast_mul, ← hnr, ← hdr, num_div_den] @[norm_cast, simp] theorem isSquare_natCast_iff {n : ℕ} : IsSquare (n : ℚ) ↔ IsSquare n := by simp_rw [isSquare_iff, num_natCast, den_natCast, IsSquare.one, and_true, Int.isSquare_natCast_iff] @[norm_cast, simp] theorem isSquare_intCast_iff {z : ℤ} : IsSquare (z : ℚ) ↔ IsSquare z := by simp_rw [isSquare_iff, num_intCast, den_intCast, IsSquare.one, and_true] @[simp] theorem isSquare_ofNat_iff {n : ℕ} : IsSquare (ofNat(n) : ℚ) ↔ IsSquare (OfNat.ofNat n : ℕ) := isSquare_natCast_iff theorem mkRat_add_mkRat_of_den (n₁ n₂ : Int) {d : Nat} (h : d ≠ 0) : mkRat n₁ d + mkRat n₂ d = mkRat (n₁ + n₂) d := by rw [mkRat_add_mkRat _ _ h h, ← add_mul, mkRat_mul_right h] section Casts theorem exists_eq_mul_div_num_and_eq_mul_div_den (n : ℤ) {d : ℤ} (d_ne_zero : d ≠ 0) : ∃ c : ℤ, n = c * ((n : ℚ) / d).num ∧ (d : ℤ) = c * ((n : ℚ) / d).den := haveI : (n : ℚ) / d = Rat.divInt n d := by rw [← Rat.divInt_eq_div] Rat.num_den_mk d_ne_zero this theorem mul_num_den' (q r : ℚ) : (q * r).num * q.den * r.den = q.num * r.num * (q * r).den := by let s := q.num * r.num /. (q.den * r.den : ℤ) have hs : (q.den * r.den : ℤ) ≠ 0 := Int.natCast_ne_zero_iff_pos.mpr (Nat.mul_pos q.pos r.pos) obtain ⟨c, ⟨c_mul_num, c_mul_den⟩⟩ := exists_eq_mul_div_num_and_eq_mul_div_den (q.num * r.num) hs rw [c_mul_num, mul_assoc, mul_comm] nth_rw 1 [c_mul_den] rw [Int.mul_assoc, Int.mul_assoc, mul_eq_mul_left_iff, or_iff_not_imp_right] intro have h : _ = s := divInt_mul_divInt q.num r.num rw [num_divInt_den, num_divInt_den] at h rw [h, mul_comm, ← Rat.eq_iff_mul_eq_mul, ← divInt_eq_div] theorem add_num_den' (q r : ℚ) : (q + r).num * q.den * r.den = (q.num * r.den + r.num * q.den) * (q + r).den := by let s := divInt (q.num * r.den + r.num * q.den) (q.den * r.den : ℤ) have hs : (q.den * r.den : ℤ) ≠ 0 := Int.natCast_ne_zero_iff_pos.mpr (Nat.mul_pos q.pos r.pos) obtain ⟨c, ⟨c_mul_num, c_mul_den⟩⟩ := exists_eq_mul_div_num_and_eq_mul_div_den (q.num * r.den + r.num * q.den) hs rw [c_mul_num, mul_assoc, mul_comm] nth_rw 1 [c_mul_den] repeat rw [Int.mul_assoc] apply mul_eq_mul_left_iff.2 rw [or_iff_not_imp_right] intro have h : _ = s := divInt_add_divInt q.num r.num (mod_cast q.den_ne_zero) (mod_cast r.den_ne_zero) rw [num_divInt_den, num_divInt_den] at h rw [h] rw [mul_comm] apply Rat.eq_iff_mul_eq_mul.mp rw [← divInt_eq_div] theorem substr_num_den' (q r : ℚ) : (q - r).num * q.den * r.den = (q.num * r.den - r.num * q.den) * (q - r).den := by rw [sub_eq_add_neg, sub_eq_add_neg, ← neg_mul, ← num_neg_eq_neg_num, ← den_neg_eq_den r, add_num_den' q (-r)] end Casts protected theorem inv_neg (q : ℚ) : (-q)⁻¹ = -q⁻¹ := by rw [← num_divInt_den q] simp only [Rat.neg_divInt, Rat.inv_divInt, Rat.divInt_neg] theorem num_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : Nat.Coprime a.natAbs b.natAbs) : (a / b : ℚ).num = a := by lift b to ℕ using hb0.le simp only [Int.natAbs_natCast, Int.natCast_pos] at h hb0 rw [← Rat.divInt_eq_div, ← mk_eq_divInt _ _ hb0.ne' h] theorem den_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : Nat.Coprime a.natAbs b.natAbs) : ((a / b : ℚ).den : ℤ) = b := by lift b to ℕ using hb0.le simp only [Int.natAbs_natCast, Int.natCast_pos] at h hb0 rw [← Rat.divInt_eq_div, ← mk_eq_divInt _ _ hb0.ne' h] theorem div_int_inj {a b c d : ℤ} (hb0 : 0 < b) (hd0 : 0 < d) (h1 : Nat.Coprime a.natAbs b.natAbs) (h2 : Nat.Coprime c.natAbs d.natAbs) (h : (a : ℚ) / b = (c : ℚ) / d) : a = c ∧ b = d := by apply And.intro · rw [← num_div_eq_of_coprime hb0 h1, h, num_div_eq_of_coprime hd0 h2] · rw [← den_div_eq_of_coprime hb0 h1, h, den_div_eq_of_coprime hd0 h2] @[norm_cast] theorem intCast_div_self (n : ℤ) : ((n / n : ℤ) : ℚ) = n / n := by by_cases hn : n = 0 · subst hn simp only [Int.cast_zero, zero_div, Int.ediv_zero] · have : (n : ℚ) ≠ 0 := by rwa [← coe_int_inj] at hn simp only [Int.ediv_self hn, Int.cast_one, div_self this] @[norm_cast] theorem natCast_div_self (n : ℕ) : ((n / n : ℕ) : ℚ) = n / n := intCast_div_self n theorem intCast_div (a b : ℤ) (h : b ∣ a) : ((a / b : ℤ) : ℚ) = a / b := by rcases h with ⟨c, rfl⟩ rw [mul_comm b, Int.mul_ediv_assoc c (dvd_refl b), Int.cast_mul, intCast_div_self, Int.cast_mul, mul_div_assoc] theorem natCast_div (a b : ℕ) (h : b ∣ a) : ((a / b : ℕ) : ℚ) = a / b := intCast_div a b (Int.ofNat_dvd.mpr h) theorem den_div_intCast_eq_one_iff (m n : ℤ) (hn : n ≠ 0) : ((m : ℚ) / n).den = 1 ↔ n ∣ m := by replace hn : (n : ℚ) ≠ 0 := num_ne_zero.mp hn constructor · rw [Rat.den_eq_one_iff, eq_div_iff hn] exact mod_cast (Dvd.intro_left _) · exact (intCast_div _ _ · ▸ rfl) theorem den_div_natCast_eq_one_iff (m n : ℕ) (hn : n ≠ 0) : ((m : ℚ) / n).den = 1 ↔ n ∣ m := (den_div_intCast_eq_one_iff m n (Int.ofNat_ne_zero.mpr hn)).trans Int.ofNat_dvd theorem inv_intCast_num_of_pos {a : ℤ} (ha0 : 0 < a) : (a : ℚ)⁻¹.num = 1 := by simp [*] theorem inv_natCast_num_of_pos {a : ℕ} (ha0 : 0 < a) : (a : ℚ)⁻¹.num = 1 := inv_intCast_num_of_pos (mod_cast ha0 : 0 < (a : ℤ)) theorem inv_intCast_den_of_pos {a : ℤ} (ha0 : 0 < a) : ((a : ℚ)⁻¹.den : ℤ) = a := by rw [← ofInt_eq_cast, ofInt, mk_eq_divInt, Rat.inv_divInt, divInt_eq_div, Nat.cast_one] apply den_div_eq_of_coprime ha0 rw [Int.natAbs_one] exact Nat.coprime_one_left _ theorem inv_natCast_den_of_pos {a : ℕ} (ha0 : 0 < a) : (a : ℚ)⁻¹.den = a := by rw [← Int.ofNat_inj, ← Int.cast_natCast a, inv_intCast_den_of_pos] rwa [Int.natCast_pos] theorem inv_intCast_num (a : ℤ) : (a : ℚ)⁻¹.num = Int.sign a := by simp theorem inv_natCast_num (a : ℕ) : (a : ℚ)⁻¹.num = Int.sign a := by simp theorem inv_ofNat_num (a : ℕ) [a.AtLeastTwo] : (ofNat(a) : ℚ)⁻¹.num = 1 := by -- This proof is quite unpleasant: golf / find better simp lemmas? have : 2 ≤ a := Nat.AtLeastTwo.prop simp only [num_inv, num_ofNat, den_ofNat, Nat.cast_one, mul_one, Int.sign_eq_one_iff_pos, gt_iff_lt] change 0 < (a : ℤ) cutsat theorem inv_intCast_den (a : ℤ) : (a : ℚ)⁻¹.den = if a = 0 then 1 else a.natAbs := by simp theorem inv_natCast_den (a : ℕ) : (a : ℚ)⁻¹.den = if a = 0 then 1 else a := by simp theorem inv_ofNat_den (a : ℕ) [a.AtLeastTwo] : (ofNat(a) : ℚ)⁻¹.den = OfNat.ofNat a := by simp [den_inv, Int.natAbs_eq_iff] theorem den_inv_of_ne_zero {q : ℚ} (hq : q ≠ 0) : (q⁻¹).den = q.num.natAbs := by simp [*] protected theorem «forall» {p : ℚ → Prop} : (∀ r, p r) ↔ ∀ a b : ℤ, b ≠ 0 → p (a / b) where mp h _ _ _ := h _ mpr h q := by simpa [num_div_den] using h q.num q.den (mod_cast q.den_ne_zero) protected theorem «exists» {p : ℚ → Prop} : (∃ r, p r) ↔ ∃ a b : ℤ, b ≠ 0 ∧ p (a / b) := by simpa using Rat.forall (p := (¬ p ·)).not /-! ### Denominator as `ℕ+` -/ section PNatDen /-- Denominator as `ℕ+`. -/ def pnatDen (x : ℚ) : ℕ+ := ⟨x.den, x.pos⟩ @[simp] theorem coe_pnatDen (x : ℚ) : (x.pnatDen : ℕ) = x.den := rfl theorem pnatDen_eq_iff_den_eq {x : ℚ} {n : ℕ+} : x.pnatDen = n ↔ x.den = ↑n := Subtype.ext_iff @[simp] theorem pnatDen_one : (1 : ℚ).pnatDen = 1 := rfl @[simp] theorem pnatDen_zero : (0 : ℚ).pnatDen = 1 := rfl end PNatDen end Rat
.lake/packages/mathlib/Mathlib/Data/Rat/Star.lean
import Mathlib.Algebra.GroupWithZero.Commute import Mathlib.Algebra.Order.Monoid.Submonoid import Mathlib.Algebra.Order.Ring.Abs import Mathlib.Algebra.Order.Star.Basic import Mathlib.Data.NNRat.Order import Mathlib.Tactic.FieldSimp /-! # Star ordered ring structures on `ℚ` and `ℚ≥0` This file shows that `ℚ` and `ℚ≥0` are `StarOrderedRing`s. In particular, this means that every nonnegative rational number is a sum of squares. -/ open AddSubmonoid Set open scoped NNRat namespace NNRat @[simp] lemma addSubmonoid_closure_range_pow {n : ℕ} (hn₀ : n ≠ 0) : closure (range fun x : ℚ≥0 ↦ x ^ n) = ⊤ := by refine (eq_top_iff' _).2 fun x ↦ ?_ suffices x = (x.num * x.den ^ (n - 1)) • (x.den : ℚ≥0)⁻¹ ^ n by rw [this] exact nsmul_mem (subset_closure <| mem_range_self _) _ rw [nsmul_eq_mul] push_cast rw [mul_assoc, pow_sub₀, pow_one, mul_right_comm, ← mul_pow, mul_inv_cancel₀, one_pow, one_mul, ← div_eq_mul_inv, num_div_den] all_goals simp [x.den_pos.ne', Nat.one_le_iff_ne_zero, *] @[simp] lemma addSubmonoid_closure_range_mul_self : closure (range fun x : ℚ≥0 ↦ x * x) = ⊤ := by simpa only [sq] using addSubmonoid_closure_range_pow two_ne_zero instance instStarOrderedRing : StarOrderedRing ℚ≥0 where le_iff a b := by simp [eq_comm, le_iff_exists_nonneg_add (a := a)] end NNRat namespace Rat @[simp] lemma addSubmonoid_closure_range_pow {n : ℕ} (hn₀ : n ≠ 0) (hn : Even n) : closure (range fun x : ℚ ↦ x ^ n) = nonneg _ := by convert (AddMonoidHom.map_mclosure NNRat.coeHom <| range fun x ↦ x ^ n).symm · have (x : ℚ) : ∃ y : ℚ≥0, y ^ n = x ^ n := ⟨x.nnabs, by simp [hn.pow_abs]⟩ simp [subset_antisymm_iff, range_subset_iff, this] · ext simp [NNRat.addSubmonoid_closure_range_pow hn₀, NNRat.exists] @[simp] lemma addSubmonoid_closure_range_mul_self : closure (range fun x : ℚ ↦ x * x) = nonneg _ := by simpa only [sq] using addSubmonoid_closure_range_pow two_ne_zero even_two instance instStarOrderedRing : StarOrderedRing ℚ where le_iff a b := by simp [eq_comm, le_iff_exists_nonneg_add (a := a)] end Rat
.lake/packages/mathlib/Mathlib/Data/Rat/Init.lean
import Mathlib.Data.Nat.Notation import Mathlib.Tactic.Lemma import Mathlib.Tactic.TypeStar import Batteries.Classes.RatCast /-! # Basic definitions around the rational numbers This file declares `ℚ` notation for the rationals and defines the nonnegative rationals `ℚ≥0`. This file is eligible to upstreaming to Batteries. -/ @[inherit_doc] notation "ℚ" => Rat /-- Nonnegative rational numbers. -/ def NNRat := {q : ℚ // 0 ≤ q} @[inherit_doc] notation "ℚ≥0" => NNRat /-! ### Cast from `NNRat` This section sets up the typeclasses necessary to declare the canonical embedding `ℚ≥0` to any semifield. -/ /-- Typeclass for the canonical homomorphism `ℚ≥0 → K`. This should be considered as a notation typeclass. The sole purpose of this typeclass is to be extended by `DivisionSemiring`. -/ class NNRatCast (K : Type*) where /-- The canonical homomorphism `ℚ≥0 → K`. Do not use directly. Use the coercion instead. -/ protected nnratCast : ℚ≥0 → K instance NNRat.instNNRatCast : NNRatCast ℚ≥0 where nnratCast q := q variable {K : Type*} [NNRatCast K] /-- Canonical homomorphism from `ℚ≥0` to a division semiring `K`. This is just the bare function in order to aid in creating instances of `DivisionSemiring`. -/ @[coe, reducible, match_pattern] protected def NNRat.cast : ℚ≥0 → K := NNRatCast.nnratCast -- See note [coercion into rings] instance NNRatCast.toCoeTail [NNRatCast K] : CoeTail ℚ≥0 K where coe := NNRat.cast -- See note [coercion into rings] instance NNRatCast.toCoeHTCT [NNRatCast K] : CoeHTCT ℚ≥0 K where coe := NNRat.cast instance Rat.instNNRatCast : NNRatCast ℚ := ⟨Subtype.val⟩ /-! ### Numerator and denominator of a nonnegative rational -/ namespace NNRat /-- The numerator of a nonnegative rational. -/ def num (q : ℚ≥0) : ℕ := (q : ℚ).num.natAbs /-- The denominator of a nonnegative rational. -/ def den (q : ℚ≥0) : ℕ := (q : ℚ).den @[simp] lemma num_mk (q : ℚ) (hq : 0 ≤ q) : num ⟨q, hq⟩ = q.num.natAbs := rfl @[simp] lemma den_mk (q : ℚ) (hq : 0 ≤ q) : den ⟨q, hq⟩ = q.den := rfl @[norm_cast] lemma cast_id (n : ℚ≥0) : NNRat.cast n = n := rfl @[simp] lemma cast_eq_id : NNRat.cast = id := rfl end NNRat namespace Rat @[norm_cast] lemma cast_id (n : ℚ) : Rat.cast n = n := rfl @[simp] lemma cast_eq_id : Rat.cast = id := rfl end Rat
.lake/packages/mathlib/Mathlib/Data/Rat/Denumerable.lean
import Mathlib.Algebra.Ring.Rat import Mathlib.Data.Rat.Encodable import Mathlib.Algebra.CharZero.Infinite import Mathlib.Logic.Denumerable /-! # Denumerability of ℚ This file proves that ℚ is denumerable. The fact that ℚ has cardinality ℵ₀ is proved in `Mathlib/Data/Rat/Cardinal.lean` -/ assert_not_exists Module Field namespace Rat open Denumerable /-- **Denumerability of the Rational Numbers** -/ instance instDenumerable : Denumerable ℚ := ofEncodableOfInfinite ℚ end Rat
.lake/packages/mathlib/Mathlib/Data/Rat/Defs.lean
import Mathlib.Algebra.Group.Defs import Mathlib.Data.Nat.Basic import Mathlib.Data.Rat.Init import Mathlib.Order.Basic import Mathlib.Tactic.Common /-! # Basics for the Rational Numbers ## Summary We define the integral domain structure on `ℚ` and prove basic lemmas about it. The definition of the field structure on `ℚ` will be done in `Mathlib/Algebra/Field/Rat.lean` once the `Field` class has been defined. ## Main Definitions - `Rat.divInt n d` constructs a rational number `q = n / d` from `n d : ℤ`. ## Notation - `/.` is infix notation for `Rat.divInt`. -/ -- TODO: If `Inv` was defined earlier than `Algebra.Group.Defs`, we could have -- assert_not_exists Monoid assert_not_exists MonoidWithZero Lattice PNat Nat.gcd_greatest open Function namespace Rat variable {q : ℚ} theorem pos (a : ℚ) : 0 < a.den := Nat.pos_of_ne_zero a.den_nz lemma mk'_num_den (q : ℚ) : mk' q.num q.den q.den_nz q.reduced = q := rfl @[simp] theorem ofInt_eq_cast (n : ℤ) : ofInt n = Int.cast n := rfl lemma intCast_injective : Injective (Int.cast : ℤ → ℚ) := fun _ _ ↦ congr_arg num lemma natCast_injective : Injective (Nat.cast : ℕ → ℚ) := intCast_injective.comp fun _ _ ↦ Int.natCast_inj.1 @[deprecated (since := "2025-10-24")] alias intCast_eq_zero := intCast_eq_zero_iff @[deprecated (since := "2025-10-24")] alias natCast_eq_zero := natCast_eq_zero_iff @[simp high, norm_cast] lemma intCast_eq_one_iff {n : ℤ} : (n : ℚ) = 1 ↔ n = 1 := intCast_inj @[deprecated (since := "2025-10-24")] alias intCast_eq_one := intCast_eq_one_iff @[simp high, norm_cast] lemma natCast_eq_one_iff {n : ℕ} : (n : ℚ) = 1 ↔ n = 1 := natCast_inj @[deprecated (since := "2025-10-24")] alias natCast_eq_one := natCast_eq_one_iff lemma mkRat_eq_divInt (n d) : mkRat n d = n /. d := rfl @[simp] lemma mk'_zero (d) (h : d ≠ 0) (w) : mk' 0 d h w = 0 := by congr; simp_all lemma num_ne_zero {q : ℚ} : q.num ≠ 0 ↔ q ≠ 0 := num_eq_zero.not @[simp] lemma den_ne_zero (q : ℚ) : q.den ≠ 0 := q.den_pos.ne' @[simp] theorem divInt_eq_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b = 0 ↔ a = 0 := by rw [← zero_divInt b, divInt_eq_divInt_iff b0 b0, Int.zero_mul, Int.mul_eq_zero, or_iff_left b0] theorem divInt_ne_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b ≠ 0 ↔ a ≠ 0 := (divInt_eq_zero b0).not -- TODO: Rename `mkRat_num_den` in Lean core alias mkRat_num_den' := mkRat_self theorem intCast_eq_divInt (z : ℤ) : (z : ℚ) = z /. 1 := mk'_eq_divInt theorem lift_binop_eq (f : ℚ → ℚ → ℚ) (f₁ : ℤ → ℤ → ℤ → ℤ → ℤ) (f₂ : ℤ → ℤ → ℤ → ℤ → ℤ) (fv : ∀ {n₁ d₁ h₁ c₁ n₂ d₂ h₂ c₂}, f ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ = f₁ n₁ d₁ n₂ d₂ /. f₂ n₁ d₁ n₂ d₂) (f0 : ∀ {n₁ d₁ n₂ d₂}, d₁ ≠ 0 → d₂ ≠ 0 → f₂ n₁ d₁ n₂ d₂ ≠ 0) (a b c d : ℤ) (b0 : b ≠ 0) (d0 : d ≠ 0) (H : ∀ {n₁ d₁ n₂ d₂}, a * d₁ = n₁ * b → c * d₂ = n₂ * d → f₁ n₁ d₁ n₂ d₂ * f₂ a b c d = f₁ a b c d * f₂ n₁ d₁ n₂ d₂) : f (a /. b) (c /. d) = f₁ a b c d /. f₂ a b c d := by generalize ha : a /. b = x; obtain ⟨n₁, d₁, h₁, c₁⟩ := x; rw [mk'_eq_divInt] at ha generalize hc : c /. d = x; obtain ⟨n₂, d₂, h₂, c₂⟩ := x; rw [mk'_eq_divInt] at hc rw [fv] have d₁0 := Int.ofNat_ne_zero.2 h₁ have d₂0 := Int.ofNat_ne_zero.2 h₂ exact (divInt_eq_divInt_iff (f0 d₁0 d₂0) (f0 b0 d0)).2 (H ((divInt_eq_divInt_iff b0 d₁0).1 ha) ((divInt_eq_divInt_iff d0 d₂0).1 hc)) attribute [simp] divInt_add_divInt attribute [simp] neg_divInt lemma neg_def (q : ℚ) : -q = -q.num /. q.den := by rw [← neg_divInt, num_divInt_den] @[simp] lemma divInt_neg (n d : ℤ) : n /. -d = -n /. d := divInt_neg' .. lemma mk'_mul_mk' (n₁ n₂ : ℤ) (d₁ d₂ : ℕ) (hd₁ hd₂ hnd₁ hnd₂) (h₁₂ : n₁.natAbs.Coprime d₂) (h₂₁ : n₂.natAbs.Coprime d₁) : mk' n₁ d₁ hd₁ hnd₁ * mk' n₂ d₂ hd₂ hnd₂ = mk' (n₁ * n₂) (d₁ * d₂) (Nat.mul_ne_zero hd₁ hd₂) (by rw [Int.natAbs_mul]; exact (hnd₁.mul_left h₂₁).mul_right (h₁₂.mul_left hnd₂)) := by rw [mul_def]; simp [mk_eq_normalize] lemma mul_eq_mkRat (q r : ℚ) : q * r = mkRat (q.num * r.num) (q.den * r.den) := by rw [mul_def, normalize_eq_mkRat] @[deprecated (since := "2025-08-25")] alias divInt_eq_divInt := divInt_eq_divInt_iff lemma pow_eq_mkRat (q : ℚ) (n : ℕ) : q ^ n = mkRat (q.num ^ n) (q.den ^ n) := by rw [pow_def, mk_eq_mkRat] lemma pow_eq_divInt (q : ℚ) (n : ℕ) : q ^ n = q.num ^ n /. q.den ^ n := by rw [pow_def, mk_eq_divInt, Int.natCast_pow] @[simp] lemma mk'_pow (num : ℤ) (den : ℕ) (hd hdn) (n : ℕ) : mk' num den hd hdn ^ n = mk' (num ^ n) (den ^ n) (by simp [Nat.pow_eq_zero, hd]) (by rw [Int.natAbs_pow]; exact hdn.pow _ _) := rfl @[deprecated (since := "2025-08-25")] alias inv_divInt' := inv_divInt @[simp] lemma inv_mkRat (a : ℤ) (b : ℕ) : (mkRat a b)⁻¹ = b /. a := by rw [mkRat_eq_divInt, inv_divInt] @[deprecated (since := "2025-08-25")] alias inv_def' := inv_def @[simp] lemma divInt_div_divInt (n₁ d₁ n₂ d₂) : (n₁ /. d₁) / (n₂ /. d₂) = (n₁ * d₂) /. (d₁ * n₂) := by rw [div_def, inv_divInt, divInt_mul_divInt] lemma div_def' (q r : ℚ) : q / r = (q.num * r.den) /. (q.den * r.num) := by rw [← divInt_div_divInt, num_divInt_den, num_divInt_den] variable (a b c : ℚ) @[simp] lemma divInt_one (n : ℤ) : n /. 1 = n := by simp [divInt, mkRat, normalize] lemma divInt_one_one : 1 /. 1 = 1 := by rw [divInt_one, Rat.intCast_one] protected theorem zero_ne_one : 0 ≠ (1 : ℚ) := by rw [ne_comm, ← divInt_one_one, divInt_ne_zero] <;> omega attribute [simp] mkRat_eq_zero -- Extra instances to short-circuit type class resolution -- TODO(Mario): this instance slows down Mathlib.Data.Real.Basic instance nontrivial : Nontrivial ℚ where exists_pair_ne := ⟨1, 0, by decide⟩ /-! ### The rational numbers are a group -/ instance addCommGroup : AddCommGroup ℚ where zero_add := Rat.zero_add add_zero := Rat.add_zero add_comm := Rat.add_comm add_assoc := Rat.add_assoc neg_add_cancel := Rat.neg_add_cancel sub_eq_add_neg := Rat.sub_eq_add_neg nsmul := (· * ·) zsmul := (· * ·) nsmul_zero := Rat.zero_mul nsmul_succ n q := by change ((n + 1 : Int) : Rat) * q = _ rw [Rat.intCast_add, Rat.add_mul, Rat.intCast_one, Rat.one_mul] rfl zsmul_zero' := Rat.zero_mul zsmul_succ' _ _ := by simp [Rat.add_mul] zsmul_neg' _ _ := by rw [Int.negSucc_eq, Rat.intCast_neg, Rat.neg_mul]; rfl instance addGroup : AddGroup ℚ := by infer_instance instance addCommMonoid : AddCommMonoid ℚ := by infer_instance instance addMonoid : AddMonoid ℚ := by infer_instance instance addLeftCancelSemigroup : AddLeftCancelSemigroup ℚ := by infer_instance instance addRightCancelSemigroup : AddRightCancelSemigroup ℚ := by infer_instance instance addCommSemigroup : AddCommSemigroup ℚ := by infer_instance instance addSemigroup : AddSemigroup ℚ := by infer_instance instance commMonoid : CommMonoid ℚ where mul_one := Rat.mul_one one_mul := Rat.one_mul mul_comm := Rat.mul_comm mul_assoc := Rat.mul_assoc npow n q := q ^ n npow_zero := Rat.pow_zero npow_succ n q := Rat.pow_succ q n instance monoid : Monoid ℚ := by infer_instance instance commSemigroup : CommSemigroup ℚ := by infer_instance instance semigroup : Semigroup ℚ := by infer_instance theorem eq_iff_mul_eq_mul {p q : ℚ} : p = q ↔ p.num * q.den = q.num * p.den := by conv => lhs rw [← num_divInt_den p, ← num_divInt_den q] apply Rat.divInt_eq_divInt_iff <;> · rw [← Int.natCast_zero, Ne, Int.ofNat_inj] apply den_nz @[simp] theorem den_neg_eq_den (q : ℚ) : (-q).den = q.den := rfl @[simp] theorem num_neg_eq_neg_num (q : ℚ) : (-q).num = -q.num := rfl -- Not `@[simp]` as `num_ofNat` is stronger. theorem num_zero : Rat.num 0 = 0 := rfl -- Not `@[simp]` as `den_ofNat` is stronger. theorem den_zero : Rat.den 0 = 1 := rfl lemma zero_of_num_zero {q : ℚ} (hq : q.num = 0) : q = 0 := by simpa [hq] using q.num_divInt_den.symm theorem zero_iff_num_zero {q : ℚ} : q = 0 ↔ q.num = 0 := ⟨fun _ => by simp [*], zero_of_num_zero⟩ -- `Not `@[simp]` as `num_ofNat` is stronger. theorem num_one : (1 : ℚ).num = 1 := rfl @[simp] theorem den_one : (1 : ℚ).den = 1 := rfl theorem mk_num_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : n ≠ 0 := fun this => hq <| by simpa [this] using hqnd theorem mk_denom_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : d ≠ 0 := fun this => hq <| by simpa [this] using hqnd theorem divInt_ne_zero_of_ne_zero {n d : ℤ} (h : n ≠ 0) (hd : d ≠ 0) : n /. d ≠ 0 := (divInt_ne_zero hd).mpr h section Casts protected theorem add_divInt (a b c : ℤ) : (a + b) /. c = a /. c + b /. c := if h : c = 0 then by simp [h] else by rw [divInt_add_divInt _ _ h h, divInt_eq_divInt_iff h (Int.mul_ne_zero h h)] simp [Int.add_mul, Int.mul_assoc] lemma intCast_div_eq_divInt (n d : ℤ) : (n : ℚ) / d = n /. d := by rw [divInt_eq_div] theorem natCast_div_eq_divInt (n d : ℕ) : (n : ℚ) / d = n /. d := Rat.intCast_div_eq_divInt n d theorem divInt_mul_divInt_cancel {x : ℤ} (hx : x ≠ 0) (n d : ℤ) : n /. x * (x /. d) = n /. d := by by_cases hd : d = 0 · rw [hd] simp rw [divInt_mul_divInt, x.mul_comm, divInt_mul_right hx] theorem coe_int_num_of_den_eq_one {q : ℚ} (hq : q.den = 1) : (q.num : ℚ) = q := by conv_rhs => rw [← num_divInt_den q, hq] rw [intCast_eq_divInt] rfl lemma eq_num_of_isInt {q : ℚ} (h : q.isInt) : q = q.num := by rw [Rat.isInt, Nat.beq_eq_true_eq] at h exact (Rat.coe_int_num_of_den_eq_one h).symm theorem den_eq_one_iff (r : ℚ) : r.den = 1 ↔ ↑r.num = r := ⟨Rat.coe_int_num_of_den_eq_one, fun h => h ▸ Rat.den_intCast r.num⟩ instance canLift : CanLift ℚ ℤ (↑) fun q => q.den = 1 := ⟨fun q hq => ⟨q.num, coe_int_num_of_den_eq_one hq⟩⟩ -- Will be subsumed by `Int.coe_inj` after we have defined -- `LinearOrderedField ℚ` (which implies characteristic zero). theorem coe_int_inj (m n : ℤ) : (m : ℚ) = n ↔ m = n := ⟨congr_arg num, congr_arg _⟩ end Casts /-- A version of `Rat.casesOn` that uses `/` instead of `Rat.mk'`. Use as ```lean cases r with | div p q nonzero coprime => ``` -/ @[elab_as_elim, cases_eliminator, induction_eliminator] def divCasesOn {C : ℚ → Sort*} (a : ℚ) (div : ∀ (n : ℤ) (d : ℕ), d ≠ 0 → n.natAbs.Coprime d → C (n / d)) : C a := a.casesOn fun n d nz red => by rw [Rat.mk'_eq_divInt, Rat.divInt_eq_div]; exact div n d nz red end Rat
.lake/packages/mathlib/Mathlib/Data/Rat/Floor.lean
import Mathlib.Algebra.Order.Round import Mathlib.Data.Rat.Cast.Order import Mathlib.Tactic.FieldSimp import Mathlib.Tactic.Ring /-! # Floor Function for Rational Numbers ## Summary We define the `FloorRing` instance on `ℚ`. Some technical lemmas relating `floor` to integer division and modulo arithmetic are derived as well as some simple inequalities. ## Tags rat, rationals, ℚ, floor -/ assert_not_exists Finset open Int namespace Rat variable {α : Type*} [Field α] [LinearOrder α] [IsStrictOrderedRing α] [FloorRing α] variable {R : Type*} [Ring R] [LinearOrder R] [IsStrictOrderedRing R] [FloorRing R] @[deprecated Rat.le_floor_iff (since := "2025-09-02")] protected theorem le_floor {z : ℤ} : ∀ {r : ℚ}, z ≤ Rat.floor r ↔ (z : ℚ) ≤ r | ⟨n, d, h, c⟩ => by simp only [Rat.floor_def] rw [mk'_eq_divInt] have h' := Int.ofNat_lt.2 (Nat.pos_of_ne_zero h) conv => rhs rw [intCast_eq_divInt, Rat.divInt_le_divInt zero_lt_one h', mul_one] exact Int.le_ediv_iff_mul_le h' instance : FloorRing ℚ := (FloorRing.ofFloor ℚ Rat.floor) fun _ _ => Rat.le_floor_iff.symm /-- This variant of `floor_def` uses the `Int.floor` (for any `FloorRing`) rather than `Rat.floor`. -/ protected theorem floor_def' {q : ℚ} : ⌊q⌋ = q.num / q.den := Rat.floor_def q /-- This variant of `ceil_def` uses the `Int.ceil` (for any `FloorRing`) rather than `Rat.ceil`. -/ protected theorem ceil_def' (q : ℚ) : ⌈q⌉ = -(-q.num / ↑q.den) := by change -⌊-q⌋ = _ rw [Rat.floor_def', num_neg_eq_neg_num, den_neg_eq_den] @[norm_cast] theorem floor_intCast_div_natCast (n : ℤ) (d : ℕ) : ⌊(↑n / ↑d : ℚ)⌋ = n / (↑d : ℤ) := by rw [Rat.floor_def'] obtain rfl | hd := eq_zero_or_pos (a := d) · simp set q := (n : ℚ) / d with q_eq obtain ⟨c, n_eq_c_mul_num, d_eq_c_mul_denom⟩ : ∃ c, n = c * q.num ∧ (d : ℤ) = c * q.den := by rw [q_eq] exact mod_cast @Rat.exists_eq_mul_div_num_and_eq_mul_div_den n d (mod_cast hd.ne') rw [n_eq_c_mul_num, d_eq_c_mul_denom] refine (Int.mul_ediv_mul_of_pos _ _ <| pos_of_mul_pos_left ?_ <| Int.natCast_nonneg q.den).symm rwa [← d_eq_c_mul_denom, Int.natCast_pos] @[norm_cast] theorem ceil_intCast_div_natCast (n : ℤ) (d : ℕ) : ⌈(↑n / ↑d : ℚ)⌉ = -((-n) / (↑d : ℤ)) := by conv_lhs => rw [← neg_neg ⌈_⌉, ← floor_neg] rw [← neg_div, ← Int.cast_neg, floor_intCast_div_natCast] @[norm_cast] theorem floor_natCast_div_natCast (n d : ℕ) : ⌊(↑n / ↑d : ℚ)⌋ = n / d := floor_intCast_div_natCast n d @[norm_cast] theorem ceil_natCast_div_natCast (n d : ℕ) : ⌈(↑n / ↑d : ℚ)⌉ = -((-n) / d) := ceil_intCast_div_natCast n d @[norm_cast] theorem natFloor_natCast_div_natCast (n d : ℕ) : ⌊(↑n / ↑d : ℚ)⌋₊ = n / d := by rw [← Int.ofNat_inj, Int.natCast_floor_eq_floor (by positivity)] push_cast exact floor_intCast_div_natCast n d @[simp, norm_cast] theorem floor_cast (x : ℚ) : ⌊(x : α)⌋ = ⌊x⌋ := floor_eq_iff.2 (mod_cast floor_eq_iff.1 (Eq.refl ⌊x⌋)) @[simp, norm_cast] theorem ceil_cast (x : ℚ) : ⌈(x : α)⌉ = ⌈x⌉ := by rw [← neg_inj, ← floor_neg, ← floor_neg, ← Rat.cast_neg, Rat.floor_cast] @[simp, norm_cast] theorem round_cast (x : ℚ) : round (x : α) = round x := by have : ((x + 1 / 2 : ℚ) : α) = x + 1 / 2 := by simp rw [round_eq, round_eq, ← this, floor_cast] @[simp, norm_cast] theorem cast_fract (x : ℚ) : (↑(fract x) : α) = fract (x : α) := by simp only [fract, cast_sub, cast_intCast, floor_cast] section NormNum open Mathlib.Meta.NormNum Qq theorem isNat_intFloor {R} [Ring R] [LinearOrder R] [IsStrictOrderedRing R] [FloorRing R] (r : R) (m : ℕ) : IsNat r m → IsNat ⌊r⌋ m := by rintro ⟨⟨⟩⟩; exact ⟨by simp⟩ theorem isInt_intFloor {R} [Ring R] [LinearOrder R] [IsStrictOrderedRing R] [FloorRing R] (r : R) (m : ℤ) : IsInt r m → IsInt ⌊r⌋ m := by rintro ⟨⟨⟩⟩; exact ⟨by simp⟩ theorem isNat_intFloor_ofIsNNRat (r : α) (n : ℕ) (d : ℕ) : IsNNRat r n d → IsNat ⌊r⌋ (n / d) := by rintro ⟨inv, rfl⟩ constructor simp only [invOf_eq_inv, ← div_eq_mul_inv] rw [← Int.ofNat_ediv_ofNat, ← floor_natCast_div_natCast n d, ← floor_cast (α := α), Rat.cast_div, cast_natCast, cast_natCast] theorem isInt_intFloor_ofIsRat_neg (r : α) (n : ℕ) (d : ℕ) : IsRat r (.negOfNat n) d → IsInt ⌊r⌋ (.negOfNat (-(-n / d) : ℤ).toNat) := by rintro ⟨inv, rfl⟩ constructor simp only [invOf_eq_inv, ← div_eq_mul_inv, Int.cast_id] rw [← ceil_intCast_div_natCast n d, Int.cast_natCast] rw [@negOfNat_eq (toNat _), ofNat_eq_coe, natCast_toNat_eq_self.mpr (ceil_nonneg (div_nonneg n.cast_nonneg d.cast_nonneg)), ← Int.cast_natCast n, ceil_intCast_div_natCast n d, neg_neg, ← ofNat_eq_coe, ← negOfNat_eq, ← floor_intCast_div_natCast (.negOfNat n) d, ← floor_cast (α := α), Rat.cast_div, cast_intCast, cast_natCast] /-- `norm_num` extension for `Int.floor` -/ @[norm_num ⌊_⌋] def evalIntFloor : NormNumExt where eval {u αZ} e := do match u, αZ, e with | 0, ~q(ℤ), ~q(@Int.floor $α $instR $instO $instF $x) => match ← derive x with | .isBool .. => failure | .isNat _ _ pb => do let _i ← synthInstanceQ q(IsStrictOrderedRing $α) assertInstancesCommute return .isNat q(inferInstance) _ q(isNat_intFloor $x _ $pb) | .isNegNat _ _ pb => do let _i ← synthInstanceQ q(IsStrictOrderedRing $α) assertInstancesCommute -- floor always keeps naturals negative, so we can shortcut `.isInt` return .isNegNat q(inferInstance) _ q(isInt_intFloor _ _ $pb) | .isNNRat _ q n d h => do let _i ← synthInstanceQ q(Field $α) let _i ← synthInstanceQ q(IsStrictOrderedRing $α) assertInstancesCommute have z : Q(ℕ) := Lean.mkRawNatLit ⌊q⌋₊ letI : $z =Q $n / $d := ⟨⟩ return .isNat q(inferInstance) z q(isNat_intFloor_ofIsNNRat $x $n $d $h) | .isNegNNRat _ q n d h => do let _i ← synthInstanceQ q(Field $α) let _i ← synthInstanceQ q(IsStrictOrderedRing $α) assertInstancesCommute have z : Q(ℕ) := Lean.mkRawNatLit (-⌊q⌋).toNat letI : $z =Q (-(-$n / $d) : ℤ).toNat := ⟨⟩ return .isNegNat q(inferInstance) z q(isInt_intFloor_ofIsRat_neg $x $n $d $h) | _, _, _ => failure theorem isNat_intCeil {R} [Ring R] [LinearOrder R] [IsStrictOrderedRing R] [FloorRing R] (r : R) (m : ℕ) : IsNat r m → IsNat ⌈r⌉ m := by rintro ⟨⟨⟩⟩; exact ⟨by simp⟩ theorem isInt_intCeil {R} [Ring R] [LinearOrder R] [IsStrictOrderedRing R] [FloorRing R] (r : R) (m : ℤ) : IsInt r m → IsInt ⌈r⌉ m := by rintro ⟨⟨⟩⟩; exact ⟨by simp⟩ theorem isNat_intCeil_ofIsNNRat (r : α) (n : ℕ) (d : ℕ) : IsNNRat r n d → IsNat ⌈r⌉ (-(-n / d) : ℤ).toNat := by rintro ⟨inv, rfl⟩ constructor simp only [invOf_eq_inv, ← div_eq_mul_inv] rw [← ceil_intCast_div_natCast n d, ← ceil_cast (α := α), Rat.cast_div, cast_intCast, cast_natCast, Int.cast_natCast, Int.natCast_toNat_eq_self.mpr (ceil_nonneg (div_nonneg n.cast_nonneg d.cast_nonneg))] theorem isInt_intCeil_ofIsRat_neg (r : α) (n : ℕ) (d : ℕ) : IsRat r (.negOfNat n) d → IsInt ⌈r⌉ (.negOfNat (n / d)) := by rintro ⟨inv, rfl⟩ constructor simp only [invOf_eq_inv, ← div_eq_mul_inv, Int.cast_id] rw [@negOfNat_eq (n / d), ofNat_eq_coe, ← ofNat_ediv_ofNat, ← floor_natCast_div_natCast n d, floor_natCast_div_natCast n d, ← neg_neg (n : ℤ), ← ofNat_eq_coe, ← negOfNat_eq, ← ceil_intCast_div_natCast (.negOfNat n) d, ← ceil_cast (α := α), Rat.cast_div, cast_intCast, cast_natCast] /-- `norm_num` extension for `Int.ceil` -/ @[norm_num ⌈_⌉] def evalIntCeil : NormNumExt where eval {u αZ} e := do match u, αZ, e with | 0, ~q(ℤ), ~q(@Int.ceil $α $instR $instO $instF $x) => match ← derive x with | .isBool .. => failure | .isNat _ _ pb => do let _i ← synthInstanceQ q(IsStrictOrderedRing $α) assertInstancesCommute return .isNat q(inferInstance) _ q(isNat_intCeil $x _ $pb) | .isNegNat _ _ pb => do let _i ← synthInstanceQ q(IsStrictOrderedRing $α) assertInstancesCommute -- ceil always keeps naturals negative, so we can shortcut `.isInt` return .isNegNat q(inferInstance) _ q(isInt_intCeil _ _ $pb) | .isNNRat _ q n d h => do let _i ← synthInstanceQ q(Field $α) let _i ← synthInstanceQ q(IsStrictOrderedRing $α) assertInstancesCommute have z : Q(ℕ) := Lean.mkRawNatLit ⌈q⌉₊ letI : $z =Q (-(-$n / $d) : ℤ).toNat := ⟨⟩ return .isNat q(inferInstance) z q(isNat_intCeil_ofIsNNRat $x $n $d $h) | .isNegNNRat _ q n d h => do let _i ← synthInstanceQ q(Field $α) let _i ← synthInstanceQ q(IsStrictOrderedRing $α) assertInstancesCommute have z : Q(ℕ) := Lean.mkRawNatLit (-⌈q⌉).toNat letI : $z =Q $n / $d := ⟨⟩ return .isNegNat q(inferInstance) z q(isInt_intCeil_ofIsRat_neg $x $n $d $h) | _, _, _ => failure theorem isNat_intFract_of_isNat (r : R) (m : ℕ) : IsNat r m → IsNat (Int.fract r) 0 := by rintro ⟨⟨⟩⟩; exact ⟨by simp⟩ theorem isNat_intFract_of_isInt (r : R) (m : ℤ) : IsInt r m → IsNat (Int.fract r) 0 := by rintro ⟨⟨⟩⟩; exact ⟨by simp⟩ theorem isNNRat_intFract_of_isNNRat (r : α) (n d : ℕ) : IsNNRat r n d → IsNNRat (Int.fract r) (n % d) d := by rintro ⟨inv, rfl⟩ refine ⟨inv, ?_⟩ simp only [invOf_eq_inv, ← div_eq_mul_inv, fract_div_natCast_eq_div_natCast_mod] theorem isRat_intFract_of_isRat_negOfNat (r : α) (n d : ℕ) : IsRat r (negOfNat n) d → IsRat (Int.fract r) (-n % d) d := by rintro ⟨inv, rfl⟩ refine ⟨inv, ?_⟩ simp only [invOf_eq_inv, ← div_eq_mul_inv, fract_div_intCast_eq_div_intCast_mod, negOfNat_eq, ofNat_eq_coe] /-- `norm_num` extension for `Int.fract` -/ @[norm_num (Int.fract _)] def evalIntFract : NormNumExt where eval {u α} e := do match e with | ~q(@Int.fract _ $instR $instO $instF $x) => match ← derive x with | .isBool .. => failure | .isNat _ _ pb => do let _i ← synthInstanceQ q(IsStrictOrderedRing $α) assertInstancesCommute have z : Q(ℕ) := Lean.mkRawNatLit 0 letI : $z =Q 0 := ⟨⟩ return .isNat _ z q(isNat_intFract_of_isNat $x _ $pb) | .isNegNat _ _ pb => do let _i ← synthInstanceQ q(IsStrictOrderedRing $α) assertInstancesCommute have z : Q(ℕ) := Lean.mkRawNatLit 0 letI : $z =Q 0 := ⟨⟩ return .isNat _ z q(isNat_intFract_of_isInt _ _ $pb) | .isNNRat _ q n d h => do let _i ← synthInstanceQ q(Field $α) let _i ← synthInstanceQ q(IsStrictOrderedRing $α) assertInstancesCommute have n' : Q(ℕ) := Lean.mkRawNatLit (q.num.natAbs % q.den) letI : $n' =Q $n % $d := ⟨⟩ return .isNNRat _ (Int.fract q) n' d q(isNNRat_intFract_of_isNNRat _ $n $d $h) | .isNegNNRat _ q n d h => do let _i ← synthInstanceQ q(Field $α) let _i ← synthInstanceQ q(IsStrictOrderedRing $α) assertInstancesCommute have n' : Q(ℤ) := mkRawIntLit (q.num % q.den) letI : $n' =Q -$n % $d := ⟨⟩ return .isRat _ (Int.fract q) n' d q(isRat_intFract_of_isRat_negOfNat _ $n $d $h) | _, _, _ => failure /-! ### `norm_num` extension for `round` -/ theorem isNat_round {R : Type*} [Ring R] [LinearOrder R] [IsStrictOrderedRing R] [FloorRing R] (r : R) (m : ℕ) : IsNat r m → IsNat (round r) m := by rintro ⟨⟨⟩⟩; exact ⟨by simp⟩ theorem isInt_round {R : Type*} [Ring R] [LinearOrder R] [IsStrictOrderedRing R] [FloorRing R] (r : R) (m : ℤ) : IsInt r m → IsInt (round r) m := by rintro ⟨⟨⟩⟩; exact ⟨by simp⟩ theorem IsRat.isInt_round {R : Type*} [Field R] [LinearOrder R] [IsStrictOrderedRing R] [FloorRing R] (r : R) (n : ℤ) (d : ℕ) (res : ℤ) (hres : round (n / d : ℚ) = res) : IsRat r n d → IsInt (round r) res := by rintro ⟨inv, rfl⟩ subst res constructor rw [invOf_eq_inv, ← div_eq_mul_inv] norm_cast /-- `norm_num` extension for `round` -/ @[norm_num round _] def evalRound : NormNumExt where eval {u αZ} e := do match u, αZ, e with | 0, ~q(ℤ), ~q(@round $α $instRing $instLinearOrder $instFloorRing $x) => match ← derive x with | .isBool .. => failure | .isNat sα nb pb => do let instIsStrictOrderedRing ← synthInstanceQ q(IsStrictOrderedRing $α) assertInstancesCommute return .isNat q(inferInstance) nb q(isNat_round $x _ $pb) | .isNegNat sα nb pb => do let _instIsStrictOrderedRing ← synthInstanceQ q(IsStrictOrderedRing $α) assertInstancesCommute return .isNegNat q(inferInstance) nb q(isInt_round _ _ $pb) | .isNNRat _ q n d h => do let _instField ← synthInstanceQ q(Field $α) let _instIsStrictOrderedRing ← synthInstanceQ q(IsStrictOrderedRing $α) assertInstancesCommute have z : Q(ℤ) := mkRawIntLit (round q) haveI : $z =Q round (Int.ofNat $n / $d : ℚ) := ⟨⟩ return .isInt q(inferInstance) z (round q) q(IsRat.isInt_round $x $n $d $z rfl (IsNNRat.to_isRat $h)) | .isNegNNRat _ q n d h => do let _instField ← synthInstanceQ q(Field $α) let _instIsStrictOrderedRing ← synthInstanceQ q(IsStrictOrderedRing $α) assertInstancesCommute have z : Q(ℤ) := mkRawIntLit (round q) haveI : $z =Q round ((Int.negOfNat $n) / $d : ℚ) := ⟨⟩ return .isInt q(inferInstance) z (round q) q(IsRat.isInt_round $x (.negOfNat $n) $d $z rfl $h) | _, _, _ => failure end NormNum end Rat theorem Int.mod_nat_eq_sub_mul_floor_rat_div {n : ℤ} {d : ℕ} : n % d = n - d * ⌊(n : ℚ) / d⌋ := by rw [Int.emod_def, Rat.floor_intCast_div_natCast] theorem Nat.coprime_sub_mul_floor_rat_div_of_coprime {n d : ℕ} (n_coprime_d : n.Coprime d) : ((n : ℤ) - d * ⌊(n : ℚ) / d⌋).natAbs.Coprime d := by have : (n : ℤ) % d = n - d * ⌊(n : ℚ) / d⌋ := Int.mod_nat_eq_sub_mul_floor_rat_div rw [← this] have : d.Coprime n := n_coprime_d.symm rwa [Nat.Coprime, Nat.gcd_rec] at this namespace Rat theorem num_lt_succ_floor_mul_den (q : ℚ) : q.num < (⌊q⌋ + 1) * q.den := by suffices (q.num : ℚ) < (⌊q⌋ + 1) * q.den from mod_cast this suffices (q.num : ℚ) < (q - fract q + 1) * q.den by have : (⌊q⌋ : ℚ) = q - fract q := eq_sub_of_add_eq <| floor_add_fract q rwa [this] suffices (q.num : ℚ) < q.num + (1 - fract q) * q.den by have : (q - fract q + 1) * q.den = q.num + (1 - fract q) * q.den := by calc (q - fract q + 1) * q.den = (q + (1 - fract q)) * q.den := by ring _ = q * q.den + (1 - fract q) * q.den := by rw [add_mul] _ = q.num + (1 - fract q) * q.den := by simp rwa [this] suffices 0 < (1 - fract q) * q.den by rw [← sub_lt_iff_lt_add'] simpa have : 0 < 1 - fract q := by have : fract q < 1 := fract_lt_one q have : 0 + fract q < 1 := by simp [this] rwa [lt_sub_iff_add_lt] exact mul_pos this (by exact mod_cast q.pos) theorem fract_inv_num_lt_num_of_pos {q : ℚ} (q_pos : 0 < q) : (fract q⁻¹).num < q.num := by -- we know that the numerator must be positive have q_num_pos : 0 < q.num := Rat.num_pos.mpr q_pos -- we will work with the absolute value of the numerator, which is equal to the numerator have q_num_abs_eq_q_num : (q.num.natAbs : ℤ) = q.num := Int.natAbs_of_nonneg q_num_pos.le set q_inv : ℚ := q.den / q.num with q_inv_def have q_inv_eq : q⁻¹ = q_inv := by rw [q_inv_def, inv_def, divInt_eq_div, Int.cast_natCast] suffices (q_inv - ⌊q_inv⌋).num < q.num by rwa [q_inv_eq] suffices ((q.den - q.num * ⌊q_inv⌋ : ℚ) / q.num).num < q.num by simp only [gt_iff_lt, q_inv] field_simp simp [q_inv, this] suffices (q.den : ℤ) - q.num * ⌊q_inv⌋ < q.num by -- use that `q.num` and `q.den` are coprime to show that the numerator stays unreduced have : ((q.den - q.num * ⌊q_inv⌋ : ℚ) / q.num).num = q.den - q.num * ⌊q_inv⌋ := by suffices ((q.den : ℤ) - q.num * ⌊q_inv⌋).natAbs.Coprime q.num.natAbs from mod_cast Rat.num_div_eq_of_coprime q_num_pos this have tmp := Nat.coprime_sub_mul_floor_rat_div_of_coprime q.reduced.symm simpa only [Nat.cast_natAbs, abs_of_nonneg q_num_pos.le] using tmp rwa [this] -- to show the claim, start with the following inequality have q_inv_num_denom_ineq : q⁻¹.num - ⌊q⁻¹⌋ * q⁻¹.den < q⁻¹.den := by have : q⁻¹.num < (⌊q⁻¹⌋ + 1) * q⁻¹.den := Rat.num_lt_succ_floor_mul_den q⁻¹ have : q⁻¹.num < ⌊q⁻¹⌋ * q⁻¹.den + q⁻¹.den := by rwa [right_distrib, one_mul] at this rwa [← sub_lt_iff_lt_add'] at this -- use that `q.num` and `q.den` are coprime to show that q_inv is the unreduced reciprocal -- of `q` have : q_inv.num = q.den ∧ q_inv.den = q.num.natAbs := by have coprime_q_denom_q_num : q.den.Coprime q.num.natAbs := q.reduced.symm have : Int.natAbs q.den = q.den := by simp rw [← this] at coprime_q_denom_q_num rw [q_inv_def] constructor · exact mod_cast Rat.num_div_eq_of_coprime q_num_pos coprime_q_denom_q_num · suffices (((q.den : ℚ) / q.num).den : ℤ) = q.num.natAbs by exact mod_cast this rw [q_num_abs_eq_q_num] exact mod_cast Rat.den_div_eq_of_coprime q_num_pos coprime_q_denom_q_num rwa [q_inv_eq, this.left, this.right, q_num_abs_eq_q_num, mul_comm] at q_inv_num_denom_ineq end Rat
.lake/packages/mathlib/Mathlib/Data/Rat/BigOperators.lean
import Mathlib.Data.Rat.Cast.CharZero import Mathlib.Algebra.BigOperators.Group.Finset.Defs /-! # Casting lemmas for rational numbers involving sums and products -/ variable {ι α : Type*} namespace Rat section WithDivRing variable [DivisionRing α] [CharZero α] @[simp, norm_cast] theorem cast_list_sum (s : List ℚ) : (↑s.sum : α) = (s.map (↑)).sum := map_list_sum (Rat.castHom α) _ @[simp, norm_cast] theorem cast_multiset_sum (s : Multiset ℚ) : (↑s.sum : α) = (s.map (↑)).sum := map_multiset_sum (Rat.castHom α) _ @[simp, norm_cast] theorem cast_sum (s : Finset ι) (f : ι → ℚ) : ∑ i ∈ s, f i = ∑ i ∈ s, (f i : α) := map_sum (Rat.castHom α) _ s @[simp, norm_cast] theorem cast_list_prod (s : List ℚ) : (↑s.prod : α) = (s.map (↑)).prod := map_list_prod (Rat.castHom α) _ end WithDivRing section Field variable [Field α] [CharZero α] @[simp, norm_cast] theorem cast_multiset_prod (s : Multiset ℚ) : (↑s.prod : α) = (s.map (↑)).prod := map_multiset_prod (Rat.castHom α) _ @[simp, norm_cast] theorem cast_prod (s : Finset ι) (f : ι → ℚ) : ∏ i ∈ s, f i = ∏ i ∈ s, (f i : α) := map_prod (Rat.castHom α) _ _ end Field end Rat
.lake/packages/mathlib/Mathlib/Data/Rat/Cardinal.lean
import Mathlib.Algebra.CharZero.Infinite import Mathlib.Algebra.Ring.Rat import Mathlib.Data.Rat.Encodable import Mathlib.SetTheory.Cardinal.Basic /-! # Cardinality of ℚ This file proves that the Cardinality of ℚ is ℵ₀ -/ assert_not_exists Module Field open Cardinal theorem Cardinal.mkRat : #ℚ = ℵ₀ := mk_eq_aleph0 ℚ
.lake/packages/mathlib/Mathlib/Data/Rat/Encodable.lean
import Mathlib.Logic.Encodable.Basic import Mathlib.Data.Rat.Init /-! # The rationals are `Encodable`. As a consequence we also get the instance `Countable ℚ`. This is kept separate from `Data.Rat.Defs` in order to minimize imports. -/ namespace Rat instance : Encodable ℚ := Encodable.ofEquiv (Σ n : ℤ, { d : ℕ // 0 < d ∧ n.natAbs.Coprime d }) ⟨fun ⟨a, b, c, d⟩ => ⟨a, b, Nat.pos_of_ne_zero c, d⟩, fun ⟨a, b, c, d⟩ => ⟨a, b, Nat.pos_iff_ne_zero.mp c, d⟩, fun _ => rfl, fun ⟨_, _, _, _⟩ => rfl⟩ end Rat
.lake/packages/mathlib/Mathlib/Data/Rat/Cast/Lemmas.lean
import Mathlib.Algebra.Order.Nonneg.Field import Mathlib.Data.Rat.Cast.Defs import Mathlib.Tactic.Positivity.Basic /-! # Some exiled lemmas about casting These lemmas have been removed from `Mathlib/Data/Rat/Cast/Defs.lean` to avoiding needing to import `Mathlib/Algebra/Field/Basic.lean` there. In fact, these lemmas don't appear to be used anywhere in Mathlib, so perhaps this file can simply be deleted. -/ namespace Rat variable {α : Type*} [DivisionRing α] -- Note that this is more general than `(Rat.castHom α).map_pow`. @[simp, norm_cast] lemma cast_pow (p : ℚ) (n : ℕ) : ↑(p ^ n) = (p ^ n : α) := by rw [cast_def, cast_def, den_pow, num_pow, Nat.cast_pow, Int.cast_pow, div_eq_mul_inv, ← inv_pow, ← (Int.cast_commute _ _).mul_pow, ← div_eq_mul_inv] @[simp] theorem cast_inv_nat (n : ℕ) : ((n⁻¹ : ℚ) : α) = (n : α)⁻¹ := by rcases n with - | n · simp rw [cast_def, inv_natCast_num, inv_natCast_den, if_neg n.succ_ne_zero, Int.sign_eq_one_of_pos (Int.ofNat_succ_pos n), Int.cast_one, one_div] @[simp] theorem cast_inv_int (n : ℤ) : ((n⁻¹ : ℚ) : α) = (n : α)⁻¹ := by rcases n with n | n · simp [cast_inv_nat] · simp only [Int.cast_negSucc, cast_neg, inv_neg, cast_inv_nat] @[simp, norm_cast] theorem cast_nnratCast {K} [DivisionRing K] (q : ℚ≥0) : ((q : ℚ) : K) = (q : K) := by rw [Rat.cast_def, NNRat.cast_def, NNRat.cast_def] have hn := @num_div_eq_of_coprime q.num q.den ?hdp q.coprime_num_den on_goal 1 => have hd := @den_div_eq_of_coprime q.num q.den ?hdp q.coprime_num_den case hdp => simpa only [Int.natCast_pos] using q.den_pos simp only [Int.cast_natCast, Nat.cast_inj] at hn hd rw [hn, hd, Int.cast_natCast] /-- Casting a scientific literal via `ℚ` is the same as casting directly. -/ @[simp, norm_cast] theorem cast_ofScientific {K} [DivisionRing K] (m : ℕ) (s : Bool) (e : ℕ) : (OfScientific.ofScientific m s e : ℚ) = (OfScientific.ofScientific m s e : K) := by rw [← NNRat.cast_ofScientific (K := K), ← NNRat.cast_ofScientific, cast_nnratCast] end Rat namespace NNRat @[simp, norm_cast] theorem cast_pow {K} [DivisionSemiring K] (q : ℚ≥0) (n : ℕ) : NNRat.cast (q ^ n) = (NNRat.cast q : K) ^ n := by rw [cast_def, cast_def, den_pow, num_pow, Nat.cast_pow, Nat.cast_pow, div_eq_mul_inv, ← inv_pow, ← (Nat.cast_commute _ _).mul_pow, ← div_eq_mul_inv] theorem cast_zpow_of_ne_zero {K} [DivisionSemiring K] (q : ℚ≥0) (z : ℤ) (hq : (q.num : K) ≠ 0) : NNRat.cast (q ^ z) = (NNRat.cast q : K) ^ z := by obtain ⟨n, rfl | rfl⟩ := z.eq_nat_or_neg · simp · simp_rw [zpow_neg, zpow_natCast, ← inv_pow, NNRat.cast_pow] congr rw [cast_inv_of_ne_zero hq] @[simp] theorem cast_mk {K} [DivisionRing K] (q : ℚ) (h : 0 ≤ q) : (NNRat.cast ⟨q, h⟩ : K) = (q : K) := by simp only [NNRat.cast_def, NNRat.num_mk, Nat.cast_natAbs, NNRat.den_mk, Rat.cast_def] rw [abs_of_nonneg (by simpa)] open OfScientific in theorem Nonneg.coe_ofScientific {K} [Field K] [LinearOrder K] [IsStrictOrderedRing K] (m : ℕ) (s : Bool) (e : ℕ) : (ofScientific m s e : {x : K // 0 ≤ x}).val = ofScientific m s e := rfl end NNRat
.lake/packages/mathlib/Mathlib/Data/Rat/Cast/Order.lean
import Mathlib.Algebra.Order.Field.Rat import Mathlib.Data.Rat.Cast.CharZero import Mathlib.Tactic.Positivity.Core /-! # Casts of rational numbers into linear ordered fields. -/ variable {F ι α β : Type*} namespace Rat variable {p q : ℚ} @[simp] theorem castHom_rat : castHom ℚ = RingHom.id ℚ := RingHom.ext cast_id section LinearOrderedField variable {K : Type*} [Field K] [LinearOrder K] [IsStrictOrderedRing K] theorem cast_pos_of_pos (hq : 0 < q) : (0 : K) < q := by rw [Rat.cast_def] exact div_pos (Int.cast_pos.2 <| num_pos.2 hq) (Nat.cast_pos.2 q.pos) @[gcongr, mono] theorem cast_strictMono : StrictMono ((↑) : ℚ → K) := fun p q => by simpa only [sub_pos, cast_sub] using cast_pos_of_pos (K := K) (q := q - p) @[gcongr, mono] theorem cast_mono : Monotone ((↑) : ℚ → K) := cast_strictMono.monotone /-- Coercion from `ℚ` as an order embedding. -/ @[simps!] def castOrderEmbedding : ℚ ↪o K := OrderEmbedding.ofStrictMono (↑) cast_strictMono @[simp, norm_cast] lemma cast_le : (p : K) ≤ q ↔ p ≤ q := castOrderEmbedding.le_iff_le @[simp, norm_cast] lemma cast_lt : (p : K) < q ↔ p < q := cast_strictMono.lt_iff_lt @[simp] lemma cast_nonneg : 0 ≤ (q : K) ↔ 0 ≤ q := by norm_cast @[simp] lemma cast_nonpos : (q : K) ≤ 0 ↔ q ≤ 0 := by norm_cast @[simp] lemma cast_pos : (0 : K) < q ↔ 0 < q := by norm_cast @[simp] lemma cast_lt_zero : (q : K) < 0 ↔ q < 0 := by norm_cast @[simp, norm_cast] theorem cast_le_natCast {m : ℚ} {n : ℕ} : (m : K) ≤ n ↔ m ≤ (n : ℚ) := by rw [← cast_le (K := K), cast_natCast] @[simp, norm_cast] theorem natCast_le_cast {m : ℕ} {n : ℚ} : (m : K) ≤ n ↔ (m : ℚ) ≤ n := by rw [← cast_le (K := K), cast_natCast] @[simp, norm_cast] theorem cast_le_intCast {m : ℚ} {n : ℤ} : (m : K) ≤ n ↔ m ≤ (n : ℚ) := by rw [← cast_le (K := K), cast_intCast] @[simp, norm_cast] theorem intCast_le_cast {m : ℤ} {n : ℚ} : (m : K) ≤ n ↔ (m : ℚ) ≤ n := by rw [← cast_le (K := K), cast_intCast] @[simp, norm_cast] theorem cast_lt_natCast {m : ℚ} {n : ℕ} : (m : K) < n ↔ m < (n : ℚ) := by rw [← cast_lt (K := K), cast_natCast] @[simp, norm_cast] theorem natCast_lt_cast {m : ℕ} {n : ℚ} : (m : K) < n ↔ (m : ℚ) < n := by rw [← cast_lt (K := K), cast_natCast] @[simp, norm_cast] theorem cast_lt_intCast {m : ℚ} {n : ℤ} : (m : K) < n ↔ m < (n : ℚ) := by rw [← cast_lt (K := K), cast_intCast] @[simp, norm_cast] theorem intCast_lt_cast {m : ℤ} {n : ℚ} : (m : K) < n ↔ (m : ℚ) < n := by rw [← cast_lt (K := K), cast_intCast] @[simp, norm_cast] lemma cast_min (p q : ℚ) : (↑(min p q) : K) = min (p : K) (q : K) := (@cast_mono K _).map_min @[simp, norm_cast] lemma cast_max (p q : ℚ) : (↑(max p q) : K) = max (p : K) (q : K) := (@cast_mono K _).map_max @[simp, norm_cast] lemma cast_abs (q : ℚ) : ((|q| : ℚ) : K) = |(q : K)| := by simp [abs_eq_max_neg] open Set @[simp] theorem preimage_cast_Icc (p q : ℚ) : (↑) ⁻¹' Icc (p : K) q = Icc p q := castOrderEmbedding.preimage_Icc .. @[simp] theorem preimage_cast_Ico (p q : ℚ) : (↑) ⁻¹' Ico (p : K) q = Ico p q := castOrderEmbedding.preimage_Ico .. @[simp] theorem preimage_cast_Ioc (p q : ℚ) : (↑) ⁻¹' Ioc (p : K) q = Ioc p q := castOrderEmbedding.preimage_Ioc p q @[simp] theorem preimage_cast_Ioo (p q : ℚ) : (↑) ⁻¹' Ioo (p : K) q = Ioo p q := castOrderEmbedding.preimage_Ioo p q @[simp] theorem preimage_cast_Ici (q : ℚ) : (↑) ⁻¹' Ici (q : K) = Ici q := castOrderEmbedding.preimage_Ici q @[simp] theorem preimage_cast_Iic (q : ℚ) : (↑) ⁻¹' Iic (q : K) = Iic q := castOrderEmbedding.preimage_Iic q @[simp] theorem preimage_cast_Ioi (q : ℚ) : (↑) ⁻¹' Ioi (q : K) = Ioi q := castOrderEmbedding.preimage_Ioi q @[simp] theorem preimage_cast_Iio (q : ℚ) : (↑) ⁻¹' Iio (q : K) = Iio q := castOrderEmbedding.preimage_Iio q @[simp] theorem preimage_cast_uIcc (p q : ℚ) : (↑) ⁻¹' uIcc (p : K) q = uIcc p q := (castOrderEmbedding (K := K)).preimage_uIcc p q @[simp] theorem preimage_cast_uIoc (p q : ℚ) : (↑) ⁻¹' uIoc (p : K) q = uIoc p q := (castOrderEmbedding (K := K)).preimage_uIoc p q end LinearOrderedField end Rat namespace NNRat variable {K} [Semifield K] [LinearOrder K] [IsStrictOrderedRing K] {p q : ℚ≥0} theorem cast_strictMono : StrictMono ((↑) : ℚ≥0 → K) := fun p q h => by rwa [NNRat.cast_def, NNRat.cast_def, div_lt_div_iff₀, ← Nat.cast_mul, ← Nat.cast_mul, Nat.cast_lt (α := K), ← NNRat.lt_def] · simp · simp @[mono] theorem cast_mono : Monotone ((↑) : ℚ≥0 → K) := cast_strictMono.monotone /-- Coercion from `ℚ` as an order embedding. -/ @[simps!] def castOrderEmbedding : ℚ≥0 ↪o K := OrderEmbedding.ofStrictMono (↑) cast_strictMono @[simp, norm_cast] lemma cast_le : (p : K) ≤ q ↔ p ≤ q := castOrderEmbedding.le_iff_le @[simp, norm_cast] lemma cast_lt : (p : K) < q ↔ p < q := cast_strictMono.lt_iff_lt @[simp] lemma cast_nonpos : (q : K) ≤ 0 ↔ q ≤ 0 := by norm_cast @[simp] lemma cast_pos : (0 : K) < q ↔ 0 < q := by norm_cast @[norm_cast] lemma cast_lt_zero : (q : K) < 0 ↔ q < 0 := by norm_cast @[simp] lemma not_cast_lt_zero : ¬(q : K) < 0 := mod_cast not_lt_zero' @[simp] lemma cast_le_one : (p : K) ≤ 1 ↔ p ≤ 1 := by norm_cast @[simp] lemma one_le_cast : 1 ≤ (p : K) ↔ 1 ≤ p := by norm_cast @[simp] lemma cast_lt_one : (p : K) < 1 ↔ p < 1 := by norm_cast @[simp] lemma one_lt_cast : 1 < (p : K) ↔ 1 < p := by norm_cast section ofNat variable {n : ℕ} [n.AtLeastTwo] @[simp] lemma cast_le_ofNat : (p : K) ≤ ofNat(n) ↔ p ≤ OfNat.ofNat n := by simp [← cast_le (K := K)] @[simp] lemma ofNat_le_cast : ofNat(n) ≤ (p : K) ↔ OfNat.ofNat n ≤ p := by simp [← cast_le (K := K)] @[simp] lemma cast_lt_ofNat : (p : K) < ofNat(n) ↔ p < OfNat.ofNat n := by simp [← cast_lt (K := K)] @[simp] lemma ofNat_lt_cast : ofNat(n) < (p : K) ↔ OfNat.ofNat n < p := by simp [← cast_lt (K := K)] end ofNat @[simp, norm_cast] theorem cast_le_natCast {m : ℚ≥0} {n : ℕ} : (m : K) ≤ n ↔ m ≤ (n : ℚ≥0) := by rw [← cast_le (K := K), cast_natCast] @[simp, norm_cast] theorem natCast_le_cast {m : ℕ} {n : ℚ≥0} : (m : K) ≤ n ↔ (m : ℚ≥0) ≤ n := by rw [← cast_le (K := K), cast_natCast] @[simp, norm_cast] theorem cast_lt_natCast {m : ℚ≥0} {n : ℕ} : (m : K) < n ↔ m < (n : ℚ≥0) := by rw [← cast_lt (K := K), cast_natCast] @[simp, norm_cast] theorem natCast_lt_cast {m : ℕ} {n : ℚ≥0} : (m : K) < n ↔ (m : ℚ≥0) < n := by rw [← cast_lt (K := K), cast_natCast] @[simp, norm_cast] lemma cast_min (p q : ℚ≥0) : (↑(min p q) : K) = min (p : K) (q : K) := (@cast_mono K _).map_min @[simp, norm_cast] lemma cast_max (p q : ℚ≥0) : (↑(max p q) : K) = max (p : K) (q : K) := (@cast_mono K _).map_max open Set @[simp] theorem preimage_cast_Icc (p q : ℚ≥0) : (↑) ⁻¹' Icc (p : K) q = Icc p q := castOrderEmbedding.preimage_Icc .. @[simp] theorem preimage_cast_Ico (p q : ℚ≥0) : (↑) ⁻¹' Ico (p : K) q = Ico p q := castOrderEmbedding.preimage_Ico .. @[simp] theorem preimage_cast_Ioc (p q : ℚ≥0) : (↑) ⁻¹' Ioc (p : K) q = Ioc p q := castOrderEmbedding.preimage_Ioc p q @[simp] theorem preimage_cast_Ioo (p q : ℚ≥0) : (↑) ⁻¹' Ioo (p : K) q = Ioo p q := castOrderEmbedding.preimage_Ioo p q @[simp] theorem preimage_cast_Ici (p : ℚ≥0) : (↑) ⁻¹' Ici (p : K) = Ici p := castOrderEmbedding.preimage_Ici p @[simp] theorem preimage_cast_Iic (p : ℚ≥0) : (↑) ⁻¹' Iic (p : K) = Iic p := castOrderEmbedding.preimage_Iic p @[simp] theorem preimage_cast_Ioi (p : ℚ≥0) : (↑) ⁻¹' Ioi (p : K) = Ioi p := castOrderEmbedding.preimage_Ioi p @[simp] theorem preimage_cast_Iio (p : ℚ≥0) : (↑) ⁻¹' Iio (p : K) = Iio p := castOrderEmbedding.preimage_Iio p @[simp] theorem preimage_cast_uIcc (p q : ℚ≥0) : (↑) ⁻¹' uIcc (p : K) q = uIcc p q := (castOrderEmbedding (K := K)).preimage_uIcc p q @[simp] theorem preimage_cast_uIoc (p q : ℚ≥0) : (↑) ⁻¹' uIoc (p : K) q = uIoc p q := (castOrderEmbedding (K := K)).preimage_uIoc p q end NNRat namespace Mathlib.Meta.Positivity open Lean Meta Qq Function /-- Extension for Rat.cast. -/ @[positivity Rat.cast _] def evalRatCast : PositivityExt where eval {u α} _zα _pα e := do let ~q(@Rat.cast _ (_) ($a : ℚ)) := e | throwError "not Rat.cast" match ← core q(inferInstance) q(inferInstance) a with | .positive pa => let _oα ← synthInstanceQ q(Field $α) let _oα ← synthInstanceQ q(LinearOrder $α) let _oα ← synthInstanceQ q(IsStrictOrderedRing $α) assumeInstancesCommute return .positive q((Rat.cast_pos (K := $α)).mpr $pa) | .nonnegative pa => let _oα ← synthInstanceQ q(Field $α) let _oα ← synthInstanceQ q(LinearOrder $α) let _oα ← synthInstanceQ q(IsStrictOrderedRing $α) assumeInstancesCommute return .nonnegative q((Rat.cast_nonneg (K := $α)).mpr $pa) | .nonzero pa => let _oα ← synthInstanceQ q(DivisionRing $α) let _cα ← synthInstanceQ q(CharZero $α) assumeInstancesCommute return .nonzero q((Rat.cast_ne_zero (α := $α)).mpr $pa) | .none => pure .none /-- Extension for NNRat.cast. -/ @[positivity NNRat.cast _] def evalNNRatCast : PositivityExt where eval {u α} _zα _pα e := do let ~q(@NNRat.cast _ (_) ($a : ℚ≥0)) := e | throwError "not NNRat.cast" match ← core q(inferInstance) q(inferInstance) a with | .positive pa => let _oα ← synthInstanceQ q(Semifield $α) let _oα ← synthInstanceQ q(LinearOrder $α) let _oα ← synthInstanceQ q(IsStrictOrderedRing $α) assumeInstancesCommute return .positive q((NNRat.cast_pos (K := $α)).mpr $pa) | _ => let _oα ← synthInstanceQ q(Semifield $α) let _oα ← synthInstanceQ q(LinearOrder $α) let _oα ← synthInstanceQ q(IsStrictOrderedRing $α) assumeInstancesCommute return .nonnegative q(NNRat.cast_nonneg _) end Mathlib.Meta.Positivity
.lake/packages/mathlib/Mathlib/Data/Rat/Cast/Defs.lean
import Mathlib.Algebra.Field.Basic import Mathlib.Algebra.Field.Rat import Mathlib.Algebra.Group.Commute.Basic import Mathlib.Algebra.GroupWithZero.Units.Lemmas import Mathlib.Data.Int.Cast.Lemmas import Mathlib.Data.Rat.Lemmas import Mathlib.Order.Nat /-! # Casts for Rational Numbers ## Summary We define the canonical injection from ℚ into an arbitrary division ring and prove various casting lemmas showing the well-behavedness of this injection. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom, cast, coercion, casting -/ assert_not_exists MulAction IsOrderedMonoid variable {F ι α β : Type*} namespace NNRat variable [DivisionSemiring α] {q r : ℚ≥0} @[simp, norm_cast] lemma cast_natCast (n : ℕ) : ((n : ℚ≥0) : α) = n := by simp [cast_def] @[simp, norm_cast] lemma cast_ofNat (n : ℕ) [n.AtLeastTwo] : (ofNat(n) : ℚ≥0) = (ofNat(n) : α) := cast_natCast _ @[simp, norm_cast] lemma cast_zero : ((0 : ℚ≥0) : α) = 0 := (cast_natCast _).trans Nat.cast_zero @[simp, norm_cast] lemma cast_one : ((1 : ℚ≥0) : α) = 1 := (cast_natCast _).trans Nat.cast_one lemma cast_commute (q : ℚ≥0) (a : α) : Commute (↑q) a := by simpa only [cast_def] using (q.num.cast_commute a).div_left (q.den.cast_commute a) lemma commute_cast (a : α) (q : ℚ≥0) : Commute a q := (cast_commute ..).symm lemma cast_comm (q : ℚ≥0) (a : α) : q * a = a * q := cast_commute _ _ @[norm_cast] lemma cast_divNat_of_ne_zero (a : ℕ) {b : ℕ} (hb : (b : α) ≠ 0) : divNat a b = (a / b : α) := by rcases e : divNat a b with ⟨⟨n, d, h, c⟩, hn⟩ rw [← Rat.num_nonneg] at hn lift n to ℕ using hn have hd : (d : α) ≠ 0 := by refine fun hd ↦ hb ?_ have : Rat.divInt a b = _ := congr_arg NNRat.cast e obtain ⟨k, rfl⟩ : d ∣ b := by simpa [Int.natCast_dvd_natCast, this] using Rat.den_dvd a b simp [*] have hb' : b ≠ 0 := by rintro rfl; exact hb Nat.cast_zero simp_rw [Rat.mk'_eq_divInt, mk_divInt, divNat_inj hb' h] at e rw [cast_def] dsimp rw [Commute.div_eq_div_iff _ hd hb] · norm_cast rw [e] exact b.commute_cast _ @[norm_cast] lemma cast_add_of_ne_zero (hq : (q.den : α) ≠ 0) (hr : (r.den : α) ≠ 0) : ↑(q + r) = (q + r : α) := by rw [add_def, cast_divNat_of_ne_zero, cast_def, cast_def, mul_comm _ q.den, (Nat.commute_cast _ _).div_add_div (Nat.commute_cast _ _) hq hr] · push_cast rfl · push_cast exact mul_ne_zero hq hr @[norm_cast] lemma cast_mul_of_ne_zero (hq : (q.den : α) ≠ 0) (hr : (r.den : α) ≠ 0) : ↑(q * r) = (q * r : α) := by rw [mul_def, cast_divNat_of_ne_zero, cast_def, cast_def, (Nat.commute_cast _ _).div_mul_div_comm (Nat.commute_cast _ _)] · push_cast rfl · push_cast exact mul_ne_zero hq hr @[norm_cast] lemma cast_inv_of_ne_zero (hq : (q.num : α) ≠ 0) : (q⁻¹ : ℚ≥0) = (q⁻¹ : α) := by rw [inv_def, cast_divNat_of_ne_zero _ hq, cast_def, inv_div] @[norm_cast] lemma cast_div_of_ne_zero (hq : (q.den : α) ≠ 0) (hr : (r.num : α) ≠ 0) : ↑(q / r) = (q / r : α) := by rw [div_def, cast_divNat_of_ne_zero, cast_def, cast_def, div_eq_mul_inv (_ / _), inv_div, (Nat.commute_cast _ _).div_mul_div_comm (Nat.commute_cast _ _)] · push_cast rfl · push_cast exact mul_ne_zero hq hr end NNRat namespace Rat variable [DivisionRing α] {p q : ℚ} @[simp, norm_cast] theorem cast_intCast (n : ℤ) : ((n : ℚ) : α) = n := (cast_def _).trans <| show (n / (1 : ℕ) : α) = n by rw [Nat.cast_one, div_one] @[simp, norm_cast] theorem cast_natCast (n : ℕ) : ((n : ℚ) : α) = n := by rw [← Int.cast_natCast, cast_intCast, Int.cast_natCast] @[simp, norm_cast] lemma cast_ofNat (n : ℕ) [n.AtLeastTwo] : ((ofNat(n) : ℚ) : α) = (ofNat(n) : α) := by simp [cast_def] @[simp, norm_cast] theorem cast_zero : ((0 : ℚ) : α) = 0 := (cast_intCast _).trans Int.cast_zero @[simp, norm_cast] theorem cast_one : ((1 : ℚ) : α) = 1 := (cast_intCast _).trans Int.cast_one theorem cast_commute (r : ℚ) (a : α) : Commute (↑r) a := by simpa only [cast_def] using (r.1.cast_commute a).div_left (r.2.cast_commute a) theorem cast_comm (r : ℚ) (a : α) : (r : α) * a = a * r := (cast_commute r a).eq theorem commute_cast (a : α) (r : ℚ) : Commute a r := (r.cast_commute a).symm @[norm_cast] lemma cast_divInt_of_ne_zero (a : ℤ) {b : ℤ} (b0 : (b : α) ≠ 0) : (a /. b : α) = a / b := by have b0' : b ≠ 0 := by refine mt ?_ b0 simp +contextual rcases e : a /. b with ⟨n, d, h, c⟩ have d0 : (d : α) ≠ 0 := by intro d0 have dd := den_dvd a b rcases show (d : ℤ) ∣ b by rwa [e] at dd with ⟨k, ke⟩ have : (b : α) = (d : α) * (k : α) := by rw [ke, Int.cast_mul, Int.cast_natCast] rw [d0, zero_mul] at this contradiction rw [mk'_eq_divInt] at e have := congr_arg ((↑) : ℤ → α) ((divInt_eq_divInt_iff b0' <| ne_of_gt <| Int.natCast_pos.2 h.bot_lt).1 e) rw [Int.cast_mul, Int.cast_mul, Int.cast_natCast] at this rw [eq_comm, cast_def, div_eq_mul_inv, eq_div_iff_mul_eq d0, mul_assoc, (d.commute_cast _).eq, ← mul_assoc, this, mul_assoc, mul_inv_cancel₀ b0, mul_one] @[norm_cast] lemma cast_mkRat_of_ne_zero (a : ℤ) {b : ℕ} (hb : (b : α) ≠ 0) : (mkRat a b : α) = a / b := by rw [Rat.mkRat_eq_divInt, cast_divInt_of_ne_zero, Int.cast_natCast]; rwa [Int.cast_natCast] @[norm_cast] lemma cast_add_of_ne_zero {q r : ℚ} (hq : (q.den : α) ≠ 0) (hr : (r.den : α) ≠ 0) : (q + r : ℚ) = (q + r : α) := by rw [add_def', cast_mkRat_of_ne_zero, cast_def, cast_def, mul_comm r.num, (Nat.cast_commute _ _).div_add_div (Nat.commute_cast _ _) hq hr] · push_cast rfl · push_cast exact mul_ne_zero hq hr @[simp, norm_cast] lemma cast_neg (q : ℚ) : ↑(-q) = (-q : α) := by simp [cast_def, neg_div] @[norm_cast] lemma cast_sub_of_ne_zero (hp : (p.den : α) ≠ 0) (hq : (q.den : α) ≠ 0) : ↑(p - q) = (p - q : α) := by simp [sub_eq_add_neg, cast_add_of_ne_zero, hp, hq] @[norm_cast] lemma cast_mul_of_ne_zero (hp : (p.den : α) ≠ 0) (hq : (q.den : α) ≠ 0) : ↑(p * q) = (p * q : α) := by rw [mul_eq_mkRat, cast_mkRat_of_ne_zero, cast_def, cast_def, (Nat.commute_cast _ _).div_mul_div_comm (Int.commute_cast _ _)] · push_cast rfl · push_cast exact mul_ne_zero hp hq @[norm_cast] lemma cast_inv_of_ne_zero (hq : (q.num : α) ≠ 0) : ↑(q⁻¹) = (q⁻¹ : α) := by rw [inv_def, cast_divInt_of_ne_zero _ hq, cast_def, inv_div, Int.cast_natCast] @[norm_cast] lemma cast_div_of_ne_zero (hp : (p.den : α) ≠ 0) (hq : (q.num : α) ≠ 0) : ↑(p / q) = (p / q : α) := by rw [div_def', cast_divInt_of_ne_zero, cast_def, cast_def, div_eq_mul_inv (_ / _), inv_div, (Int.commute_cast _ _).div_mul_div_comm (Nat.commute_cast _ _)] · push_cast rfl · push_cast exact mul_ne_zero hp hq end Rat open Rat variable [FunLike F α β] @[simp] lemma map_nnratCast [DivisionSemiring α] [DivisionSemiring β] [RingHomClass F α β] (f : F) (q : ℚ≥0) : f q = q := by simp_rw [NNRat.cast_def, map_div₀, map_natCast] @[simp] lemma eq_nnratCast [DivisionSemiring α] [FunLike F ℚ≥0 α] [RingHomClass F ℚ≥0 α] (f : F) (q : ℚ≥0) : f q = q := by rw [← map_nnratCast f, NNRat.cast_id] @[simp] theorem map_ratCast [DivisionRing α] [DivisionRing β] [RingHomClass F α β] (f : F) (q : ℚ) : f q = q := by rw [cast_def, map_div₀, map_intCast, map_natCast, cast_def] @[simp] lemma eq_ratCast [DivisionRing α] [FunLike F ℚ α] [RingHomClass F ℚ α] (f : F) (q : ℚ) : f q = q := by rw [← map_ratCast f, Rat.cast_id] namespace MonoidWithZeroHomClass variable {M₀ : Type*} [MonoidWithZero M₀] section NNRat variable [FunLike F ℚ≥0 M₀] [MonoidWithZeroHomClass F ℚ≥0 M₀] {f g : F} /-- If monoid with zero homs `f` and `g` from `ℚ≥0` agree on the naturals then they are equal. -/ lemma ext_nnrat' (h : ∀ n : ℕ, f n = g n) : f = g := (DFunLike.ext f g) fun r => by rw [← r.num_div_den, div_eq_mul_inv, map_mul, map_mul, h, eq_on_inv₀ f g] apply h /-- If monoid with zero homs `f` and `g` from `ℚ≥0` agree on the naturals then they are equal. See note [partially-applied ext lemmas] for why `comp` is used here. -/ @[ext] lemma ext_nnrat {f g : ℚ≥0 →*₀ M₀} (h : f.comp (Nat.castRingHom ℚ≥0 : ℕ →*₀ ℚ≥0) = g.comp (Nat.castRingHom ℚ≥0)) : f = g := ext_nnrat' <| DFunLike.congr_fun h /-- If monoid with zero homs `f` and `g` from `ℚ≥0` agree on the positive naturals then they are equal. -/ lemma ext_nnrat_on_pnat (same_on_pnat : ∀ n : ℕ, 0 < n → f n = g n) : f = g := ext_nnrat' <| DFunLike.congr_fun <| ext_nat'' ((f : ℚ≥0 →*₀ M₀).comp (Nat.castRingHom ℚ≥0 : ℕ →*₀ ℚ≥0)) ((g : ℚ≥0 →*₀ M₀).comp (Nat.castRingHom ℚ≥0 : ℕ →*₀ ℚ≥0)) (by simpa) end NNRat section Rat variable [FunLike F ℚ M₀] [MonoidWithZeroHomClass F ℚ M₀] {f g : F} /-- If monoid with zero homs `f` and `g` from `ℚ` agree on the integers then they are equal. -/ theorem ext_rat' (h : ∀ m : ℤ, f m = g m) : f = g := (DFunLike.ext f g) fun r => by rw [← r.num_div_den, div_eq_mul_inv, map_mul, map_mul, h, ← Int.cast_natCast, eq_on_inv₀ f g] apply h /-- If monoid with zero homs `f` and `g` from `ℚ` agree on the integers then they are equal. See note [partially-applied ext lemmas] for why `comp` is used here. -/ @[ext] theorem ext_rat {f g : ℚ →*₀ M₀} (h : f.comp (Int.castRingHom ℚ : ℤ →*₀ ℚ) = g.comp (Int.castRingHom ℚ)) : f = g := ext_rat' <| DFunLike.congr_fun h /-- If monoid with zero homs `f` and `g` from `ℚ` agree on the positive naturals and `-1` then they are equal. -/ theorem ext_rat_on_pnat (same_on_neg_one : f (-1) = g (-1)) (same_on_pnat : ∀ n : ℕ, 0 < n → f n = g n) : f = g := ext_rat' <| DFunLike.congr_fun <| show (f : ℚ →*₀ M₀).comp (Int.castRingHom ℚ : ℤ →*₀ ℚ) = (g : ℚ →*₀ M₀).comp (Int.castRingHom ℚ : ℤ →*₀ ℚ) from ext_int' (by simpa) (by simpa) end Rat end MonoidWithZeroHomClass /-- Any two ring homomorphisms from `ℚ` to a semiring are equal. If the codomain is a division ring, then this lemma follows from `eq_ratCast`. -/ theorem RingHom.ext_rat {R : Type*} [Semiring R] [FunLike F ℚ R] [RingHomClass F ℚ R] (f g : F) : f = g := MonoidWithZeroHomClass.ext_rat' <| RingHom.congr_fun <| ((f : ℚ →+* R).comp (Int.castRingHom ℚ)).ext_int ((g : ℚ →+* R).comp (Int.castRingHom ℚ)) instance NNRat.subsingleton_ringHom {R : Type*} [Semiring R] : Subsingleton (ℚ≥0 →+* R) where allEq f g := MonoidWithZeroHomClass.ext_nnrat' <| by simp instance Rat.subsingleton_ringHom {R : Type*} [Semiring R] : Subsingleton (ℚ →+* R) := ⟨RingHom.ext_rat⟩
.lake/packages/mathlib/Mathlib/Data/Rat/Cast/CharZero.lean
import Mathlib.Algebra.GroupWithZero.Units.Lemmas import Mathlib.Data.Rat.Cast.Defs /-! # Casts of rational numbers into characteristic zero fields (or division rings). -/ open Function variable {F ι α β : Type*} namespace Rat variable [DivisionRing α] [CharZero α] {p q : ℚ} @[stacks 09FR "Characteristic zero case."] lemma cast_injective : Injective ((↑) : ℚ → α) | ⟨n₁, d₁, d₁0, c₁⟩, ⟨n₂, d₂, d₂0, c₂⟩, h => by have d₁a : (d₁ : α) ≠ 0 := Nat.cast_ne_zero.2 d₁0 have d₂a : (d₂ : α) ≠ 0 := Nat.cast_ne_zero.2 d₂0 rw [mk'_eq_divInt, mk'_eq_divInt] at h ⊢ rw [cast_divInt_of_ne_zero, cast_divInt_of_ne_zero] at h <;> simp [d₁0, d₂0] at h ⊢ rwa [eq_div_iff_mul_eq d₂a, division_def, mul_assoc, (d₁.cast_commute (d₂ : α)).inv_left₀.eq, ← mul_assoc, ← division_def, eq_comm, eq_div_iff_mul_eq d₁a, eq_comm, ← Int.cast_natCast d₁, ← Int.cast_mul, ← Int.cast_natCast d₂, ← Int.cast_mul, Int.cast_inj, ← mkRat_eq_iff d₁0 d₂0] at h @[simp, norm_cast] lemma cast_inj : (p : α) = q ↔ p = q := cast_injective.eq_iff @[simp, norm_cast] lemma cast_eq_zero : (p : α) = 0 ↔ p = 0 := cast_injective.eq_iff' cast_zero lemma cast_ne_zero : (p : α) ≠ 0 ↔ p ≠ 0 := cast_eq_zero.ne @[simp, norm_cast] lemma cast_add (p q : ℚ) : ↑(p + q) = (p + q : α) := cast_add_of_ne_zero (Nat.cast_ne_zero.2 p.pos.ne') (Nat.cast_ne_zero.2 q.pos.ne') @[simp, norm_cast] lemma cast_sub (p q : ℚ) : ↑(p - q) = (p - q : α) := cast_sub_of_ne_zero (Nat.cast_ne_zero.2 p.pos.ne') (Nat.cast_ne_zero.2 q.pos.ne') @[simp, norm_cast] lemma cast_mul (p q : ℚ) : ↑(p * q) = (p * q : α) := cast_mul_of_ne_zero (Nat.cast_ne_zero.2 p.pos.ne') (Nat.cast_ne_zero.2 q.pos.ne') variable (α) in /-- Coercion `ℚ → α` as a `RingHom`. -/ def castHom : ℚ →+* α where toFun := (↑) map_one' := cast_one map_mul' := cast_mul map_zero' := cast_zero map_add' := cast_add @[simp] lemma coe_castHom : ⇑(castHom α) = ((↑) : ℚ → α) := rfl @[simp, norm_cast] lemma cast_inv (p : ℚ) : ↑(p⁻¹) = (p⁻¹ : α) := map_inv₀ (castHom α) _ @[simp, norm_cast] lemma cast_div (p q : ℚ) : ↑(p / q) = (p / q : α) := map_div₀ (castHom α) .. @[simp, norm_cast] lemma cast_zpow (p : ℚ) (n : ℤ) : ↑(p ^ n) = (p ^ n : α) := map_zpow₀ (castHom α) .. @[norm_cast] theorem cast_divInt (a b : ℤ) : (a /. b : α) = a / b := by simp only [divInt_eq_div, cast_div, cast_intCast] @[deprecated (since := "2025-08-13")] alias cast_mk := cast_divInt end Rat namespace NNRat variable [DivisionSemiring α] [CharZero α] {p q : ℚ≥0} lemma cast_injective : Injective ((↑) : ℚ≥0 → α) := by rintro p q hpq rw [NNRat.cast_def, NNRat.cast_def, Commute.div_eq_div_iff] at hpq on_goal 1 => rw [← p.num_div_den, ← q.num_div_den, div_eq_div_iff] · norm_cast at hpq ⊢ any_goals norm_cast any_goals apply den_ne_zero exact Nat.cast_commute .. @[simp, norm_cast] lemma cast_inj : (p : α) = q ↔ p = q := cast_injective.eq_iff @[simp, norm_cast] lemma cast_eq_zero : (q : α) = 0 ↔ q = 0 := by rw [← cast_zero, cast_inj] lemma cast_ne_zero : (q : α) ≠ 0 ↔ q ≠ 0 := cast_eq_zero.not @[simp, norm_cast] lemma cast_add (p q : ℚ≥0) : ↑(p + q) = (p + q : α) := cast_add_of_ne_zero (Nat.cast_ne_zero.2 p.den_pos.ne') (Nat.cast_ne_zero.2 q.den_pos.ne') @[simp, norm_cast] lemma cast_mul (p q) : (p * q : ℚ≥0) = (p * q : α) := cast_mul_of_ne_zero (Nat.cast_ne_zero.2 p.den_pos.ne') (Nat.cast_ne_zero.2 q.den_pos.ne') variable (α) in /-- Coercion `ℚ≥0 → α` as a `RingHom`. -/ def castHom : ℚ≥0 →+* α where toFun := (↑) map_one' := cast_one map_mul' := cast_mul map_zero' := cast_zero map_add' := cast_add @[simp, norm_cast] lemma coe_castHom : ⇑(castHom α) = (↑) := rfl @[simp, norm_cast] lemma cast_inv (p) : (p⁻¹ : ℚ≥0) = (p : α)⁻¹ := map_inv₀ (castHom α) _ @[simp, norm_cast] lemma cast_div (p q) : (p / q : ℚ≥0) = (p / q : α) := map_div₀ (castHom α) .. @[simp, norm_cast] lemma cast_zpow (q : ℚ≥0) (p : ℤ) : ↑(q ^ p) = ((q : α) ^ p : α) := map_zpow₀ (castHom α) .. @[simp] lemma cast_divNat (a b : ℕ) : (divNat a b : α) = a / b := by rw [← cast_natCast, ← cast_natCast b, ← cast_div] congr ext apply Rat.mkRat_eq_div end NNRat
.lake/packages/mathlib/Mathlib/Data/Rat/NatSqrt/Defs.lean
import Mathlib.Tactic.Positivity import Mathlib.Algebra.Order.Field.Basic /-! Rational approximation of the square root of a natural number. See also `Mathlib.Data.Rat.NatSqrt.Real` for comparisons with the real square root. -/ namespace Nat /-- Approximate the square root of a natural number as a rational number, to within `1 / prec`. -/ def ratSqrt (x : ℕ) (prec : ℕ) : ℚ := ((x * prec ^ 2).sqrt : ℚ) / prec theorem ratSqrt_nonneg (x prec : ℕ) : 0 ≤ ratSqrt x prec := by unfold ratSqrt positivity theorem ratSqrt_sq_le (x : ℕ) {prec : ℕ} (h : 0 < prec) : (ratSqrt x prec) ^ 2 ≤ x := by unfold ratSqrt rw [div_pow, div_le_iff₀ (by positivity)] norm_cast exact sqrt_le' (x * prec ^ 2) theorem lt_ratSqrt_add_inv_prec_sq (x : ℕ) {prec : ℕ} (h : 0 < prec) : x < (ratSqrt x prec + 1 / prec) ^ 2 := by unfold ratSqrt rw [← mul_lt_mul_iff_of_pos_right (a := (prec ^ 2 : ℚ)) (by positivity)] rw [← mul_pow, add_mul] rw [div_mul_cancel₀, div_mul_cancel₀] · norm_cast exact lt_succ_sqrt' (x * prec ^ 2) all_goals norm_cast; positivity end Nat
.lake/packages/mathlib/Mathlib/Data/Rat/NatSqrt/Real.lean
import Mathlib.Data.Rat.NatSqrt.Defs import Mathlib.Data.Real.Sqrt /-! Comparisons between rational approximations to the square root of a natural number and the real square root. -/ namespace Nat theorem ratSqrt_le_realSqrt (x : ℕ) {prec : ℕ} (h : 0 < prec) : ratSqrt x prec ≤ √x := by have := ratSqrt_sq_le (x := x) h have : (x.ratSqrt prec ^ 2 : ℝ) ≤ ↑x := by norm_cast have := Real.sqrt_monotone this rwa [Real.sqrt_sq] at this simpa only [Rat.cast_nonneg] using ratSqrt_nonneg _ _ theorem realSqrt_lt_ratSqrt_add_inv_prec (x : ℕ) {prec : ℕ} (h : 0 < prec) : √x < ratSqrt x prec + 1 / prec := by have := lt_ratSqrt_add_inv_prec_sq (x := x) h have : (x : ℝ) < ↑((x.ratSqrt prec + 1 / prec) ^ 2 : ℚ) := by norm_cast have := Real.sqrt_lt_sqrt (by simp) this rw [Rat.cast_pow, Real.sqrt_sq] at this · push_cast at this exact this · push_cast exact add_nonneg (by simpa using ratSqrt_nonneg _ _) (by simp) theorem realSqrt_mem_Ico (x : ℕ) {prec : ℕ} (h : 0 < prec) : √x ∈ Set.Ico (ratSqrt x prec : ℝ) (ratSqrt x prec + 1 / prec : ℝ) := by grind [ratSqrt_le_realSqrt, realSqrt_lt_ratSqrt_add_inv_prec] #adaptation_note /-- nightly-2025-09-11 We're investigating changing the `grind` heuristics for selecting patterns. Under one heuristic, the next proof would fail if we just passed `realSqrt_lt_ratSqrt_add_inv_prec` to `grind` in the next proof. So for robustness I'm explicitly setting the pattern here. -/ local grind_pattern realSqrt_lt_ratSqrt_add_inv_prec => (x.ratSqrt prec : ℝ) theorem ratSqrt_mem_Ioc (x : ℕ) {prec : ℕ} (h : 0 < prec) : (ratSqrt x prec : ℝ) ∈ Set.Ioc (√x - 1 / prec) √x := by grind [ratSqrt_le_realSqrt] end Nat
.lake/packages/mathlib/Mathlib/Data/Num/Bitwise.lean
import Mathlib.Data.Num.Basic import Mathlib.Data.Vector.Basic /-! # Bitwise operations using binary representation of integers ## Definitions * bitwise operations for `PosNum` and `Num`, * `SNum`, a type that represents integers as a bit string with a sign bit at the end, * arithmetic operations for `SNum`. -/ open List (Vector) namespace PosNum /-- Bitwise "or" for `PosNum`. -/ def lor : PosNum → PosNum → PosNum | 1, bit0 q => bit1 q | 1, q => q | bit0 p, 1 => bit1 p | p, 1 => p | bit0 p, bit0 q => bit0 (lor p q) | bit0 p, bit1 q => bit1 (lor p q) | bit1 p, bit0 q => bit1 (lor p q) | bit1 p, bit1 q => bit1 (lor p q) instance : OrOp PosNum where or := PosNum.lor @[simp] lemma lor_eq_or (p q : PosNum) : p.lor q = p ||| q := rfl /-- Bitwise "and" for `PosNum`. -/ def land : PosNum → PosNum → Num | 1, bit0 _ => 0 | 1, _ => 1 | bit0 _, 1 => 0 | _, 1 => 1 | bit0 p, bit0 q => Num.bit0 (land p q) | bit0 p, bit1 q => Num.bit0 (land p q) | bit1 p, bit0 q => Num.bit0 (land p q) | bit1 p, bit1 q => Num.bit1 (land p q) instance : HAnd PosNum PosNum Num where hAnd := PosNum.land @[simp] lemma land_eq_and (p q : PosNum) : p.land q = p &&& q := rfl /-- Bitwise `fun a b ↦ a && !b` for `PosNum`. For example, `ldiff 5 9 = 4`: ``` 101 1001 ---- 100 ``` -/ def ldiff : PosNum → PosNum → Num | 1, bit0 _ => 1 | 1, _ => 0 | bit0 p, 1 => Num.pos (bit0 p) | bit1 p, 1 => Num.pos (bit0 p) | bit0 p, bit0 q => Num.bit0 (ldiff p q) | bit0 p, bit1 q => Num.bit0 (ldiff p q) | bit1 p, bit0 q => Num.bit1 (ldiff p q) | bit1 p, bit1 q => Num.bit0 (ldiff p q) /-- Bitwise "xor" for `PosNum`. -/ def lxor : PosNum → PosNum → Num | 1, 1 => 0 | 1, bit0 q => Num.pos (bit1 q) | 1, bit1 q => Num.pos (bit0 q) | bit0 p, 1 => Num.pos (bit1 p) | bit1 p, 1 => Num.pos (bit0 p) | bit0 p, bit0 q => Num.bit0 (lxor p q) | bit0 p, bit1 q => Num.bit1 (lxor p q) | bit1 p, bit0 q => Num.bit1 (lxor p q) | bit1 p, bit1 q => Num.bit0 (lxor p q) instance : HXor PosNum PosNum Num where hXor := PosNum.lxor @[simp] lemma lxor_eq_xor (p q : PosNum) : p.lxor q = p ^^^ q := rfl /-- `a.testBit n` is `true` iff the `n`-th bit (starting from the LSB) in the binary representation of `a` is active. If the size of `a` is less than `n`, this evaluates to `false`. -/ def testBit : PosNum → Nat → Bool | 1, 0 => true | 1, _ => false | bit0 _, 0 => false | bit0 p, n + 1 => testBit p n | bit1 _, 0 => true | bit1 p, n + 1 => testBit p n /-- `n.oneBits 0` is the list of indices of active bits in the binary representation of `n`. -/ def oneBits : PosNum → Nat → List Nat | 1, d => [d] | bit0 p, d => oneBits p (d + 1) | bit1 p, d => d :: oneBits p (d + 1) /-- Left-shift the binary representation of a `PosNum`. -/ def shiftl : PosNum → Nat → PosNum | p, 0 => p | p, n + 1 => shiftl p.bit0 n instance : HShiftLeft PosNum Nat PosNum where hShiftLeft := PosNum.shiftl @[simp] lemma shiftl_eq_shiftLeft (p : PosNum) (n : Nat) : p.shiftl n = p <<< n := rfl -- This shows that the tail-recursive definition is the same as the more naïve recursion. theorem shiftl_succ_eq_bit0_shiftl : ∀ (p : PosNum) (n : Nat), p <<< n.succ = bit0 (p <<< n) | _, 0 => rfl | p, .succ n => shiftl_succ_eq_bit0_shiftl p.bit0 n /-- Right-shift the binary representation of a `PosNum`. -/ def shiftr : PosNum → Nat → Num | p, 0 => Num.pos p | 1, _ => 0 | bit0 p, n + 1 => shiftr p n | bit1 p, n + 1 => shiftr p n instance : HShiftRight PosNum Nat Num where hShiftRight := PosNum.shiftr @[simp] lemma shiftr_eq_shiftRight (p : PosNum) (n : Nat) : p.shiftr n = p >>> n := rfl end PosNum namespace Num /-- Bitwise "or" for `Num`. -/ protected def lor : Num → Num → Num | 0, q => q | p, 0 => p | pos p, pos q => pos (p ||| q) instance : OrOp Num where or := Num.lor @[simp] lemma lor_eq_or (p q : Num) : p.lor q = p ||| q := rfl /-- Bitwise "and" for `Num`. -/ def land : Num → Num → Num | 0, _ => 0 | _, 0 => 0 | pos p, pos q => p &&& q instance : AndOp Num where and := Num.land @[simp] lemma land_eq_and (p q : Num) : p.land q = p &&& q := rfl /-- Bitwise `fun a b ↦ a && !b` for `Num`. For example, `ldiff 5 9 = 4`: ``` 101 1001 ---- 100 ``` -/ def ldiff : Num → Num → Num | 0, _ => 0 | p, 0 => p | pos p, pos q => p.ldiff q /-- Bitwise "xor" for `Num`. -/ def lxor : Num → Num → Num | 0, q => q | p, 0 => p | pos p, pos q => p ^^^ q instance : XorOp Num where xor := Num.lxor @[simp] lemma lxor_eq_xor (p q : Num) : p.lxor q = p ^^^ q := rfl /-- Left-shift the binary representation of a `Num`. -/ def shiftl : Num → Nat → Num | 0, _ => 0 | pos p, n => pos (p <<< n) instance : HShiftLeft Num Nat Num where hShiftLeft := Num.shiftl @[simp] lemma shiftl_eq_shiftLeft (p : Num) (n : Nat) : p.shiftl n = p <<< n := rfl /-- Right-shift the binary representation of a `Num`. -/ def shiftr : Num → Nat → Num | 0, _ => 0 | pos p, n => p >>> n instance : HShiftRight Num Nat Num where hShiftRight := Num.shiftr @[simp] lemma shiftr_eq_shiftRight (p : Num) (n : Nat) : p.shiftr n = p >>> n := rfl /-- `a.testBit n` is `true` iff the `n`-th bit (starting from the LSB) in the binary representation of `a` is active. If the size of `a` is less than `n`, this evaluates to `false`. -/ def testBit : Num → Nat → Bool | 0, _ => false | pos p, n => p.testBit n /-- `n.oneBits` is the list of indices of active bits in the binary representation of `n`. -/ def oneBits : Num → List Nat | 0 => [] | pos p => p.oneBits 0 end Num /-- This is a nonzero (and "non minus one") version of `SNum`. See the documentation of `SNum` for more details. -/ inductive NzsNum : Type | msb : Bool → NzsNum /-- Add a bit at the end of a `NzsNum`. -/ | bit : Bool → NzsNum → NzsNum deriving DecidableEq /-- Alternative representation of integers using a sign bit at the end. The convention on sign here is to have the argument to `msb` denote the sign of the MSB itself, with all higher bits set to the negation of this sign. The result is interpreted in two's complement. 13 = ..0001101(base 2) = nz (bit1 (bit0 (bit1 (msb true)))) -13 = ..1110011(base 2) = nz (bit1 (bit1 (bit0 (msb false)))) As with `Num`, a special case must be added for zero, which has no msb, but by two's complement symmetry there is a second special case for -1. Here the `Bool` field indicates the sign of the number. 0 = ..0000000(base 2) = zero false -1 = ..1111111(base 2) = zero true -/ inductive SNum : Type | zero : Bool → SNum | nz : NzsNum → SNum deriving DecidableEq instance : Coe NzsNum SNum := ⟨SNum.nz⟩ instance : Zero SNum := ⟨SNum.zero false⟩ instance : One NzsNum := ⟨NzsNum.msb true⟩ instance : One SNum := ⟨SNum.nz 1⟩ instance : Inhabited NzsNum := ⟨1⟩ instance : Inhabited SNum := ⟨0⟩ /-! The `SNum` representation uses a bit string, essentially a list of 0 (`false`) and 1 (`true`) bits, and the negation of the MSB is sign-extended to all higher bits. -/ namespace NzsNum @[inherit_doc] scoped notation a "::" b => bit a b /-- Sign of a `NzsNum`. -/ def sign : NzsNum → Bool | msb b => not b | _ :: p => sign p /-- Bitwise `not` for `NzsNum`. -/ @[match_pattern] def not : NzsNum → NzsNum | msb b => msb (Not b) | b :: p => Not b :: not p @[inherit_doc] scoped prefix:100 "~" => not /-- Add an inactive bit at the end of a `NzsNum`. This mimics `PosNum.bit0`. -/ def bit0 : NzsNum → NzsNum := bit false /-- Add an active bit at the end of a `NzsNum`. This mimics `PosNum.bit1`. -/ def bit1 : NzsNum → NzsNum := bit true /-- The `head` of a `NzsNum` is the Boolean value of its LSB. -/ def head : NzsNum → Bool | msb b => b | b :: _ => b /-- The `tail` of a `NzsNum` is the `SNum` obtained by removing the LSB. Edge cases: `tail 1 = 0` and `tail (-2) = -1`. -/ def tail : NzsNum → SNum | msb b => SNum.zero (Not b) | _ :: p => p end NzsNum namespace SNum open NzsNum /-- Sign of a `SNum`. -/ def sign : SNum → Bool | zero z => z | nz p => p.sign /-- Bitwise `not` for `SNum`. -/ @[match_pattern] def not : SNum → SNum | zero z => zero (Not z) | nz p => ~p -- Higher `priority` so that `~1 : SNum` is unambiguous. @[inherit_doc] scoped prefix:100 (priority := default + 1) "~" => not /-- Add a bit at the end of a `SNum`. This mimics `NzsNum.bit`. -/ @[match_pattern] def bit : Bool → SNum → SNum | b, zero z => if b = z then zero b else msb b | b, nz p => p.bit b @[inherit_doc] scoped notation a "::" b => bit a b /-- Add an inactive bit at the end of a `SNum`. This mimics `ZNum.bit0`. -/ def bit0 : SNum → SNum := bit false /-- Add an active bit at the end of a `SNum`. This mimics `ZNum.bit1`. -/ def bit1 : SNum → SNum := bit true theorem bit_zero (b : Bool) : (b :: zero b) = zero b := by cases b <;> rfl theorem bit_one (b : Bool) : (b :: zero (Not b)) = msb b := by cases b <;> rfl end SNum namespace NzsNum open SNum /-- A dependent induction principle for `NzsNum`, with base cases `0 : SNum` and `(-1) : SNum`. -/ def drec' {C : SNum → Sort*} (z : ∀ b, C (SNum.zero b)) (s : ∀ b p, C p → C (b :: p)) : ∀ p : NzsNum, C p | msb b => by rw [← bit_one]; exact s b (SNum.zero (Not b)) (z (Not b)) | bit b p => s b p (drec' z s p) end NzsNum namespace SNum open NzsNum /-- The `head` of a `SNum` is the Boolean value of its LSB. -/ def head : SNum → Bool | zero z => z | nz p => p.head /-- The `tail` of a `SNum` is obtained by removing the LSB. Edge cases: `tail 1 = 0`, `tail (-2) = -1`, `tail 0 = 0` and `tail (-1) = -1`. -/ def tail : SNum → SNum | zero z => zero z | nz p => p.tail /-- A dependent induction principle for `SNum` which avoids relying on `NzsNum`. -/ def drec' {C : SNum → Sort*} (z : ∀ b, C (SNum.zero b)) (s : ∀ b p, C p → C (b :: p)) : ∀ p, C p | zero b => z b | nz p => p.drec' z s /-- An induction principle for `SNum` which avoids relying on `NzsNum`. -/ def rec' {α} (z : Bool → α) (s : Bool → SNum → α → α) : SNum → α := drec' z s /-- `SNum.testBit n a` is `true` iff the `n`-th bit (starting from the LSB) of `a` is active. If the size of `a` is less than `n`, this evaluates to `false`. -/ def testBit : Nat → SNum → Bool | 0, p => head p | n + 1, p => testBit n (tail p) /-- The successor of a `SNum` (i.e. the operation adding one). -/ def succ : SNum → SNum := rec' (fun b ↦ cond b 0 1) fun b p succp ↦ cond b (false :: succp) (true :: p) /-- The predecessor of a `SNum` (i.e. the operation of removing one). -/ def pred : SNum → SNum := rec' (fun b ↦ cond b (~1) (~0)) fun b p predp ↦ cond b (false :: p) (true :: predp) /-- The opposite of a `SNum`. -/ protected def neg (n : SNum) : SNum := succ (~n) instance : Neg SNum := ⟨SNum.neg⟩ /-- `SNum.czAdd a b n` is `n + a - b` (where `a` and `b` should be read as either 0 or 1). This is useful to implement the carry system in `cAdd`. -/ def czAdd : Bool → Bool → SNum → SNum | false, false, p => p | false, true, p => pred p | true, false, p => succ p | true, true, p => p end SNum namespace SNum /-- `a.bits n` is the vector of the `n` first bits of `a` (starting from the LSB). -/ def bits : SNum → ∀ n, List.Vector Bool n | _, 0 => Vector.nil | p, n + 1 => head p ::ᵥ bits (tail p) n /-- `SNum.cAdd n m a` is `n + m + a` (where `a` should be read as either 0 or 1). `a` represents a carry bit. -/ def cAdd : SNum → SNum → Bool → SNum := rec' (fun a p c ↦ czAdd c a p) fun a p IH ↦ rec' (fun b c ↦ czAdd c b (a :: p)) fun b q _ c ↦ Bool.xor3 a b c :: IH q (Bool.carry a b c) /-- Add two `SNum`s. -/ protected def add (a b : SNum) : SNum := cAdd a b false instance : Add SNum := ⟨SNum.add⟩ /-- Subtract two `SNum`s. -/ protected def sub (a b : SNum) : SNum := a + -b instance : Sub SNum := ⟨SNum.sub⟩ /-- Multiply two `SNum`s. -/ protected def mul (a : SNum) : SNum → SNum := rec' (fun b ↦ cond b (-a) 0) fun b _ IH ↦ cond b (bit0 IH + a) (bit0 IH) instance : Mul SNum := ⟨SNum.mul⟩ end SNum
.lake/packages/mathlib/Mathlib/Data/Num/Lemmas.lean
import Mathlib.Algebra.Order.Ring.Nat import Mathlib.Algebra.Ring.Int.Defs import Mathlib.Data.Nat.Bitwise import Mathlib.Data.Nat.Cast.Order.Basic import Mathlib.Data.Nat.PSub import Mathlib.Data.Nat.Size import Mathlib.Data.Num.Bitwise /-! # Properties of the binary representation of integers -/ open Int attribute [local simp] add_assoc namespace PosNum variable {α : Type*} @[simp, norm_cast] theorem cast_one [One α] [Add α] : ((1 : PosNum) : α) = 1 := rfl @[simp] theorem cast_one' [One α] [Add α] : (PosNum.one : α) = 1 := rfl @[simp, norm_cast] theorem cast_bit0 [One α] [Add α] (n : PosNum) : (n.bit0 : α) = (n : α) + n := rfl @[simp, norm_cast] theorem cast_bit1 [One α] [Add α] (n : PosNum) : (n.bit1 : α) = ((n : α) + n) + 1 := rfl @[simp, norm_cast] theorem cast_to_nat [AddMonoidWithOne α] : ∀ n : PosNum, ((n : ℕ) : α) = n | 1 => Nat.cast_one | bit0 p => by dsimp; rw [Nat.cast_add, p.cast_to_nat] | bit1 p => by dsimp; rw [Nat.cast_add, Nat.cast_add, Nat.cast_one, p.cast_to_nat] @[norm_cast] theorem to_nat_to_int (n : PosNum) : ((n : ℕ) : ℤ) = n := cast_to_nat _ @[simp, norm_cast] theorem cast_to_int [AddGroupWithOne α] (n : PosNum) : ((n : ℤ) : α) = n := by rw [← to_nat_to_int, Int.cast_natCast, cast_to_nat] theorem succ_to_nat : ∀ n, (succ n : ℕ) = n + 1 | 1 => rfl | bit0 _ => rfl | bit1 p => (congr_arg (fun n ↦ n + n) (succ_to_nat p)).trans <| show ↑p + 1 + ↑p + 1 = ↑p + ↑p + 1 + 1 by simp [add_left_comm] theorem one_add (n : PosNum) : 1 + n = succ n := by cases n <;> rfl theorem add_one (n : PosNum) : n + 1 = succ n := by cases n <;> rfl @[norm_cast] theorem add_to_nat : ∀ m n, ((m + n : PosNum) : ℕ) = m + n | 1, b => by rw [one_add b, succ_to_nat, add_comm, cast_one] | a, 1 => by rw [add_one a, succ_to_nat, cast_one] | bit0 a, bit0 b => (congr_arg (fun n ↦ n + n) (add_to_nat a b)).trans <| add_add_add_comm _ _ _ _ | bit0 a, bit1 b => (congr_arg (fun n ↦ (n + n) + 1) (add_to_nat a b)).trans <| show (a + b + (a + b) + 1 : ℕ) = a + a + (b + b + 1) by simp [add_left_comm] | bit1 a, bit0 b => (congr_arg (fun n ↦ (n + n) + 1) (add_to_nat a b)).trans <| show (a + b + (a + b) + 1 : ℕ) = a + a + 1 + (b + b) by simp [add_comm, add_left_comm] | bit1 a, bit1 b => show (succ (a + b) + succ (a + b) : ℕ) = a + a + 1 + (b + b + 1) by rw [succ_to_nat, add_to_nat a b]; simp [add_left_comm] theorem add_succ : ∀ m n : PosNum, m + succ n = succ (m + n) | 1, b => by simp [one_add] | bit0 a, 1 => congr_arg bit0 (add_one a) | bit1 a, 1 => congr_arg bit1 (add_one a) | bit0 _, bit0 _ => rfl | bit0 a, bit1 b => congr_arg bit0 (add_succ a b) | bit1 _, bit0 _ => rfl | bit1 a, bit1 b => congr_arg bit1 (add_succ a b) theorem bit0_of_bit0 : ∀ n, n + n = bit0 n | 1 => rfl | bit0 p => congr_arg bit0 (bit0_of_bit0 p) | bit1 p => show bit0 (succ (p + p)) = _ by rw [bit0_of_bit0 p, succ] theorem bit1_of_bit1 (n : PosNum) : (n + n) + 1 = bit1 n := show (n + n) + 1 = bit1 n by rw [add_one, bit0_of_bit0, succ] @[norm_cast] theorem mul_to_nat (m) : ∀ n, ((m * n : PosNum) : ℕ) = m * n | 1 => (mul_one _).symm | bit0 p => show (↑(m * p) + ↑(m * p) : ℕ) = ↑m * (p + p) by rw [mul_to_nat m p, left_distrib] | bit1 p => (add_to_nat (bit0 (m * p)) m).trans <| show (↑(m * p) + ↑(m * p) + ↑m : ℕ) = ↑m * (p + p) + m by rw [mul_to_nat m p, left_distrib] theorem to_nat_pos : ∀ n : PosNum, 0 < (n : ℕ) | 1 => Nat.zero_lt_one | bit0 p => let h := to_nat_pos p add_pos h h | bit1 _p => Nat.succ_pos _ theorem cmp_to_nat_lemma {m n : PosNum} : (m : ℕ) < n → (bit1 m : ℕ) < bit0 n := show (m : ℕ) < n → (m + m + 1 + 1 : ℕ) ≤ n + n by intro h; rw [Nat.add_right_comm m m 1, add_assoc]; exact Nat.add_le_add h h theorem cmp_swap (m) : ∀ n, (cmp m n).swap = cmp n m := by induction m with | one => ?_ | bit1 m IH => ?_ | bit0 m IH => ?_ <;> intro n <;> obtain - | n | n := n <;> unfold cmp <;> try { rfl } <;> rw [← IH] <;> cases cmp m n <;> rfl theorem cmp_to_nat : ∀ m n, (Ordering.casesOn (cmp m n) ((m : ℕ) < n) (m = n) ((n : ℕ) < m) : Prop) | 1, 1 => rfl | bit0 a, 1 => let h : (1 : ℕ) ≤ a := to_nat_pos a Nat.add_le_add h h | bit1 a, 1 => Nat.succ_lt_succ <| to_nat_pos <| bit0 a | 1, bit0 b => let h : (1 : ℕ) ≤ b := to_nat_pos b Nat.add_le_add h h | 1, bit1 b => Nat.succ_lt_succ <| to_nat_pos <| bit0 b | bit0 a, bit0 b => by dsimp [cmp] have := cmp_to_nat a b; revert this; cases cmp a b <;> dsimp <;> intro this · exact Nat.add_lt_add this this · rw [this] · exact Nat.add_lt_add this this | bit0 a, bit1 b => by dsimp [cmp] have := cmp_to_nat a b; revert this; cases cmp a b <;> dsimp <;> intro this · exact Nat.le_succ_of_le (Nat.add_lt_add this this) · rw [this] apply Nat.lt_succ_self · exact cmp_to_nat_lemma this | bit1 a, bit0 b => by dsimp [cmp] have := cmp_to_nat a b; revert this; cases cmp a b <;> dsimp <;> intro this · exact cmp_to_nat_lemma this · rw [this] apply Nat.lt_succ_self · exact Nat.le_succ_of_le (Nat.add_lt_add this this) | bit1 a, bit1 b => by dsimp [cmp] have := cmp_to_nat a b; revert this; cases cmp a b <;> dsimp <;> intro this · exact Nat.succ_lt_succ (Nat.add_lt_add this this) · rw [this] · exact Nat.succ_lt_succ (Nat.add_lt_add this this) @[norm_cast] theorem lt_to_nat {m n : PosNum} : (m : ℕ) < n ↔ m < n := show (m : ℕ) < n ↔ cmp m n = Ordering.lt from match cmp m n, cmp_to_nat m n with | Ordering.lt, h => by simp [h] | Ordering.eq, h => by simp [h] | Ordering.gt, h => by simp [not_lt_of_gt h] @[norm_cast] theorem le_to_nat {m n : PosNum} : (m : ℕ) ≤ n ↔ m ≤ n := by rw [← not_lt]; exact not_congr lt_to_nat end PosNum namespace Num variable {α : Type*} open PosNum theorem add_zero (n : Num) : n + 0 = n := by cases n <;> rfl theorem zero_add (n : Num) : 0 + n = n := by cases n <;> rfl theorem add_one : ∀ n : Num, n + 1 = succ n | 0 => rfl | pos p => by cases p <;> rfl theorem add_succ : ∀ m n : Num, m + succ n = succ (m + n) | 0, n => by simp [zero_add] | pos p, 0 => show pos (p + 1) = succ (pos p + 0) by rw [PosNum.add_one, add_zero, succ, succ'] | pos _, pos _ => congr_arg pos (PosNum.add_succ _ _) theorem bit0_of_bit0 : ∀ n : Num, n + n = n.bit0 | 0 => rfl | pos p => congr_arg pos p.bit0_of_bit0 theorem bit1_of_bit1 : ∀ n : Num, (n + n) + 1 = n.bit1 | 0 => rfl | pos p => congr_arg pos p.bit1_of_bit1 @[simp] theorem ofNat'_zero : Num.ofNat' 0 = 0 := by simp [Num.ofNat'] theorem ofNat'_bit (b n) : ofNat' (Nat.bit b n) = cond b Num.bit1 Num.bit0 (ofNat' n) := Nat.binaryRec_eq _ _ (.inl rfl) @[simp] theorem ofNat'_one : Num.ofNat' 1 = 1 := by erw [ofNat'_bit true 0, cond, ofNat'_zero]; rfl theorem bit1_succ : ∀ n : Num, n.bit1.succ = n.succ.bit0 | 0 => rfl | pos _n => rfl theorem ofNat'_succ : ∀ {n}, ofNat' (n + 1) = ofNat' n + 1 := @(Nat.binaryRec (by simp [zero_add]) fun b n ih => by cases b · erw [ofNat'_bit true n, ofNat'_bit] simp only [← bit1_of_bit1, ← bit0_of_bit0, cond] · rw [show n.bit true + 1 = (n + 1).bit false by simp [Nat.bit, mul_add], ofNat'_bit, ofNat'_bit, ih] simp only [cond, add_one, bit1_succ]) @[simp] theorem add_ofNat' (m n) : Num.ofNat' (m + n) = Num.ofNat' m + Num.ofNat' n := by induction n · simp only [Nat.add_zero, ofNat'_zero, add_zero] · simp only [Nat.add_succ, Nat.add_zero, ofNat'_succ, add_one, add_succ, *] @[simp, norm_cast] theorem cast_zero [Zero α] [One α] [Add α] : ((0 : Num) : α) = 0 := rfl @[simp] theorem cast_zero' [Zero α] [One α] [Add α] : (Num.zero : α) = 0 := rfl @[simp, norm_cast] theorem cast_one [Zero α] [One α] [Add α] : ((1 : Num) : α) = 1 := rfl @[simp] theorem cast_pos [Zero α] [One α] [Add α] (n : PosNum) : (Num.pos n : α) = n := rfl theorem succ'_to_nat : ∀ n, (succ' n : ℕ) = n + 1 | 0 => (Nat.zero_add _).symm | pos _p => PosNum.succ_to_nat _ theorem succ_to_nat (n) : (succ n : ℕ) = n + 1 := succ'_to_nat n @[simp, norm_cast] theorem cast_to_nat [AddMonoidWithOne α] : ∀ n : Num, ((n : ℕ) : α) = n | 0 => Nat.cast_zero | pos p => p.cast_to_nat @[norm_cast] theorem add_to_nat : ∀ m n, ((m + n : Num) : ℕ) = m + n | 0, 0 => rfl | 0, pos _q => (Nat.zero_add _).symm | pos _p, 0 => rfl | pos _p, pos _q => PosNum.add_to_nat _ _ @[norm_cast] theorem mul_to_nat : ∀ m n, ((m * n : Num) : ℕ) = m * n | 0, 0 => rfl | 0, pos _q => (zero_mul _).symm | pos _p, 0 => rfl | pos _p, pos _q => PosNum.mul_to_nat _ _ theorem cmp_to_nat : ∀ m n, (Ordering.casesOn (cmp m n) ((m : ℕ) < n) (m = n) ((n : ℕ) < m) : Prop) | 0, 0 => rfl | 0, pos _ => to_nat_pos _ | pos _, 0 => to_nat_pos _ | pos a, pos b => by have := PosNum.cmp_to_nat a b; revert this; dsimp [cmp]; cases PosNum.cmp a b exacts [id, congr_arg pos, id] @[norm_cast] theorem lt_to_nat {m n : Num} : (m : ℕ) < n ↔ m < n := show (m : ℕ) < n ↔ cmp m n = Ordering.lt from match cmp m n, cmp_to_nat m n with | Ordering.lt, h => by simp [h] | Ordering.eq, h => by simp [h] | Ordering.gt, h => by simp [not_lt_of_gt h] @[norm_cast] theorem le_to_nat {m n : Num} : (m : ℕ) ≤ n ↔ m ≤ n := by rw [← not_lt]; exact not_congr lt_to_nat end Num namespace PosNum @[simp] theorem of_to_nat' : ∀ n : PosNum, Num.ofNat' (n : ℕ) = Num.pos n | 1 => by erw [@Num.ofNat'_bit true 0, Num.ofNat'_zero]; rfl | bit0 p => by simpa only [Nat.bit_false, cond_false, two_mul, of_to_nat' p] using Num.ofNat'_bit false p | bit1 p => by simpa only [Nat.bit_true, cond_true, two_mul, of_to_nat' p] using Num.ofNat'_bit true p end PosNum namespace Num @[simp, norm_cast] theorem of_to_nat' : ∀ n : Num, Num.ofNat' (n : ℕ) = n | 0 => ofNat'_zero | pos p => p.of_to_nat' lemma toNat_injective : Function.Injective (castNum : Num → ℕ) := Function.LeftInverse.injective of_to_nat' @[norm_cast] theorem to_nat_inj {m n : Num} : (m : ℕ) = n ↔ m = n := toNat_injective.eq_iff /-- This tactic tries to turn an (in)equality about `Num`s to one about `Nat`s by rewriting. ```lean example (n : Num) (m : Num) : n ≤ n + m := by transfer_rw exact Nat.le_add_right _ _ ``` -/ scoped macro (name := transfer_rw) "transfer_rw" : tactic => `(tactic| (repeat first | rw [← to_nat_inj] | rw [← lt_to_nat] | rw [← le_to_nat] repeat first | rw [add_to_nat] | rw [mul_to_nat] | rw [cast_one] | rw [cast_zero])) /-- This tactic tries to prove (in)equalities about `Num`s by transferring them to the `Nat` world and then trying to call `simp`. ```lean example (n : Num) (m : Num) : n ≤ n + m := by transfer ``` -/ scoped macro (name := transfer) "transfer" : tactic => `(tactic| (intros; transfer_rw; try simp)) instance addMonoid : AddMonoid Num where zero_add := zero_add add_zero := add_zero add_assoc := by transfer nsmul := nsmulRec instance addMonoidWithOne : AddMonoidWithOne Num := { Num.addMonoid with natCast := Num.ofNat' natCast_zero := ofNat'_zero natCast_succ := fun _ => ofNat'_succ } instance commSemiring : CommSemiring Num where __ := Num.addMonoid __ := Num.addMonoidWithOne npow := @npowRec Num ⟨1⟩ ⟨(· * ·)⟩ mul_zero _ := by rw [← to_nat_inj, mul_to_nat, cast_zero, mul_zero] zero_mul _ := by rw [← to_nat_inj, mul_to_nat, cast_zero, zero_mul] mul_one _ := by rw [← to_nat_inj, mul_to_nat, cast_one, mul_one] one_mul _ := by rw [← to_nat_inj, mul_to_nat, cast_one, one_mul] add_comm _ _ := by simp_rw [← to_nat_inj, add_to_nat, add_comm] mul_comm _ _ := by simp_rw [← to_nat_inj, mul_to_nat, mul_comm] mul_assoc _ _ _ := by simp_rw [← to_nat_inj, mul_to_nat, mul_assoc] left_distrib _ _ _ := by simp only [← to_nat_inj, mul_to_nat, add_to_nat, mul_add] right_distrib _ _ _ := by simp only [← to_nat_inj, mul_to_nat, add_to_nat, add_mul] instance partialOrder : PartialOrder Num where lt_iff_le_not_ge a b := by simp only [← lt_to_nat, ← le_to_nat, lt_iff_le_not_ge] le_refl := by transfer le_trans a b c := by transfer_rw; apply le_trans le_antisymm a b := by transfer_rw; apply le_antisymm instance isOrderedCancelAddMonoid : IsOrderedCancelAddMonoid Num where add_le_add_left a b h c := by revert h; transfer_rw; exact fun h => add_le_add_left h c le_of_add_le_add_left a b c := by transfer_rw; apply le_of_add_le_add_left instance linearOrder : LinearOrder Num := { le_total := by intro a b transfer_rw apply le_total toDecidableLT := Num.decidableLT toDecidableLE := Num.decidableLE -- This is relying on an automatically generated instance name, -- generated in a `deriving` handler. -- See https://github.com/leanprover/lean4/issues/2343 toDecidableEq := instDecidableEqNum } instance isStrictOrderedRing : IsStrictOrderedRing Num where zero_le_one := by decide exists_pair_ne := ⟨0, 1, by decide⟩ mul_lt_mul_of_pos_left a ha b c := by revert ha transfer_rw apply flip mul_lt_mul_of_pos_left mul_lt_mul_of_pos_right a ha b c := by revert ha transfer_rw apply flip mul_lt_mul_of_pos_right @[norm_cast] theorem add_of_nat (m n) : ((m + n : ℕ) : Num) = m + n := add_ofNat' _ _ @[norm_cast] theorem to_nat_to_int (n : Num) : ((n : ℕ) : ℤ) = n := cast_to_nat _ @[simp, norm_cast] theorem cast_to_int {α} [AddGroupWithOne α] (n : Num) : ((n : ℤ) : α) = n := by rw [← to_nat_to_int, Int.cast_natCast, cast_to_nat] theorem to_of_nat : ∀ n : ℕ, ((n : Num) : ℕ) = n | 0 => by rw [Nat.cast_zero, cast_zero] | n + 1 => by rw [Nat.cast_succ, add_one, succ_to_nat, to_of_nat n] @[simp, norm_cast] theorem of_natCast {α} [AddMonoidWithOne α] (n : ℕ) : ((n : Num) : α) = n := by rw [← cast_to_nat, to_of_nat] @[norm_cast] theorem of_nat_inj {m n : ℕ} : (m : Num) = n ↔ m = n := ⟨fun h => Function.LeftInverse.injective to_of_nat h, congr_arg _⟩ -- The priority should be `high`er than `cast_to_nat`. @[simp high, norm_cast] theorem of_to_nat : ∀ n : Num, ((n : ℕ) : Num) = n := of_to_nat' @[norm_cast] theorem dvd_to_nat (m n : Num) : (m : ℕ) ∣ n ↔ m ∣ n := ⟨fun ⟨k, e⟩ => ⟨k, by rw [← of_to_nat n, e]; simp⟩, fun ⟨k, e⟩ => ⟨k, by simp [e, mul_to_nat]⟩⟩ end Num namespace PosNum variable {α : Type*} open Num -- The priority should be `high`er than `cast_to_nat`. @[simp high, norm_cast] theorem of_to_nat : ∀ n : PosNum, ((n : ℕ) : Num) = Num.pos n := of_to_nat' @[norm_cast] theorem to_nat_inj {m n : PosNum} : (m : ℕ) = n ↔ m = n := ⟨fun h => Num.pos.inj <| by rw [← PosNum.of_to_nat, ← PosNum.of_to_nat, h], congr_arg _⟩ theorem pred'_to_nat : ∀ n, (pred' n : ℕ) = Nat.pred n | 1 => rfl | bit0 n => have : Nat.succ ↑(pred' n) = ↑n := by rw [pred'_to_nat n, Nat.succ_pred_eq_of_pos (to_nat_pos n)] match (motive := ∀ k : Num, Nat.succ ↑k = ↑n → ↑(Num.casesOn k 1 bit1 : PosNum) = Nat.pred (n + n)) pred' n, this with | 0, (h : ((1 : Num) : ℕ) = n) => by rw [← to_nat_inj.1 h]; rfl | Num.pos p, (h : Nat.succ ↑p = n) => by rw [← h]; exact (Nat.succ_add p p).symm | bit1 _ => rfl @[simp] theorem pred'_succ' (n) : pred' (succ' n) = n := Num.to_nat_inj.1 <| by rw [pred'_to_nat, succ'_to_nat, Nat.add_one, Nat.pred_succ] @[simp] theorem succ'_pred' (n) : succ' (pred' n) = n := to_nat_inj.1 <| by rw [succ'_to_nat, pred'_to_nat, Nat.add_one, Nat.succ_pred_eq_of_pos (to_nat_pos _)] instance dvd : Dvd PosNum := ⟨fun m n => pos m ∣ pos n⟩ @[norm_cast] theorem dvd_to_nat {m n : PosNum} : (m : ℕ) ∣ n ↔ m ∣ n := Num.dvd_to_nat (pos m) (pos n) theorem size_to_nat : ∀ n, (size n : ℕ) = Nat.size n | 1 => Nat.size_one.symm | bit0 n => by rw [size, succ_to_nat, size_to_nat n, cast_bit0, ← two_mul, ← Nat.bit_false_apply, Nat.size_bit] have := to_nat_pos n dsimp [Nat.bit]; cutsat | bit1 n => by rw [size, succ_to_nat, size_to_nat n, cast_bit1, ← two_mul, ← Nat.bit_true_apply, Nat.size_bit] dsimp [Nat.bit]; cutsat theorem size_eq_natSize : ∀ n, (size n : ℕ) = natSize n | 1 => rfl | bit0 n => by rw [size, succ_to_nat, natSize, size_eq_natSize n] | bit1 n => by rw [size, succ_to_nat, natSize, size_eq_natSize n] theorem natSize_to_nat (n) : natSize n = Nat.size n := by rw [← size_eq_natSize, size_to_nat] theorem natSize_pos (n) : 0 < natSize n := by cases n <;> apply Nat.succ_pos /-- This tactic tries to turn an (in)equality about `PosNum`s to one about `Nat`s by rewriting. ```lean example (n : PosNum) (m : PosNum) : n ≤ n + m := by transfer_rw exact Nat.le_add_right _ _ ``` -/ scoped macro (name := transfer_rw) "transfer_rw" : tactic => `(tactic| (repeat first | rw [← to_nat_inj] | rw [← lt_to_nat] | rw [← le_to_nat] repeat first | rw [add_to_nat] | rw [mul_to_nat] | rw [cast_one] | rw [cast_zero])) /-- This tactic tries to prove (in)equalities about `PosNum`s by transferring them to the `Nat` world and then trying to call `simp`. ```lean example (n : PosNum) (m : PosNum) : n ≤ n + m := by transfer ``` -/ scoped macro (name := transfer) "transfer" : tactic => `(tactic| (intros; transfer_rw; try simp [add_comm, add_left_comm, mul_comm, mul_left_comm])) instance addCommSemigroup : AddCommSemigroup PosNum where add_assoc := by transfer add_comm := by transfer instance commMonoid : CommMonoid PosNum where npow := @npowRec PosNum ⟨1⟩ ⟨(· * ·)⟩ mul_assoc := by transfer one_mul := by transfer mul_one := by transfer mul_comm := by transfer instance distrib : Distrib PosNum where left_distrib := by transfer; simp [mul_add] right_distrib := by transfer; simp [mul_add, mul_comm] instance linearOrder : LinearOrder PosNum where lt_iff_le_not_ge := by intro a b transfer_rw apply lt_iff_le_not_ge le_refl := by transfer le_trans := by intro a b c transfer_rw apply le_trans le_antisymm := by intro a b transfer_rw apply le_antisymm le_total := by intro a b transfer_rw apply le_total toDecidableLT := by infer_instance toDecidableLE := by infer_instance toDecidableEq := by infer_instance @[simp] theorem cast_to_num (n : PosNum) : ↑n = Num.pos n := by rw [← cast_to_nat, ← of_to_nat n] @[simp, norm_cast] theorem bit_to_nat (b n) : (bit b n : ℕ) = Nat.bit b n := by cases b <;> simp [bit, two_mul] @[simp, norm_cast] theorem cast_add [AddMonoidWithOne α] (m n) : ((m + n : PosNum) : α) = m + n := by rw [← cast_to_nat, add_to_nat, Nat.cast_add, cast_to_nat, cast_to_nat] @[simp 500, norm_cast] theorem cast_succ [AddMonoidWithOne α] (n : PosNum) : (succ n : α) = n + 1 := by rw [← add_one, cast_add, cast_one] @[simp, norm_cast] theorem cast_inj [AddMonoidWithOne α] [CharZero α] {m n : PosNum} : (m : α) = n ↔ m = n := by rw [← cast_to_nat m, ← cast_to_nat n, Nat.cast_inj, to_nat_inj] @[simp] theorem one_le_cast [Semiring α] [PartialOrder α] [IsStrictOrderedRing α] (n : PosNum) : (1 : α) ≤ n := by rw [← cast_to_nat, ← Nat.cast_one, Nat.cast_le (α := α)]; apply to_nat_pos @[simp] theorem cast_pos [Semiring α] [PartialOrder α] [IsStrictOrderedRing α] (n : PosNum) : 0 < (n : α) := lt_of_lt_of_le zero_lt_one (one_le_cast n) @[simp, norm_cast] theorem cast_mul [NonAssocSemiring α] (m n) : ((m * n : PosNum) : α) = m * n := by rw [← cast_to_nat, mul_to_nat, Nat.cast_mul, cast_to_nat, cast_to_nat] @[simp] theorem cmp_eq (m n) : cmp m n = Ordering.eq ↔ m = n := by have := cmp_to_nat m n -- Porting note: `cases` didn't rewrite at `this`, so `revert` & `intro` are required. revert this; cases cmp m n <;> intro this <;> simp at this ⊢ <;> try { exact this } <;> simp [show m ≠ n from fun e => by rw [e] at this; exact lt_irrefl _ this] @[simp, norm_cast] theorem cast_lt [Semiring α] [PartialOrder α] [IsStrictOrderedRing α] {m n : PosNum} : (m : α) < n ↔ m < n := by rw [← cast_to_nat m, ← cast_to_nat n, Nat.cast_lt (α := α), lt_to_nat] @[simp, norm_cast] theorem cast_le [Semiring α] [LinearOrder α] [IsStrictOrderedRing α] {m n : PosNum} : (m : α) ≤ n ↔ m ≤ n := by rw [← not_lt]; exact not_congr cast_lt end PosNum namespace Num variable {α : Type*} open PosNum theorem bit_to_nat (b n) : (bit b n : ℕ) = Nat.bit b n := by cases b <;> cases n <;> simp [bit, two_mul] <;> rfl theorem cast_succ' [AddMonoidWithOne α] (n) : (succ' n : α) = n + 1 := by rw [← PosNum.cast_to_nat, succ'_to_nat, Nat.cast_add_one, cast_to_nat] theorem cast_succ [AddMonoidWithOne α] (n) : (succ n : α) = n + 1 := cast_succ' n @[simp, norm_cast] theorem cast_add [AddMonoidWithOne α] (m n) : ((m + n : Num) : α) = m + n := by rw [← cast_to_nat, add_to_nat, Nat.cast_add, cast_to_nat, cast_to_nat] @[simp, norm_cast] theorem cast_bit0 [NonAssocSemiring α] (n : Num) : (n.bit0 : α) = 2 * (n : α) := by rw [← bit0_of_bit0, two_mul, cast_add] @[simp, norm_cast] theorem cast_bit1 [NonAssocSemiring α] (n : Num) : (n.bit1 : α) = 2 * (n : α) + 1 := by rw [← bit1_of_bit1, bit0_of_bit0, cast_add, cast_bit0]; rfl @[simp, norm_cast] theorem cast_mul [NonAssocSemiring α] : ∀ m n, ((m * n : Num) : α) = m * n | 0, 0 => (zero_mul _).symm | 0, pos _q => (zero_mul _).symm | pos _p, 0 => (mul_zero _).symm | pos _p, pos _q => PosNum.cast_mul _ _ theorem size_to_nat : ∀ n, (size n : ℕ) = Nat.size n | 0 => Nat.size_zero.symm | pos p => p.size_to_nat theorem size_eq_natSize : ∀ n, (size n : ℕ) = natSize n | 0 => rfl | pos p => p.size_eq_natSize theorem natSize_to_nat (n) : natSize n = Nat.size n := by rw [← size_eq_natSize, size_to_nat] @[simp 999] theorem ofNat'_eq : ∀ n, Num.ofNat' n = n := Nat.binaryRec (by simp) fun b n IH => by tauto theorem zneg_toZNum (n : Num) : -n.toZNum = n.toZNumNeg := by cases n <;> rfl theorem zneg_toZNumNeg (n : Num) : -n.toZNumNeg = n.toZNum := by cases n <;> rfl theorem toZNum_inj {m n : Num} : m.toZNum = n.toZNum ↔ m = n := ⟨fun h => by cases m <;> cases n <;> cases h <;> rfl, congr_arg _⟩ @[simp] theorem cast_toZNum [Zero α] [One α] [Add α] [Neg α] : ∀ n : Num, (n.toZNum : α) = n | 0 => rfl | Num.pos _p => rfl @[simp] theorem cast_toZNumNeg [SubtractionMonoid α] [One α] : ∀ n : Num, (n.toZNumNeg : α) = -n | 0 => neg_zero.symm | Num.pos _p => rfl @[simp] theorem add_toZNum (m n : Num) : Num.toZNum (m + n) = m.toZNum + n.toZNum := by cases m <;> cases n <;> rfl end Num namespace PosNum open Num theorem pred_to_nat {n : PosNum} (h : 1 < n) : (pred n : ℕ) = Nat.pred n := by unfold pred cases e : pred' n · have : (1 : ℕ) ≤ Nat.pred n := Nat.pred_le_pred ((@cast_lt ℕ _ _ _).2 h) rw [← pred'_to_nat, e] at this exact absurd this (by decide) · rw [← pred'_to_nat, e] rfl theorem sub'_one (a : PosNum) : sub' a 1 = (pred' a).toZNum := by cases a <;> rfl theorem one_sub' (a : PosNum) : sub' 1 a = (pred' a).toZNumNeg := by cases a <;> rfl theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = Ordering.lt := Iff.rfl theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ Ordering.gt := not_congr <| lt_iff_cmp.trans <| by rw [← cmp_swap]; cases cmp m n <;> decide end PosNum namespace Num variable {α : Type*} open PosNum theorem pred_to_nat : ∀ n : Num, (pred n : ℕ) = Nat.pred n | 0 => rfl | pos p => by rw [pred, PosNum.pred'_to_nat]; rfl theorem ppred_to_nat : ∀ n : Num, (↑) <$> ppred n = Nat.ppred n | 0 => rfl | pos p => by rw [ppred, Option.map_eq_map, Option.map_some, Nat.ppred_eq_some.2] rw [PosNum.pred'_to_nat, Nat.succ_pred_eq_of_pos (PosNum.to_nat_pos _)] rfl theorem cmp_swap (m n) : (cmp m n).swap = cmp n m := by cases m <;> cases n <;> try { rfl }; apply PosNum.cmp_swap theorem cmp_eq (m n) : cmp m n = Ordering.eq ↔ m = n := by have := cmp_to_nat m n -- Porting note: `cases` didn't rewrite at `this`, so `revert` & `intro` are required. revert this; cases cmp m n <;> intro this <;> simp at this ⊢ <;> try { exact this } <;> simp [show m ≠ n from fun e => by rw [e] at this; exact lt_irrefl _ this] @[simp, norm_cast] theorem cast_lt [Semiring α] [PartialOrder α] [IsStrictOrderedRing α] {m n : Num} : (m : α) < n ↔ m < n := by rw [← cast_to_nat m, ← cast_to_nat n, Nat.cast_lt (α := α), lt_to_nat] @[simp, norm_cast] theorem cast_le [Semiring α] [LinearOrder α] [IsStrictOrderedRing α] {m n : Num} : (m : α) ≤ n ↔ m ≤ n := by rw [← not_lt]; exact not_congr cast_lt @[simp, norm_cast] theorem cast_inj [Semiring α] [PartialOrder α] [IsStrictOrderedRing α] {m n : Num} : (m : α) = n ↔ m = n := by rw [← cast_to_nat m, ← cast_to_nat n, Nat.cast_inj, to_nat_inj] theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = Ordering.lt := Iff.rfl theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ Ordering.gt := not_congr <| lt_iff_cmp.trans <| by rw [← cmp_swap]; cases cmp m n <;> decide theorem castNum_eq_bitwise {f : Num → Num → Num} {g : Bool → Bool → Bool} (p : PosNum → PosNum → Num) (gff : g false false = false) (f00 : f 0 0 = 0) (f0n : ∀ n, f 0 (pos n) = cond (g false true) (pos n) 0) (fn0 : ∀ n, f (pos n) 0 = cond (g true false) (pos n) 0) (fnn : ∀ m n, f (pos m) (pos n) = p m n) (p11 : p 1 1 = cond (g true true) 1 0) (p1b : ∀ b n, p 1 (PosNum.bit b n) = bit (g true b) (cond (g false true) (pos n) 0)) (pb1 : ∀ a m, p (PosNum.bit a m) 1 = bit (g a true) (cond (g true false) (pos m) 0)) (pbb : ∀ a b m n, p (PosNum.bit a m) (PosNum.bit b n) = bit (g a b) (p m n)) : ∀ m n : Num, (f m n : ℕ) = Nat.bitwise g m n := by intro m n obtain - | m := m <;> obtain - | n := n <;> try simp only [show zero = 0 from rfl, show ((0 : Num) : ℕ) = 0 from rfl] · rw [f00, Nat.bitwise_zero]; rfl · rw [f0n, Nat.bitwise_zero_left] cases g false true <;> rfl · rw [fn0, Nat.bitwise_zero_right] cases g true false <;> rfl · rw [fnn] have this b (n : PosNum) : (cond b (↑n) 0 : ℕ) = ↑(cond b (pos n) 0 : Num) := by cases b <;> rfl have this' b (n : PosNum) : ↑(pos (PosNum.bit b n)) = Nat.bit b ↑n := by cases b <;> simp induction m generalizing n with | one => ?_ | bit1 m IH => ?_ | bit0 m IH => ?_ <;> obtain - | n | n := n any_goals simp only [show one = 1 from rfl, show pos 1 = 1 from rfl, show PosNum.bit0 = PosNum.bit false from rfl, show PosNum.bit1 = PosNum.bit true from rfl, show ((1 : Num) : ℕ) = Nat.bit true 0 from rfl] all_goals repeat rw [this'] rw [Nat.bitwise_bit gff] any_goals rw [Nat.bitwise_zero, p11]; cases g true true <;> rfl any_goals rw [Nat.bitwise_zero_left, ← Bool.cond_eq_ite, this, ← bit_to_nat, p1b] any_goals rw [Nat.bitwise_zero_right, ← Bool.cond_eq_ite, this, ← bit_to_nat, pb1] all_goals rw [← show ∀ n : PosNum, ↑(p m n) = Nat.bitwise g ↑m ↑n from IH] rw [← bit_to_nat, pbb] @[simp, norm_cast] theorem castNum_or : ∀ m n : Num, ↑(m ||| n) = (↑m ||| ↑n : ℕ) := by apply castNum_eq_bitwise fun x y => pos (PosNum.lor x y) <;> (try rintro (_ | _)) <;> (try rintro (_ | _)) <;> intros <;> rfl @[simp, norm_cast] theorem castNum_and : ∀ m n : Num, ↑(m &&& n) = (↑m &&& ↑n : ℕ) := by apply castNum_eq_bitwise PosNum.land <;> intros <;> (try cases_type* Bool) <;> rfl @[simp, norm_cast] theorem castNum_ldiff : ∀ m n : Num, (ldiff m n : ℕ) = Nat.ldiff m n := by apply castNum_eq_bitwise PosNum.ldiff <;> intros <;> (try cases_type* Bool) <;> rfl @[simp, norm_cast] theorem castNum_xor : ∀ m n : Num, ↑(m ^^^ n) = (↑m ^^^ ↑n : ℕ) := by apply castNum_eq_bitwise PosNum.lxor <;> intros <;> (try cases_type* Bool) <;> rfl @[simp, norm_cast] theorem castNum_shiftLeft (m : Num) (n : Nat) : ↑(m <<< n) = (m : ℕ) <<< (n : ℕ) := by cases m <;> dsimp only [← shiftl_eq_shiftLeft, shiftl] · symm apply Nat.zero_shiftLeft simp only [cast_pos] induction n with | zero => rfl | succ n IH => simp [PosNum.shiftl_succ_eq_bit0_shiftl, Nat.shiftLeft_succ, IH, mul_comm, -shiftl_eq_shiftLeft, -PosNum.shiftl_eq_shiftLeft, mul_two] @[simp, norm_cast] theorem castNum_shiftRight (m : Num) (n : Nat) : ↑(m >>> n) = (m : ℕ) >>> (n : ℕ) := by obtain - | m := m <;> dsimp only [← shiftr_eq_shiftRight, shiftr] · symm apply Nat.zero_shiftRight induction n generalizing m with | zero => cases m <;> rfl | succ n IH => ?_ have hdiv2 : ∀ m, Nat.div2 (m + m) = m := by intro; rw [Nat.div2_val]; omega obtain - | m | m := m <;> dsimp only [PosNum.shiftr, ← PosNum.shiftr_eq_shiftRight] · rw [Nat.shiftRight_eq_div_pow] symm apply Nat.div_eq_of_lt simp · trans · apply IH change Nat.shiftRight m n = Nat.shiftRight (m + m + 1) (n + 1) rw [add_comm n 1, @Nat.shiftRight_eq _ (1 + n), Nat.shiftRight_add] apply congr_arg fun x => Nat.shiftRight x n simp [-add_assoc, Nat.shiftRight_succ, Nat.shiftRight_zero, ← Nat.div2_val, hdiv2] · trans · apply IH change Nat.shiftRight m n = Nat.shiftRight (m + m) (n + 1) rw [add_comm n 1, @Nat.shiftRight_eq _ (1 + n), Nat.shiftRight_add] apply congr_arg fun x => Nat.shiftRight x n simp [-add_assoc, Nat.shiftRight_succ, Nat.shiftRight_zero, ← Nat.div2_val, hdiv2] @[simp] theorem castNum_testBit (m n) : testBit m n = Nat.testBit m n := by cases m with dsimp only [testBit] | zero => rw [show (Num.zero : Nat) = 0 from rfl, Nat.zero_testBit] | pos m => rw [cast_pos] induction n generalizing m <;> obtain - | m | m := m <;> simp only [PosNum.testBit] · rfl · rw [PosNum.cast_bit1, ← two_mul, ← congr_fun Nat.bit_true, Nat.testBit_bit_zero] · rw [PosNum.cast_bit0, ← two_mul, ← congr_fun Nat.bit_false, Nat.testBit_bit_zero] · simp [Nat.testBit_add_one] case succ.bit1 n IH => rw [PosNum.cast_bit1, ← two_mul, ← congr_fun Nat.bit_true, Nat.testBit_bit_succ, IH] case succ.bit0 n IH => rw [PosNum.cast_bit0, ← two_mul, ← congr_fun Nat.bit_false, Nat.testBit_bit_succ, IH] end Num namespace Int /-- Cast a `SNum` to the corresponding integer. -/ def ofSnum : SNum → ℤ := SNum.rec' (fun a => cond a (-1) 0) fun a _p IH => cond a (2 * IH + 1) (2 * IH) instance snumCoe : Coe SNum ℤ := ⟨ofSnum⟩ end Int instance SNum.lt : LT SNum := ⟨fun a b => (a : ℤ) < b⟩ instance SNum.le : LE SNum := ⟨fun a b => (a : ℤ) ≤ b⟩
.lake/packages/mathlib/Mathlib/Data/Num/Basic.lean
import Lean.Linter.Deprecated import Mathlib.Data.Nat.Notation import Mathlib.Data.Int.Notation import Mathlib.Data.Nat.BinaryRec import Mathlib.Tactic.TypeStar /-! # Binary representation of integers using inductive types Note: Unlike in Coq, where this representation is preferred because of the reliance on kernel reduction, in Lean this representation is discouraged in favor of the "Peano" natural numbers `Nat`, and the purpose of this collection of theorems is to show the equivalence of the different approaches. -/ /-- The type of positive binary numbers. 13 = 1101(base 2) = bit1 (bit0 (bit1 one)) -/ inductive PosNum : Type | one : PosNum | bit1 : PosNum → PosNum | bit0 : PosNum → PosNum deriving DecidableEq instance : One PosNum := ⟨PosNum.one⟩ instance : Inhabited PosNum := ⟨1⟩ /-- The type of nonnegative binary numbers, using `PosNum`. 13 = 1101(base 2) = pos (bit1 (bit0 (bit1 one))) -/ inductive Num : Type | zero : Num | pos : PosNum → Num deriving DecidableEq instance : Zero Num := ⟨Num.zero⟩ instance : One Num := ⟨Num.pos 1⟩ instance : Inhabited Num := ⟨0⟩ /-- Representation of integers using trichotomy around zero. 13 = 1101(base 2) = pos (bit1 (bit0 (bit1 one))) -13 = -1101(base 2) = neg (bit1 (bit0 (bit1 one))) -/ inductive ZNum : Type | zero : ZNum | pos : PosNum → ZNum | neg : PosNum → ZNum deriving DecidableEq instance : Zero ZNum := ⟨ZNum.zero⟩ instance : One ZNum := ⟨ZNum.pos 1⟩ instance : Inhabited ZNum := ⟨0⟩ namespace PosNum /-- `bit b n` appends the bit `b` to the end of `n`, where `bit tt x = x1` and `bit ff x = x0`. -/ def bit (b : Bool) : PosNum → PosNum := cond b bit1 bit0 /-- The successor of a `PosNum`. -/ def succ : PosNum → PosNum | 1 => bit0 one | bit1 n => bit0 (succ n) | bit0 n => bit1 n /-- Returns a Boolean for whether the `PosNum` is `one`. -/ def isOne : PosNum → Bool | 1 => true | _ => false /-- Addition of two `PosNum`s. -/ protected def add : PosNum → PosNum → PosNum | 1, b => succ b | a, 1 => succ a | bit0 a, bit0 b => bit0 (PosNum.add a b) | bit1 a, bit1 b => bit0 (succ (PosNum.add a b)) | bit0 a, bit1 b => bit1 (PosNum.add a b) | bit1 a, bit0 b => bit1 (PosNum.add a b) instance : Add PosNum := ⟨PosNum.add⟩ /-- The predecessor of a `PosNum` as a `Num`. -/ def pred' : PosNum → Num | 1 => 0 | bit0 n => Num.pos (Num.casesOn (pred' n) 1 bit1) | bit1 n => Num.pos (bit0 n) /-- The predecessor of a `PosNum` as a `PosNum`. This means that `pred 1 = 1`. -/ def pred (a : PosNum) : PosNum := Num.casesOn (pred' a) 1 id /-- The number of bits of a `PosNum`, as a `PosNum`. -/ def size : PosNum → PosNum | 1 => 1 | bit0 n => succ (size n) | bit1 n => succ (size n) /-- The number of bits of a `PosNum`, as a `Nat`. -/ def natSize : PosNum → Nat | 1 => 1 | bit0 n => Nat.succ (natSize n) | bit1 n => Nat.succ (natSize n) /-- Multiplication of two `PosNum`s. -/ protected def mul (a : PosNum) : PosNum → PosNum | 1 => a | bit0 b => bit0 (PosNum.mul a b) | bit1 b => bit0 (PosNum.mul a b) + a instance : Mul PosNum := ⟨PosNum.mul⟩ /-- `ofNatSucc n` is the `PosNum` corresponding to `n + 1`. -/ def ofNatSucc : ℕ → PosNum | 0 => 1 | Nat.succ n => succ (ofNatSucc n) /-- `ofNat n` is the `PosNum` corresponding to `n`, except for `ofNat 0 = 1`. -/ def ofNat (n : ℕ) : PosNum := ofNatSucc (Nat.pred n) instance (priority := low) {n : ℕ} : OfNat PosNum (n + 1) where ofNat := ofNat (n + 1) open Ordering /-- Ordering of `PosNum`s. -/ def cmp : PosNum → PosNum → Ordering | 1, 1 => eq | _, 1 => gt | 1, _ => lt | bit0 a, bit0 b => cmp a b | bit0 a, bit1 b => Ordering.casesOn (cmp a b) lt lt gt | bit1 a, bit0 b => Ordering.casesOn (cmp a b) lt gt gt | bit1 a, bit1 b => cmp a b instance : LT PosNum := ⟨fun a b => cmp a b = Ordering.lt⟩ instance : LE PosNum := ⟨fun a b => ¬b < a⟩ instance decidableLT : DecidableLT PosNum | a, b => by dsimp [LT.lt]; infer_instance instance decidableLE : DecidableLE PosNum | a, b => by dsimp [LE.le]; infer_instance end PosNum section variable {α : Type*} [One α] [Add α] /-- `castPosNum` casts a `PosNum` into any type which has `1` and `+`. -/ @[coe] def castPosNum : PosNum → α | 1 => 1 | PosNum.bit0 a => castPosNum a + castPosNum a | PosNum.bit1 a => castPosNum a + castPosNum a + 1 /-- `castNum` casts a `Num` into any type which has `0`, `1` and `+`. -/ @[coe] def castNum [Zero α] : Num → α | 0 => 0 | Num.pos p => castPosNum p -- see Note [coercion into rings] instance (priority := 900) posNumCoe : CoeHTCT PosNum α := ⟨castPosNum⟩ -- see Note [coercion into rings] instance (priority := 900) numNatCoe [Zero α] : CoeHTCT Num α := ⟨castNum⟩ instance : Repr PosNum := ⟨fun n _ => repr (n : ℕ)⟩ instance : Repr Num := ⟨fun n _ => repr (n : ℕ)⟩ end namespace Num open PosNum /-- The successor of a `Num` as a `PosNum`. -/ def succ' : Num → PosNum | 0 => 1 | pos p => succ p /-- The successor of a `Num` as a `Num`. -/ def succ (n : Num) : Num := pos (succ' n) /-- Addition of two `Num`s. -/ protected def add : Num → Num → Num | 0, a => a | b, 0 => b | pos a, pos b => pos (a + b) instance : Add Num := ⟨Num.add⟩ /-- `bit0 n` appends a `0` to the end of `n`, where `bit0 n = n0`. -/ protected def bit0 : Num → Num | 0 => 0 | pos n => pos (PosNum.bit0 n) /-- `bit1 n` appends a `1` to the end of `n`, where `bit1 n = n1`. -/ protected def bit1 : Num → Num | 0 => 1 | pos n => pos (PosNum.bit1 n) /-- `bit b n` appends the bit `b` to the end of `n`, where `bit tt x = x1` and `bit ff x = x0`. -/ def bit (b : Bool) : Num → Num := cond b Num.bit1 Num.bit0 /-- The number of bits required to represent a `Num`, as a `Num`. `size 0` is defined to be `0`. -/ def size : Num → Num | 0 => 0 | pos n => pos (PosNum.size n) /-- The number of bits required to represent a `Num`, as a `Nat`. `size 0` is defined to be `0`. -/ def natSize : Num → Nat | 0 => 0 | pos n => PosNum.natSize n /-- Multiplication of two `Num`s. -/ protected def mul : Num → Num → Num | 0, _ => 0 | _, 0 => 0 | pos a, pos b => pos (a * b) instance : Mul Num := ⟨Num.mul⟩ open Ordering /-- Ordering of `Num`s. -/ def cmp : Num → Num → Ordering | 0, 0 => eq | _, 0 => gt | 0, _ => lt | pos a, pos b => PosNum.cmp a b instance : LT Num := ⟨fun a b => cmp a b = Ordering.lt⟩ instance : LE Num := ⟨fun a b => ¬b < a⟩ instance decidableLT : DecidableLT Num | a, b => by dsimp [LT.lt]; infer_instance instance decidableLE : DecidableLE Num | a, b => by dsimp [LE.le]; infer_instance /-- Converts a `Num` to a `ZNum`. -/ def toZNum : Num → ZNum | 0 => 0 | pos a => ZNum.pos a /-- Converts `x : Num` to `-x : ZNum`. -/ def toZNumNeg : Num → ZNum | 0 => 0 | pos a => ZNum.neg a /-- Converts a `Nat` to a `Num`. -/ def ofNat' : ℕ → Num := Nat.binaryRec 0 (fun b _ => cond b Num.bit1 Num.bit0) end Num namespace ZNum open PosNum /-- The negation of a `ZNum`. -/ def zNeg : ZNum → ZNum | 0 => 0 | pos a => neg a | neg a => pos a instance : Neg ZNum := ⟨zNeg⟩ /-- The absolute value of a `ZNum` as a `Num`. -/ def abs : ZNum → Num | 0 => 0 | pos a => Num.pos a | neg a => Num.pos a /-- The successor of a `ZNum`. -/ def succ : ZNum → ZNum | 0 => 1 | pos a => pos (PosNum.succ a) | neg a => (PosNum.pred' a).toZNumNeg /-- The predecessor of a `ZNum`. -/ def pred : ZNum → ZNum | 0 => neg 1 | pos a => (PosNum.pred' a).toZNum | neg a => neg (PosNum.succ a) /-- `bit0 n` appends a `0` to the end of `n`, where `bit0 n = n0`. -/ protected def bit0 : ZNum → ZNum | 0 => 0 | pos n => pos (PosNum.bit0 n) | neg n => neg (PosNum.bit0 n) /-- `bit1 x` appends a `1` to the end of `x`, mapping `x` to `2 * x + 1`. -/ protected def bit1 : ZNum → ZNum | 0 => 1 | pos n => pos (PosNum.bit1 n) | neg n => neg (Num.casesOn (pred' n) 1 PosNum.bit1) /-- `bitm1 x` appends a `1` to the end of `x`, mapping `x` to `2 * x - 1`. -/ protected def bitm1 : ZNum → ZNum | 0 => neg 1 | pos n => pos (Num.casesOn (pred' n) 1 PosNum.bit1) | neg n => neg (PosNum.bit1 n) /-- Converts an `Int` to a `ZNum`. -/ def ofInt' : ℤ → ZNum | Int.ofNat n => Num.toZNum (Num.ofNat' n) | Int.negSucc n => Num.toZNumNeg (Num.ofNat' (n + 1)) end ZNum namespace PosNum open ZNum /-- Subtraction of two `PosNum`s, producing a `ZNum`. -/ def sub' : PosNum → PosNum → ZNum | a, 1 => (pred' a).toZNum | 1, b => (pred' b).toZNumNeg | bit0 a, bit0 b => (sub' a b).bit0 | bit0 a, bit1 b => (sub' a b).bitm1 | bit1 a, bit0 b => (sub' a b).bit1 | bit1 a, bit1 b => (sub' a b).bit0 /-- Converts a `ZNum` to `Option PosNum`, where it is `some` if the `ZNum` was positive and `none` otherwise. -/ def ofZNum' : ZNum → Option PosNum | ZNum.pos p => some p | _ => none /-- Converts a `ZNum` to a `PosNum`, mapping all out of range values to `1`. -/ def ofZNum : ZNum → PosNum | ZNum.pos p => p | _ => 1 /-- Subtraction of `PosNum`s, where if `a < b`, then `a - b = 1`. -/ protected def sub (a b : PosNum) : PosNum := match sub' a b with | ZNum.pos p => p | _ => 1 instance : Sub PosNum := ⟨PosNum.sub⟩ end PosNum namespace Num /-- The predecessor of a `Num` as an `Option Num`, where `ppred 0 = none` -/ def ppred : Num → Option Num | 0 => none | pos p => some p.pred' /-- The predecessor of a `Num` as a `Num`, where `pred 0 = 0`. -/ def pred : Num → Num | 0 => 0 | pos p => p.pred' /-- Divides a `Num` by `2` -/ def div2 : Num → Num | 0 => 0 | 1 => 0 | pos (PosNum.bit0 p) => pos p | pos (PosNum.bit1 p) => pos p /-- Converts a `ZNum` to an `Option Num`, where `ofZNum' p = none` if `p < 0`. -/ def ofZNum' : ZNum → Option Num | 0 => some 0 | ZNum.pos p => some (pos p) | ZNum.neg _ => none /-- Converts a `ZNum` to an `Option Num`, where `ofZNum p = 0` if `p < 0`. -/ def ofZNum : ZNum → Num | ZNum.pos p => pos p | _ => 0 /-- Subtraction of two `Num`s, producing a `ZNum`. -/ def sub' : Num → Num → ZNum | 0, 0 => 0 | pos a, 0 => ZNum.pos a | 0, pos b => ZNum.neg b | pos a, pos b => a.sub' b /-- Subtraction of two `Num`s, producing an `Option Num`. -/ def psub (a b : Num) : Option Num := ofZNum' (sub' a b) /-- Subtraction of two `Num`s, where if `a < b`, `a - b = 0`. -/ protected def sub (a b : Num) : Num := ofZNum (sub' a b) instance : Sub Num := ⟨Num.sub⟩ end Num namespace ZNum open PosNum /-- Addition of `ZNum`s. -/ protected def add : ZNum → ZNum → ZNum | 0, a => a | b, 0 => b | pos a, pos b => pos (a + b) | pos a, neg b => sub' a b | neg a, pos b => sub' b a | neg a, neg b => neg (a + b) instance : Add ZNum := ⟨ZNum.add⟩ /-- Multiplication of `ZNum`s. -/ protected def mul : ZNum → ZNum → ZNum | 0, _ => 0 | _, 0 => 0 | pos a, pos b => pos (a * b) | pos a, neg b => neg (a * b) | neg a, pos b => neg (a * b) | neg a, neg b => pos (a * b) instance : Mul ZNum := ⟨ZNum.mul⟩ open Ordering /-- Ordering on `ZNum`s. -/ def cmp : ZNum → ZNum → Ordering | 0, 0 => eq | pos a, pos b => PosNum.cmp a b | neg a, neg b => PosNum.cmp b a | pos _, _ => gt | neg _, _ => lt | _, pos _ => lt | _, neg _ => gt instance : LT ZNum := ⟨fun a b => cmp a b = Ordering.lt⟩ instance : LE ZNum := ⟨fun a b => ¬b < a⟩ instance decidableLT : DecidableLT ZNum | a, b => by dsimp [LT.lt]; infer_instance instance decidableLE : DecidableLE ZNum | a, b => by dsimp [LE.le]; infer_instance end ZNum namespace PosNum /-- Auxiliary definition for `PosNum.divMod`. -/ def divModAux (d : PosNum) (q r : Num) : Num × Num := match Num.ofZNum' (Num.sub' r (Num.pos d)) with | some r' => (Num.bit1 q, r') | none => (Num.bit0 q, r) /-- `divMod x y = (y / x, y % x)`. -/ def divMod (d : PosNum) : PosNum → Num × Num | bit0 n => let (q, r₁) := divMod d n divModAux d q (Num.bit0 r₁) | bit1 n => let (q, r₁) := divMod d n divModAux d q (Num.bit1 r₁) | 1 => divModAux d 0 1 /-- Division of `PosNum` -/ def div' (n d : PosNum) : Num := (divMod d n).1 /-- Modulus of `PosNum`s. -/ def mod' (n d : PosNum) : Num := (divMod d n).2 /-- Auxiliary definition for `sqrtAux`. -/ private def sqrtAux1 (b : PosNum) (r n : Num) : Num × Num := match Num.ofZNum' (n.sub' (r + Num.pos b)) with | some n' => (r.div2 + Num.pos b, n') | none => (r.div2, n) /-- Auxiliary definition for a `sqrt` function which is not currently implemented. -/ private def sqrtAux : PosNum → Num → Num → Num | b@(bit0 b') => fun r n => let (r', n') := sqrtAux1 b r n; sqrtAux b' r' n' | b@(bit1 b') => fun r n => let (r', n') := sqrtAux1 b r n; sqrtAux b' r' n' | 1 => fun r n => (sqrtAux1 1 r n).1 end PosNum namespace Num /-- Division of `Num`s, where `x / 0 = 0`. -/ def div : Num → Num → Num | 0, _ => 0 | _, 0 => 0 | pos n, pos d => PosNum.div' n d /-- Modulus of `Num`s. -/ def mod : Num → Num → Num | 0, _ => 0 | n, 0 => n | pos n, pos d => PosNum.mod' n d instance : Div Num := ⟨Num.div⟩ instance : Mod Num := ⟨Num.mod⟩ /-- Auxiliary definition for `Num.gcd`. -/ def gcdAux : Nat → Num → Num → Num | 0, _, b => b | Nat.succ _, 0, b => b | Nat.succ n, a, b => gcdAux n (b % a) a /-- Greatest Common Divisor (GCD) of two `Num`s. -/ def gcd (a b : Num) : Num := if a ≤ b then gcdAux (a.natSize + b.natSize) a b else gcdAux (b.natSize + a.natSize) b a end Num namespace ZNum /-- Division of `ZNum`, where `x / 0 = 0`. -/ def div : ZNum → ZNum → ZNum | 0, _ => 0 | _, 0 => 0 | pos n, pos d => Num.toZNum (PosNum.div' n d) | pos n, neg d => Num.toZNumNeg (PosNum.div' n d) | neg n, pos d => neg (PosNum.pred' n / Num.pos d).succ' | neg n, neg d => pos (PosNum.pred' n / Num.pos d).succ' /-- Modulus of `ZNum`s. -/ def mod : ZNum → ZNum → ZNum | 0, _ => 0 | pos n, d => Num.toZNum (Num.pos n % d.abs) | neg n, d => d.abs.sub' (PosNum.pred' n % d.abs).succ instance : Div ZNum := ⟨ZNum.div⟩ instance : Mod ZNum := ⟨ZNum.mod⟩ /-- Greatest Common Divisor (GCD) of two `ZNum`s. -/ def gcd (a b : ZNum) : Num := a.abs.gcd b.abs end ZNum section variable {α : Type*} [Zero α] [One α] [Add α] [Neg α] /-- `castZNum` casts a `ZNum` into any type which has `0`, `1`, `+` and `neg` -/ @[coe] def castZNum : ZNum → α | 0 => 0 | ZNum.pos p => p | ZNum.neg p => -p -- see Note [coercion into rings] instance (priority := 900) znumCoe : CoeHTCT ZNum α := ⟨castZNum⟩ instance : Repr ZNum := ⟨fun n _ => repr (n : ℤ)⟩ end
.lake/packages/mathlib/Mathlib/Data/Num/ZNum.lean
import Mathlib.Algebra.Order.Ring.Cast import Mathlib.Data.Int.Cast.Lemmas import Mathlib.Data.Num.Lemmas /-! # Properties of the `ZNum` representation of integers This file was split from `Mathlib/Data/Num/Lemmas.lean` to keep the former under 1500 lines. -/ open Int attribute [local simp] add_assoc namespace ZNum variable {α : Type*} open PosNum @[simp, norm_cast] theorem cast_zero [Zero α] [One α] [Add α] [Neg α] : ((0 : ZNum) : α) = 0 := rfl @[simp] theorem cast_zero' [Zero α] [One α] [Add α] [Neg α] : (ZNum.zero : α) = 0 := rfl @[simp, norm_cast] theorem cast_one [Zero α] [One α] [Add α] [Neg α] : ((1 : ZNum) : α) = 1 := rfl @[simp] theorem cast_pos [Zero α] [One α] [Add α] [Neg α] (n : PosNum) : (pos n : α) = n := rfl @[simp] theorem cast_neg [Zero α] [One α] [Add α] [Neg α] (n : PosNum) : (neg n : α) = -n := rfl @[simp, norm_cast] theorem cast_zneg [SubtractionMonoid α] [One α] : ∀ n, ((-n : ZNum) : α) = -n | 0 => neg_zero.symm | pos _p => rfl | neg _p => (neg_neg _).symm theorem neg_zero : (-0 : ZNum) = 0 := rfl theorem zneg_pos (n : PosNum) : -pos n = neg n := rfl theorem zneg_neg (n : PosNum) : -neg n = pos n := rfl theorem zneg_zneg (n : ZNum) : - -n = n := by cases n <;> rfl theorem zneg_bit1 (n : ZNum) : -n.bit1 = (-n).bitm1 := by cases n <;> rfl theorem zneg_bitm1 (n : ZNum) : -n.bitm1 = (-n).bit1 := by cases n <;> rfl theorem zneg_succ (n : ZNum) : -n.succ = (-n).pred := by cases n <;> try { rfl }; rw [succ, Num.zneg_toZNumNeg]; rfl theorem zneg_pred (n : ZNum) : -n.pred = (-n).succ := by rw [← zneg_zneg (succ (-n)), zneg_succ, zneg_zneg] @[simp] theorem abs_to_nat : ∀ n, (abs n : ℕ) = Int.natAbs n | 0 => rfl | pos p => congr_arg Int.natAbs p.to_nat_to_int | neg p => show Int.natAbs ((p : ℕ) : ℤ) = Int.natAbs (-p) by rw [p.to_nat_to_int, Int.natAbs_neg] @[simp] theorem abs_toZNum : ∀ n : Num, abs n.toZNum = n | 0 => rfl | Num.pos _p => rfl @[simp, norm_cast] theorem cast_to_int [AddGroupWithOne α] : ∀ n : ZNum, ((n : ℤ) : α) = n | 0 => by rw [cast_zero, cast_zero, Int.cast_zero] | pos p => by rw [cast_pos, cast_pos, PosNum.cast_to_int] | neg p => by rw [cast_neg, cast_neg, Int.cast_neg, PosNum.cast_to_int] theorem bit0_of_bit0 : ∀ n : ZNum, n + n = n.bit0 | 0 => rfl | pos a => congr_arg pos a.bit0_of_bit0 | neg a => congr_arg neg a.bit0_of_bit0 theorem bit1_of_bit1 : ∀ n : ZNum, n + n + 1 = n.bit1 | 0 => rfl | pos a => congr_arg pos a.bit1_of_bit1 | neg a => show PosNum.sub' 1 (a + a) = _ by rw [PosNum.one_sub', a.bit0_of_bit0]; rfl @[simp, norm_cast] theorem cast_bit0 [AddGroupWithOne α] : ∀ n : ZNum, (n.bit0 : α) = (n : α) + n | 0 => (add_zero _).symm | pos p => by rw [ZNum.bit0, cast_pos, cast_pos]; rfl | neg p => by rw [ZNum.bit0, cast_neg, cast_neg, PosNum.cast_bit0, neg_add_rev] @[simp, norm_cast] theorem cast_bit1 [AddGroupWithOne α] : ∀ n : ZNum, (n.bit1 : α) = ((n : α) + n) + 1 | 0 => by simp [ZNum.bit1] | pos p => by rw [ZNum.bit1, cast_pos, cast_pos]; rfl | neg p => by rw [ZNum.bit1, cast_neg, cast_neg] rcases e : pred' p with - | a <;> have ep : p = _ := (succ'_pred' p).symm.trans (congr_arg Num.succ' e) · conv at ep => change p = 1 subst p simp · dsimp only [Num.succ'] at ep subst p have : (↑(-↑a : ℤ) : α) = -1 + ↑(-↑a + 1 : ℤ) := by simp [add_comm (-↑a : ℤ) 1] simpa using this @[simp] theorem cast_bitm1 [AddGroupWithOne α] (n : ZNum) : (n.bitm1 : α) = (n : α) + n - 1 := by conv => lhs rw [← zneg_zneg n] rw [← zneg_bit1, cast_zneg, cast_bit1] have : ((-1 + n + n : ℤ) : α) = (n + n + -1 : ℤ) := by simp [add_comm] simpa [sub_eq_add_neg] using this theorem add_zero (n : ZNum) : n + 0 = n := by cases n <;> rfl theorem zero_add (n : ZNum) : 0 + n = n := by cases n <;> rfl theorem add_one : ∀ n : ZNum, n + 1 = succ n | 0 => rfl | pos p => congr_arg pos p.add_one | neg p => by cases p <;> rfl end ZNum namespace PosNum variable {α : Type*} theorem cast_to_znum : ∀ n : PosNum, (n : ZNum) = ZNum.pos n | 1 => rfl | bit0 p => by have := congr_arg ZNum.bit0 (cast_to_znum p) rwa [← ZNum.bit0_of_bit0] at this | bit1 p => by have := congr_arg ZNum.bit1 (cast_to_znum p) rwa [← ZNum.bit1_of_bit1] at this theorem cast_sub' [AddGroupWithOne α] : ∀ m n : PosNum, (sub' m n : α) = m - n | a, 1 => by rw [sub'_one, Num.cast_toZNum, ← Num.cast_to_nat, pred'_to_nat, ← Nat.sub_one] simp | 1, b => by rw [one_sub', Num.cast_toZNumNeg, ← neg_sub, neg_inj, ← Num.cast_to_nat, pred'_to_nat, ← Nat.sub_one] simp | bit0 a, bit0 b => by rw [sub', ZNum.cast_bit0, cast_sub' a b] have : ((a + -b + (a + -b) : ℤ) : α) = a + a + (-b + -b) := by simp [add_left_comm] simpa [sub_eq_add_neg] using this | bit0 a, bit1 b => by rw [sub', ZNum.cast_bitm1, cast_sub' a b] have : ((-b + (a + (-b + -1)) : ℤ) : α) = (a + -1 + (-b + -b) : ℤ) := by simp [add_comm, add_left_comm] simpa [sub_eq_add_neg] using this | bit1 a, bit0 b => by rw [sub', ZNum.cast_bit1, cast_sub' a b] have : ((-b + (a + (-b + 1)) : ℤ) : α) = (a + 1 + (-b + -b) : ℤ) := by simp [add_comm, add_left_comm] simpa [sub_eq_add_neg] using this | bit1 a, bit1 b => by rw [sub', ZNum.cast_bit0, cast_sub' a b] have : ((-b + (a + -b) : ℤ) : α) = a + (-b + -b) := by simp [add_left_comm] simpa [sub_eq_add_neg] using this theorem to_nat_eq_succ_pred (n : PosNum) : (n : ℕ) = n.pred' + 1 := by rw [← Num.succ'_to_nat, n.succ'_pred'] theorem to_int_eq_succ_pred (n : PosNum) : (n : ℤ) = (n.pred' : ℕ) + 1 := by rw [← n.to_nat_to_int, to_nat_eq_succ_pred]; rfl end PosNum namespace Num variable {α : Type*} @[simp] theorem cast_sub' [AddGroupWithOne α] : ∀ m n : Num, (sub' m n : α) = m - n | 0, 0 => (sub_zero _).symm | pos _a, 0 => (sub_zero _).symm | 0, pos _b => (zero_sub _).symm | pos _a, pos _b => PosNum.cast_sub' _ _ theorem toZNum_succ : ∀ n : Num, n.succ.toZNum = n.toZNum.succ | 0 => rfl | pos _n => rfl theorem toZNumNeg_succ : ∀ n : Num, n.succ.toZNumNeg = n.toZNumNeg.pred | 0 => rfl | pos _n => rfl @[simp] theorem pred_succ : ∀ n : ZNum, n.pred.succ = n | 0 => rfl | ZNum.neg p => show toZNumNeg (pos p).succ'.pred' = _ by rw [PosNum.pred'_succ']; rfl | ZNum.pos p => by rw [ZNum.pred, ← toZNum_succ, Num.succ, PosNum.succ'_pred', toZNum] theorem succ_ofInt' : ∀ n, ZNum.ofInt' (n + 1) = ZNum.ofInt' n + 1 | (n : ℕ) => by change ZNum.ofInt' (n + 1 : ℕ) = ZNum.ofInt' (n : ℕ) + 1 dsimp only [ZNum.ofInt', ZNum.ofInt'] rw [Num.ofNat'_succ, Num.add_one, toZNum_succ, ZNum.add_one] | -[0+1] => by change ZNum.ofInt' 0 = ZNum.ofInt' (-[0+1]) + 1 dsimp only [ZNum.ofInt', ZNum.ofInt'] rw [ofNat'_succ, ofNat'_zero]; rfl | -[(n + 1)+1] => by change ZNum.ofInt' -[n+1] = ZNum.ofInt' -[(n + 1)+1] + 1 dsimp only [ZNum.ofInt', ZNum.ofInt'] rw [@Num.ofNat'_succ (n + 1), Num.add_one, toZNumNeg_succ, @ofNat'_succ n, Num.add_one, ZNum.add_one, pred_succ] theorem ofInt'_toZNum : ∀ n : ℕ, toZNum n = ZNum.ofInt' n | 0 => rfl | n + 1 => by rw [Nat.cast_succ, Num.add_one, toZNum_succ, ofInt'_toZNum n, Nat.cast_succ, succ_ofInt', ZNum.add_one] theorem mem_ofZNum' : ∀ {m : Num} {n : ZNum}, m ∈ ofZNum' n ↔ n = toZNum m | 0, 0 => ⟨fun _ => rfl, fun _ => rfl⟩ | pos _, 0 => ⟨nofun, nofun⟩ | m, ZNum.pos p => Option.some_inj.trans <| by cases m <;> constructor <;> intro h <;> try cases h <;> rfl | m, ZNum.neg p => ⟨nofun, fun h => by cases m <;> cases h⟩ theorem ofZNum'_toNat : ∀ n : ZNum, (↑) <$> ofZNum' n = Int.toNat? n | 0 => rfl | ZNum.pos p => show _ = Int.toNat? p by rw [← PosNum.to_nat_to_int p]; rfl | ZNum.neg p => (congr_arg fun x => Int.toNat? (-x)) <| show ((p.pred' + 1 : ℕ) : ℤ) = p by rw [← succ'_to_nat]; simp theorem ofZNum_toNat : ∀ n : ZNum, (ofZNum n : ℕ) = Int.toNat n | 0 => rfl | ZNum.pos p => show _ = Int.toNat p by rw [← PosNum.to_nat_to_int p]; rfl | ZNum.neg p => (congr_arg fun x => Int.toNat (-x)) <| show ((p.pred' + 1 : ℕ) : ℤ) = p by rw [← succ'_to_nat]; simp @[simp] theorem cast_ofZNum [AddMonoidWithOne α] (n : ZNum) : (ofZNum n : α) = Int.toNat n := by rw [← cast_to_nat, ofZNum_toNat] @[simp, norm_cast] theorem sub_to_nat (m n) : ((m - n : Num) : ℕ) = m - n := show (ofZNum _ : ℕ) = _ by rw [ofZNum_toNat, cast_sub', ← to_nat_to_int, ← to_nat_to_int, Int.toNat_sub] end Num namespace ZNum variable {α : Type*} @[simp, norm_cast] theorem cast_add [AddGroupWithOne α] : ∀ m n, ((m + n : ZNum) : α) = m + n | 0, a => by cases a <;> exact (_root_.zero_add _).symm | b, 0 => by cases b <;> exact (_root_.add_zero _).symm | pos _, pos _ => PosNum.cast_add _ _ | pos a, neg b => by simpa only [sub_eq_add_neg] using PosNum.cast_sub' (α := α) _ _ | neg a, pos b => have : (↑b + -↑a : α) = -↑a + ↑b := by rw [← PosNum.cast_to_int a, ← PosNum.cast_to_int b, ← Int.cast_neg, ← Int.cast_add (-a)] simp [add_comm] (PosNum.cast_sub' _ _).trans <| (sub_eq_add_neg _ _).trans this | neg a, neg b => show -(↑(a + b) : α) = -a + -b by rw [PosNum.cast_add, neg_eq_iff_eq_neg, neg_add_rev, neg_neg, neg_neg, ← PosNum.cast_to_int a, ← PosNum.cast_to_int b, ← Int.cast_add, ← Int.cast_add, add_comm] @[simp] theorem cast_succ [AddGroupWithOne α] (n) : ((succ n : ZNum) : α) = n + 1 := by rw [← add_one, cast_add, cast_one] @[simp, norm_cast] theorem mul_to_int : ∀ m n, ((m * n : ZNum) : ℤ) = m * n | 0, a => by cases a <;> exact (zero_mul _).symm | b, 0 => by cases b <;> exact (mul_zero _).symm | pos a, pos b => PosNum.cast_mul a b | pos a, neg b => show -↑(a * b) = ↑a * -↑b by rw [PosNum.cast_mul, neg_mul_eq_mul_neg] | neg a, pos b => show -↑(a * b) = -↑a * ↑b by rw [PosNum.cast_mul, neg_mul_eq_neg_mul] | neg a, neg b => show ↑(a * b) = -↑a * -↑b by rw [PosNum.cast_mul, neg_mul_neg] theorem cast_mul [NonAssocRing α] (m n) : ((m * n : ZNum) : α) = m * n := by rw [← cast_to_int, mul_to_int, Int.cast_mul, cast_to_int, cast_to_int] theorem ofInt'_neg : ∀ n : ℤ, ofInt' (-n) = -ofInt' n | -[n+1] => show ofInt' (n + 1 : ℕ) = _ by simp only [ofInt', Num.zneg_toZNumNeg] | 0 => show Num.toZNum (Num.ofNat' 0) = -Num.toZNum (Num.ofNat' 0) by rw [Num.ofNat'_zero]; rfl | (n + 1 : ℕ) => show Num.toZNumNeg _ = -Num.toZNum _ by rw [Num.zneg_toZNum] theorem of_to_int' : ∀ n : ZNum, ZNum.ofInt' n = n | 0 => by dsimp [ofInt', cast_zero] simp only [Num.ofNat'_zero, Num.toZNum] | pos a => by rw [cast_pos, ← PosNum.cast_to_nat, ← Num.ofInt'_toZNum, PosNum.of_to_nat]; rfl | neg a => by rw [cast_neg, ofInt'_neg, ← PosNum.cast_to_nat, ← Num.ofInt'_toZNum, PosNum.of_to_nat]; rfl theorem to_int_inj {m n : ZNum} : (m : ℤ) = n ↔ m = n := ⟨fun h => Function.LeftInverse.injective of_to_int' h, congr_arg _⟩ theorem cmp_to_int : ∀ m n, (Ordering.casesOn (cmp m n) ((m : ℤ) < n) (m = n) ((n : ℤ) < m) : Prop) | 0, 0 => rfl | pos a, pos b => by have := PosNum.cmp_to_nat a b; revert this; dsimp [cmp] cases PosNum.cmp a b <;> [simp; exact congr_arg pos; simp] | neg a, neg b => by have := PosNum.cmp_to_nat b a; revert this; dsimp [cmp] cases PosNum.cmp b a <;> [simp; simp +contextual; simp] | pos _, 0 => PosNum.cast_pos _ | pos _, neg _ => lt_trans (neg_lt_zero.2 <| PosNum.cast_pos _) (PosNum.cast_pos _) | 0, neg _ => neg_lt_zero.2 <| PosNum.cast_pos _ | neg _, 0 => neg_lt_zero.2 <| PosNum.cast_pos _ | neg _, pos _ => lt_trans (neg_lt_zero.2 <| PosNum.cast_pos _) (PosNum.cast_pos _) | 0, pos _ => PosNum.cast_pos _ @[norm_cast] theorem lt_to_int {m n : ZNum} : (m : ℤ) < n ↔ m < n := show (m : ℤ) < n ↔ cmp m n = Ordering.lt from match cmp m n, cmp_to_int m n with | Ordering.lt, h => by simp only at h; simp [h] | Ordering.eq, h => by simp only at h; simp [h] | Ordering.gt, h => by simp [not_lt_of_gt h] theorem le_to_int {m n : ZNum} : (m : ℤ) ≤ n ↔ m ≤ n := by rw [← not_lt]; exact not_congr lt_to_int @[simp, norm_cast] theorem cast_lt [Ring α] [PartialOrder α] [IsStrictOrderedRing α] {m n : ZNum} : (m : α) < n ↔ m < n := by rw [← cast_to_int m, ← cast_to_int n, Int.cast_lt, lt_to_int] @[simp, norm_cast] theorem cast_le [Ring α] [LinearOrder α] [IsStrictOrderedRing α] {m n : ZNum} : (m : α) ≤ n ↔ m ≤ n := by rw [← not_lt]; exact not_congr cast_lt @[simp, norm_cast] theorem cast_inj [Ring α] [PartialOrder α] [IsStrictOrderedRing α] {m n : ZNum} : (m : α) = n ↔ m = n := by rw [← cast_to_int m, ← cast_to_int n, Int.cast_inj (α := α), to_int_inj] /-- This tactic tries to turn an (in)equality about `ZNum`s to one about `Int`s by rewriting. ```lean example (n : ZNum) (m : ZNum) : n ≤ n + m * m := by transfer_rw exact le_add_of_nonneg_right (mul_self_nonneg _) ``` -/ scoped macro (name := transfer_rw) "transfer_rw" : tactic => `(tactic| (repeat first | rw [← to_int_inj] | rw [← lt_to_int] | rw [← le_to_int] repeat first | rw [cast_add] | rw [mul_to_int] | rw [cast_one] | rw [cast_zero])) /-- This tactic tries to prove (in)equalities about `ZNum`s by transferring them to the `Int` world and then trying to call `simp`. ```lean example (n : ZNum) (m : ZNum) : n ≤ n + m * m := by transfer exact mul_self_nonneg _ ``` -/ scoped macro (name := transfer) "transfer" : tactic => `(tactic| (intros; transfer_rw; try simp [add_comm, add_left_comm, mul_comm, mul_left_comm])) instance linearOrder : LinearOrder ZNum where lt_iff_le_not_ge := by intro a b transfer_rw apply lt_iff_le_not_ge le_refl := by transfer le_trans := by intro a b c transfer_rw apply le_trans le_antisymm := by intro a b transfer_rw apply le_antisymm le_total := by intro a b transfer_rw apply le_total -- This is relying on an automatically generated instance name, generated in a `deriving` handler. -- See https://github.com/leanprover/lean4/issues/2343 toDecidableEq := instDecidableEqZNum toDecidableLE := ZNum.decidableLE toDecidableLT := ZNum.decidableLT instance addMonoid : AddMonoid ZNum where add_assoc := by transfer zero_add := zero_add add_zero := add_zero nsmul := nsmulRec instance addCommGroup : AddCommGroup ZNum := { ZNum.addMonoid with add_comm := by transfer zsmul := zsmulRec neg_add_cancel := by transfer } instance addMonoidWithOne : AddMonoidWithOne ZNum := { ZNum.addMonoid with natCast := fun n => ZNum.ofInt' n natCast_zero := show (Num.ofNat' 0).toZNum = 0 by rw [Num.ofNat'_zero]; rfl natCast_succ := fun n => show (Num.ofNat' (n + 1)).toZNum = (Num.ofNat' n).toZNum + 1 by rw [Num.ofNat'_succ, Num.add_one, Num.toZNum_succ, ZNum.add_one] } -- The next theorems are declared outside of the instance to prevent timeouts. private theorem mul_comm : ∀ (a b : ZNum), a * b = b * a := by transfer private theorem add_le_add_left : ∀ (a b : ZNum), a ≤ b → ∀ (c : ZNum), c + a ≤ c + b := by intro a b h c revert h transfer_rw exact fun h => _root_.add_le_add_left h c instance commRing : CommRing ZNum := { ZNum.addCommGroup, ZNum.addMonoidWithOne with mul_assoc a b c := by transfer zero_mul := by transfer mul_zero := by transfer one_mul := by transfer mul_one := by transfer left_distrib := by transfer simp [mul_add] right_distrib := by transfer simp [mul_add, _root_.mul_comm] mul_comm := mul_comm } instance nontrivial : Nontrivial ZNum := { exists_pair_ne := ⟨0, 1, by decide⟩ } instance zeroLEOneClass : ZeroLEOneClass ZNum := { zero_le_one := by decide } instance isOrderedAddMonoid : IsOrderedAddMonoid ZNum := { add_le_add_left := add_le_add_left } instance isStrictOrderedRing : IsStrictOrderedRing ZNum := .of_mul_pos fun a b ↦ by transfer_rw apply mul_pos @[simp, norm_cast] theorem cast_sub [AddCommGroupWithOne α] (m n) : ((m - n : ZNum) : α) = m - n := by simp [sub_eq_neg_add] @[norm_cast] theorem neg_of_int : ∀ n, ((-n : ℤ) : ZNum) = -n | (_ + 1 : ℕ) => rfl | 0 => by rw [Int.cast_neg] | -[_+1] => (zneg_zneg _).symm @[simp] theorem ofInt'_eq : ∀ n : ℤ, ZNum.ofInt' n = n | (n : ℕ) => rfl | -[n+1] => by change Num.toZNumNeg (n + 1 : ℕ) = -(n + 1 : ℕ) rw [← neg_inj, neg_neg, Nat.cast_succ, Num.add_one, Num.zneg_toZNumNeg, Num.toZNum_succ, Nat.cast_succ, ZNum.add_one] rfl @[simp] theorem of_nat_toZNum (n : ℕ) : Num.toZNum n = n := rfl -- The priority should be `high`er than `cast_to_int`. @[simp high, norm_cast] theorem of_to_int (n : ZNum) : ((n : ℤ) : ZNum) = n := by rw [← ofInt'_eq, of_to_int'] theorem to_of_int (n : ℤ) : ((n : ZNum) : ℤ) = n := Int.inductionOn' n 0 (by simp) (by simp) (by simp) @[simp] theorem of_nat_toZNumNeg (n : ℕ) : Num.toZNumNeg n = -n := by rw [← of_nat_toZNum, Num.zneg_toZNum] @[simp, norm_cast] theorem of_intCast [AddGroupWithOne α] (n : ℤ) : ((n : ZNum) : α) = n := by rw [← cast_to_int, to_of_int] @[simp, norm_cast] theorem of_natCast [AddGroupWithOne α] (n : ℕ) : ((n : ZNum) : α) = n := by rw [← Int.cast_natCast, of_intCast, Int.cast_natCast] @[simp, norm_cast] theorem dvd_to_int (m n : ZNum) : (m : ℤ) ∣ n ↔ m ∣ n := ⟨fun ⟨k, e⟩ => ⟨k, by rw [← of_to_int n, e]; simp⟩, fun ⟨k, e⟩ => ⟨k, by simp [e]⟩⟩ end ZNum namespace PosNum theorem divMod_to_nat_aux {n d : PosNum} {q r : Num} (h₁ : (r : ℕ) + d * ((q : ℕ) + q) = n) (h₂ : (r : ℕ) < 2 * d) : ((divModAux d q r).2 + d * (divModAux d q r).1 : ℕ) = ↑n ∧ ((divModAux d q r).2 : ℕ) < d := by unfold divModAux have : ∀ {r₂}, Num.ofZNum' (Num.sub' r (Num.pos d)) = some r₂ ↔ (r : ℕ) = r₂ + d := by intro r₂ apply Num.mem_ofZNum'.trans rw [← ZNum.to_int_inj, Num.cast_toZNum, Num.cast_sub', sub_eq_iff_eq_add, ← Int.natCast_inj] simp rcases e : Num.ofZNum' (Num.sub' r (Num.pos d)) with - | r₂ · rw [Num.cast_bit0, two_mul] refine ⟨h₁, lt_of_not_ge fun h => ?_⟩ obtain ⟨r₂, e'⟩ := Nat.le.dest h rw [← Num.to_of_nat r₂, add_comm] at e' cases e.symm.trans (this.2 e'.symm) · have := this.1 e simp only [Num.cast_bit1] constructor · rwa [two_mul, add_comm _ 1, mul_add, mul_one, ← add_assoc, ← this] · rwa [this, two_mul, add_lt_add_iff_right] at h₂ theorem divMod_to_nat (d n : PosNum) : (n / d : ℕ) = (divMod d n).1 ∧ (n % d : ℕ) = (divMod d n).2 := by rw [Nat.div_mod_unique (PosNum.cast_pos _)] induction n with | one => exact divMod_to_nat_aux (by simp) (Nat.mul_le_mul_left 2 (PosNum.cast_pos d : (0 : ℕ) < d)) | bit1 n IH => unfold divMod -- Porting note: `cases'` didn't rewrite at `this`, so `revert` & `intro` are required. revert IH; obtain ⟨q, r⟩ := divMod d n; intro IH simp only at IH ⊢ apply divMod_to_nat_aux <;> simp only [Num.cast_bit1, cast_bit1] · rw [← two_mul, ← two_mul, add_right_comm, mul_left_comm, ← mul_add, IH.1] · omega | bit0 n IH => unfold divMod -- Porting note: `cases'` didn't rewrite at `this`, so `revert` & `intro` are required. revert IH; obtain ⟨q, r⟩ := divMod d n; intro IH simp only at IH ⊢ apply divMod_to_nat_aux · simp only [Num.cast_bit0, cast_bit0] rw [← two_mul, ← two_mul, mul_left_comm, ← mul_add, ← IH.1] · simpa using IH.2 @[simp] theorem div'_to_nat (n d) : (div' n d : ℕ) = n / d := (divMod_to_nat _ _).1.symm @[simp] theorem mod'_to_nat (n d) : (mod' n d : ℕ) = n % d := (divMod_to_nat _ _).2.symm end PosNum namespace Num @[simp] protected theorem div_zero (n : Num) : n / 0 = 0 := show n.div 0 = 0 by cases n · rfl · simp [Num.div] @[simp, norm_cast] theorem div_to_nat : ∀ n d, ((n / d : Num) : ℕ) = n / d | 0, 0 => by simp | 0, pos _ => (Nat.zero_div _).symm | pos _, 0 => (Nat.div_zero _).symm | pos _, pos _ => PosNum.div'_to_nat _ _ @[simp] protected theorem mod_zero (n : Num) : n % 0 = n := show n.mod 0 = n by cases n · rfl · simp [Num.mod] @[simp, norm_cast] theorem mod_to_nat : ∀ n d, ((n % d : Num) : ℕ) = n % d | 0, 0 => by simp | 0, pos _ => (Nat.zero_mod _).symm | pos _, 0 => (Nat.mod_zero _).symm | pos _, pos _ => PosNum.mod'_to_nat _ _ theorem gcd_to_nat_aux : ∀ {n} {a b : Num}, a ≤ b → (a * b).natSize ≤ n → (gcdAux n a b : ℕ) = Nat.gcd a b | 0, 0, _, _ab, _h => (Nat.gcd_zero_left _).symm | 0, pos _, 0, ab, _h => (not_lt_of_ge ab).elim rfl | 0, pos _, pos _, _ab, h => (not_lt_of_ge h).elim <| PosNum.natSize_pos _ | Nat.succ _, 0, _, _ab, _h => (Nat.gcd_zero_left _).symm | Nat.succ n, pos a, b, ab, h => by simp only [gcdAux, cast_pos] rw [Nat.gcd_rec, gcd_to_nat_aux, mod_to_nat] · rfl · rw [← le_to_nat, mod_to_nat] exact le_of_lt (Nat.mod_lt _ (PosNum.cast_pos _)) rw [natSize_to_nat, mul_to_nat, Nat.size_le] at h ⊢ rw [mod_to_nat, mul_comm] rw [pow_succ, ← Nat.mod_add_div b (pos a)] at h refine lt_of_mul_lt_mul_right (lt_of_le_of_lt ?_ h) (Nat.zero_le 2) rw [mul_two, mul_add] gcongr _ + _ * ?_ grw [Nat.mod_lt, ← le_to_nat.2 ab] · simp · exact PosNum.cast_pos _ @[simp] theorem gcd_to_nat : ∀ a b, (gcd a b : ℕ) = Nat.gcd a b := by have : ∀ a b : Num, (a * b).natSize ≤ a.natSize + b.natSize := by intros simp only [natSize_to_nat, cast_mul] rw [Nat.size_le, pow_add] exact mul_lt_mul'' (Nat.lt_size_self _) (Nat.lt_size_self _) (Nat.zero_le _) (Nat.zero_le _) intros unfold gcd split_ifs with h · exact gcd_to_nat_aux h (this _ _) · rw [Nat.gcd_comm] exact gcd_to_nat_aux (le_of_not_ge h) (this _ _) theorem dvd_iff_mod_eq_zero {m n : Num} : m ∣ n ↔ n % m = 0 := by rw [← dvd_to_nat, Nat.dvd_iff_mod_eq_zero, ← to_nat_inj, mod_to_nat]; rfl instance decidableDvd : DecidableRel ((· ∣ ·) : Num → Num → Prop) | _a, _b => decidable_of_iff' _ dvd_iff_mod_eq_zero end Num instance PosNum.decidableDvd : DecidableRel ((· ∣ ·) : PosNum → PosNum → Prop) | _a, _b => Num.decidableDvd _ _ namespace ZNum @[simp] protected theorem div_zero (n : ZNum) : n / 0 = 0 := show n.div 0 = 0 by cases n <;> rfl @[simp, norm_cast] theorem div_to_int : ∀ n d, ((n / d : ZNum) : ℤ) = n / d | 0, 0 => by simp [Int.ediv_zero] | 0, pos _ => (Int.zero_ediv _).symm | 0, neg _ => (Int.zero_ediv _).symm | pos _, 0 => (Int.ediv_zero _).symm | neg _, 0 => (Int.ediv_zero _).symm | pos n, pos d => (Num.cast_toZNum _).trans <| by rw [← Num.to_nat_to_int]; simp | pos n, neg d => (Num.cast_toZNumNeg _).trans <| by rw [← Num.to_nat_to_int]; simp | neg n, pos d => show -_ = -_ / ↑d by rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred, ← PosNum.to_nat_to_int, Num.succ'_to_nat, Num.div_to_nat] change -[n.pred' / ↑d+1] = -[n.pred' / (d.pred' + 1)+1] rw [d.to_nat_eq_succ_pred] | neg n, neg d => show ↑(PosNum.pred' n / Num.pos d).succ' = -_ / -↑d by rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred, ← PosNum.to_nat_to_int, Num.succ'_to_nat, Num.div_to_nat] change (Nat.succ (_ / d) : ℤ) = Nat.succ (n.pred' / (d.pred' + 1)) rw [d.to_nat_eq_succ_pred] @[simp, norm_cast] theorem mod_to_int : ∀ n d, ((n % d : ZNum) : ℤ) = n % d | 0, _ => (Int.zero_emod _).symm | pos n, d => (Num.cast_toZNum _).trans <| by rw [← Num.to_nat_to_int, cast_pos, Num.mod_to_nat, ← PosNum.to_nat_to_int, abs_to_nat] rfl | neg n, d => (Num.cast_sub' _ _).trans <| by rw [← Num.to_nat_to_int, cast_neg, ← Num.to_nat_to_int, Num.succ_to_nat, Num.mod_to_nat, abs_to_nat, ← Int.subNatNat_eq_coe, n.to_int_eq_succ_pred] rfl @[simp] theorem gcd_to_nat (a b) : (gcd a b : ℕ) = Int.gcd a b := (Num.gcd_to_nat _ _).trans <| by simp only [abs_to_nat]; rfl theorem dvd_iff_mod_eq_zero {m n : ZNum} : m ∣ n ↔ n % m = 0 := by rw [← dvd_to_int, Int.dvd_iff_emod_eq_zero, ← to_int_inj, mod_to_int]; rfl instance decidableDvd : DecidableRel ((· ∣ ·) : ZNum → ZNum → Prop) | _a, _b => decidable_of_iff' _ dvd_iff_mod_eq_zero end ZNum
.lake/packages/mathlib/Mathlib/Data/Num/Prime.lean
import Mathlib.Data.Nat.Prime.Defs import Mathlib.Data.Num.ZNum import Mathlib.Tactic.Ring /-! # Primality for binary natural numbers This file defines versions of `Nat.minFac` and `Nat.Prime` for `Num` and `PosNum`. As with other `Num` definitions, they are not intended for general use (`Nat` should be used instead of `Num` in most cases) but they can be used in contexts where kernel computation is required, such as proofs by `rfl` and `decide`, as well as in `#reduce`. The default decidable instance for `Nat.Prime` is optimized for VM evaluation, so it should be preferred within `#eval` or in tactic execution, while for proofs the `norm_num` tactic can be used to construct primality and non-primality proofs more efficiently than kernel computation. Nevertheless, sometimes proof by computational reflection requires natural number computations, and `Num` implements algorithms directly on binary natural numbers for this purpose. -/ namespace PosNum /-- Auxiliary function for computing the smallest prime factor of a `PosNum`. Unlike `Nat.minFacAux`, we use a natural number `fuel` variable that is set to an upper bound on the number of iterations. It is initialized to the number `n` we are determining primality for. Even though this is exponential in the input (since it is a `Nat`, not a `Num`), it will get lazily evaluated during kernel reduction, so we will only require about `sqrt n` unfoldings, for the `sqrt n` iterations of the loop. -/ def minFacAux (n : PosNum) : ℕ → PosNum → PosNum | 0, _ => n | fuel + 1, k => if n < k.bit1 * k.bit1 then n else if k.bit1 ∣ n then k.bit1 else minFacAux n fuel k.succ theorem minFacAux_to_nat {fuel : ℕ} {n k : PosNum} (h : Nat.sqrt n < fuel + k.bit1) : (minFacAux n fuel k : ℕ) = Nat.minFacAux n k.bit1 := by induction fuel generalizing k <;> rw [minFacAux, Nat.minFacAux] case zero => rw [Nat.zero_add, Nat.sqrt_lt] at h simp only [h, ite_true] case succ fuel ih => simp_rw [← mul_to_nat] simp only [cast_lt, dvd_to_nat] split_ifs <;> try rfl rw [ih] <;> [congr; convert Nat.lt_succ_of_lt h using 1] <;> simp only [cast_bit1, cast_succ, Nat.succ_eq_add_one, add_assoc, add_left_comm, ← one_add_one_eq_two] /-- Returns the smallest prime factor of `n ≠ 1`. -/ def minFac : PosNum → PosNum | 1 => 1 | bit0 _ => 2 | bit1 n => minFacAux (bit1 n) n 1 @[simp] theorem minFac_to_nat (n : PosNum) : (minFac n : ℕ) = Nat.minFac n := by obtain - | n := n · simp [minFac] · rw [minFac, Nat.minFac_eq, if_neg] swap · simp [← two_mul] rw [minFacAux_to_nat] · rfl simp only [cast_one, cast_bit1] rw [Nat.sqrt_lt] calc (n : ℕ) + (n : ℕ) + 1 ≤ (n : ℕ) + (n : ℕ) + (n : ℕ) := by simp _ = (n : ℕ) * (1 + 1 + 1) := by simp only [mul_add, mul_one] _ < _ := by simp [mul_lt_mul] · rw [minFac, Nat.minFac_eq, if_pos] · rfl simp [← two_mul] /-- Primality predicate for a `PosNum`. -/ @[simp] def Prime (n : PosNum) : Prop := Nat.Prime n instance decidablePrime : DecidablePred PosNum.Prime | 1 => Decidable.isFalse Nat.not_prime_one | bit0 n => decidable_of_iff' (n = 1) (by refine Nat.prime_def_minFac.trans ((and_iff_right ?_).trans <| eq_comm.trans ?_) · exact add_le_add (Nat.succ_le_of_lt (to_nat_pos _)) (Nat.succ_le_of_lt (to_nat_pos _)) rw [← minFac_to_nat, to_nat_inj] exact ⟨bit0.inj, congr_arg _⟩) | bit1 n => decidable_of_iff' (minFacAux (bit1 n) n 1 = bit1 n) <| by refine Nat.prime_def_minFac.trans ((and_iff_right ?_).trans ?_) · simp only [cast_bit1] have := to_nat_pos n omega rw [← minFac_to_nat, to_nat_inj]; rfl end PosNum namespace Num /-- Returns the smallest prime factor of `n ≠ 1`. -/ def minFac : Num → PosNum | 0 => 2 | pos n => n.minFac @[simp] theorem minFac_to_nat : ∀ n : Num, (minFac n : ℕ) = Nat.minFac n | 0 => rfl | pos _ => PosNum.minFac_to_nat _ /-- Primality predicate for a `Num`. -/ @[simp] def Prime (n : Num) : Prop := Nat.Prime n instance decidablePrime : DecidablePred Num.Prime | 0 => Decidable.isFalse Nat.not_prime_zero | pos n => PosNum.decidablePrime n end Num
.lake/packages/mathlib/Mathlib/Data/Option/NAry.lean
import Batteries.Tactic.Init import Mathlib.Logic.Function.Defs /-! # Binary map of options This file defines the binary map of `Option`. This is mostly useful to define pointwise operations on intervals. ## Main declarations * `Option.map₂`: Binary map of options. ## Notes This file is very similar to the n-ary section of `Mathlib/Data/Set/Basic.lean`, to `Mathlib/Data/Finset/NAry.lean` and to `Mathlib/Order/Filter/NAry.lean`. Please keep them in sync. We do not define `Option.map₃` as its only purpose so far would be to prove properties of `Option.map₂` and casing already fulfills this task. -/ universe u open Function namespace Option -- Allow `grind` to case split on `Option` in this file. attribute [local grind cases] Option variable {α β γ δ : Type*} {f : α → β → γ} {a : Option α} {b : Option β} {c : Option γ} /-- The image of a binary function `f : α → β → γ` as a function `Option α → Option β → Option γ`. Mathematically this should be thought of as the image of the corresponding function `α × β → γ`. -/ def map₂ (f : α → β → γ) (a : Option α) (b : Option β) : Option γ := a.bind fun a => b.map <| f a /-- `Option.map₂` in terms of monadic operations. Note that this can't be taken as the definition because of the lack of universe polymorphism. -/ theorem map₂_def {α β γ : Type u} (f : α → β → γ) (a : Option α) (b : Option β) : map₂ f a b = f <$> a <*> b := by cases a <;> rfl @[simp, grind =] theorem map₂_some_some (f : α → β → γ) (a : α) (b : β) : map₂ f (some a) (some b) = f a b := rfl theorem map₂_coe_coe (f : α → β → γ) (a : α) (b : β) : map₂ f a b = f a b := rfl @[simp, grind =] theorem map₂_none_left (f : α → β → γ) (b : Option β) : map₂ f none b = none := rfl @[simp, grind =] theorem map₂_none_right (f : α → β → γ) (a : Option α) : map₂ f a none = none := by cases a <;> rfl @[simp] theorem map₂_coe_left (f : α → β → γ) (a : α) (b : Option β) : map₂ f a b = b.map fun b => f a b := rfl @[simp] theorem map₂_coe_right (f : α → β → γ) (a : Option α) (b : β) : map₂ f a b = a.map fun a => f a b := by grind theorem mem_map₂_iff {c : γ} : c ∈ map₂ f a b ↔ ∃ a' b', a' ∈ a ∧ b' ∈ b ∧ f a' b' = c := by grind /-- `simp`-normal form of `mem_map₂_iff`. -/ @[simp] theorem map₂_eq_some_iff {c : γ} : map₂ f a b = some c ↔ ∃ a' b', a' ∈ a ∧ b' ∈ b ∧ f a' b' = c := by grind @[simp] theorem map₂_eq_none_iff : map₂ f a b = none ↔ a = none ∨ b = none := by grind theorem map₂_swap (f : α → β → γ) (a : Option α) (b : Option β) : map₂ f a b = map₂ (fun a b => f b a) b a := by grind theorem map_map₂ (f : α → β → γ) (g : γ → δ) : (map₂ f a b).map g = map₂ (fun a b => g (f a b)) a b := by grind theorem map₂_map_left (f : γ → β → δ) (g : α → γ) : map₂ f (a.map g) b = map₂ (fun a b => f (g a) b) a b := by grind theorem map₂_map_right (f : α → γ → δ) (g : β → γ) : map₂ f a (b.map g) = map₂ (fun a b => f a (g b)) a b := by grind @[simp] theorem map₂_curry (f : α × β → γ) (a : Option α) (b : Option β) : map₂ (curry f) a b = Option.map f (map₂ Prod.mk a b) := by grind @[simp] theorem map_uncurry (f : α → β → γ) (x : Option (α × β)) : x.map (uncurry f) = map₂ f (x.map Prod.fst) (x.map Prod.snd) := by grind /-! ### Algebraic replacement rules A collection of lemmas to transfer associativity, commutativity, distributivity, ... of operations to the associativity, commutativity, distributivity, ... of `Option.map₂` of those operations. The proof pattern is `map₂_lemma operation_lemma`. For example, `map₂_comm mul_comm` proves that `map₂ (*) a b = map₂ (*) g f` in a `CommSemigroup`. -/ variable {α' β' δ' ε ε' : Type*} theorem map₂_assoc {f : δ → γ → ε} {g : α → β → δ} {f' : α → ε' → ε} {g' : β → γ → ε'} (h_assoc : ∀ a b c, f (g a b) c = f' a (g' b c)) : map₂ f (map₂ g a b) c = map₂ f' a (map₂ g' b c) := by grind theorem map₂_comm {g : β → α → γ} (h_comm : ∀ a b, f a b = g b a) : map₂ f a b = map₂ g b a := by grind theorem map₂_left_comm {f : α → δ → ε} {g : β → γ → δ} {f' : α → γ → δ'} {g' : β → δ' → ε} (h_left_comm : ∀ a b c, f a (g b c) = g' b (f' a c)) : map₂ f a (map₂ g b c) = map₂ g' b (map₂ f' a c) := by grind theorem map₂_right_comm {f : δ → γ → ε} {g : α → β → δ} {f' : α → γ → δ'} {g' : δ' → β → ε} (h_right_comm : ∀ a b c, f (g a b) c = g' (f' a c) b) : map₂ f (map₂ g a b) c = map₂ g' (map₂ f' a c) b := by grind theorem map_map₂_distrib {g : γ → δ} {f' : α' → β' → δ} {g₁ : α → α'} {g₂ : β → β'} (h_distrib : ∀ a b, g (f a b) = f' (g₁ a) (g₂ b)) : (map₂ f a b).map g = map₂ f' (a.map g₁) (b.map g₂) := by grind /-! The following symmetric restatement are needed because unification has a hard time figuring all the functions if you symmetrize on the spot. This is also how the other n-ary APIs do it. -/ /-- Symmetric statement to `Option.map₂_map_left_comm`. -/ theorem map_map₂_distrib_left {g : γ → δ} {f' : α' → β → δ} {g' : α → α'} (h_distrib : ∀ a b, g (f a b) = f' (g' a) b) : (map₂ f a b).map g = map₂ f' (a.map g') b := by grind /-- Symmetric statement to `Option.map_map₂_right_comm`. -/ theorem map_map₂_distrib_right {g : γ → δ} {f' : α → β' → δ} {g' : β → β'} (h_distrib : ∀ a b, g (f a b) = f' a (g' b)) : (map₂ f a b).map g = map₂ f' a (b.map g') := by grind /-- Symmetric statement to `Option.map_map₂_distrib_left`. -/ theorem map₂_map_left_comm {f : α' → β → γ} {g : α → α'} {f' : α → β → δ} {g' : δ → γ} (h_left_comm : ∀ a b, f (g a) b = g' (f' a b)) : map₂ f (a.map g) b = (map₂ f' a b).map g' := by grind /-- Symmetric statement to `Option.map_map₂_distrib_right`. -/ theorem map_map₂_right_comm {f : α → β' → γ} {g : β → β'} {f' : α → β → δ} {g' : δ → γ} (h_right_comm : ∀ a b, f a (g b) = g' (f' a b)) : map₂ f a (b.map g) = (map₂ f' a b).map g' := by grind theorem map_map₂_antidistrib {g : γ → δ} {f' : β' → α' → δ} {g₁ : β → β'} {g₂ : α → α'} (h_antidistrib : ∀ a b, g (f a b) = f' (g₁ b) (g₂ a)) : (map₂ f a b).map g = map₂ f' (b.map g₁) (a.map g₂) := by grind /-- Symmetric statement to `Option.map₂_map_left_anticomm`. -/ theorem map_map₂_antidistrib_left {g : γ → δ} {f' : β' → α → δ} {g' : β → β'} (h_antidistrib : ∀ a b, g (f a b) = f' (g' b) a) : (map₂ f a b).map g = map₂ f' (b.map g') a := by grind /-- Symmetric statement to `Option.map_map₂_right_anticomm`. -/ theorem map_map₂_antidistrib_right {g : γ → δ} {f' : β → α' → δ} {g' : α → α'} (h_antidistrib : ∀ a b, g (f a b) = f' b (g' a)) : (map₂ f a b).map g = map₂ f' b (a.map g') := by grind /-- Symmetric statement to `Option.map_map₂_antidistrib_left`. -/ theorem map₂_map_left_anticomm {f : α' → β → γ} {g : α → α'} {f' : β → α → δ} {g' : δ → γ} (h_left_anticomm : ∀ a b, f (g a) b = g' (f' b a)) : map₂ f (a.map g) b = (map₂ f' b a).map g' := by grind /-- Symmetric statement to `Option.map_map₂_antidistrib_right`. -/ theorem map_map₂_right_anticomm {f : α → β' → γ} {g : β → β'} {f' : β → α → δ} {g' : δ → γ} (h_right_anticomm : ∀ a b, f a (g b) = g' (f' b a)) : map₂ f a (b.map g) = (map₂ f' b a).map g' := by grind /-- If `a` is a left identity for a binary operation `f`, then `some a` is a left identity for `Option.map₂ f`. -/ lemma map₂_left_identity {f : α → β → β} {a : α} (h : ∀ b, f a b = b) (o : Option β) : map₂ f (some a) o = o := by grind /-- If `b` is a right identity for a binary operation `f`, then `some b` is a right identity for `Option.map₂ f`. -/ lemma map₂_right_identity {f : α → β → α} {b : β} (h : ∀ a, f a b = a) (o : Option α) : map₂ f o (some b) = o := by grind end Option
.lake/packages/mathlib/Mathlib/Data/Option/Basic.lean
import Mathlib.Control.Combinators import Mathlib.Data.Option.Defs import Mathlib.Logic.IsEmpty import Mathlib.Logic.Relator import Mathlib.Util.CompileInductive import Aesop /-! # Option of a type This file develops the basic theory of option types. If `α` is a type, then `Option α` can be understood as the type with one more element than `α`. `Option α` has terms `some a`, where `a : α`, and `none`, which is the added element. This is useful in multiple ways: * It is the prototype of addition of terms to a type. See for example `WithBot α` which uses `none` as an element smaller than all others. * It can be used to define failsafe partial functions, which return `some the_result_we_expect` if we can find `the_result_we_expect`, and `none` if there is no meaningful result. This forces any subsequent use of the partial function to explicitly deal with the exceptions that make it return `none`. * `Option` is a monad. We love monads. `Part` is an alternative to `Option` that can be seen as the type of `True`/`False` values along with a term `a : α` if the value is `True`. -/ universe u namespace Option variable {α β γ δ : Type*} theorem coe_def : (fun a ↦ ↑a : α → Option α) = some := rfl theorem mem_map {f : α → β} {y : β} {o : Option α} : y ∈ o.map f ↔ ∃ x ∈ o, f x = y := by simp -- The simpNF linter says that the LHS can be simplified via `Option.mem_def`. -- However this is a higher priority lemma. -- It seems the side condition `H` is not applied by `simpNF`. -- https://github.com/leanprover/std4/issues/207 @[simp 1100, nolint simpNF] theorem mem_map_of_injective {f : α → β} (H : Function.Injective f) {a : α} {o : Option α} : f a ∈ o.map f ↔ a ∈ o := by aesop theorem forall_mem_map {f : α → β} {o : Option α} {p : β → Prop} : (∀ y ∈ o.map f, p y) ↔ ∀ x ∈ o, p (f x) := by simp theorem exists_mem_map {f : α → β} {o : Option α} {p : β → Prop} : (∃ y ∈ o.map f, p y) ↔ ∃ x ∈ o, p (f x) := by simp theorem coe_get {o : Option α} (h : o.isSome) : ((Option.get _ h : α) : Option α) = o := Option.some_get h theorem eq_of_mem_of_mem {a : α} {o1 o2 : Option α} (h1 : a ∈ o1) (h2 : a ∈ o2) : o1 = o2 := h1.trans h2.symm theorem Mem.leftUnique : Relator.LeftUnique ((· ∈ ·) : α → Option α → Prop) := fun _ _ _ => mem_unique theorem some_injective (α : Type*) : Function.Injective (@some α) := fun _ _ ↦ some_inj.mp /-- `Option.map f` is injective if `f` is injective. -/ theorem map_injective {f : α → β} (Hf : Function.Injective f) : Function.Injective (Option.map f) | none, none, _ => rfl | some a₁, some a₂, H => by rw [Hf (Option.some.inj H)] @[simp] theorem map_comp_some (f : α → β) : Option.map f ∘ some = some ∘ f := rfl @[congr] theorem bind_congr' {f g : α → Option β} {x y : Option α} (hx : x = y) (hf : ∀ a ∈ y, f a = g a) : x.bind f = y.bind g := hx.symm ▸ bind_congr hf theorem joinM_eq_join : joinM = @join α := funext fun _ ↦ rfl theorem bind_eq_bind' {α β : Type u} {f : α → Option β} {x : Option α} : x >>= f = x.bind f := rfl theorem map_coe {α β} {a : α} {f : α → β} : f <$> (a : Option α) = ↑(f a) := rfl @[simp] theorem map_coe' {a : α} {f : α → β} : Option.map f (a : Option α) = ↑(f a) := rfl /-- `Option.map` as a function between functions is injective. -/ theorem map_injective' : Function.Injective (@Option.map α β) := fun f g h ↦ funext fun x ↦ some_injective _ <| by simp only [← map_some, h] @[simp] theorem map_inj {f g : α → β} : Option.map f = Option.map g ↔ f = g := map_injective'.eq_iff @[simp] theorem map_eq_id {f : α → α} : Option.map f = id ↔ f = id := map_injective'.eq_iff' map_id theorem map_comm {f₁ : α → β} {f₂ : α → γ} {g₁ : β → δ} {g₂ : γ → δ} (h : g₁ ∘ f₁ = g₂ ∘ f₂) (a : α) : (Option.map f₁ a).map g₁ = (Option.map f₂ a).map g₂ := by rw [map_map, h, ← map_map] section pmap variable {p : α → Prop} (f : ∀ a : α, p a → β) (x : Option α) theorem mem_pmem {a : α} (h : ∀ a ∈ x, p a) (ha : a ∈ x) : f a (h a ha) ∈ pmap f x h := by rw [mem_def] at ha ⊢ subst ha rfl theorem pmap_bind {α β γ} {x : Option α} {g : α → Option β} {p : β → Prop} {f : ∀ b, p b → γ} (H) (H' : ∀ (a : α), ∀ b ∈ g a, b ∈ x >>= g) : pmap f (x >>= g) H = x >>= fun a ↦ pmap f (g a) fun _ h ↦ H _ (H' a _ h) := by grind [cases Option] theorem bind_pmap {α β γ} {p : α → Prop} (f : ∀ a, p a → β) (x : Option α) (g : β → Option γ) (H) : pmap f x H >>= g = x.pbind fun a h ↦ g (f a (H _ h)) := by grind [cases Option, pmap] variable {f x} theorem pbind_eq_none {f : ∀ a : α, a ∈ x → Option β} (h' : ∀ a (H : a ∈ x), f a H = none → x = none) : x.pbind f = none ↔ x = none := by grind [cases Option] theorem join_pmap_eq_pmap_join {f : ∀ a, p a → β} {x : Option (Option α)} (H) : (pmap (pmap f) x H).join = pmap f x.join fun a h ↦ H (some a) (mem_of_mem_join h) _ rfl := by grind [cases Option] theorem pmap_bind_id_eq_pmap_join {f : ∀ a, p a → β} {x : Option (Option α)} (H) : ((pmap (pmap f) x H).bind fun a ↦ a) = pmap f x.join fun a h ↦ H (some a) (mem_of_mem_join h) _ rfl := by grind [cases Option] end pmap @[simp] theorem seq_some {α β} {a : α} {f : α → β} : some f <*> some a = some (f a) := rfl theorem iget_mem [Inhabited α] : ∀ {o : Option α}, isSome o → o.iget ∈ o | some _, _ => rfl theorem iget_of_mem [Inhabited α] {a : α} : ∀ {o : Option α}, a ∈ o → o.iget = a | _, rfl => rfl theorem getD_default_eq_iget [Inhabited α] (o : Option α) : o.getD default = o.iget := by cases o <;> rfl @[simp, grind =] theorem failure_eq_none {α} : failure = (none : Option α) := rfl @[simp] theorem guard_eq_some' {p : Prop} [Decidable p] (u) : _root_.guard p = some u ↔ p := by grind [cases Option, _root_.guard] /-- Given an element of `a : Option α`, a default element `b : β` and a function `α → β`, apply this function to `a` if it comes from `α`, and return `b` otherwise. -/ def casesOn' : Option α → β → (α → β) → β | none, n, _ => n | some a, _, s => s a @[simp] theorem casesOn'_none (x : β) (f : α → β) : casesOn' none x f = x := rfl @[simp] theorem casesOn'_some (x : β) (f : α → β) (a : α) : casesOn' (some a) x f = f a := rfl @[simp] theorem casesOn'_coe (x : β) (f : α → β) (a : α) : casesOn' (a : Option α) x f = f a := rfl @[simp] theorem casesOn'_none_coe (f : Option α → β) (o : Option α) : casesOn' o (f none) (f ∘ (fun a ↦ ↑a)) = f o := by cases o <;> rfl lemma casesOn'_eq_elim (b : β) (f : α → β) (a : Option α) : Option.casesOn' a b f = Option.elim a b f := by cases a <;> rfl theorem orElse_eq_some (o o' : Option α) (x : α) : (o <|> o') = some x ↔ o = some x ∨ o = none ∧ o' = some x := by simp theorem orElse_eq_none (o o' : Option α) : (o <|> o') = none ↔ o = none ∧ o' = none := by simp section theorem choice_eq_none (α : Type*) [IsEmpty α] : choice α = none := dif_neg (not_nonempty_iff_imp_false.mpr isEmptyElim) end @[simp] theorem elim_none_some (f : Option α → β) (i : Option α) : i.elim (f none) (f ∘ some) = f i := by cases i <;> rfl theorem elim_comp (h : α → β) {f : γ → α} {x : α} {i : Option γ} : (i.elim (h x) fun j => h (f j)) = h (i.elim x f) := by cases i <;> rfl theorem elim_comp₂ (h : α → β → γ) {f : γ → α} {x : α} {g : γ → β} {y : β} {i : Option γ} : (i.elim (h x y) fun j => h (f j) (g j)) = h (i.elim x f) (i.elim y g) := by cases i <;> rfl theorem elim_apply {f : γ → α → β} {x : α → β} {i : Option γ} {y : α} : i.elim x f y = i.elim (x y) fun j => f j y := by rw [elim_comp fun f : α → β => f y] open Function in @[simp] lemma elim'_update {α : Type*} {β : Type*} [DecidableEq α] (f : β) (g : α → β) (a : α) (x : β) : Option.elim' f (update g a x) = update (Option.elim' f g) (some a) x := -- Can't reuse `Option.rec_update` as `Option.elim'` is not defeq. Function.rec_update (α := fun _ => β) (@Option.some.inj _) (Option.elim' f) (fun _ _ => rfl) (fun | _, _, some _, h => (h _ rfl).elim | _, _, none, _ => rfl) _ _ _ end Option
.lake/packages/mathlib/Mathlib/Data/Option/Defs.lean
import Mathlib.Tactic.Lemma import Mathlib.Tactic.TypeStar import Batteries.Tactic.Alias /-! # Extra definitions on `Option` This file defines more operations involving `Option α`. Lemmas about them are located in other files under `Mathlib/Data/Option.lean`. Other basic operations on `Option` are defined in the core library. -/ namespace Option /-- Traverse an object of `Option α` with a function `f : α → F β` for an applicative `F`. -/ protected def traverse.{u, v} {F : Type u → Type v} [Applicative F] {α : Type*} {β : Type u} (f : α → F β) : Option α → F (Option β) := Option.mapA f variable {α : Type*} {β : Type*} /-- An elimination principle for `Option`. It is a nondependent version of `Option.rec`. -/ protected def elim' (b : β) (f : α → β) : Option α → β | some a => f a | none => b @[simp] theorem elim'_none (b : β) (f : α → β) : Option.elim' b f none = b := rfl @[simp] theorem elim'_some {a : α} (b : β) (f : α → β) : Option.elim' b f (some a) = f a := rfl @[simp] theorem elim'_none_some (f : Option α → β) : (Option.elim' (f none) (f ∘ some)) = f := funext fun o ↦ by cases o <;> rfl lemma elim'_eq_elim {α β : Type*} (b : β) (f : α → β) (a : Option α) : Option.elim' b f a = Option.elim a b f := by cases a <;> rfl /-- Inhabited `get` function. Returns `a` if the input is `some a`, otherwise returns `default`. -/ abbrev iget [Inhabited α] : Option α → α | some x => x | none => default theorem iget_some [Inhabited α] {a : α} : (some a).iget = a := rfl @[deprecated commutative_merge (since := "2025-06-03")] theorem merge_isCommutative (f : α → α → α) [Std.Commutative f] : Std.Commutative (merge f) := commutative_merge f @[deprecated associative_merge (since := "2025-06-03")] theorem merge_isAssociative (f : α → α → α) [Std.Associative f] : Std.Associative (merge f) := associative_merge f @[deprecated idempotentOp_merge (since := "2025-06-03")] theorem merge_isIdempotent (f : α → α → α) [Std.IdempotentOp f] : Std.IdempotentOp (merge f) := idempotentOp_merge f @[deprecated lawfulIdentity_merge (since := "2025-06-03")] theorem merge_isId (f : α → α → α) : Std.LawfulIdentity (merge f) none := lawfulIdentity_merge f end Option
.lake/packages/mathlib/Mathlib/Data/FunLike/Fintype.lean
import Mathlib.Data.Fintype.Basic import Mathlib.Data.FunLike.Basic import Mathlib.Data.Finite.Prod /-! # Finiteness of `DFunLike` types We show a type `F` with a `DFunLike F α β` is finite if both `α` and `β` are finite. This corresponds to the following two pairs of declarations: * `DFunLike.fintype` is a definition stating all `DFunLike`s are finite if their domain and codomain are. * `DFunLike.finite` is a lemma stating all `DFunLike`s are finite if their domain and codomain are. * `FunLike.fintype` is a non-dependent version of `DFunLike.fintype` and * `FunLike.finite` is a non-dependent version of `DFunLike.finite`, because dependent instances are harder to infer. You can use these to produce instances for specific `DFunLike` types. (Although there might be options for `Fintype` instances with better definitional behaviour.) They can't be instances themselves since they can cause loops. -/ -- `Type` is a reserved word, switched to `Type'` section Type' variable (F G : Type*) {α γ : Type*} {β : α → Type*} [DFunLike F α β] [FunLike G α γ] /-- All `DFunLike`s are finite if their domain and codomain are. This is not an instance because specific `DFunLike` types might have a better-suited definition. See also `DFunLike.finite`. -/ noncomputable def DFunLike.fintype [DecidableEq α] [Fintype α] [∀ i, Fintype (β i)] : Fintype F := Fintype.ofInjective _ DFunLike.coe_injective /-- All `FunLike`s are finite if their domain and codomain are. Non-dependent version of `DFunLike.fintype` that might be easier to infer. This is not an instance because specific `FunLike` types might have a better-suited definition. -/ noncomputable def FunLike.fintype [DecidableEq α] [Fintype α] [Fintype γ] : Fintype G := DFunLike.fintype G end Type' -- `Sort` is a reserved word, switched to `Sort'` section Sort' variable (F G : Sort*) {α γ : Sort*} {β : α → Sort*} [DFunLike F α β] [FunLike G α γ] /-- All `DFunLike`s are finite if their domain and codomain are. Can't be an instance because it can cause infinite loops. -/ theorem DFunLike.finite [Finite α] [∀ i, Finite (β i)] : Finite F := Finite.of_injective _ DFunLike.coe_injective /-- All `FunLike`s are finite if their domain and codomain are. Non-dependent version of `DFunLike.finite` that might be easier to infer. Can't be an instance because it can cause infinite loops. -/ theorem FunLike.finite [Finite α] [Finite γ] : Finite G := DFunLike.finite G end Sort' -- See note [lower instance priority] instance (priority := 100) FunLike.toDecidableEq {F α β : Type*} [DecidableEq β] [Fintype α] [FunLike F α β] : DecidableEq F := fun a b ↦ decidable_of_iff ((a : α → β) = b) DFunLike.coe_injective.eq_iff
.lake/packages/mathlib/Mathlib/Data/FunLike/Basic.lean
import Mathlib.Logic.Function.Basic import Mathlib.Logic.Unique import Mathlib.Util.CompileInductive import Mathlib.Tactic.Simps.NotationClass /-! # Typeclass for a type `F` with an injective map to `A → B` This typeclass is primarily for use by homomorphisms like `MonoidHom` and `LinearMap`. There is the "D"ependent version `DFunLike` and the non-dependent version `FunLike`. ## Basic usage of `DFunLike` and `FunLike` A typical type of morphisms should be declared as: ``` structure MyHom (A B : Type*) [MyClass A] [MyClass B] where (toFun : A → B) (map_op' : ∀ (x y : A), toFun (MyClass.op x y) = MyClass.op (toFun x) (toFun y)) namespace MyHom variable (A B : Type*) [MyClass A] [MyClass B] instance : FunLike (MyHom A B) A B where coe := MyHom.toFun coe_injective' := fun f g h => by cases f; cases g; congr @[ext] theorem ext {f g : MyHom A B} (h : ∀ x, f x = g x) : f = g := DFunLike.ext f g h /-- Copy of a `MyHom` with a new `toFun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : MyHom A B) (f' : A → B) (h : f' = ⇑f) : MyHom A B where toFun := f' map_op' := h.symm ▸ f.map_op' end MyHom ``` This file will then provide a `CoeFun` instance and various extensionality and simp lemmas. ## Morphism classes extending `DFunLike` and `FunLike` The `FunLike` design provides further benefits if you put in a bit more work. The first step is to extend `FunLike` to create a class of those types satisfying the axioms of your new type of morphisms. Continuing the example above: ``` /-- `MyHomClass F A B` states that `F` is a type of `MyClass.op`-preserving morphisms. You should extend this class when you extend `MyHom`. -/ class MyHomClass (F : Type*) (A B : outParam Type*) [MyClass A] [MyClass B] [FunLike F A B] : Prop := (map_op : ∀ (f : F) (x y : A), f (MyClass.op x y) = MyClass.op (f x) (f y)) @[simp] lemma map_op {F A B : Type*} [MyClass A] [MyClass B] [FunLike F A B] [MyHomClass F A B] (f : F) (x y : A) : f (MyClass.op x y) = MyClass.op (f x) (f y) := MyHomClass.map_op _ _ _ -- You can add the below instance next to `MyHomClass.instFunLike`: instance : MyHomClass (MyHom A B) A B where map_op := MyHom.map_op' -- [Insert `ext` and `copy` here] ``` Note that `A B` are marked as `outParam` even though they are not purely required to be so due to the `FunLike` parameter already filling them in. This is required to see through type synonyms, which is important in the category theory library. Also, it appears having them as `outParam` is slightly faster. The second step is to add instances of your new `MyHomClass` for all types extending `MyHom`. Typically, you can just declare a new class analogous to `MyHomClass`: ``` structure CoolerHom (A B : Type*) [CoolClass A] [CoolClass B] extends MyHom A B where (map_cool' : toFun CoolClass.cool = CoolClass.cool) class CoolerHomClass (F : Type*) (A B : outParam Type*) [CoolClass A] [CoolClass B] [FunLike F A B] extends MyHomClass F A B := (map_cool : ∀ (f : F), f CoolClass.cool = CoolClass.cool) @[simp] lemma map_cool {F A B : Type*} [CoolClass A] [CoolClass B] [FunLike F A B] [CoolerHomClass F A B] (f : F) : f CoolClass.cool = CoolClass.cool := CoolerHomClass.map_cool _ variable {A B : Type*} [CoolClass A] [CoolClass B] instance : FunLike (CoolerHom A B) A B where coe f := f.toFun coe_injective' := fun f g h ↦ by cases f; cases g; congr; apply DFunLike.coe_injective; congr instance : CoolerHomClass (CoolerHom A B) A B where map_op f := f.map_op' map_cool f := f.map_cool' -- [Insert `ext` and `copy` here] ``` Then any declaration taking a specific type of morphisms as parameter can instead take the class you just defined: ``` -- Compare with: lemma do_something (f : MyHom A B) : sorry := sorry lemma do_something {F : Type*} [FunLike F A B] [MyHomClass F A B] (f : F) : sorry := sorry ``` This means anything set up for `MyHom`s will automatically work for `CoolerHomClass`es, and defining `CoolerHomClass` only takes a constant amount of effort, instead of linearly increasing the work per `MyHom`-related declaration. ## Design rationale The current form of FunLike was set up in pull request https://github.com/leanprover-community/mathlib4/pull/8386: https://github.com/leanprover-community/mathlib4/pull/8386 We made `FunLike` *unbundled*: child classes don't extend `FunLike`, they take a `[FunLike F A B]` parameter instead. This suits the instance synthesis algorithm better: it's easy to verify a type does **not** have a `FunLike` instance by checking the discrimination tree once instead of searching the entire `extends` hierarchy. -/ /-- The class `DFunLike F α β` expresses that terms of type `F` have an injective coercion to (dependent) functions from `α` to `β`. For non-dependent functions you can also use the abbreviation `FunLike`. This typeclass is used in the definition of the homomorphism typeclasses, such as `ZeroHomClass`, `MulHomClass`, `MonoidHomClass`, .... -/ @[notation_class* toFun Simps.findCoercionArgs] class DFunLike (F : Sort*) (α : outParam (Sort*)) (β : outParam <| α → Sort*) where /-- The coercion from `F` to a function. -/ coe : F → ∀ a : α, β a /-- The coercion to functions must be injective. -/ coe_injective' : Function.Injective coe /-- The class `FunLike F α β` (`Fun`ction-`Like`) expresses that terms of type `F` have an injective coercion to functions from `α` to `β`. `FunLike` is the non-dependent version of `DFunLike`. This typeclass is used in the definition of the homomorphism typeclasses, such as `ZeroHomClass`, `MulHomClass`, `MonoidHomClass`, .... -/ abbrev FunLike F α β := DFunLike F α fun _ => β section Dependent /-! ### `DFunLike F α β` where `β` depends on `a : α` -/ variable (F α : Sort*) (β : α → Sort*) namespace DFunLike variable {F α β} [i : DFunLike F α β] instance (priority := 100) hasCoeToFun : CoeFun F (fun _ ↦ ∀ a : α, β a) where coe := @DFunLike.coe _ _ β _ -- need to make explicit to beta reduce for non-dependent functions run_cmd Lean.Elab.Command.liftTermElabM do Lean.Meta.registerCoercion ``DFunLike.coe (some { numArgs := 5, coercee := 4, type := .coeFun }) theorem coe_eq_coe_fn : (DFunLike.coe (F := F)) = (fun f => ↑f) := rfl theorem coe_injective : Function.Injective (fun f : F ↦ (f : ∀ a : α, β a)) := DFunLike.coe_injective' @[simp] theorem coe_fn_eq {f g : F} : (f : ∀ a : α, β a) = (g : ∀ a : α, β a) ↔ f = g := ⟨fun h ↦ DFunLike.coe_injective' h, fun h ↦ by cases h; rfl⟩ theorem ext' {f g : F} (h : (f : ∀ a : α, β a) = (g : ∀ a : α, β a)) : f = g := DFunLike.coe_injective' h theorem ext'_iff {f g : F} : f = g ↔ (f : ∀ a : α, β a) = (g : ∀ a : α, β a) := coe_fn_eq.symm theorem ext (f g : F) (h : ∀ x : α, f x = g x) : f = g := DFunLike.coe_injective' (funext h) theorem ext_iff {f g : F} : f = g ↔ ∀ x, f x = g x := coe_fn_eq.symm.trans funext_iff protected theorem congr_fun {f g : F} (h₁ : f = g) (x : α) : f x = g x := congr_fun (congr_arg _ h₁) x theorem ne_iff {f g : F} : f ≠ g ↔ ∃ a, f a ≠ g a := ext_iff.not.trans not_forall theorem exists_ne {f g : F} (h : f ≠ g) : ∃ x, f x ≠ g x := ne_iff.mp h /-- This is not an instance to avoid slowing down every single `Subsingleton` typeclass search. -/ lemma subsingleton_cod [∀ a, Subsingleton (β a)] : Subsingleton F := coe_injective.subsingleton include β in /-- This is not an instance to avoid slowing down every single `Subsingleton` typeclass search. -/ lemma subsingleton_dom [IsEmpty α] : Subsingleton F := coe_injective.subsingleton end DFunLike end Dependent section NonDependent /-! ### `FunLike F α β` where `β` does not depend on `a : α` -/ variable {F α β : Sort*} [i : FunLike F α β] namespace DFunLike protected theorem congr {f g : F} {x y : α} (h₁ : f = g) (h₂ : x = y) : f x = g y := congr (congr_arg _ h₁) h₂ protected theorem congr_arg (f : F) {x y : α} (h₂ : x = y) : f x = f y := congr_arg _ h₂ theorem dite_apply {P : Prop} [Decidable P] (f : P → F) (g : ¬P → F) (x : α) : (if h : P then f h else g h) x = if h : P then f h x else g h x := by split_ifs <;> rfl theorem ite_apply {P : Prop} [Decidable P] (f g : F) (x : α) : (if P then f else g) x = if P then f x else g x := dite_apply _ _ _ end DFunLike end NonDependent
.lake/packages/mathlib/Mathlib/Data/FunLike/Embedding.lean
import Mathlib.Data.FunLike.Basic /-! # Typeclass for a type `F` with an injective map to `A ↪ B` This typeclass is primarily for use by embeddings such as `RelEmbedding`. ## Basic usage of `EmbeddingLike` A typical type of embeddings should be declared as: ``` structure MyEmbedding (A B : Type*) [MyClass A] [MyClass B] where (toFun : A → B) (injective' : Function.Injective toFun) (map_op' : ∀ (x y : A), toFun (MyClass.op x y) = MyClass.op (toFun x) (toFun y)) namespace MyEmbedding variable (A B : Type*) [MyClass A] [MyClass B] instance : FunLike (MyEmbedding A B) A B where coe := MyEmbedding.toFun coe_injective' := fun f g h ↦ by cases f; cases g; congr -- This instance is optional if you follow the "Embedding class" design below: instance : EmbeddingLike (MyEmbedding A B) A B where injective' := MyEmbedding.injective' @[ext] theorem ext {f g : MyEmbedding A B} (h : ∀ x, f x = g x) : f = g := DFunLike.ext f g h /-- Copy of a `MyEmbedding` with a new `toFun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : MyEmbedding A B) (f' : A → B) (h : f' = ⇑f) : MyEmbedding A B := { toFun := f' injective' := h.symm ▸ f.injective' map_op' := h.symm ▸ f.map_op' } end MyEmbedding ``` This file will then provide a `CoeFun` instance and various extensionality and simp lemmas. ## Embedding classes extending `EmbeddingLike` The `EmbeddingLike` design provides further benefits if you put in a bit more work. The first step is to extend `EmbeddingLike` to create a class of those types satisfying the axioms of your new type of morphisms. Continuing the example above: ``` /-- `MyEmbeddingClass F A B` states that `F` is a type of `MyClass.op`-preserving embeddings. You should extend this class when you extend `MyEmbedding`. -/ class MyEmbeddingClass (F : Type*) (A B : outParam Type*) [MyClass A] [MyClass B] [FunLike F A B] extends EmbeddingLike F A B where map_op : ∀ (f : F) (x y : A), f (MyClass.op x y) = MyClass.op (f x) (f y) @[simp] lemma map_op {F A B : Type*} [MyClass A] [MyClass B] [FunLike F A B] [MyEmbeddingClass F A B] (f : F) (x y : A) : f (MyClass.op x y) = MyClass.op (f x) (f y) := MyEmbeddingClass.map_op _ _ _ namespace MyEmbedding variable {A B : Type*} [MyClass A] [MyClass B] -- You can replace `MyEmbedding.EmbeddingLike` with the below instance: instance : MyEmbeddingClass (MyEmbedding A B) A B where injective' := MyEmbedding.injective' map_op := MyEmbedding.map_op' end MyEmbedding ``` The second step is to add instances of your new `MyEmbeddingClass` for all types extending `MyEmbedding`. Typically, you can just declare a new class analogous to `MyEmbeddingClass`: ``` structure CoolerEmbedding (A B : Type*) [CoolClass A] [CoolClass B] extends MyEmbedding A B where (map_cool' : toFun CoolClass.cool = CoolClass.cool) class CoolerEmbeddingClass (F : Type*) (A B : outParam Type*) [CoolClass A] [CoolClass B] [FunLike F A B] extends MyEmbeddingClass F A B where (map_cool : ∀ (f : F), f CoolClass.cool = CoolClass.cool) @[simp] lemma map_cool {F A B : Type*} [CoolClass A] [CoolClass B] [FunLike F A B] [CoolerEmbeddingClass F A B] (f : F) : f CoolClass.cool = CoolClass.cool := CoolerEmbeddingClass.map_cool _ variable {A B : Type*} [CoolClass A] [CoolClass B] instance : FunLike (CoolerEmbedding A B) A B where coe f := f.toFun coe_injective' f g h := by cases f; cases g; congr; apply DFunLike.coe_injective; congr instance : CoolerEmbeddingClass (CoolerEmbedding A B) A B where injective' f := f.injective' map_op f := f.map_op' map_cool f := f.map_cool' -- [Insert `ext` and `copy` here] ``` Then any declaration taking a specific type of morphisms as parameter can instead take the class you just defined: ``` -- Compare with: lemma do_something (f : MyEmbedding A B) : sorry := sorry lemma do_something {F : Type*} [FunLike F A B] [MyEmbeddingClass F A B] (f : F) : sorry := sorry ``` This means anything set up for `MyEmbedding`s will automatically work for `CoolerEmbeddingClass`es, and defining `CoolerEmbeddingClass` only takes a constant amount of effort, instead of linearly increasing the work per `MyEmbedding`-related declaration. -/ /-- The class `EmbeddingLike F α β` expresses that terms of type `F` have an injective coercion to injective functions `α ↪ β`. -/ class EmbeddingLike (F : Sort*) (α β : outParam (Sort*)) [FunLike F α β] : Prop where /-- The coercion to functions must produce injective functions. -/ injective' : ∀ f : F, Function.Injective (DFunLike.coe f) namespace EmbeddingLike variable {F α β γ : Sort*} [FunLike F α β] [i : EmbeddingLike F α β] protected theorem injective (f : F) : Function.Injective f := injective' f @[simp] theorem apply_eq_iff_eq (f : F) {x y : α} : f x = f y ↔ x = y := (EmbeddingLike.injective f).eq_iff @[simp] theorem comp_injective {F : Sort*} [FunLike F β γ] [EmbeddingLike F β γ] (f : α → β) (e : F) : Function.Injective (e ∘ f) ↔ Function.Injective f := (EmbeddingLike.injective e).of_comp_iff f end EmbeddingLike
.lake/packages/mathlib/Mathlib/Data/FunLike/Equiv.lean
import Mathlib.Data.FunLike.Embedding /-! # Typeclass for a type `F` with an injective map to `A ≃ B` This typeclass is primarily for use by isomorphisms like `MonoidEquiv` and `LinearEquiv`. ## Basic usage of `EquivLike` A typical type of isomorphisms should be declared as: ``` structure MyIso (A B : Type*) [MyClass A] [MyClass B] extends Equiv A B where (map_op' : ∀ (x y : A), toFun (MyClass.op x y) = MyClass.op (toFun x) (toFun y)) namespace MyIso variable (A B : Type*) [MyClass A] [MyClass B] instance instEquivLike : EquivLike (MyIso A B) A B where coe f := f.toFun inv f := f.invFun left_inv f := f.left_inv right_inv f := f.right_inv coe_injective' f g h₁ h₂ := by cases f; cases g; congr; exact EquivLike.coe_injective' _ _ h₁ h₂ @[ext] theorem ext {f g : MyIso A B} (h : ∀ x, f x = g x) : f = g := DFunLike.ext f g h /-- Copy of a `MyIso` with a new `toFun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : MyIso A B) (f' : A → B) (f_inv : B → A) (h₁ : f' = f) (h₂ : f_inv = f.invFun) : MyIso A B where toFun := f' invFun := f_inv left_inv := h₁.symm ▸ h₂.symm ▸ f.left_inv right_inv := h₁.symm ▸ h₂.symm ▸ f.right_inv map_op' := h₁.symm ▸ f.map_op' end MyIso ``` This file will then provide a `CoeFun` instance and various extensionality and simp lemmas. ## Isomorphism classes extending `EquivLike` The `EquivLike` design provides further benefits if you put in a bit more work. The first step is to extend `EquivLike` to create a class of those types satisfying the axioms of your new type of isomorphisms. Continuing the example above: ``` /-- `MyIsoClass F A B` states that `F` is a type of `MyClass.op`-preserving morphisms. You should extend this class when you extend `MyIso`. -/ class MyIsoClass (F : Type*) (A B : outParam Type*) [MyClass A] [MyClass B] [EquivLike F A B] extends MyHomClass F A B namespace MyIso variable {A B : Type*} [MyClass A] [MyClass B] -- This goes after `MyIsoClass.instEquivLike`: instance : MyIsoClass (MyIso A B) A B where map_op := MyIso.map_op' -- [Insert `ext` and `copy` here] end MyIso ``` The second step is to add instances of your new `MyIsoClass` for all types extending `MyIso`. Typically, you can just declare a new class analogous to `MyIsoClass`: ``` structure CoolerIso (A B : Type*) [CoolClass A] [CoolClass B] extends MyIso A B where (map_cool' : toFun CoolClass.cool = CoolClass.cool) class CoolerIsoClass (F : Type*) (A B : outParam Type*) [CoolClass A] [CoolClass B] [EquivLike F A B] extends MyIsoClass F A B where (map_cool : ∀ (f : F), f CoolClass.cool = CoolClass.cool) @[simp] lemma map_cool {F A B : Type*} [CoolClass A] [CoolClass B] [EquivLike F A B] [CoolerIsoClass F A B] (f : F) : f CoolClass.cool = CoolClass.cool := CoolerIsoClass.map_cool _ namespace CoolerIso variable {A B : Type*} [CoolClass A] [CoolClass B] instance : EquivLike (CoolerIso A B) A B where coe f := f.toFun inv f := f.invFun left_inv f := f.left_inv right_inv f := f.right_inv coe_injective' f g h₁ h₂ := by cases f; cases g; congr; exact EquivLike.coe_injective' _ _ h₁ h₂ instance : CoolerIsoClass (CoolerIso A B) A B where map_op f := f.map_op' map_cool f := f.map_cool' -- [Insert `ext` and `copy` here] end CoolerIso ``` Then any declaration taking a specific type of morphisms as parameter can instead take the class you just defined: ``` -- Compare with: lemma do_something (f : MyIso A B) : sorry := sorry lemma do_something {F : Type*} [EquivLike F A B] [MyIsoClass F A B] (f : F) : sorry := sorry ``` This means anything set up for `MyIso`s will automatically work for `CoolerIsoClass`es, and defining `CoolerIsoClass` only takes a constant amount of effort, instead of linearly increasing the work per `MyIso`-related declaration. -/ /-- The class `EquivLike E α β` expresses that terms of type `E` have an injective coercion to bijections between `α` and `β`. Note that this does not directly extend `FunLike`, nor take `FunLike` as a parameter, so we can state `coe_injective'` in a nicer way. This typeclass is used in the definition of the isomorphism (or equivalence) typeclasses, such as `ZeroEquivClass`, `MulEquivClass`, `MonoidEquivClass`, .... -/ class EquivLike (E : Sort*) (α β : outParam (Sort*)) where /-- The coercion to a function in the forward direction. -/ coe : E → α → β /-- The coercion to a function in the backwards direction. -/ inv : E → β → α /-- The coercions are left inverses. -/ left_inv : ∀ e, Function.LeftInverse (inv e) (coe e) /-- The coercions are right inverses. -/ right_inv : ∀ e, Function.RightInverse (inv e) (coe e) /-- The two coercions to functions are jointly injective. -/ coe_injective' : ∀ e g, coe e = coe g → inv e = inv g → e = g -- This is mathematically equivalent to either of the coercions to functions being injective, but -- the `inv` hypothesis makes this easier to prove with `congr'` namespace EquivLike variable {E F α β γ : Sort*} [EquivLike E α β] [EquivLike F β γ] theorem inv_injective : Function.Injective (EquivLike.inv : E → β → α) := fun e g h ↦ coe_injective' e g ((right_inv e).eq_rightInverse (h.symm ▸ left_inv g)) h instance (priority := 100) toFunLike : FunLike E α β where coe := (coe : E → α → β) coe_injective' e g h := coe_injective' e g h ((left_inv e).eq_rightInverse (h.symm ▸ right_inv g)) @[simp] theorem coe_apply {e : E} {a : α} : coe e a = e a := rfl theorem inv_apply_eq {e : E} {b : β} {a : α} : inv e b = a ↔ b = e a := by constructor <;> rintro ⟨_, rfl⟩ exacts [(right_inv e b).symm, left_inv e a] instance (priority := 100) toEmbeddingLike : EmbeddingLike E α β where injective' e := (left_inv e).injective protected theorem injective (e : E) : Function.Injective e := EmbeddingLike.injective e protected theorem surjective (e : E) : Function.Surjective e := (right_inv e).surjective protected theorem bijective (e : E) : Function.Bijective (e : α → β) := ⟨EquivLike.injective e, EquivLike.surjective e⟩ theorem apply_eq_iff_eq (f : E) {x y : α} : f x = f y ↔ x = y := EmbeddingLike.apply_eq_iff_eq f @[simp] theorem injective_comp (e : E) (f : β → γ) : Function.Injective (f ∘ e) ↔ Function.Injective f := Function.Injective.of_comp_iff' f (EquivLike.bijective e) @[simp] theorem surjective_comp (e : E) (f : β → γ) : Function.Surjective (f ∘ e) ↔ Function.Surjective f := (EquivLike.surjective e).of_comp_iff f @[simp] theorem bijective_comp (e : E) (f : β → γ) : Function.Bijective (f ∘ e) ↔ Function.Bijective f := (EquivLike.bijective e).of_comp_iff f /-- This lemma is only supposed to be used in the generic context, when working with instances of classes extending `EquivLike`. For concrete isomorphism types such as `Equiv`, you should use `Equiv.symm_apply_apply` or its equivalent. TODO: define a generic form of `Equiv.symm`. -/ @[simp] theorem inv_apply_apply (e : E) (a : α) : inv e (e a) = a := left_inv _ _ /-- This lemma is only supposed to be used in the generic context, when working with instances of classes extending `EquivLike`. For concrete isomorphism types such as `Equiv`, you should use `Equiv.apply_symm_apply` or its equivalent. TODO: define a generic form of `Equiv.symm`. -/ @[simp] theorem apply_inv_apply (e : E) (b : β) : e (inv e b) = b := right_inv _ _ @[deprecated inv_apply_eq (since := "2025-06-20")] lemma inv_apply_eq_iff_eq_apply {e : E} {b : β} {a : α} : inv e b = a ↔ b = e a := inv_apply_eq theorem comp_injective (f : α → β) (e : F) : Function.Injective (e ∘ f) ↔ Function.Injective f := EmbeddingLike.comp_injective f e @[simp] theorem comp_surjective (f : α → β) (e : F) : Function.Surjective (e ∘ f) ↔ Function.Surjective f := Function.Surjective.of_comp_iff' (EquivLike.bijective e) f @[simp] theorem comp_bijective (f : α → β) (e : F) : Function.Bijective (e ∘ f) ↔ Function.Bijective f := (EquivLike.bijective e).of_comp_iff' f include β in /-- This is not an instance to avoid slowing down every single `Subsingleton` typeclass search. -/ lemma subsingleton_dom [Subsingleton α] : Subsingleton E := ⟨fun f g ↦ DFunLike.ext f g fun _ ↦ (right_inv f).injective <| Subsingleton.elim _ _⟩ end EquivLike
.lake/packages/mathlib/Mathlib/Data/Sigma/Interval.lean
import Mathlib.Data.Sigma.Order import Mathlib.Order.Interval.Finset.Defs /-! # Finite intervals in a sigma type This file provides the `LocallyFiniteOrder` instance for the disjoint sum of orders `Σ i, α i` and calculates the cardinality of its finite intervals. ## TODO Do the same for the lexicographical order -/ open Finset Function namespace Sigma variable {ι : Type*} {α : ι → Type*} /-! ### Disjoint sum of orders -/ section Disjoint section LocallyFiniteOrder variable [DecidableEq ι] [∀ i, Preorder (α i)] [∀ i, LocallyFiniteOrder (α i)] instance instLocallyFiniteOrder : LocallyFiniteOrder (Σ i, α i) where finsetIcc := sigmaLift fun _ => Icc finsetIco := sigmaLift fun _ => Ico finsetIoc := sigmaLift fun _ => Ioc finsetIoo := sigmaLift fun _ => Ioo finset_mem_Icc := fun ⟨i, a⟩ ⟨j, b⟩ ⟨k, c⟩ => by simp_rw [mem_sigmaLift, le_def, mem_Icc, exists_and_left, ← exists_and_right, ← exists_prop] exact exists₂_congr fun _ _ => by constructor <;> rintro ⟨⟨⟩, ht⟩ <;> exact ⟨rfl, ht⟩ finset_mem_Ico := fun ⟨i, a⟩ ⟨j, b⟩ ⟨k, c⟩ => by simp_rw [mem_sigmaLift, le_def, lt_def, mem_Ico, exists_and_left, ← exists_and_right, ← exists_prop] exact exists₂_congr fun _ _ => by constructor <;> rintro ⟨⟨⟩, ht⟩ <;> exact ⟨rfl, ht⟩ finset_mem_Ioc := fun ⟨i, a⟩ ⟨j, b⟩ ⟨k, c⟩ => by simp_rw [mem_sigmaLift, le_def, lt_def, mem_Ioc, exists_and_left, ← exists_and_right, ← exists_prop] exact exists₂_congr fun _ _ => by constructor <;> rintro ⟨⟨⟩, ht⟩ <;> exact ⟨rfl, ht⟩ finset_mem_Ioo := fun ⟨i, a⟩ ⟨j, b⟩ ⟨k, c⟩ => by simp_rw [mem_sigmaLift, lt_def, mem_Ioo, exists_and_left, ← exists_and_right, ← exists_prop] exact exists₂_congr fun _ _ => by constructor <;> rintro ⟨⟨⟩, ht⟩ <;> exact ⟨rfl, ht⟩ section variable (a b : Σ i, α i) theorem card_Icc : #(Icc a b) = if h : a.1 = b.1 then #(Icc (h.rec a.2) b.2) else 0 := card_sigmaLift (fun _ => Icc) _ _ theorem card_Ico : #(Ico a b) = if h : a.1 = b.1 then #(Ico (h.rec a.2) b.2) else 0 := card_sigmaLift (fun _ => Ico) _ _ theorem card_Ioc : #(Ioc a b) = if h : a.1 = b.1 then #(Ioc (h.rec a.2) b.2) else 0 := card_sigmaLift (fun _ => Ioc) _ _ theorem card_Ioo : #(Ioo a b) = if h : a.1 = b.1 then #(Ioo (h.rec a.2) b.2) else 0 := card_sigmaLift (fun _ => Ioo) _ _ end variable (i : ι) (a b : α i) @[simp] theorem Icc_mk_mk : Icc (⟨i, a⟩ : Sigma α) ⟨i, b⟩ = (Icc a b).map (Embedding.sigmaMk i) := dif_pos rfl @[simp] theorem Ico_mk_mk : Ico (⟨i, a⟩ : Sigma α) ⟨i, b⟩ = (Ico a b).map (Embedding.sigmaMk i) := dif_pos rfl @[simp] theorem Ioc_mk_mk : Ioc (⟨i, a⟩ : Sigma α) ⟨i, b⟩ = (Ioc a b).map (Embedding.sigmaMk i) := dif_pos rfl @[simp] theorem Ioo_mk_mk : Ioo (⟨i, a⟩ : Sigma α) ⟨i, b⟩ = (Ioo a b).map (Embedding.sigmaMk i) := dif_pos rfl end LocallyFiniteOrder section LocallyFiniteOrderBot variable [∀ i, Preorder (α i)] [∀ i, LocallyFiniteOrderBot (α i)] instance instLocallyFiniteOrderBot : LocallyFiniteOrderBot (Σ i, α i) where finsetIic | ⟨i, a⟩ => (Iic a).map (Embedding.sigmaMk i) finsetIio | ⟨i, a⟩ => (Iio a).map (Embedding.sigmaMk i) finset_mem_Iic := fun ⟨i, a⟩ ⟨j, b⟩ => by obtain rfl | hij := eq_or_ne i j · simp · simp [hij, le_def, hij.symm] finset_mem_Iio := fun ⟨i, a⟩ ⟨j, b⟩ => by obtain rfl | hij := eq_or_ne i j · simp · simp [hij, lt_def, hij.symm] variable (i : ι) (a : α i) @[simp] theorem Iic_mk : Iic (⟨i, a⟩ : Sigma α) = (Iic a).map (Embedding.sigmaMk i) := rfl @[simp] theorem Iio_mk : Iio (⟨i, a⟩ : Sigma α) = (Iio a).map (Embedding.sigmaMk i) := rfl end LocallyFiniteOrderBot section LocallyFiniteOrderTop variable [∀ i, Preorder (α i)] [∀ i, LocallyFiniteOrderTop (α i)] instance instLocallyFiniteOrderTop : LocallyFiniteOrderTop (Σ i, α i) where finsetIci | ⟨i, a⟩ => (Ici a).map (Embedding.sigmaMk i) finsetIoi | ⟨i, a⟩ => (Ioi a).map (Embedding.sigmaMk i) finset_mem_Ici := fun ⟨i, a⟩ ⟨j, b⟩ => by obtain rfl | hij := eq_or_ne i j · simp · simp [hij, le_def] finset_mem_Ioi := fun ⟨i, a⟩ ⟨j, b⟩ => by obtain rfl | hij := eq_or_ne i j · simp · simp [hij, lt_def] variable (i : ι) (a : α i) @[simp] theorem Ici_mk : Ici (⟨i, a⟩ : Sigma α) = (Ici a).map (Embedding.sigmaMk i) := rfl @[simp] theorem Ioi_mk : Ioi (⟨i, a⟩ : Sigma α) = (Ioi a).map (Embedding.sigmaMk i) := rfl end LocallyFiniteOrderTop end Disjoint end Sigma
.lake/packages/mathlib/Mathlib/Data/Sigma/Lex.lean
import Mathlib.Logic.Function.Defs import Mathlib.Order.Defs.Unbundled import Batteries.Logic /-! # Lexicographic order on a sigma type This defines the lexicographical order of two arbitrary relations on a sigma type and proves some lemmas about `PSigma.Lex`, which is defined in core Lean. Given a relation in the index type and a relation on each summand, the lexicographical order on the sigma type relates `a` and `b` if their summands are related or they are in the same summand and related by the summand's relation. ## See also Related files are: * `Combinatorics.CoLex`: Colexicographic order on finite sets. * `Data.List.Lex`: Lexicographic order on lists. * `Data.Sigma.Order`: Lexicographic order on `Σ i, α i` per say. * `Data.PSigma.Order`: Lexicographic order on `Σ' i, α i`. * `Data.Prod.Lex`: Lexicographic order on `α × β`. Can be thought of as the special case of `Sigma.Lex` where all summands are the same -/ namespace Sigma variable {ι : Type*} {α : ι → Type*} {r r₁ r₂ : ι → ι → Prop} {s s₁ s₂ : ∀ i, α i → α i → Prop} {a b : Σ i, α i} /-- The lexicographical order on a sigma type. It takes in a relation on the index type and a relation for each summand. `a` is related to `b` iff their summands are related or they are in the same summand and are related through the summand's relation. -/ inductive Lex (r : ι → ι → Prop) (s : ∀ i, α i → α i → Prop) : ∀ _ _ : Σ i, α i, Prop | left {i j : ι} (a : α i) (b : α j) : r i j → Lex r s ⟨i, a⟩ ⟨j, b⟩ | right {i : ι} (a b : α i) : s i a b → Lex r s ⟨i, a⟩ ⟨i, b⟩ theorem lex_iff : Lex r s a b ↔ r a.1 b.1 ∨ ∃ h : a.1 = b.1, s b.1 (h.rec a.2) b.2 := by constructor · rintro (⟨a, b, hij⟩ | ⟨a, b, hab⟩) · exact Or.inl hij · exact Or.inr ⟨rfl, hab⟩ · obtain ⟨i, a⟩ := a obtain ⟨j, b⟩ := b dsimp only rintro (h | ⟨rfl, h⟩) · exact Lex.left _ _ h · exact Lex.right _ _ h instance Lex.decidable (r : ι → ι → Prop) (s : ∀ i, α i → α i → Prop) [DecidableEq ι] [DecidableRel r] [∀ i, DecidableRel (s i)] : DecidableRel (Lex r s) := fun _ _ => decidable_of_decidable_of_iff lex_iff.symm theorem Lex.mono (hr : ∀ a b, r₁ a b → r₂ a b) (hs : ∀ i a b, s₁ i a b → s₂ i a b) {a b : Σ i, α i} (h : Lex r₁ s₁ a b) : Lex r₂ s₂ a b := by obtain ⟨a, b, hij⟩ | ⟨a, b, hab⟩ := h · exact Lex.left _ _ (hr _ _ hij) · exact Lex.right _ _ (hs _ _ _ hab) theorem Lex.mono_left (hr : ∀ a b, r₁ a b → r₂ a b) {a b : Σ i, α i} (h : Lex r₁ s a b) : Lex r₂ s a b := h.mono hr fun _ _ _ => id theorem Lex.mono_right (hs : ∀ i a b, s₁ i a b → s₂ i a b) {a b : Σ i, α i} (h : Lex r s₁ a b) : Lex r s₂ a b := h.mono (fun _ _ => id) hs theorem lex_swap : Lex (Function.swap r) s a b ↔ Lex r (fun i => Function.swap (s i)) b a := by constructor <;> · rintro (⟨a, b, h⟩ | ⟨a, b, h⟩) · exact Lex.left _ _ h · exact Lex.right _ _ h instance [∀ i, IsRefl (α i) (s i)] : IsRefl _ (Lex r s) := ⟨fun ⟨_, _⟩ => Lex.right _ _ <| refl _⟩ instance [IsIrrefl ι r] [∀ i, IsIrrefl (α i) (s i)] : IsIrrefl _ (Lex r s) := ⟨by rintro _ (⟨a, b, hi⟩ | ⟨a, b, ha⟩) · exact irrefl _ hi · exact irrefl _ ha ⟩ instance [IsTrans ι r] [∀ i, IsTrans (α i) (s i)] : IsTrans _ (Lex r s) := ⟨by rintro _ _ _ (⟨a, b, hij⟩ | ⟨a, b, hab⟩) (⟨_, c, hk⟩ | ⟨_, c, hc⟩) · exact Lex.left _ _ (_root_.trans hij hk) · exact Lex.left _ _ hij · exact Lex.left _ _ hk · exact Lex.right _ _ (_root_.trans hab hc)⟩ instance [IsSymm ι r] [∀ i, IsSymm (α i) (s i)] : IsSymm _ (Lex r s) := ⟨by rintro _ _ (⟨a, b, hij⟩ | ⟨a, b, hab⟩) · exact Lex.left _ _ (symm hij) · exact Lex.right _ _ (symm hab) ⟩ attribute [local instance] IsAsymm.isIrrefl instance [IsAsymm ι r] [∀ i, IsAntisymm (α i) (s i)] : IsAntisymm _ (Lex r s) := ⟨by rintro _ _ (⟨a, b, hij⟩ | ⟨a, b, hab⟩) (⟨_, _, hji⟩ | ⟨_, _, hba⟩) · exact (asymm hij hji).elim · exact (irrefl _ hij).elim · exact (irrefl _ hji).elim · exact congr_arg (Sigma.mk _ ·) <| antisymm hab hba⟩ instance [IsTrichotomous ι r] [∀ i, IsTotal (α i) (s i)] : IsTotal _ (Lex r s) := ⟨by rintro ⟨i, a⟩ ⟨j, b⟩ obtain hij | rfl | hji := trichotomous_of r i j · exact Or.inl (Lex.left _ _ hij) · obtain hab | hba := total_of (s i) a b · exact Or.inl (Lex.right _ _ hab) · exact Or.inr (Lex.right _ _ hba) · exact Or.inr (Lex.left _ _ hji)⟩ instance [IsTrichotomous ι r] [∀ i, IsTrichotomous (α i) (s i)] : IsTrichotomous _ (Lex r s) := ⟨by rintro ⟨i, a⟩ ⟨j, b⟩ obtain hij | rfl | hji := trichotomous_of r i j · exact Or.inl (Lex.left _ _ hij) · obtain hab | rfl | hba := trichotomous_of (s i) a b · exact Or.inl (Lex.right _ _ hab) · exact Or.inr (Or.inl rfl) · exact Or.inr (Or.inr <| Lex.right _ _ hba) · exact Or.inr (Or.inr <| Lex.left _ _ hji)⟩ end Sigma /-! ### `PSigma` -/ namespace PSigma variable {ι : Sort*} {α : ι → Sort*} {r : ι → ι → Prop} {s : ∀ i, α i → α i → Prop} theorem lex_iff {a b : Σ' i, α i} : Lex r s a b ↔ r a.1 b.1 ∨ ∃ h : a.1 = b.1, s b.1 (h.rec a.2) b.2 := by constructor · rintro (⟨a, b, hij⟩ | ⟨i, hab⟩) · exact Or.inl hij · exact Or.inr ⟨rfl, hab⟩ · obtain ⟨i, a⟩ := a obtain ⟨j, b⟩ := b dsimp only rintro (h | ⟨rfl, h⟩) · exact Lex.left _ _ h · exact Lex.right _ h instance Lex.decidable (r : ι → ι → Prop) (s : ∀ i, α i → α i → Prop) [DecidableEq ι] [DecidableRel r] [∀ i, DecidableRel (s i)] : DecidableRel (Lex r s) := fun _ _ => decidable_of_decidable_of_iff lex_iff.symm theorem Lex.mono {r₁ r₂ : ι → ι → Prop} {s₁ s₂ : ∀ i, α i → α i → Prop} (hr : ∀ a b, r₁ a b → r₂ a b) (hs : ∀ i a b, s₁ i a b → s₂ i a b) {a b : Σ' i, α i} (h : Lex r₁ s₁ a b) : Lex r₂ s₂ a b := by obtain ⟨a, b, hij⟩ | ⟨i, hab⟩ := h · exact Lex.left _ _ (hr _ _ hij) · exact Lex.right _ (hs _ _ _ hab) theorem Lex.mono_left {r₁ r₂ : ι → ι → Prop} {s : ∀ i, α i → α i → Prop} (hr : ∀ a b, r₁ a b → r₂ a b) {a b : Σ' i, α i} (h : Lex r₁ s a b) : Lex r₂ s a b := h.mono hr fun _ _ _ => id theorem Lex.mono_right {r : ι → ι → Prop} {s₁ s₂ : ∀ i, α i → α i → Prop} (hs : ∀ i a b, s₁ i a b → s₂ i a b) {a b : Σ' i, α i} (h : Lex r s₁ a b) : Lex r s₂ a b := h.mono (fun _ _ => id) hs end PSigma
.lake/packages/mathlib/Mathlib/Data/Sigma/Order.lean
import Mathlib.Data.Sigma.Lex import Mathlib.Util.Notation3 import Mathlib.Data.Sigma.Basic import Mathlib.Order.Lattice import Mathlib.Order.BoundedOrder.Basic /-! # Orders on a sigma type This file defines two orders on a sigma type: * The disjoint sum of orders. `a` is less `b` iff `a` and `b` are in the same summand and `a` is less than `b` there. * The lexicographical order. `a` is less than `b` if its summand is strictly less than the summand of `b` or they are in the same summand and `a` is less than `b` there. We make the disjoint sum of orders the default set of instances. The lexicographic order goes on a type synonym. ## Notation * `_root_.Lex (Sigma α)`: Sigma type equipped with the lexicographic order. Type synonym of `Σ i, α i`. ## See also Related files are: * `Data.Finset.CoLex`: Colexicographic order on finite sets. * `Data.List.Lex`: Lexicographic order on lists. * `Data.Pi.Lex`: Lexicographic order on `Πₗ i, α i`. * `Data.PSigma.Order`: Lexicographic order on `Σₗ' i, α i`. Basically a twin of this file. * `Data.Prod.Lex`: Lexicographic order on `α × β`. ## TODO Upgrade `Equiv.sigma_congr_left`, `Equiv.sigma_congr`, `Equiv.sigma_assoc`, `Equiv.sigma_prod_of_equiv`, `Equiv.sigma_equiv_prod`, ... to order isomorphisms. -/ namespace Sigma variable {ι : Type*} {α : ι → Type*} /-! ### Disjoint sum of orders on `Sigma` -/ /-- Disjoint sum of orders. `⟨i, a⟩ ≤ ⟨j, b⟩` iff `i = j` and `a ≤ b`. -/ protected inductive LE [∀ i, LE (α i)] : ∀ _a _b : Σ i, α i, Prop | fiber (i : ι) (a b : α i) : a ≤ b → Sigma.LE ⟨i, a⟩ ⟨i, b⟩ /-- Disjoint sum of orders. `⟨i, a⟩ < ⟨j, b⟩` iff `i = j` and `a < b`. -/ protected inductive LT [∀ i, LT (α i)] : ∀ _a _b : Σ i, α i, Prop | fiber (i : ι) (a b : α i) : a < b → Sigma.LT ⟨i, a⟩ ⟨i, b⟩ protected instance [∀ i, LE (α i)] : LE (Σ i, α i) where le := Sigma.LE protected instance [∀ i, LT (α i)] : LT (Σ i, α i) where lt := Sigma.LT @[simp] theorem mk_le_mk_iff [∀ i, LE (α i)] {i : ι} {a b : α i} : (⟨i, a⟩ : Sigma α) ≤ ⟨i, b⟩ ↔ a ≤ b := ⟨fun ⟨_, _, _, h⟩ => h, Sigma.LE.fiber _ _ _⟩ @[simp] theorem mk_lt_mk_iff [∀ i, LT (α i)] {i : ι} {a b : α i} : (⟨i, a⟩ : Sigma α) < ⟨i, b⟩ ↔ a < b := ⟨fun ⟨_, _, _, h⟩ => h, Sigma.LT.fiber _ _ _⟩ theorem le_def [∀ i, LE (α i)] {a b : Σ i, α i} : a ≤ b ↔ ∃ h : a.1 = b.1, h.rec a.2 ≤ b.2 := by constructor · rintro ⟨i, a, b, h⟩ exact ⟨rfl, h⟩ · obtain ⟨i, a⟩ := a obtain ⟨j, b⟩ := b rintro ⟨rfl : i = j, h⟩ exact LE.fiber _ _ _ h theorem lt_def [∀ i, LT (α i)] {a b : Σ i, α i} : a < b ↔ ∃ h : a.1 = b.1, h.rec a.2 < b.2 := by constructor · rintro ⟨i, a, b, h⟩ exact ⟨rfl, h⟩ · obtain ⟨i, a⟩ := a obtain ⟨j, b⟩ := b rintro ⟨rfl : i = j, h⟩ exact LT.fiber _ _ _ h protected instance preorder [∀ i, Preorder (α i)] : Preorder (Σ i, α i) := { le_refl := fun ⟨i, a⟩ => Sigma.LE.fiber i a a le_rfl, le_trans := by rintro _ _ _ ⟨i, a, b, hab⟩ ⟨_, _, c, hbc⟩ exact LE.fiber i a c (hab.trans hbc), lt_iff_le_not_ge := fun _ _ => by constructor · rintro ⟨i, a, b, hab⟩ rwa [mk_le_mk_iff, mk_le_mk_iff, ← lt_iff_le_not_ge] · rintro ⟨⟨i, a, b, hab⟩, h⟩ rw [mk_le_mk_iff] at h exact mk_lt_mk_iff.2 (hab.lt_of_not_ge h) } instance [∀ i, PartialOrder (α i)] : PartialOrder (Σ i, α i) := { Sigma.preorder with le_antisymm := by rintro _ _ ⟨i, a, b, hab⟩ ⟨_, _, _, hba⟩ exact congr_arg (Sigma.mk _ ·) <| hab.antisymm hba } instance [∀ i, Preorder (α i)] [∀ i, DenselyOrdered (α i)] : DenselyOrdered (Σ i, α i) where dense := by rintro ⟨i, a⟩ ⟨_, _⟩ ⟨_, _, b, h⟩ obtain ⟨c, ha, hb⟩ := exists_between h exact ⟨⟨i, c⟩, LT.fiber i a c ha, LT.fiber i c b hb⟩ /-! ### Lexicographical order on `Sigma` -/ namespace Lex /-- The notation `Σₗ i, α i` refers to a sigma type equipped with the lexicographic order. -/ notation3 "Σₗ " (...) ", " r:(scoped p => _root_.Lex (Sigma p)) => r /-- The lexicographical `≤` on a sigma type. -/ protected instance LE [LT ι] [∀ i, LE (α i)] : LE (Σₗ i, α i) where le := Lex (· < ·) fun _ => (· ≤ ·) /-- The lexicographical `<` on a sigma type. -/ protected instance LT [LT ι] [∀ i, LT (α i)] : LT (Σₗ i, α i) where lt := Lex (· < ·) fun _ => (· < ·) theorem le_def [LT ι] [∀ i, LE (α i)] {a b : Σₗ i, α i} : a ≤ b ↔ a.1 < b.1 ∨ ∃ h : a.1 = b.1, h.rec a.2 ≤ b.2 := Sigma.lex_iff theorem lt_def [LT ι] [∀ i, LT (α i)] {a b : Σₗ i, α i} : a < b ↔ a.1 < b.1 ∨ ∃ h : a.1 = b.1, h.rec a.2 < b.2 := Sigma.lex_iff /-- The lexicographical preorder on a sigma type. -/ instance preorder [Preorder ι] [∀ i, Preorder (α i)] : Preorder (Σₗ i, α i) := { Sigma.Lex.LE, Sigma.Lex.LT with le_refl := fun ⟨_, a⟩ => Lex.right a a le_rfl, le_trans := fun _ _ _ => trans_of ((Lex (· < ·)) fun _ => (· ≤ ·)), lt_iff_le_not_ge := by refine fun a b => ⟨fun hab => ⟨hab.mono_right fun i a b => le_of_lt, ?_⟩, ?_⟩ · rintro (⟨b, a, hji⟩ | ⟨b, a, hba⟩) <;> obtain ⟨_, _, hij⟩ | ⟨_, _, hab⟩ := hab · exact hij.not_gt hji · exact lt_irrefl _ hji · exact lt_irrefl _ hij · exact hab.not_ge hba · rintro ⟨⟨a, b, hij⟩ | ⟨a, b, hab⟩, hba⟩ · exact Sigma.Lex.left _ _ hij · exact Sigma.Lex.right _ _ (hab.lt_of_not_ge fun h => hba <| Sigma.Lex.right _ _ h) } /-- The lexicographical partial order on a sigma type. -/ instance partialOrder [Preorder ι] [∀ i, PartialOrder (α i)] : PartialOrder (Σₗ i, α i) := { Lex.preorder with le_antisymm := fun _ _ => antisymm_of ((Lex (· < ·)) fun _ => (· ≤ ·)) } /-- The lexicographical linear order on a sigma type. -/ instance linearOrder [LinearOrder ι] [∀ i, LinearOrder (α i)] : LinearOrder (Σₗ i, α i) := { Lex.partialOrder with le_total := total_of ((Lex (· < ·)) fun _ => (· ≤ ·)), toDecidableEq := Sigma.instDecidableEqSigma toDecidableLE := Lex.decidable _ _ toDecidableLT := Lex.decidable _ _ } /-- The lexicographical linear order on a sigma type. -/ instance orderBot [PartialOrder ι] [OrderBot ι] [∀ i, Preorder (α i)] [OrderBot (α ⊥)] : OrderBot (Σₗ i, α i) where bot := ⟨⊥, ⊥⟩ bot_le := fun ⟨a, b⟩ => by obtain rfl | ha := eq_bot_or_bot_lt a · exact Lex.right _ _ bot_le · exact Lex.left _ _ ha /-- The lexicographical linear order on a sigma type. -/ instance orderTop [PartialOrder ι] [OrderTop ι] [∀ i, Preorder (α i)] [OrderTop (α ⊤)] : OrderTop (Σₗ i, α i) where top := ⟨⊤, ⊤⟩ le_top := fun ⟨a, b⟩ => by obtain rfl | ha := eq_top_or_lt_top a · exact Lex.right _ _ le_top · exact Lex.left _ _ ha /-- The lexicographical linear order on a sigma type. -/ instance boundedOrder [PartialOrder ι] [BoundedOrder ι] [∀ i, Preorder (α i)] [OrderBot (α ⊥)] [OrderTop (α ⊤)] : BoundedOrder (Σₗ i, α i) := { Lex.orderBot, Lex.orderTop with } instance denselyOrdered [Preorder ι] [DenselyOrdered ι] [∀ i, Nonempty (α i)] [∀ i, Preorder (α i)] [∀ i, DenselyOrdered (α i)] : DenselyOrdered (Σₗ i, α i) where dense := by rintro ⟨i, a⟩ ⟨j, b⟩ (⟨_, _, h⟩ | ⟨_, b, h⟩) · obtain ⟨k, hi, hj⟩ := exists_between h obtain ⟨c⟩ : Nonempty (α k) := inferInstance exact ⟨⟨k, c⟩, left _ _ hi, left _ _ hj⟩ · obtain ⟨c, ha, hb⟩ := exists_between h exact ⟨⟨i, c⟩, right _ _ ha, right _ _ hb⟩ instance denselyOrdered_of_noMaxOrder [Preorder ι] [∀ i, Preorder (α i)] [∀ i, DenselyOrdered (α i)] [∀ i, NoMaxOrder (α i)] : DenselyOrdered (Σₗ i, α i) where dense := by rintro ⟨i, a⟩ ⟨j, b⟩ (⟨_, _, h⟩ | ⟨_, b, h⟩) · obtain ⟨c, ha⟩ := exists_gt a exact ⟨⟨i, c⟩, right _ _ ha, left _ _ h⟩ · obtain ⟨c, ha, hb⟩ := exists_between h exact ⟨⟨i, c⟩, right _ _ ha, right _ _ hb⟩ instance denselyOrdered_of_noMinOrder [Preorder ι] [∀ i, Preorder (α i)] [∀ i, DenselyOrdered (α i)] [∀ i, NoMinOrder (α i)] : DenselyOrdered (Σₗ i, α i) where dense := by rintro ⟨i, a⟩ ⟨j, b⟩ (⟨_, _, h⟩ | ⟨_, b, h⟩) · obtain ⟨c, hb⟩ := exists_lt b exact ⟨⟨j, c⟩, left _ _ h, right _ _ hb⟩ · obtain ⟨c, ha, hb⟩ := exists_between h exact ⟨⟨i, c⟩, right _ _ ha, right _ _ hb⟩ instance noMaxOrder_of_nonempty [Preorder ι] [∀ i, Preorder (α i)] [NoMaxOrder ι] [∀ i, Nonempty (α i)] : NoMaxOrder (Σₗ i, α i) where exists_gt := by rintro ⟨i, a⟩ obtain ⟨j, h⟩ := exists_gt i obtain ⟨b⟩ : Nonempty (α j) := inferInstance exact ⟨⟨j, b⟩, left _ _ h⟩ instance noMinOrder_of_nonempty [Preorder ι] [∀ i, Preorder (α i)] [NoMinOrder ι] [∀ i, Nonempty (α i)] : NoMinOrder (Σₗ i, α i) where exists_lt := by rintro ⟨i, a⟩ obtain ⟨j, h⟩ := exists_lt i obtain ⟨b⟩ : Nonempty (α j) := inferInstance exact ⟨⟨j, b⟩, left _ _ h⟩ instance noMaxOrder [Preorder ι] [∀ i, Preorder (α i)] [∀ i, NoMaxOrder (α i)] : NoMaxOrder (Σₗ i, α i) where exists_gt := by rintro ⟨i, a⟩ obtain ⟨b, h⟩ := exists_gt a exact ⟨⟨i, b⟩, right _ _ h⟩ instance noMinOrder [Preorder ι] [∀ i, Preorder (α i)] [∀ i, NoMinOrder (α i)] : NoMinOrder (Σₗ i, α i) where exists_lt := by rintro ⟨i, a⟩ obtain ⟨b, h⟩ := exists_lt a exact ⟨⟨i, b⟩, right _ _ h⟩ end Lex end Sigma
.lake/packages/mathlib/Mathlib/Data/Sigma/Basic.lean
import Mathlib.Logic.Function.Defs import Mathlib.Logic.Function.Basic /-! # Sigma types This file proves basic results about sigma types. A sigma type is a dependent pair type. Like `α × β` but where the type of the second component depends on the first component. More precisely, given `β : ι → Type*`, `Sigma β` is made of stuff which is of type `β i` for some `i : ι`, so the sigma type is a disjoint union of types. For example, the sum type `X ⊕ Y` can be emulated using a sigma type, by taking `ι` with exactly two elements (see `Equiv.sumEquivSigmaBool`). `Σ x, A x` is notation for `Sigma A` (note that this is `\Sigma`, not the sum operator `∑`). `Σ x y z ..., A x y z ...` is notation for `Σ x, Σ y, Σ z, ..., A x y z ...`. Here we have `α : Type*`, `β : α → Type*`, `γ : Π a : α, β a → Type*`, ..., `A : Π (a : α) (b : β a) (c : γ a b) ..., Type*` with `x : α` `y : β x`, `z : γ x y`, ... ## Notes The definition of `Sigma` takes values in `Type*`. This effectively forbids `Prop`-valued sigma types. To that effect, we have `PSigma`, which takes value in `Sort*` and carries a more complicated universe signature as a consequence. -/ open Function section Sigma variable {α α₁ α₂ : Type*} {β : α → Type*} {β₁ : α₁ → Type*} {β₂ : α₂ → Type*} namespace Sigma instance instInhabitedSigma [Inhabited α] [Inhabited (β default)] : Inhabited (Sigma β) := ⟨⟨default, default⟩⟩ instance instDecidableEqSigma [h₁ : DecidableEq α] [h₂ : ∀ a, DecidableEq (β a)] : DecidableEq (Sigma β) | ⟨a₁, b₁⟩, ⟨a₂, b₂⟩ => match a₁, b₁, a₂, b₂, h₁ a₁ a₂ with | _, b₁, _, b₂, isTrue (Eq.refl _) => match b₁, b₂, h₂ _ b₁ b₂ with | _, _, isTrue (Eq.refl _) => isTrue rfl | _, _, isFalse n => isFalse fun h ↦ Sigma.noConfusion h fun _ e₂ ↦ n <| eq_of_heq e₂ | _, _, _, _, isFalse n => isFalse fun h ↦ Sigma.noConfusion h fun e₁ _ ↦ n e₁ theorem mk.inj_iff {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂} : Sigma.mk a₁ b₁ = ⟨a₂, b₂⟩ ↔ a₁ = a₂ ∧ b₁ ≍ b₂ := by simp @[simp] theorem eta : ∀ x : Σ a, β a, Sigma.mk x.1 x.2 = x | ⟨_, _⟩ => rfl protected theorem eq {α : Type*} {β : α → Type*} : ∀ {p₁ p₂ : Σ a, β a} (h₁ : p₁.1 = p₂.1), (Eq.recOn h₁ p₁.2 : β p₂.1) = p₂.2 → p₁ = p₂ | ⟨_, _⟩, _, rfl, rfl => rfl /-- A version of `Iff.mp Sigma.ext_iff` for functions from a nonempty type to a sigma type. -/ theorem _root_.Function.eq_of_sigmaMk_comp {γ : Type*} [Nonempty γ] {a b : α} {f : γ → β a} {g : γ → β b} (h : Sigma.mk a ∘ f = Sigma.mk b ∘ g) : a = b ∧ f ≍ g := by rcases ‹Nonempty γ› with ⟨i⟩ obtain rfl : a = b := congr_arg Sigma.fst (congr_fun h i) simpa [funext_iff] using h /-- A specialized ext lemma for equality of sigma types over an indexed subtype. -/ @[ext] theorem subtype_ext {β : Type*} {p : α → β → Prop} : ∀ {x₀ x₁ : Σ a, Subtype (p a)}, x₀.fst = x₁.fst → (x₀.snd : β) = x₁.snd → x₀ = x₁ | ⟨_, _, _⟩, ⟨_, _, _⟩, rfl, rfl => rfl -- This is not a good simp lemma, as its discrimination tree key is just an arrow. theorem «forall» {p : (Σ a, β a) → Prop} : (∀ x, p x) ↔ ∀ a b, p ⟨a, b⟩ := ⟨fun h a b ↦ h ⟨a, b⟩, fun h ⟨a, b⟩ ↦ h a b⟩ @[simp] theorem «exists» {p : (Σ a, β a) → Prop} : (∃ x, p x) ↔ ∃ a b, p ⟨a, b⟩ := ⟨fun ⟨⟨a, b⟩, h⟩ ↦ ⟨a, b, h⟩, fun ⟨a, b, h⟩ ↦ ⟨⟨a, b⟩, h⟩⟩ lemma exists' {p : ∀ a, β a → Prop} : (∃ a b, p a b) ↔ ∃ x : Σ a, β a, p x.1 x.2 := (Sigma.exists (p := fun x ↦ p x.1 x.2)).symm lemma forall' {p : ∀ a, β a → Prop} : (∀ a b, p a b) ↔ ∀ x : Σ a, β a, p x.1 x.2 := (Sigma.forall (p := fun x ↦ p x.1 x.2)).symm theorem _root_.sigma_mk_injective {i : α} : Injective (@Sigma.mk α β i) | _, _, rfl => rfl theorem fst_surjective [h : ∀ a, Nonempty (β a)] : Surjective (fst : (Σ a, β a) → α) := fun a ↦ let ⟨b⟩ := h a; ⟨⟨a, b⟩, rfl⟩ theorem fst_surjective_iff : Surjective (fst : (Σ a, β a) → α) ↔ ∀ a, Nonempty (β a) := ⟨fun h a ↦ let ⟨x, hx⟩ := h a; hx ▸ ⟨x.2⟩, @fst_surjective _ _⟩ theorem fst_injective [h : ∀ a, Subsingleton (β a)] : Injective (fst : (Σ a, β a) → α) := by rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ (rfl : a₁ = a₂) exact congr_arg (mk a₁) <| Subsingleton.elim _ _ theorem fst_injective_iff : Injective (fst : (Σ a, β a) → α) ↔ ∀ a, Subsingleton (β a) := ⟨fun h _ ↦ ⟨fun _ _ ↦ sigma_mk_injective <| h rfl⟩, @fst_injective _ _⟩ /-- Map the left and right components of a sigma -/ def map (f₁ : α₁ → α₂) (f₂ : ∀ a, β₁ a → β₂ (f₁ a)) (x : Sigma β₁) : Sigma β₂ := ⟨f₁ x.1, f₂ x.1 x.2⟩ lemma map_mk (f₁ : α₁ → α₂) (f₂ : ∀ a, β₁ a → β₂ (f₁ a)) (x : α₁) (y : β₁ x) : map f₁ f₂ ⟨x, y⟩ = ⟨f₁ x, f₂ x y⟩ := rfl end Sigma theorem Function.Injective.sigma_map {f₁ : α₁ → α₂} {f₂ : ∀ a, β₁ a → β₂ (f₁ a)} (h₁ : Injective f₁) (h₂ : ∀ a, Injective (f₂ a)) : Injective (Sigma.map f₁ f₂) | ⟨i, x⟩, ⟨j, y⟩, h => by obtain rfl : i = j := h₁ (Sigma.mk.inj_iff.mp h).1 obtain rfl : x = y := h₂ i (sigma_mk_injective h) rfl theorem Function.Injective.of_sigma_map {f₁ : α₁ → α₂} {f₂ : ∀ a, β₁ a → β₂ (f₁ a)} (h : Injective (Sigma.map f₁ f₂)) (a : α₁) : Injective (f₂ a) := fun x y hxy ↦ sigma_mk_injective <| @h ⟨a, x⟩ ⟨a, y⟩ (Sigma.ext rfl (heq_of_eq hxy)) theorem Function.Injective.sigma_map_iff {f₁ : α₁ → α₂} {f₂ : ∀ a, β₁ a → β₂ (f₁ a)} (h₁ : Injective f₁) : Injective (Sigma.map f₁ f₂) ↔ ∀ a, Injective (f₂ a) := ⟨fun h ↦ h.of_sigma_map, h₁.sigma_map⟩ theorem Function.Surjective.sigma_map {f₁ : α₁ → α₂} {f₂ : ∀ a, β₁ a → β₂ (f₁ a)} (h₁ : Surjective f₁) (h₂ : ∀ a, Surjective (f₂ a)) : Surjective (Sigma.map f₁ f₂) := by simp only [Surjective, Sigma.forall, h₁.forall] exact fun i ↦ (h₂ _).forall.2 fun x ↦ ⟨⟨i, x⟩, rfl⟩ /-- Interpret a function on `Σ x : α, β x` as a dependent function with two arguments. This also exists as an `Equiv` as `Equiv.piCurry γ`. -/ def Sigma.curry {γ : ∀ a, β a → Type*} (f : ∀ x : Sigma β, γ x.1 x.2) (x : α) (y : β x) : γ x y := f ⟨x, y⟩ /-- Interpret a dependent function with two arguments as a function on `Σ x : α, β x`. This also exists as an `Equiv` as `(Equiv.piCurry γ).symm`. -/ def Sigma.uncurry {γ : ∀ a, β a → Type*} (f : ∀ (x) (y : β x), γ x y) (x : Sigma β) : γ x.1 x.2 := f x.1 x.2 @[simp] theorem Sigma.uncurry_curry {γ : ∀ a, β a → Type*} (f : ∀ x : Sigma β, γ x.1 x.2) : Sigma.uncurry (Sigma.curry f) = f := funext fun ⟨_, _⟩ ↦ rfl @[simp] theorem Sigma.curry_uncurry {γ : ∀ a, β a → Type*} (f : ∀ (x) (y : β x), γ x y) : Sigma.curry (Sigma.uncurry f) = f := rfl theorem Sigma.curry_update {γ : ∀ a, β a → Type*} [DecidableEq α] [∀ a, DecidableEq (β a)] (i : Σ a, β a) (f : (i : Σ a, β a) → γ i.1 i.2) (x : γ i.1 i.2) : Sigma.curry (Function.update f i x) = Function.update (Sigma.curry f) i.1 (Function.update (Sigma.curry f i.1) i.2 x) := by obtain ⟨ia, ib⟩ := i ext ja jb unfold Sigma.curry obtain rfl | ha := eq_or_ne ia ja · obtain rfl | hb := eq_or_ne ib jb · simp · simp only [update_self] rw [Function.update_of_ne (mt _ hb.symm), Function.update_of_ne hb.symm] rintro h injection h · rw [Function.update_of_ne (ne_of_apply_ne Sigma.fst _), Function.update_of_ne] · exact ha.symm · exact ha.symm /-- Convert a product type to a Σ-type. -/ def Prod.toSigma {α β} (p : α × β) : Σ _ : α, β := ⟨p.1, p.2⟩ @[simp] theorem Prod.fst_comp_toSigma {α β} : Sigma.fst ∘ @Prod.toSigma α β = Prod.fst := rfl @[simp] theorem Prod.fst_toSigma {α β} (x : α × β) : (Prod.toSigma x).fst = x.fst := rfl @[simp] theorem Prod.snd_toSigma {α β} (x : α × β) : (Prod.toSigma x).snd = x.snd := rfl @[simp] theorem Prod.toSigma_mk {α β} (x : α) (y : β) : (x, y).toSigma = ⟨x, y⟩ := rfl theorem Prod.toSigma_injective {α β} : Function.Injective (α := α × β) Prod.toSigma := by rintro ⟨a, b⟩ ⟨c, d⟩ h simp_all @[simp] theorem Prod.toSigma_inj {α β} {x y : α × β} : x.toSigma = y.toSigma ↔ x = y := Prod.toSigma_injective.eq_iff end Sigma namespace PSigma variable {α : Sort*} {β : α → Sort*} /-- Nondependent eliminator for `PSigma`. -/ def elim {γ} (f : ∀ a, β a → γ) (a : PSigma β) : γ := PSigma.casesOn a f @[simp] theorem elim_val {γ} (f : ∀ a, β a → γ) (a b) : PSigma.elim f ⟨a, b⟩ = f a b := rfl instance [Inhabited α] [Inhabited (β default)] : Inhabited (PSigma β) := ⟨⟨default, default⟩⟩ instance decidableEq [h₁ : DecidableEq α] [h₂ : ∀ a, DecidableEq (β a)] : DecidableEq (PSigma β) | ⟨a₁, b₁⟩, ⟨a₂, b₂⟩ => match a₁, b₁, a₂, b₂, h₁ a₁ a₂ with | _, b₁, _, b₂, isTrue (Eq.refl _) => match b₁, b₂, h₂ _ b₁ b₂ with | _, _, isTrue (Eq.refl _) => isTrue rfl | _, _, isFalse n => isFalse fun h ↦ PSigma.noConfusion h fun _ e₂ ↦ n <| eq_of_heq e₂ | _, _, _, _, isFalse n => isFalse fun h ↦ PSigma.noConfusion h fun e₁ _ ↦ n e₁ theorem mk.inj_iff {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂} : @PSigma.mk α β a₁ b₁ = @PSigma.mk α β a₂ b₂ ↔ a₁ = a₂ ∧ b₁ ≍ b₂ := (Iff.intro PSigma.mk.inj) fun ⟨h₁, h₂⟩ ↦ match a₁, a₂, b₁, b₂, h₁, h₂ with | _, _, _, _, Eq.refl _, HEq.refl _ => rfl -- This should not be a simp lemma, since its discrimination tree key would just be `→`. theorem «forall» {p : (Σ' a, β a) → Prop} : (∀ x, p x) ↔ ∀ a b, p ⟨a, b⟩ := ⟨fun h a b ↦ h ⟨a, b⟩, fun h ⟨a, b⟩ ↦ h a b⟩ @[simp] lemma «exists» {p : (Σ' a, β a) → Prop} : (∃ x, p x) ↔ ∃ a b, p ⟨a, b⟩ := ⟨fun ⟨⟨a, b⟩, h⟩ ↦ ⟨a, b, h⟩, fun ⟨a, b, h⟩ ↦ ⟨⟨a, b⟩, h⟩⟩ /-- A specialized ext lemma for equality of `PSigma` types over an indexed subtype. -/ @[ext] theorem subtype_ext {β : Sort*} {p : α → β → Prop} : ∀ {x₀ x₁ : Σ' a, Subtype (p a)}, x₀.fst = x₁.fst → (x₀.snd : β) = x₁.snd → x₀ = x₁ | ⟨_, _, _⟩, ⟨_, _, _⟩, rfl, rfl => rfl variable {α₁ : Sort*} {α₂ : Sort*} {β₁ : α₁ → Sort*} {β₂ : α₂ → Sort*} /-- Map the left and right components of a sigma -/ def map (f₁ : α₁ → α₂) (f₂ : ∀ a, β₁ a → β₂ (f₁ a)) : PSigma β₁ → PSigma β₂ | ⟨a, b⟩ => ⟨f₁ a, f₂ a b⟩ end PSigma
.lake/packages/mathlib/Mathlib/Data/Pi/Interval.lean
import Mathlib.Order.Interval.Finset.Basic import Mathlib.Data.Fintype.BigOperators /-! # Intervals in a pi type This file shows that (dependent) functions to locally finite orders equipped with the pointwise order are locally finite and calculates the cardinality of their intervals. -/ open Finset Fintype variable {ι : Type*} {α : ι → Type*} [Fintype ι] [DecidableEq ι] [∀ i, DecidableEq (α i)] namespace Pi section PartialOrder variable [∀ i, PartialOrder (α i)] section LocallyFiniteOrder variable [∀ i, LocallyFiniteOrder (α i)] instance instLocallyFiniteOrder : LocallyFiniteOrder (∀ i, α i) := LocallyFiniteOrder.ofIcc _ (fun a b => piFinset fun i => Icc (a i) (b i)) fun a b x => by simp_rw [mem_piFinset, mem_Icc, le_def, forall_and] variable (a b : ∀ i, α i) theorem Icc_eq : Icc a b = piFinset fun i => Icc (a i) (b i) := rfl theorem card_Icc : #(Icc a b) = ∏ i, #(Icc (a i) (b i)) := card_piFinset _ theorem card_Ico : #(Ico a b) = ∏ i, #(Icc (a i) (b i)) - 1 := by rw [card_Ico_eq_card_Icc_sub_one, card_Icc] theorem card_Ioc : #(Ioc a b) = ∏ i, #(Icc (a i) (b i)) - 1 := by rw [card_Ioc_eq_card_Icc_sub_one, card_Icc] theorem card_Ioo : #(Ioo a b) = ∏ i, #(Icc (a i) (b i)) - 2 := by rw [card_Ioo_eq_card_Icc_sub_two, card_Icc] end LocallyFiniteOrder section LocallyFiniteOrderBot variable [∀ i, LocallyFiniteOrderBot (α i)] (b : ∀ i, α i) instance instLocallyFiniteOrderBot : LocallyFiniteOrderBot (∀ i, α i) := .ofIic _ (fun b => piFinset fun i => Iic (b i)) fun b x => by simp_rw [mem_piFinset, mem_Iic, le_def] lemma card_Iic : #(Iic b) = ∏ i, #(Iic (b i)) := card_piFinset _ lemma card_Iio : #(Iio b) = ∏ i, #(Iic (b i)) - 1 := by rw [card_Iio_eq_card_Iic_sub_one, card_Iic] end LocallyFiniteOrderBot section LocallyFiniteOrderTop variable [∀ i, LocallyFiniteOrderTop (α i)] (a : ∀ i, α i) instance instLocallyFiniteOrderTop : LocallyFiniteOrderTop (∀ i, α i) := LocallyFiniteOrderTop.ofIci _ (fun a => piFinset fun i => Ici (a i)) fun a x => by simp_rw [mem_piFinset, mem_Ici, le_def] lemma card_Ici : #(Ici a) = ∏ i, #(Ici (a i)) := card_piFinset _ lemma card_Ioi : #(Ioi a) = ∏ i, #(Ici (a i)) - 1 := by rw [card_Ioi_eq_card_Ici_sub_one, card_Ici] end LocallyFiniteOrderTop end PartialOrder section Lattice variable [∀ i, Lattice (α i)] [∀ i, LocallyFiniteOrder (α i)] (a b : ∀ i, α i) theorem uIcc_eq : uIcc a b = piFinset fun i => uIcc (a i) (b i) := rfl theorem card_uIcc : #(uIcc a b) = ∏ i, #(uIcc (a i) (b i)) := card_Icc _ _ end Lattice end Pi
.lake/packages/mathlib/Mathlib/Data/Int/ModEq.lean
import Mathlib.Data.Nat.ModEq /-! # Congruences modulo an integer This file defines the equivalence relation `a ≡ b [ZMOD n]` on the integers, similarly to how `Data.Nat.ModEq` defines them for the natural numbers. The notation is short for `n.ModEq a b`, which is defined to be `a % n = b % n` for integers `a b n`. ## Tags modeq, congruence, mod, MOD, modulo, integers -/ namespace Int /-- `a ≡ b [ZMOD n]` when `a % n = b % n`. -/ def ModEq (n a b : ℤ) := a % n = b % n @[inherit_doc] notation:50 a " ≡ " b " [ZMOD " n "]" => ModEq n a b variable {m n a b c d : ℤ} instance : Decidable (ModEq n a b) := decEq (a % n) (b % n) namespace ModEq @[refl, simp] protected theorem refl (a : ℤ) : a ≡ a [ZMOD n] := @rfl _ _ protected theorem rfl : a ≡ a [ZMOD n] := ModEq.refl _ instance : IsRefl _ (ModEq n) := ⟨ModEq.refl⟩ @[symm] protected theorem symm : a ≡ b [ZMOD n] → b ≡ a [ZMOD n] := Eq.symm @[trans] protected theorem trans : a ≡ b [ZMOD n] → b ≡ c [ZMOD n] → a ≡ c [ZMOD n] := Eq.trans instance : IsTrans ℤ (ModEq n) where trans := @Int.ModEq.trans n protected theorem eq : a ≡ b [ZMOD n] → a % n = b % n := id end ModEq theorem modEq_comm : a ≡ b [ZMOD n] ↔ b ≡ a [ZMOD n] := ⟨ModEq.symm, ModEq.symm⟩ @[simp, norm_cast] theorem natCast_modEq_iff {a b n : ℕ} : a ≡ b [ZMOD n] ↔ a ≡ b [MOD n] := by unfold ModEq Nat.ModEq; rw [← Int.ofNat_inj]; simp theorem modEq_zero_iff_dvd : a ≡ 0 [ZMOD n] ↔ n ∣ a := by rw [ModEq, zero_emod, dvd_iff_emod_eq_zero] theorem _root_.Dvd.dvd.modEq_zero_int (h : n ∣ a) : a ≡ 0 [ZMOD n] := modEq_zero_iff_dvd.2 h theorem _root_.Dvd.dvd.zero_modEq_int (h : n ∣ a) : 0 ≡ a [ZMOD n] := h.modEq_zero_int.symm theorem modEq_iff_dvd : a ≡ b [ZMOD n] ↔ n ∣ b - a := by rw [ModEq, eq_comm] simp [emod_eq_emod_iff_emod_sub_eq_zero, dvd_iff_emod_eq_zero] theorem modEq_iff_add_fac {a b n : ℤ} : a ≡ b [ZMOD n] ↔ ∃ t, b = a + n * t := by rw [modEq_iff_dvd] exact exists_congr fun t => sub_eq_iff_eq_add' alias ⟨ModEq.dvd, modEq_of_dvd⟩ := modEq_iff_dvd theorem mod_modEq (a n) : a % n ≡ a [ZMOD n] := emod_emod _ _ @[simp] theorem neg_modEq_neg : -a ≡ -b [ZMOD n] ↔ a ≡ b [ZMOD n] := by simp only [modEq_iff_dvd, (by cutsat : -b - -a = -(b - a)), Int.dvd_neg] @[simp] theorem modEq_neg : a ≡ b [ZMOD -n] ↔ a ≡ b [ZMOD n] := by simp [modEq_iff_dvd] namespace ModEq protected theorem of_dvd (d : m ∣ n) (h : a ≡ b [ZMOD n]) : a ≡ b [ZMOD m] := modEq_iff_dvd.2 <| d.trans h.dvd protected theorem mul_left' (h : a ≡ b [ZMOD n]) : c * a ≡ c * b [ZMOD c * n] := by obtain hc | rfl | hc := lt_trichotomy c 0 · rw [← neg_modEq_neg, ← modEq_neg, ← Int.neg_mul, ← Int.neg_mul, ← Int.neg_mul] simp only [ModEq, mul_emod_mul_of_pos _ _ (neg_pos.2 hc), h.eq] · simp only [Int.zero_mul, ModEq.rfl] · simp only [ModEq, mul_emod_mul_of_pos _ _ hc, h.eq] protected theorem mul_right' (h : a ≡ b [ZMOD n]) : a * c ≡ b * c [ZMOD n * c] := by rw [mul_comm a, mul_comm b, mul_comm n]; exact h.mul_left' @[gcongr] protected theorem add (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a + c ≡ b + d [ZMOD n] := modEq_iff_dvd.2 <| by convert Int.dvd_add h₁.dvd h₂.dvd using 1; cutsat protected theorem add_left (c : ℤ) (h : a ≡ b [ZMOD n]) : c + a ≡ c + b [ZMOD n] := ModEq.rfl.add h protected theorem add_right (c : ℤ) (h : a ≡ b [ZMOD n]) : a + c ≡ b + c [ZMOD n] := h.add ModEq.rfl protected theorem add_left_cancel (h₁ : a ≡ b [ZMOD n]) (h₂ : a + c ≡ b + d [ZMOD n]) : c ≡ d [ZMOD n] := have : d - c = b + d - (a + c) - (b - a) := by cutsat modEq_iff_dvd.2 <| by rw [this] exact Int.dvd_sub h₂.dvd h₁.dvd protected theorem add_left_cancel' (c : ℤ) (h : c + a ≡ c + b [ZMOD n]) : a ≡ b [ZMOD n] := ModEq.rfl.add_left_cancel h protected theorem add_right_cancel (h₁ : c ≡ d [ZMOD n]) (h₂ : a + c ≡ b + d [ZMOD n]) : a ≡ b [ZMOD 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 [ZMOD n]) : a ≡ b [ZMOD n] := ModEq.rfl.add_right_cancel h @[gcongr] protected theorem neg (h : a ≡ b [ZMOD n]) : -a ≡ -b [ZMOD n] := h.add_left_cancel (by simp_rw [← sub_eq_add_neg, sub_self]; rfl) @[gcongr] protected theorem sub (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a - c ≡ b - d [ZMOD n] := by rw [sub_eq_add_neg, sub_eq_add_neg] exact h₁.add h₂.neg protected theorem sub_left (c : ℤ) (h : a ≡ b [ZMOD n]) : c - a ≡ c - b [ZMOD n] := ModEq.rfl.sub h protected theorem sub_right (c : ℤ) (h : a ≡ b [ZMOD n]) : a - c ≡ b - c [ZMOD n] := h.sub ModEq.rfl protected theorem mul_left (c : ℤ) (h : a ≡ b [ZMOD n]) : c * a ≡ c * b [ZMOD n] := h.mul_left'.of_dvd <| dvd_mul_left _ _ protected theorem mul_right (c : ℤ) (h : a ≡ b [ZMOD n]) : a * c ≡ b * c [ZMOD n] := h.mul_right'.of_dvd <| dvd_mul_right _ _ @[gcongr] protected theorem mul (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a * c ≡ b * d [ZMOD n] := (h₂.mul_left _).trans (h₁.mul_right _) @[gcongr] protected theorem pow (m : ℕ) (h : a ≡ b [ZMOD n]) : a ^ m ≡ b ^ m [ZMOD n] := by induction m with | zero => rfl | succ d hd => rw [pow_succ, pow_succ]; exact hd.mul h lemma of_mul_left (m : ℤ) (h : a ≡ b [ZMOD m * n]) : a ≡ b [ZMOD n] := by rw [modEq_iff_dvd] at *; exact (dvd_mul_left n m).trans h lemma of_mul_right (m : ℤ) : a ≡ b [ZMOD n * m] → a ≡ b [ZMOD n] := mul_comm m n ▸ of_mul_left _ /-- To cancel a common factor `c` from a `ModEq` we must divide the modulus `m` by `gcd m c`. -/ theorem cancel_right_div_gcd (hm : 0 < m) (h : a * c ≡ b * c [ZMOD m]) : a ≡ b [ZMOD m / gcd m c] := by letI d := gcd m c rw [modEq_iff_dvd] at h ⊢ refine Int.dvd_of_dvd_mul_right_of_gcd_one (?_ : m / d ∣ c / d * (b - a)) ?_ · rw [mul_comm, ← Int.mul_ediv_assoc (b - a) (gcd_dvd_right ..), Int.sub_mul] exact Int.ediv_dvd_ediv (gcd_dvd_left ..) h · rw [gcd_div (gcd_dvd_left ..) (gcd_dvd_right ..), natAbs_natCast, Nat.div_self (gcd_pos_of_ne_zero_left c hm.ne')] /-- To cancel a common factor `c` from a `ModEq` we must divide the modulus `m` by `gcd m c`. -/ theorem cancel_left_div_gcd (hm : 0 < m) (h : c * a ≡ c * b [ZMOD m]) : a ≡ b [ZMOD m / gcd m c] := cancel_right_div_gcd hm <| by simpa [mul_comm] using h theorem of_div (h : a / c ≡ b / c [ZMOD m / c]) (ha : c ∣ a) (ha : c ∣ b) (ha : c ∣ m) : a ≡ b [ZMOD m] := by convert h.mul_left' <;> rwa [Int.mul_ediv_cancel'] /-- Cancel left multiplication on both sides of the `≡` and in the modulus. For cancelling left multiplication in the modulus, see `Int.ModEq.of_mul_left`. -/ protected theorem mul_left_cancel' (hc : c ≠ 0) : c * a ≡ c * b [ZMOD c * m] → a ≡ b [ZMOD m] := by simp only [modEq_iff_dvd, ← Int.mul_sub] exact Int.dvd_of_mul_dvd_mul_left hc protected theorem mul_left_cancel_iff' (hc : c ≠ 0) : c * a ≡ c * b [ZMOD c * m] ↔ a ≡ b [ZMOD m] := ⟨ModEq.mul_left_cancel' hc, Int.ModEq.mul_left'⟩ /-- Cancel right multiplication on both sides of the `≡` and in the modulus. For cancelling right multiplication in the modulus, see `Int.ModEq.of_mul_right`. -/ protected theorem mul_right_cancel' (hc : c ≠ 0) : a * c ≡ b * c [ZMOD m * c] → a ≡ b [ZMOD m] := by simp only [modEq_iff_dvd, ← Int.sub_mul] exact Int.dvd_of_mul_dvd_mul_right hc protected theorem mul_right_cancel_iff' (hc : c ≠ 0) : a * c ≡ b * c [ZMOD m * c] ↔ a ≡ b [ZMOD m] := ⟨ModEq.mul_right_cancel' hc, ModEq.mul_right'⟩ theorem dvd_iff (h : a ≡ b [ZMOD n]) : n ∣ a ↔ n ∣ b := by simp only [← modEq_zero_iff_dvd] exact ⟨fun ha ↦ h.symm.trans ha, h.trans⟩ end ModEq @[simp] theorem modulus_modEq_zero : n ≡ 0 [ZMOD n] := by simp [ModEq] @[simp] theorem modEq_abs : a ≡ b [ZMOD |n|] ↔ a ≡ b [ZMOD n] := by simp [ModEq] theorem modEq_natAbs : a ≡ b [ZMOD n.natAbs] ↔ a ≡ b [ZMOD n] := by simp [natCast_natAbs] @[simp] theorem add_modEq_left_iff : a + b ≡ a [ZMOD n] ↔ n ∣ b := by simp [modEq_iff_dvd] @[simp] theorem add_modEq_right_iff : a + b ≡ b [ZMOD n] ↔ n ∣ a := by rw [add_comm, add_modEq_left_iff] @[simp] theorem left_modEq_add_iff : a ≡ a + b [ZMOD n] ↔ n ∣ b := by rw [modEq_comm, add_modEq_left_iff] @[simp] theorem right_modEq_add_iff : b ≡ a + b [ZMOD n] ↔ n ∣ a := by rw [modEq_comm, add_modEq_right_iff] @[simp] theorem add_modulus_modEq_iff : a + n ≡ b [ZMOD n] ↔ a ≡ b [ZMOD n] := by simp [ModEq] @[simp] theorem modulus_add_modEq_iff : n + a ≡ b [ZMOD n] ↔ a ≡ b [ZMOD n] := by rw [add_comm, add_modulus_modEq_iff] @[simp] theorem modEq_add_modulus_iff : a ≡ b + n [ZMOD n] ↔ a ≡ b [ZMOD n] := by simp [ModEq] @[simp] theorem modEq_modulus_add_iff : a ≡ n + b [ZMOD n] ↔ a ≡ b [ZMOD n] := by simp [ModEq] @[simp] theorem add_mul_modulus_modEq_iff : a + b * n ≡ c [ZMOD n] ↔ a ≡ c [ZMOD n] := by simp [ModEq] @[simp] theorem mul_modulus_add_modEq_iff : b * n + a ≡ c [ZMOD n] ↔ a ≡ c [ZMOD n] := by rw [add_comm, add_mul_modulus_modEq_iff] @[simp] theorem modEq_add_mul_modulus_iff : a ≡ b + c * n [ZMOD n] ↔ a ≡ b [ZMOD n] := by simp [ModEq] @[simp] theorem modEq_mul_modulus_add_iff : a ≡ b * n + c [ZMOD n] ↔ a ≡ c [ZMOD n] := by rw [add_comm, modEq_add_mul_modulus_iff] @[simp] theorem add_modulus_mul_modEq_iff : a + n * b ≡ c [ZMOD n] ↔ a ≡ c [ZMOD n] := by simp [ModEq] @[simp] theorem modulus_mul_add_modEq_iff : n * b + a ≡ c [ZMOD n] ↔ a ≡ c [ZMOD n] := by rw [add_comm, add_modulus_mul_modEq_iff] @[simp] theorem modEq_add_modulus_mul_iff : a ≡ b + n * c [ZMOD n] ↔ a ≡ b [ZMOD n] := by simp [ModEq] @[simp] theorem modEq_modulus_mul_add_iff : a ≡ n * b + c [ZMOD n] ↔ a ≡ c [ZMOD n] := by rw [add_comm, modEq_add_modulus_mul_iff] @[simp] theorem sub_modulus_modEq_iff : a - n ≡ b [ZMOD n] ↔ a ≡ b [ZMOD n] := by rw [← add_modulus_modEq_iff, sub_add_cancel] @[simp] theorem sub_modulus_mul_modEq_iff : a - n * b ≡ c [ZMOD n] ↔ a ≡ c [ZMOD n] := by rw [← add_modulus_mul_modEq_iff, sub_add_cancel] @[simp] theorem modEq_sub_modulus_iff : a ≡ b - n [ZMOD n] ↔ a ≡ b [ZMOD n] := by rw [← modEq_add_modulus_iff, sub_add_cancel] @[simp] theorem modEq_sub_modulus_mul_iff : a ≡ b - n * c [ZMOD n] ↔ a ≡ b [ZMOD n] := by rw [← modEq_add_modulus_mul_iff, sub_add_cancel] theorem modEq_one : a ≡ b [ZMOD 1] := modEq_of_dvd (one_dvd _) theorem modEq_sub (a b : ℤ) : a ≡ b [ZMOD a - b] := (modEq_of_dvd dvd_rfl).symm @[simp] theorem modEq_zero_iff : a ≡ b [ZMOD 0] ↔ a = b := by rw [ModEq, emod_zero, emod_zero] theorem add_modEq_left : n + a ≡ a [ZMOD n] := by simp theorem add_modEq_right : a + n ≡ a [ZMOD n] := by simp theorem modEq_and_modEq_iff_modEq_lcm {a b m n : ℤ} : a ≡ b [ZMOD m] ∧ a ≡ b [ZMOD n] ↔ a ≡ b [ZMOD m.lcm n] := by simp only [modEq_iff_dvd, coe_lcm_dvd_iff] theorem modEq_and_modEq_iff_modEq_mul {a b m n : ℤ} (hmn : m.natAbs.Coprime n.natAbs) : a ≡ b [ZMOD m] ∧ a ≡ b [ZMOD n] ↔ a ≡ b [ZMOD m * n] := by convert ← modEq_and_modEq_iff_modEq_lcm using 1 rw [lcm_eq_mul_iff.mpr (.inr <| .inr hmn), ← natAbs_mul, modEq_natAbs] theorem gcd_a_modEq (a b : ℕ) : (a : ℤ) * Nat.gcdA a b ≡ Nat.gcd a b [ZMOD b] := by rw [← add_zero ((a : ℤ) * _), Nat.gcd_eq_gcd_ab] exact (dvd_mul_right _ _).zero_modEq_int.add_left _ @[deprecated add_modulus_mul_modEq_iff (since := "2025-10-16")] theorem modEq_add_fac {a b n : ℤ} (c : ℤ) (ha : a ≡ b [ZMOD n]) : a + n * c ≡ b [ZMOD n] := by simpa @[deprecated sub_modulus_mul_modEq_iff (since := "2025-10-16")] theorem modEq_sub_fac {a b n : ℤ} (c : ℤ) (ha : a ≡ b [ZMOD n]) : a - n * c ≡ b [ZMOD n] := by simpa theorem modEq_add_fac_self {a t n : ℤ} : a + n * t ≡ a [ZMOD n] := by simp theorem mod_coprime {a b : ℕ} (hab : Nat.Coprime a b) : ∃ y : ℤ, a * y ≡ 1 [ZMOD b] := ⟨Nat.gcdA a b, have hgcd : Nat.gcd a b = 1 := Nat.Coprime.gcd_eq_one hab calc ↑a * Nat.gcdA a b ≡ ↑a * Nat.gcdA a b + ↑b * Nat.gcdB a b [ZMOD ↑b] := by simp _ ≡ 1 [ZMOD ↑b] := by rw [← Nat.gcd_eq_gcd_ab, hgcd]; rfl ⟩ theorem existsUnique_equiv (a : ℤ) {b : ℤ} (hb : 0 < b) : ∃ z : ℤ, 0 ≤ z ∧ z < b ∧ z ≡ a [ZMOD b] := ⟨a % b, emod_nonneg _ (ne_of_gt hb), by have : a % b < |b| := emod_lt_abs _ (ne_of_gt hb) rwa [abs_of_pos hb] at this, by simp [ModEq]⟩ theorem existsUnique_equiv_nat (a : ℤ) {b : ℤ} (hb : 0 < b) : ∃ z : ℕ, ↑z < b ∧ ↑z ≡ a [ZMOD b] := let ⟨z, hz1, hz2, hz3⟩ := existsUnique_equiv a hb ⟨z.natAbs, by constructor <;> rw [natAbs_of_nonneg hz1] <;> assumption⟩ theorem mod_mul_right_mod (a b c : ℤ) : a % (b * c) % b = a % b := (mod_modEq _ _).of_mul_right _ theorem mod_mul_left_mod (a b c : ℤ) : a % (b * c) % c = a % c := (mod_modEq _ _).of_mul_left _ end Int
.lake/packages/mathlib/Mathlib/Data/Int/DivMod.lean
import Batteries.Tactic.Alias import Mathlib.Init /-! # Basic lemmas about division and modulo for integers -/ namespace Int /-! ### `ediv` and `fdiv` -/ theorem mul_ediv_le_mul_ediv_assoc {a : Int} (ha : 0 ≤ a) (b : Int) {c : Int} (hc : 0 ≤ c) : a * (b / c) ≤ a * b / c := by obtain rfl | hlt : c = 0 ∨ 0 < c := by cutsat · simp · rw [Int.le_ediv_iff_mul_le hlt, Int.mul_assoc] exact Int.mul_le_mul_of_nonneg_left (Int.ediv_mul_le b (Int.ne_of_gt hlt)) ha @[deprecated (since := "2025-10-06")] alias ediv_ediv_eq_ediv_mul := ediv_ediv theorem fdiv_fdiv_eq_fdiv_mul (m : Int) {n k : Int} (hn : 0 ≤ n) (hk : 0 ≤ k) : (m.fdiv n).fdiv k = m.fdiv (n * k) := by rw [Int.fdiv_eq_ediv_of_nonneg _ hn, Int.fdiv_eq_ediv_of_nonneg _ hk, Int.fdiv_eq_ediv_of_nonneg _ (Int.mul_nonneg hn hk), ediv_ediv hn] /-! ### `emod` -/ theorem emod_eq_sub_self_emod {a b : Int} : a % b = (a - b) % b := (sub_emod_right a b).symm end Int
.lake/packages/mathlib/Mathlib/Data/Int/Bitwise.lean
import Mathlib.Algebra.Ring.Int.Defs import Mathlib.Data.Nat.Bitwise import Mathlib.Data.Nat.Size import Batteries.Data.Int /-! # Bitwise operations on integers Possibly only of archaeological significance. ## Recursors * `Int.bitCasesOn`: Parity disjunction. Something is true/defined on `ℤ` if it's true/defined for even and for odd values. -/ namespace Int /-- `div2 n = n/2` -/ def div2 : ℤ → ℤ | (n : ℕ) => n.div2 | -[n+1] => negSucc n.div2 /-- `bodd n` returns `true` if `n` is odd -/ def bodd : ℤ → Bool | (n : ℕ) => n.bodd | -[n+1] => not (n.bodd) /-- `bit b` appends the digit `b` to the binary representation of its integer input. -/ def bit (b : Bool) : ℤ → ℤ := cond b (2 * · + 1) (2 * ·) /-- `Int.natBitwise` is an auxiliary definition for `Int.bitwise`. -/ def natBitwise (f : Bool → Bool → Bool) (m n : ℕ) : ℤ := cond (f false false) -[Nat.bitwise (fun x y => not (f x y)) m n+1] (Nat.bitwise f m n) /-- `Int.bitwise` applies the function `f` to pairs of bits in the same position in the binary representations of its inputs. -/ def bitwise (f : Bool → Bool → Bool) : ℤ → ℤ → ℤ | (m : ℕ), (n : ℕ) => natBitwise f m n | (m : ℕ), -[n+1] => natBitwise (fun x y => f x (not y)) m n | -[m+1], (n : ℕ) => natBitwise (fun x y => f (not x) y) m n | -[m+1], -[n+1] => natBitwise (fun x y => f (not x) (not y)) m n /-- `lnot` flips all the bits in the binary representation of its input -/ def lnot : ℤ → ℤ | (m : ℕ) => -[m+1] | -[m+1] => m /-- `lor` takes two integers and returns their bitwise `or` -/ def lor : ℤ → ℤ → ℤ | (m : ℕ), (n : ℕ) => m ||| n | (m : ℕ), -[n+1] => -[Nat.ldiff n m+1] | -[m+1], (n : ℕ) => -[Nat.ldiff m n+1] | -[m+1], -[n+1] => -[m &&& n+1] /-- `land` takes two integers and returns their bitwise `and` -/ def land : ℤ → ℤ → ℤ | (m : ℕ), (n : ℕ) => m &&& n | (m : ℕ), -[n+1] => Nat.ldiff m n | -[m+1], (n : ℕ) => Nat.ldiff n m | -[m+1], -[n+1] => -[m ||| n+1] /-- `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 : ℤ → ℤ → ℤ | (m : ℕ), (n : ℕ) => Nat.ldiff m n | (m : ℕ), -[n+1] => m &&& n | -[m+1], (n : ℕ) => -[m ||| n+1] | -[m+1], -[n+1] => Nat.ldiff n m /-- `xor` computes the bitwise `xor` of two natural numbers -/ protected def xor : ℤ → ℤ → ℤ | (m : ℕ), (n : ℕ) => (m ^^^ n) | (m : ℕ), -[n+1] => -[(m ^^^ n)+1] | -[m+1], (n : ℕ) => -[(m ^^^ n)+1] | -[m+1], -[n+1] => (m ^^^ n) /-- `m <<< n` produces an integer whose binary representation is obtained by left-shifting the binary representation of `m` by `n` places -/ instance : ShiftLeft ℤ where shiftLeft | (m : ℕ), (n : ℕ) => Nat.shiftLeft' false m n | (m : ℕ), -[n +1] => m >>> (Nat.succ n) | -[m +1], (n : ℕ) => -[Nat.shiftLeft' true m n +1] | -[m +1], -[n +1] => -[m >>> (Nat.succ n) +1] /-- `m >>> n` produces an integer whose binary representation is obtained by right-shifting the binary representation of `m` by `n` places -/ instance : ShiftRight ℤ where shiftRight m n := m <<< (-n) /-! ### bitwise ops -/ @[simp] theorem bodd_zero : bodd 0 = false := rfl @[simp] theorem bodd_one : bodd 1 = true := rfl theorem bodd_two : bodd 2 = false := rfl @[simp, norm_cast] theorem bodd_coe (n : ℕ) : Int.bodd n = Nat.bodd n := rfl @[simp] theorem bodd_subNatNat (m n : ℕ) : bodd (subNatNat m n) = xor m.bodd n.bodd := by apply subNatNat_elim m n fun m n i => bodd i = xor m.bodd n.bodd <;> intro i j <;> simp only [Int.bodd, Nat.bodd_add] <;> cases Nat.bodd i <;> simp @[simp] theorem bodd_negOfNat (n : ℕ) : bodd (negOfNat n) = n.bodd := by cases n <;> simp +decide rfl @[simp] theorem bodd_neg (n : ℤ) : bodd (-n) = bodd n := by cases n <;> simp only [← negOfNat_eq, bodd_negOfNat, neg_negSucc] <;> simp [bodd] @[simp] theorem bodd_add (m n : ℤ) : bodd (m + n) = xor (bodd m) (bodd n) := by rcases m with m | m <;> rcases n with n | n <;> simp only [ofNat_eq_coe, ofNat_add_negSucc, negSucc_add_ofNat, negSucc_add_negSucc, bodd_subNatNat, ← Nat.cast_add] <;> simp [bodd, Bool.xor_comm] @[simp] theorem bodd_mul (m n : ℤ) : bodd (m * n) = (bodd m && bodd n) := by rcases m with m | m <;> rcases n with n | n <;> simp only [ofNat_eq_coe, ofNat_mul_negSucc, negSucc_mul_ofNat, ofNat_mul_ofNat, negSucc_mul_negSucc] <;> simp only [negSucc_eq, ← Int.natCast_succ, bodd_neg, bodd_coe, Nat.bodd_mul] theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | (n : ℕ) => by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ) by cases bodd n <;> rfl] exact congr_arg ofNat n.bodd_add_div2 | -[n+1] => by refine Eq.trans ?_ (congr_arg negSucc n.bodd_add_div2) dsimp [bodd]; cases Nat.bodd n <;> dsimp [cond, not, div2, Int.mul] · change -[2 * Nat.div2 n+1] = _ rw [zero_add] · rw [zero_add, add_comm] rfl theorem div2_val : ∀ n, div2 n = n / 2 | (n : ℕ) => congr_arg ofNat n.div2_val | -[n+1] => congr_arg negSucc n.div2_val theorem bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by cases b · apply (add_zero _).symm · rfl theorem bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans <| (add_comm _ _).trans <| bodd_add_div2 _ /-- Defines a function from `ℤ` conditionally, if it is defined for odd and even integers separately using `bit`. -/ def bitCasesOn.{u} {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n] apply h @[simp] theorem bit_zero : bit false 0 = 0 := rfl @[simp] theorem bit_coe_nat (b) (n : ℕ) : bit b n = Nat.bit b n := by rw [bit_val, Nat.bit_val] cases b <;> rfl @[simp] theorem bit_negSucc (b) (n : ℕ) : bit b -[n+1] = -[Nat.bit (not b) n+1] := by rw [bit_val, Nat.bit_val] cases b <;> rfl @[simp] theorem bodd_bit (b n) : bodd (bit b n) = b := by rw [bit_val] cases b <;> cases bodd n <;> simp [(show bodd 2 = false by rfl)] @[simp] theorem testBit_bit_zero (b) : ∀ n, testBit (bit b n) 0 = b | (n : ℕ) => by rw [bit_coe_nat]; apply Nat.testBit_bit_zero | -[n+1] => by rw [bit_negSucc]; dsimp [testBit]; rw [Nat.testBit_bit_zero]; clear testBit_bit_zero cases b <;> rfl @[simp] theorem testBit_bit_succ (m b) : ∀ n, testBit (bit b n) (Nat.succ m) = testBit n m | (n : ℕ) => by rw [bit_coe_nat]; apply Nat.testBit_bit_succ | -[n+1] => by dsimp only [testBit] simp only [bit_negSucc] cases b <;> simp only [Bool.not_false, Bool.not_true, Nat.testBit_bit_succ] -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11215): TODO -- private unsafe def bitwise_tac : tactic Unit := -- sorry -- Porting note: Was `bitwise_tac` in mathlib theorem bitwise_or : bitwise or = lor := by funext m n rcases m with m | m <;> rcases n with n | n <;> try {rfl} <;> simp only [bitwise, natBitwise, Bool.not_false, Bool.or_true, cond_true, lor, Nat.ldiff, negSucc.injEq, Bool.true_or] · rw [Nat.bitwise_swap, Function.swap] congr funext x y cases x <;> cases y <;> rfl · simp · congr simp -- Porting note: Was `bitwise_tac` in mathlib theorem bitwise_and : bitwise and = land := by funext m n rcases m with m | m <;> rcases n with n | n <;> try {rfl} <;> simp only [bitwise, natBitwise, Bool.not_false, cond_false, cond_true, Bool.and_true, Bool.and_false] · rw [Nat.bitwise_swap, Function.swap] congr funext x y cases x <;> cases y <;> rfl · congr simp -- Porting note: Was `bitwise_tac` in mathlib theorem bitwise_diff : (bitwise fun a b => a && not b) = ldiff := by funext m n rcases m with m | m <;> rcases n with n | n <;> try {rfl} <;> simp only [bitwise, natBitwise, Bool.not_false, cond_false, cond_true, Nat.ldiff, Bool.and_true, negSucc.injEq, Bool.and_false, Bool.not_true, ldiff] · congr simp · congr simp · rw [Nat.bitwise_swap, Function.swap] congr funext x y cases x <;> cases y <;> rfl -- Porting note: Was `bitwise_tac` in mathlib theorem bitwise_xor : bitwise xor = Int.xor := by funext m n rcases m with m | m <;> rcases n with n | n <;> try {rfl} <;> simp only [bitwise, natBitwise, Bool.not_false, Bool.bne_eq_xor, cond_false, cond_true, negSucc.injEq, Bool.false_xor, Bool.true_xor, Bool.not_true, Int.xor, HXor.hXor, XorOp.xor, Nat.xor] <;> simp @[simp] theorem bitwise_bit (f : Bool → Bool → Bool) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := by rcases m with m | m <;> rcases n with n | n <;> simp [bitwise, ofNat_eq_coe, bit_coe_nat, natBitwise, Bool.not_false, bit_negSucc] · by_cases h : f false false <;> simp +decide [h] · by_cases h : f false true <;> simp +decide [h] · by_cases h : f true false <;> simp +decide [h] · by_cases h : f true true <;> simp +decide [h] @[simp] theorem lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := by rw [← bitwise_or, bitwise_bit] @[simp] theorem land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) := by rw [← bitwise_and, bitwise_bit] @[simp] theorem ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && not b) (ldiff m n) := by rw [← bitwise_diff, bitwise_bit] @[simp] theorem lxor_bit (a m b n) : Int.xor (bit a m) (bit b n) = bit (xor a b) (Int.xor m n) := by rw [← bitwise_xor, bitwise_bit] @[simp] theorem lnot_bit (b) : ∀ n, lnot (bit b n) = bit (not b) (lnot n) | (n : ℕ) => by simp [lnot] | -[n+1] => by simp [lnot] @[simp] theorem testBit_bitwise (f : Bool → Bool → Bool) (m n k) : testBit (bitwise f m n) k = f (testBit m k) (testBit n k) := by cases m <;> cases n <;> simp only [testBit, bitwise, natBitwise] · by_cases h : f false false <;> simp [h] · by_cases h : f false true <;> simp [h] · by_cases h : f true false <;> simp [h] · by_cases h : f true true <;> simp [h] @[simp] theorem testBit_lor (m n k) : testBit (lor m n) k = (testBit m k || testBit n k) := by rw [← bitwise_or, testBit_bitwise] @[simp] theorem testBit_land (m n k) : testBit (land m n) k = (testBit m k && testBit n k) := by rw [← bitwise_and, testBit_bitwise] @[simp] theorem testBit_ldiff (m n k) : testBit (ldiff m n) k = (testBit m k && not (testBit n k)) := by rw [← bitwise_diff, testBit_bitwise] @[simp] theorem testBit_lxor (m n k) : testBit (Int.xor m n) k = xor (testBit m k) (testBit n k) := by rw [← bitwise_xor, testBit_bitwise] @[simp] theorem testBit_lnot : ∀ n k, testBit (lnot n) k = not (testBit n k) | (n : ℕ), k => by simp [lnot, testBit] | -[n+1], k => by simp [lnot, testBit] @[simp] theorem shiftLeft_neg (m n : ℤ) : m <<< (-n) = m >>> n := rfl @[simp] theorem shiftRight_neg (m n : ℤ) : m >>> (-n) = m <<< n := by rw [← shiftLeft_neg, neg_neg] @[simp] theorem shiftLeft_natCast (m n : ℕ) : (m : ℤ) <<< (n : ℤ) = ↑(m <<< n) := by unfold_projs; simp @[simp] theorem shiftRight_natCast (m n : ℕ) : (m : ℤ) >>> (n : ℤ) = m >>> n := by cases n <;> rfl @[simp] theorem shiftLeft_negSucc (m n : ℕ) : -[m+1] <<< (n : ℤ) = -[Nat.shiftLeft' true m n+1] := rfl @[simp] theorem shiftRight_negSucc (m n : ℕ) : -[m+1] >>> (n : ℤ) = -[m >>> n+1] := by cases n <;> rfl /-- Compare with `Int.shiftRight_add`, which doesn't have the coercions `ℕ → ℤ`. -/ theorem shiftRight_add' : ∀ (m : ℤ) (n k : ℕ), m >>> (n + k : ℤ) = (m >>> (n : ℤ)) >>> (k : ℤ) | (m : ℕ), n, k => by rw [shiftRight_natCast, shiftRight_natCast, ← Int.natCast_add, shiftRight_natCast, Nat.shiftRight_add] | -[m+1], n, k => by rw [shiftRight_negSucc, shiftRight_negSucc, ← Int.natCast_add, shiftRight_negSucc, Nat.shiftRight_add] /-! ### bitwise ops -/ theorem shiftLeft_add' : ∀ (m : ℤ) (n : ℕ) (k : ℤ), m <<< (n + k) = (m <<< (n : ℤ)) <<< k | (m : ℕ), n, (k : ℕ) => congr_arg ofNat (by simp [Nat.shiftLeft_eq, Nat.pow_add, mul_assoc]) | -[_+1], _, (k : ℕ) => congr_arg negSucc (Nat.shiftLeft'_add _ _ _ _) | (m : ℕ), n, -[k+1] => subNatNat_elim n k.succ (fun n k i => (↑m) <<< i = (Nat.shiftLeft' false m n) >>> k) (fun (i n : ℕ) => by simp [← Nat.shiftLeft_sub _, Nat.add_sub_cancel_left]) fun i n => by dsimp only [← Int.natCast_shiftRight] simp_rw [negSucc_eq, shiftLeft_neg, Nat.shiftLeft'_false, Nat.shiftRight_add, ← Nat.shiftLeft_sub _ le_rfl, Nat.sub_self, Nat.shiftLeft_zero, ← shiftRight_natCast, ← shiftRight_add', Nat.cast_one] | -[m+1], n, -[k+1] => subNatNat_elim n k.succ (fun n k i => -[m+1] <<< i = -[(Nat.shiftLeft' true m n) >>> k+1]) (fun i n => congr_arg negSucc <| by rw [← Nat.shiftLeft'_sub, Nat.add_sub_cancel_left]; apply Nat.le_add_right) fun i n => congr_arg negSucc <| by rw [add_assoc, Nat.shiftRight_add, ← Nat.shiftLeft'_sub _ _ le_rfl, Nat.sub_self, Nat.shiftLeft'] theorem shiftLeft_sub (m : ℤ) (n : ℕ) (k : ℤ) : m <<< (n - k) = (m <<< (n : ℤ)) >>> k := shiftLeft_add' _ _ _ theorem shiftLeft_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), m <<< (n : ℤ) = m * (2 ^ n : ℕ) | (m : ℕ), _ => congr_arg ((↑) : ℕ → ℤ) (by simp [Nat.shiftLeft_eq]) | -[_+1], _ => @congr_arg ℕ ℤ _ _ (fun i => -i) (Nat.shiftLeft'_tt_eq_mul_pow _ _) theorem one_shiftLeft (n : ℕ) : 1 <<< (n : ℤ) = (2 ^ n : ℕ) := congr_arg ((↑) : ℕ → ℤ) (by simp [Nat.shiftLeft_eq]) /-- Compare with `Int.zero_shiftLeft`, which has `n : ℕ`. -/ @[simp] theorem zero_shiftLeft' : ∀ n : ℤ, 0 <<< n = 0 | (n : ℕ) => congr_arg ((↑) : ℕ → ℤ) (by simp) | -[_+1] => congr_arg ((↑) : ℕ → ℤ) (by simp) /-- Compare with `Int.zero_shiftRight`, which has `n : ℕ`. -/ @[simp] theorem zero_shiftRight' (n : ℤ) : 0 >>> n = 0 := zero_shiftLeft' _ end Int
.lake/packages/mathlib/Mathlib/Data/Int/GCD.lean
import Mathlib.Algebra.GroupWithZero.Semiconj import Mathlib.Algebra.Group.Commute.Units import Mathlib.Data.Set.Operations import Mathlib.Order.Basic import Mathlib.Order.Bounds.Defs import Mathlib.Algebra.Group.Int.Defs import Mathlib.Data.Int.Basic import Mathlib.Algebra.Divisibility.Basic import Mathlib.Algebra.Group.Nat.Defs /-! # Extended GCD and divisibility over ℤ ## Main definitions * Given `x y : ℕ`, `xgcd x y` computes the pair of integers `(a, b)` such that `gcd x y = x * a + y * b`. `gcdA x y` and `gcdB x y` are defined to be `a` and `b`, respectively. ## Main statements * `gcd_eq_gcd_ab`: Bézout's lemma, given `x y : ℕ`, `gcd x y = x * gcdA x y + y * gcdB x y`. ## Tags Bézout's lemma, Bezout's lemma -/ /-! ### Extended Euclidean algorithm -/ namespace Nat /-- Helper function for the extended GCD algorithm (`Nat.xgcd`). -/ def xgcdAux : ℕ → ℤ → ℤ → ℕ → ℤ → ℤ → ℕ × ℤ × ℤ | 0, _, _, r', s', t' => (r', s', t') | succ k, s, t, r', s', t' => let q := r' / succ k xgcdAux (r' % succ k) (s' - q * s) (t' - q * t) (succ k) s t termination_by k => k decreasing_by exact mod_lt _ <| (succ_pos _).gt @[simp] theorem xgcd_zero_left {s t r' s' t'} : xgcdAux 0 s t r' s' t' = (r', s', t') := by simp [xgcdAux] theorem xgcdAux_rec {r s t r' s' t'} (h : 0 < r) : xgcdAux r s t r' s' t' = xgcdAux (r' % r) (s' - r' / r * s) (t' - r' / r * t) r s t := by obtain ⟨r, rfl⟩ := Nat.exists_eq_succ_of_ne_zero h.ne' simp [xgcdAux] /-- Use the extended GCD algorithm to generate the `a` and `b` values satisfying `gcd x y = x * a + y * b`. -/ def xgcd (x y : ℕ) : ℤ × ℤ := (xgcdAux x 1 0 y 0 1).2 /-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/ def gcdA (x y : ℕ) : ℤ := (xgcd x y).1 /-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/ def gcdB (x y : ℕ) : ℤ := (xgcd x y).2 @[simp] theorem gcdA_zero_left {s : ℕ} : gcdA 0 s = 0 := by unfold gcdA rw [xgcd, xgcd_zero_left] @[simp] theorem gcdB_zero_left {s : ℕ} : gcdB 0 s = 1 := by unfold gcdB rw [xgcd, xgcd_zero_left] @[simp] theorem gcdA_zero_right {s : ℕ} (h : s ≠ 0) : gcdA s 0 = 1 := by unfold gcdA xgcd obtain ⟨s, rfl⟩ := Nat.exists_eq_succ_of_ne_zero h rw [xgcdAux] simp @[simp] theorem gcdB_zero_right {s : ℕ} (h : s ≠ 0) : gcdB s 0 = 0 := by unfold gcdB xgcd obtain ⟨s, rfl⟩ := Nat.exists_eq_succ_of_ne_zero h rw [xgcdAux] simp @[simp] theorem xgcdAux_fst (x y) : ∀ s t s' t', (xgcdAux x s t y s' t').1 = gcd x y := gcd.induction x y (by simp) fun x y h IH s t s' t' => by simp only [h, xgcdAux_rec, IH] rw [← gcd_rec] theorem xgcdAux_val (x y) : xgcdAux x 1 0 y 0 1 = (gcd x y, xgcd x y) := by rw [xgcd, ← xgcdAux_fst x y 1 0 0 1] theorem xgcd_val (x y) : xgcd x y = (gcdA x y, gcdB x y) := by unfold gcdA gcdB; constructor section variable (x y : ℕ) private def P : ℕ × ℤ × ℤ → Prop | (r, s, t) => (r : ℤ) = x * s + y * t theorem xgcdAux_P {r r'} : ∀ {s t s' t'}, P x y (r, s, t) → P x y (r', s', t') → P x y (xgcdAux r s t r' s' t') := by induction r, r' using gcd.induction with | H0 => simp | H1 a b h IH => intro s t s' t' p p' rw [xgcdAux_rec h]; refine IH ?_ p; dsimp [P] at * rw [Int.emod_def]; generalize (b / a : ℤ) = k rw [p, p', Int.mul_sub, sub_add_eq_add_sub, Int.mul_sub, Int.add_mul, mul_comm k t, mul_comm k s, ← mul_assoc, ← mul_assoc, add_comm (x * s * k), ← add_sub_assoc, sub_sub] /-- **Bézout's lemma**: given `x y : ℕ`, `gcd x y = x * a + y * b`, where `a = gcd_a x y` and `b = gcd_b x y` are computed by the extended Euclidean algorithm. -/ theorem gcd_eq_gcd_ab : (gcd x y : ℤ) = x * gcdA x y + y * gcdB x y := by have := @xgcdAux_P x y x y 1 0 0 1 (by simp [P]) (by simp [P]) rwa [xgcdAux_val, xgcd_val] at this end theorem exists_mul_emod_eq_gcd {k n : ℕ} (hk : gcd n k < k) : ∃ m, n * m % k = gcd n k := by have hk' := Int.ofNat_ne_zero.2 (ne_of_gt (lt_of_le_of_lt (zero_le (gcd n k)) hk)) have key := congr_arg (fun (m : ℤ) => (m % k).toNat) (gcd_eq_gcd_ab n k) simp only at key rw [Int.add_mul_emod_self_left, ← Int.natCast_mod, Int.toNat_natCast, mod_eq_of_lt hk] at key refine ⟨(n.gcdA k % k).toNat, Eq.trans (Int.ofNat.inj ?_) key.symm⟩ rw [Int.ofNat_eq_coe, Int.natCast_mod, Int.natCast_mul, Int.toNat_of_nonneg (Int.emod_nonneg _ hk'), Int.ofNat_eq_coe, Int.toNat_of_nonneg (Int.emod_nonneg _ hk'), Int.mul_emod, Int.emod_emod, ← Int.mul_emod] theorem exists_mul_emod_eq_one_of_coprime {k n : ℕ} (hkn : Coprime n k) (hk : 1 < k) : ∃ m, n * m % k = 1 := Exists.recOn (exists_mul_emod_eq_gcd (lt_of_le_of_lt (le_of_eq hkn) hk)) fun m hm ↦ ⟨m, hm.trans hkn⟩ end Nat /-! ### Divisibility over ℤ -/ namespace Int theorem gcd_def (i j : ℤ) : gcd i j = Nat.gcd i.natAbs j.natAbs := rfl /-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/ def gcdA : ℤ → ℤ → ℤ | ofNat m, n => m.gcdA n.natAbs | -[m+1], n => -m.succ.gcdA n.natAbs /-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/ def gcdB : ℤ → ℤ → ℤ | m, ofNat n => m.natAbs.gcdB n | m, -[n+1] => -m.natAbs.gcdB n.succ /-- **Bézout's lemma** -/ theorem gcd_eq_gcd_ab : ∀ x y : ℤ, (gcd x y : ℤ) = x * gcdA x y + y * gcdB x y | (m : ℕ), (n : ℕ) => Nat.gcd_eq_gcd_ab _ _ | (m : ℕ), -[n+1] => show (_ : ℤ) = _ + -(n + 1) * -_ by rw [Int.neg_mul_neg]; apply Nat.gcd_eq_gcd_ab | -[m+1], (n : ℕ) => show (_ : ℤ) = -(m + 1) * -_ + _ by rw [Int.neg_mul_neg]; apply Nat.gcd_eq_gcd_ab | -[m+1], -[n+1] => show (_ : ℤ) = -(m + 1) * -_ + -(n + 1) * -_ by rw [Int.neg_mul_neg, Int.neg_mul_neg] apply Nat.gcd_eq_gcd_ab theorem lcm_def (i j : ℤ) : lcm i j = Nat.lcm (natAbs i) (natAbs j) := rfl alias gcd_div := gcd_ediv alias gcd_div_gcd_div_gcd := gcd_ediv_gcd_ediv_gcd /-- If `gcd a (m * n) = 1`, then `gcd a m = 1`. -/ theorem gcd_eq_one_of_gcd_mul_right_eq_one_left {a : ℤ} {m n : ℕ} (h : a.gcd (m * n) = 1) : a.gcd m = 1 := Nat.dvd_one.mp <| h ▸ gcd_dvd_gcd_mul_right_right a m n /-- If `gcd a (m * n) = 1`, then `gcd a n = 1`. -/ theorem gcd_eq_one_of_gcd_mul_right_eq_one_right {a : ℤ} {m n : ℕ} (h : a.gcd (m * n) = 1) : a.gcd n = 1 := Nat.dvd_one.mp <| h ▸ gcd_dvd_gcd_mul_left_right a n m theorem ne_zero_of_gcd {x y : ℤ} (hc : gcd x y ≠ 0) : x ≠ 0 ∨ y ≠ 0 := by contrapose! hc rw [hc.left, hc.right, gcd_zero_right, natAbs_zero] theorem exists_gcd_one {m n : ℤ} (H : 0 < gcd m n) : ∃ m' n' : ℤ, gcd m' n' = 1 ∧ m = m' * gcd m n ∧ n = n' * gcd m n := ⟨_, _, gcd_div_gcd_div_gcd H, (Int.ediv_mul_cancel (gcd_dvd_left ..)).symm, (Int.ediv_mul_cancel (gcd_dvd_right ..)).symm⟩ theorem exists_gcd_one' {m n : ℤ} (H : 0 < gcd m n) : ∃ (g : ℕ) (m' n' : ℤ), 0 < g ∧ gcd m' n' = 1 ∧ m = m' * g ∧ n = n' * g := let ⟨m', n', h⟩ := exists_gcd_one H ⟨_, m', n', H, h⟩ theorem gcd_dvd_iff {a b : ℤ} {n : ℕ} : gcd a b ∣ n ↔ ∃ x y : ℤ, ↑n = a * x + b * y := by constructor · intro h rw [← Nat.mul_div_cancel' h, Int.natCast_mul, gcd_eq_gcd_ab, Int.add_mul, mul_assoc, mul_assoc] exact ⟨_, _, rfl⟩ · rintro ⟨x, y, h⟩ rw [← Int.natCast_dvd_natCast, h] exact Int.dvd_add (dvd_mul_of_dvd_left (gcd_dvd_left ..) _) (dvd_mul_of_dvd_left (gcd_dvd_right ..) y) theorem gcd_greatest {a b d : ℤ} (hd_pos : 0 ≤ d) (hda : d ∣ a) (hdb : d ∣ b) (hd : ∀ e : ℤ, e ∣ a → e ∣ b → e ∣ d) : d = gcd a b := dvd_antisymm hd_pos (ofNat_zero_le (gcd a b)) (dvd_coe_gcd hda hdb) (hd _ (gcd_dvd_left ..) (gcd_dvd_right ..)) /-- Euclid's lemma: if `a ∣ b * c` and `gcd a c = 1` then `a ∣ b`. Compare with `IsCoprime.dvd_of_dvd_mul_left` and `UniqueFactorizationMonoid.dvd_of_dvd_mul_left_of_no_prime_factors` -/ theorem dvd_of_dvd_mul_left_of_gcd_one {a b c : ℤ} (habc : a ∣ b * c) (hab : gcd a c = 1) : a ∣ b := by have := gcd_eq_gcd_ab a c simp only [hab, Int.ofNat_zero, Int.natCast_succ, zero_add] at this have : b * a * gcdA a c + b * c * gcdB a c = b := by simp [mul_assoc, ← Int.mul_add, ← this] rw [← this] exact Int.dvd_add (dvd_mul_of_dvd_left (dvd_mul_left a b) _) (dvd_mul_of_dvd_left habc _) /-- Euclid's lemma: if `a ∣ b * c` and `gcd a b = 1` then `a ∣ c`. Compare with `IsCoprime.dvd_of_dvd_mul_right` and `UniqueFactorizationMonoid.dvd_of_dvd_mul_right_of_no_prime_factors` -/ theorem dvd_of_dvd_mul_right_of_gcd_one {a b c : ℤ} (habc : a ∣ b * c) (hab : gcd a b = 1) : a ∣ c := by rw [mul_comm] at habc exact dvd_of_dvd_mul_left_of_gcd_one habc hab /-- For nonzero integers `a` and `b`, `gcd a b` is the smallest positive natural number that can be written in the form `a * x + b * y` for some pair of integers `x` and `y` -/ theorem gcd_least_linear {a b : ℤ} (ha : a ≠ 0) : IsLeast { n : ℕ | 0 < n ∧ ∃ x y : ℤ, ↑n = a * x + b * y } (a.gcd b) := by simp_rw [← gcd_dvd_iff] constructor · simpa [and_true, dvd_refl, Set.mem_setOf_eq] using gcd_pos_of_ne_zero_left b ha · simp only [lowerBounds, and_imp, Set.mem_setOf_eq] exact fun n hn_pos hn => Nat.le_of_dvd hn_pos hn end Int @[to_additive gcd_nsmul_eq_zero] theorem pow_gcd_eq_one {M : Type*} [Monoid M] (x : M) {m n : ℕ} (hm : x ^ m = 1) (hn : x ^ n = 1) : x ^ m.gcd n = 1 := by rcases m with (rfl | m); · simp [hn] obtain ⟨y, rfl⟩ := IsUnit.of_pow_eq_one hm m.succ_ne_zero rw [← Units.val_pow_eq_pow_val, ← Units.val_one (α := M), ← zpow_natCast, ← Units.ext_iff] at * rw [Nat.gcd_eq_gcd_ab, zpow_add, zpow_mul, zpow_mul, hn, hm, one_zpow, one_zpow, one_mul] variable {α : Type*} section GroupWithZero variable [GroupWithZero α] {a b : α} {m n : ℕ} protected lemma Commute.pow_eq_pow_iff_of_coprime (hab : Commute a b) (hmn : m.Coprime n) : a ^ m = b ^ n ↔ ∃ c, a = c ^ n ∧ b = c ^ m := by refine ⟨fun h ↦ ?_, by rintro ⟨c, rfl, rfl⟩; rw [← pow_mul, ← pow_mul']⟩ by_cases m = 0; · simp_all by_cases n = 0; · simp_all by_cases hb : b = 0; · exact ⟨0, by simp_all⟩ by_cases ha : a = 0; · exact ⟨0, by have := h.symm; simp_all⟩ refine ⟨a ^ Nat.gcdB m n * b ^ Nat.gcdA m n, ?_, ?_⟩ <;> · refine (pow_one _).symm.trans ?_ conv_lhs => rw [← zpow_natCast, ← hmn, Nat.gcd_eq_gcd_ab] simp only [zpow_add₀ ha, zpow_add₀ hb, ← zpow_natCast, (hab.zpow_zpow₀ _ _).mul_zpow, ← zpow_mul, mul_comm (Nat.gcdB m n), mul_comm (Nat.gcdA m n)] simp only [zpow_mul, zpow_natCast, h] exact ((Commute.pow_pow (by aesop) _ _).zpow_zpow₀ _ _).symm end GroupWithZero section CommGroupWithZero variable [CommGroupWithZero α] {a b : α} {m n : ℕ} lemma pow_eq_pow_iff_of_coprime (hmn : m.Coprime n) : a ^ m = b ^ n ↔ ∃ c, a = c ^ n ∧ b = c ^ m := (Commute.all _ _).pow_eq_pow_iff_of_coprime hmn lemma pow_mem_range_pow_of_coprime (hmn : m.Coprime n) (a : α) : a ^ m ∈ Set.range (· ^ n : α → α) ↔ a ∈ Set.range (· ^ n : α → α) := by simp [pow_eq_pow_iff_of_coprime hmn.symm]; aesop end CommGroupWithZero
.lake/packages/mathlib/Mathlib/Data/Int/SuccPred.lean
import Mathlib.Algebra.Order.Ring.Int import Mathlib.Data.Nat.SuccPred /-! # Successors and predecessors of integers In this file, we show that `ℤ` is both an archimedean `SuccOrder` and an archimedean `PredOrder`. -/ open Function Order namespace Int -- so that Lean reads `Int.succ` through `SuccOrder.succ` @[instance] abbrev instSuccOrder : SuccOrder ℤ := { SuccOrder.ofSuccLeIff succ fun {_ _} => Iff.rfl with succ := succ } instance instSuccAddOrder : SuccAddOrder ℤ := ⟨fun _ => rfl⟩ -- so that Lean reads `Int.pred` through `PredOrder.pred` @[instance] abbrev instPredOrder : PredOrder ℤ where pred := pred pred_le _ := (sub_one_lt_of_le le_rfl).le min_of_le_pred ha := ((sub_one_lt_of_le le_rfl).not_ge ha).elim le_pred_of_lt {_ _} := le_sub_one_of_lt instance instPredSubOrder : PredSubOrder ℤ := ⟨fun _ => rfl⟩ @[simp] theorem succ_eq_succ : Order.succ = succ := rfl @[simp] theorem pred_eq_pred : Order.pred = pred := rfl instance : IsSuccArchimedean ℤ := ⟨fun {a b} h => ⟨(b - a).toNat, by rw [succ_iterate, toNat_sub_of_le h, ← add_sub_assoc, add_sub_cancel_left]⟩⟩ instance : IsPredArchimedean ℤ := ⟨fun {a b} h => ⟨(b - a).toNat, by rw [pred_iterate, toNat_sub_of_le h, sub_sub_cancel]⟩⟩ /-! ### Covering relation -/ @[simp, norm_cast] theorem natCast_covBy {a b : ℕ} : (a : ℤ) ⋖ b ↔ a ⋖ b := by rw [Order.covBy_iff_add_one_eq, Order.covBy_iff_add_one_eq] exact Int.natCast_inj end Int alias ⟨_, CovBy.intCast⟩ := Int.natCast_covBy
.lake/packages/mathlib/Mathlib/Data/Int/Sqrt.lean
import Mathlib.Data.Nat.Sqrt import Mathlib.Tactic.Common /-! # Square root of integers This file defines the square root function on integers. `Int.sqrt z` is the greatest integer `r` such that `r * r ≤ z`. If `z ≤ 0`, then `Int.sqrt z = 0`. -/ namespace Int /-- `sqrt z` is the square root of an integer `z`. If `z` is positive, it returns the largest integer `r` such that `r * r ≤ n`. If it is negative, it returns `0`. For example, `sqrt (-1) = 0`, `sqrt 1 = 1`, `sqrt 2 = 1` -/ @[pp_nodot] def sqrt (z : ℤ) : ℤ := Nat.sqrt <| Int.toNat z theorem sqrt_eq (n : ℤ) : sqrt (n * n) = n.natAbs := by rw [sqrt, ← natAbs_mul_self, toNat_natCast, Nat.sqrt_eq] theorem exists_mul_self (x : ℤ) : (∃ n, n * n = x) ↔ sqrt x * sqrt x = x := ⟨fun ⟨n, hn⟩ => by rw [← hn, sqrt_eq, ← Int.natCast_mul, natAbs_mul_self], fun h => ⟨sqrt x, h⟩⟩ theorem sqrt_nonneg (n : ℤ) : 0 ≤ sqrt n := natCast_nonneg _ @[simp, norm_cast] theorem sqrt_natCast (n : ℕ) : Int.sqrt (n : ℤ) = Nat.sqrt n := by rw [sqrt, toNat_natCast] @[simp] theorem sqrt_ofNat (n : ℕ) : Int.sqrt ofNat(n) = Nat.sqrt ofNat(n) := sqrt_natCast _ end Int
.lake/packages/mathlib/Mathlib/Data/Int/WithZero.lean
import Mathlib.Data.NNReal.Defs /-! # WithZero In this file we provide some basic API lemmas for the `WithZero` construction and we define the morphism `WithZeroMultInt.toNNReal`. ## Main Definitions * `WithZeroMultInt.toNNReal` : The `MonoidWithZeroHom` from `ℤᵐ⁰ → ℝ≥0` sending `0 ↦ 0` and `x ↦ e^((WithZero.unzero hx).toAdd)` when `x ≠ 0`, for a nonzero `e : ℝ≥0`. ## Main Results * `WithZeroMultInt.toNNReal_strictMono` : The map `withZeroMultIntToNNReal` is strictly monotone whenever `1 < e`. ## Tags WithZero, multiplicative, nnreal -/ assert_not_exists Finset noncomputable section open scoped NNReal open Multiplicative WithZero namespace WithZeroMulInt /-- Given a nonzero `e : ℝ≥0`, this is the map `ℤᵐ⁰ → ℝ≥0` sending `0 ↦ 0` and `x ↦ e^(WithZero.unzero hx).toAdd` when `x ≠ 0` as a `MonoidWithZeroHom`. -/ def toNNReal {e : ℝ≥0} (he : e ≠ 0) : ℤᵐ⁰ →*₀ ℝ≥0 where toFun := fun x ↦ if hx : x = 0 then 0 else e ^ (WithZero.unzero hx).toAdd map_zero' := rfl map_one' := by simp only [dif_neg one_ne_zero] erw [toAdd_one, zpow_zero] map_mul' x y := by by_cases hxy : x * y = 0 · rcases mul_eq_zero.mp hxy with hx | hy -- either x = 0 or y = 0 · rw [dif_pos hxy, dif_pos hx, zero_mul] · rw [dif_pos hxy, dif_pos hy, mul_zero] · obtain ⟨hx, hy⟩ := mul_ne_zero_iff.mp hxy -- x ≠ 0 and y ≠ 0 rw [dif_neg hxy, dif_neg hx, dif_neg hy, ← zpow_add' (Or.inl he), ← toAdd_mul] congr rw [← WithZero.coe_inj, WithZero.coe_mul, coe_unzero hx, coe_unzero hy, coe_unzero hxy] theorem toNNReal_pos_apply {e : ℝ≥0} (he : e ≠ 0) {x : ℤᵐ⁰} (hx : x = 0) : toNNReal he x = 0 := by simp [toNNReal, hx] theorem toNNReal_neg_apply {e : ℝ≥0} (he : e ≠ 0) {x : ℤᵐ⁰} (hx : x ≠ 0) : toNNReal he x = e ^ (WithZero.unzero hx).toAdd := by simp [toNNReal, hx] /-- `toNNReal` sends nonzero elements to nonzero elements. -/ theorem toNNReal_ne_zero {e : ℝ≥0} {m : ℤᵐ⁰} (he : e ≠ 0) (hm : m ≠ 0) : toNNReal he m ≠ 0 := by simp only [ne_eq, map_eq_zero, hm, not_false_eq_true] /-- `toNNReal` sends nonzero elements to positive elements. -/ theorem toNNReal_pos {e : ℝ≥0} {m : ℤᵐ⁰} (he : e ≠ 0) (hm : m ≠ 0) : 0 < toNNReal he m := lt_of_le_of_ne zero_le' (toNNReal_ne_zero he hm).symm /-- The map `toNNReal` is strictly monotone whenever `1 < e`. -/ theorem toNNReal_strictMono {e : ℝ≥0} (he : 1 < e) : StrictMono (toNNReal (ne_zero_of_lt he)) := by intro x y hxy simp only [toNNReal, MonoidWithZeroHom.coe_mk, ZeroHom.coe_mk] split_ifs with hx hy hy · simp only [hy, not_lt_zero'] at hxy · exact zpow_pos he.bot_lt _ · simp only [hy, not_lt_zero'] at hxy · rw [zpow_lt_zpow_iff_right₀ he, Multiplicative.toAdd_lt, ← coe_lt_coe, coe_unzero hx, WithZero.coe_unzero hy] exact hxy theorem toNNReal_eq_one_iff {e : ℝ≥0} (m : ℤᵐ⁰) (he0 : e ≠ 0) (he1 : e ≠ 1) : toNNReal he0 m = 1 ↔ m = 1 := by by_cases hm : m = 0 · simp only [hm, map_zero, zero_ne_one] · refine ⟨fun h1 ↦ ?_, fun h1 ↦ h1 ▸ map_one _⟩ rw [toNNReal_neg_apply he0 hm, zpow_eq_one_iff_right₀ (zero_le e) he1, toAdd_eq_zero] at h1 rw [← WithZero.coe_unzero hm, h1, coe_one] theorem toNNReal_lt_one_iff {e : ℝ≥0} {m : ℤᵐ⁰} (he : 1 < e) : toNNReal (ne_zero_of_lt he) m < 1 ↔ m < 1 := by rw [← (toNNReal_strictMono he).lt_iff_lt, map_one] theorem toNNReal_le_one_iff {e : ℝ≥0} {m : ℤᵐ⁰} (he : 1 < e) : toNNReal (ne_zero_of_lt he) m ≤ 1 ↔ m ≤ 1 := by rw [← (toNNReal_strictMono he).le_iff_le, map_one] end WithZeroMulInt
.lake/packages/mathlib/Mathlib/Data/Int/CardIntervalMod.lean
import Mathlib.Data.Int.Interval import Mathlib.Data.Int.ModEq import Mathlib.Data.Nat.Count import Mathlib.Data.Rat.Floor import Mathlib.Order.Interval.Finset.Nat /-! # Counting elements in an interval with given residue The theorems in this file generalise `Nat.card_multiples` in `Mathlib/Data/Nat/Factorization/Basic.lean` to all integer intervals and any fixed residue (not just zero, which reduces to the multiples). Theorems are given for `Ico` and `Ioc` intervals. -/ open Finset Int namespace Int variable (a b : ℤ) {r : ℤ} lemma Ico_filter_modEq_eq (v : ℤ) : {x ∈ Ico a b | x ≡ v [ZMOD r]} = {x ∈ Ico (a - v) (b - v) | r ∣ x}.map ⟨(· + v), add_left_injective v⟩ := by ext x simp_rw [mem_map, mem_filter, mem_Ico, Function.Embedding.coeFn_mk, ← eq_sub_iff_add_eq, exists_eq_right, modEq_comm, modEq_iff_dvd, sub_lt_sub_iff_right, sub_le_sub_iff_right] lemma Ioc_filter_modEq_eq (v : ℤ) : {x ∈ Ioc a b | x ≡ v [ZMOD r]} = {x ∈ Ioc (a - v) (b - v) | r ∣ x}.map ⟨(· + v), add_left_injective v⟩ := by ext x simp_rw [mem_map, mem_filter, mem_Ioc, Function.Embedding.coeFn_mk, ← eq_sub_iff_add_eq, exists_eq_right, modEq_comm, modEq_iff_dvd, sub_lt_sub_iff_right, sub_le_sub_iff_right] variable (hr : 0 < r) include hr lemma Ico_filter_dvd_eq : {x ∈ Ico a b | r ∣ x} = (Ico ⌈a / (r : ℚ)⌉ ⌈b / (r : ℚ)⌉).map ⟨(· * r), mul_left_injective₀ hr.ne'⟩ := by ext x simp only [mem_map, mem_filter, mem_Ico, ceil_le, lt_ceil, div_le_iff₀, lt_div_iff₀, dvd_iff_exists_eq_mul_left, cast_pos.2 hr, ← cast_mul, cast_lt, cast_le] aesop lemma Ioc_filter_dvd_eq : {x ∈ Ioc a b | r ∣ x} = (Ioc ⌊a / (r : ℚ)⌋ ⌊b / (r : ℚ)⌋).map ⟨(· * r), mul_left_injective₀ hr.ne'⟩ := by ext x simp only [mem_map, mem_filter, mem_Ioc, floor_lt, le_floor, div_lt_iff₀, le_div_iff₀, dvd_iff_exists_eq_mul_left, cast_pos.2 hr, ← cast_mul, cast_lt, cast_le] aesop /-- There are `⌈b / r⌉ - ⌈a / r⌉` multiples of `r` in `[a, b)`, if `a ≤ b`. -/ theorem Ico_filter_dvd_card : #{x ∈ Ico a b | r ∣ x} = max (⌈b / (r : ℚ)⌉ - ⌈a / (r : ℚ)⌉) 0 := by rw [Ico_filter_dvd_eq _ _ hr, card_map, card_Ico, toNat_eq_max] /-- There are `⌊b / r⌋ - ⌊a / r⌋` multiples of `r` in `(a, b]`, if `a ≤ b`. -/ theorem Ioc_filter_dvd_card : #{x ∈ Ioc a b | r ∣ x} = max (⌊b / (r : ℚ)⌋ - ⌊a / (r : ℚ)⌋) 0 := by rw [Ioc_filter_dvd_eq _ _ hr, card_map, card_Ioc, toNat_eq_max] /-- There are `⌈(b - v) / r⌉ - ⌈(a - v) / r⌉` numbers congruent to `v` mod `r` in `[a, b)`, if `a ≤ b`. -/ theorem Ico_filter_modEq_card (v : ℤ) : #{x ∈ Ico a b | x ≡ v [ZMOD r]} = max (⌈(b - v) / (r : ℚ)⌉ - ⌈(a - v) / (r : ℚ)⌉) 0 := by simp [Ico_filter_modEq_eq, Ico_filter_dvd_eq, hr] /-- There are `⌊(b - v) / r⌋ - ⌊(a - v) / r⌋` numbers congruent to `v` mod `r` in `(a, b]`, if `a ≤ b`. -/ theorem Ioc_filter_modEq_card (v : ℤ) : #{x ∈ Ioc a b | x ≡ v [ZMOD r]} = max (⌊(b - v) / (r : ℚ)⌋ - ⌊(a - v) / (r : ℚ)⌋) 0 := by simp [Ioc_filter_modEq_eq, Ioc_filter_dvd_eq, hr] end Int namespace Nat variable (a b : ℕ) {r : ℕ} lemma Ico_filter_modEq_cast {v : ℕ} : {x ∈ Ico a b | x ≡ v [MOD r]}.map castEmbedding = {x ∈ Ico (a : ℤ) (b : ℤ) | x ≡ v [ZMOD r]} := by ext x simp only [mem_map, mem_filter, mem_Ico, castEmbedding_apply] constructor · simp_rw [forall_exists_index, ← natCast_modEq_iff]; intro y ⟨h, c⟩; subst c; exact_mod_cast h · intro h; lift x to ℕ using (by omega); exact ⟨x, by simp_all [natCast_modEq_iff]⟩ lemma Ioc_filter_modEq_cast {v : ℕ} : {x ∈ Ioc a b | x ≡ v [MOD r]}.map castEmbedding = {x ∈ Ioc (a : ℤ) (b : ℤ) | x ≡ v [ZMOD r]} := by ext x simp only [mem_map, mem_filter, mem_Ioc, castEmbedding_apply] constructor · simp_rw [forall_exists_index, ← natCast_modEq_iff]; intro y ⟨h, c⟩; subst c; exact_mod_cast h · intro h; lift x to ℕ using (by cutsat); exact ⟨x, by simp_all [natCast_modEq_iff]⟩ variable (hr : 0 < r) include hr /-- There are `⌈(b - v) / r⌉ - ⌈(a - v) / r⌉` numbers congruent to `v` mod `r` in `[a, b)`, if `a ≤ b`. `Nat` version of `Int.Ico_filter_modEq_card`. -/ theorem Ico_filter_modEq_card (v : ℕ) : #{x ∈ Ico a b | x ≡ v [MOD r]} = max (⌈(b - v) / (r : ℚ)⌉ - ⌈(a - v) / (r : ℚ)⌉) 0 := by simp_rw [← Ico_filter_modEq_cast _ _ ▸ card_map _, Int.Ico_filter_modEq_card _ _ (cast_lt.mpr hr), Int.cast_natCast] /-- There are `⌊(b - v) / r⌋ - ⌊(a - v) / r⌋` numbers congruent to `v` mod `r` in `(a, b]`, if `a ≤ b`. `Nat` version of `Int.Ioc_filter_modEq_card`. -/ theorem Ioc_filter_modEq_card (v : ℕ) : #{x ∈ Ioc a b | x ≡ v [MOD r]} = max (⌊(b - v) / (r : ℚ)⌋ - ⌊(a - v) / (r : ℚ)⌋) 0 := by simp_rw [← Ioc_filter_modEq_cast _ _ ▸ card_map _, Int.Ioc_filter_modEq_card _ _ (cast_lt.mpr hr), Int.cast_natCast] /-- There are `⌈(b - v % r) / r⌉` numbers in `[0, b)` congruent to `v` mod `r`. -/ theorem count_modEq_card_eq_ceil (v : ℕ) : b.count (· ≡ v [MOD r]) = ⌈(b - (v % r : ℕ)) / (r : ℚ)⌉ := by have hr' : 0 < (r : ℚ) := by positivity rw [count_eq_card_filter_range, ← Ico_zero_eq_range, Ico_filter_modEq_card _ _ hr, max_eq_left (sub_nonneg.mpr <| by gcongr; positivity)] conv_lhs => rw [← div_add_mod v r, cast_add, cast_mul, add_comm] tactic => simp_rw [← sub_sub, sub_div (_ - _), mul_div_cancel_left₀ _ hr'.ne', Int.ceil_sub_natCast] rw [sub_sub_sub_cancel_right, cast_zero, zero_sub] rw [sub_eq_self, ceil_eq_zero_iff, Set.mem_Ioc, div_le_iff₀ hr', lt_div_iff₀ hr', neg_one_mul, zero_mul, neg_lt_neg_iff, cast_lt] exact ⟨mod_lt _ hr, by simp⟩ /-- There are `b / r + [v % r < b % r]` numbers in `[0, b)` congruent to `v` mod `r`, where `[·]` is the Iverson bracket. -/ theorem count_modEq_card (v : ℕ) : b.count (· ≡ v [MOD r]) = b / r + if v % r < b % r then 1 else 0 := by have hr' : 0 < (r : ℚ) := by positivity rw [← ofNat_inj, count_modEq_card_eq_ceil _ hr, cast_add] conv_lhs => rw [← div_add_mod b r, cast_add, cast_mul, ← add_sub, _root_.add_div, mul_div_cancel_left₀ _ hr'.ne', add_comm, Int.ceil_add_natCast, add_comm] rw [add_right_inj] split_ifs with h · rw [← cast_sub h.le, Int.ceil_eq_iff, div_le_iff₀ hr', lt_div_iff₀ hr', cast_one, Int.cast_one, sub_self, zero_mul, cast_pos, tsub_pos_iff_lt, one_mul, cast_le, tsub_le_iff_right] exact ⟨h, ((mod_lt _ hr).trans_le (by simp)).le⟩ · rw [cast_zero, ceil_eq_zero_iff, Set.mem_Ioc, div_le_iff₀ hr', lt_div_iff₀ hr', zero_mul, tsub_nonpos, ← neg_eq_neg_one_mul, neg_lt_sub_iff_lt_add, ← cast_add, cast_lt, cast_le] exact ⟨(mod_lt _ hr).trans_le (by simp), not_lt.mp h⟩ end Nat
.lake/packages/mathlib/Mathlib/Data/Int/Lemmas.lean
import Mathlib.Data.Int.Bitwise import Mathlib.Data.Int.Order.Lemmas import Mathlib.Order.Interval.Set.Defs /-! # Miscellaneous lemmas about the integers This file contains lemmas about integers, which require further imports than `Data.Int.Basic` or `Data.Int.Order`. -/ open Nat namespace Int theorem le_natCast_sub (m n : ℕ) : (m - n : ℤ) ≤ ↑(m - n : ℕ) := by cutsat /-! ### `succ` and `pred` -/ theorem succ_natCast_pos (n : ℕ) : 0 < (n : ℤ) + 1 := lt_add_one_iff.mpr (by simp) /-! ### `natAbs` -/ theorem natAbs_eq_iff_sq_eq {a b : ℤ} : a.natAbs = b.natAbs ↔ a ^ 2 = b ^ 2 := by rw [sq, sq] exact natAbs_eq_iff_mul_self_eq theorem natAbs_lt_iff_sq_lt {a b : ℤ} : a.natAbs < b.natAbs ↔ a ^ 2 < b ^ 2 := by rw [sq, sq] exact natAbs_lt_iff_mul_self_lt theorem natAbs_le_iff_sq_le {a b : ℤ} : a.natAbs ≤ b.natAbs ↔ a ^ 2 ≤ b ^ 2 := by rw [sq, sq] exact natAbs_le_iff_mul_self_le theorem natAbs_inj_of_nonneg_of_nonneg {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : natAbs a = natAbs b ↔ a = b := by rw [← sq_eq_sq₀ ha hb, ← natAbs_eq_iff_sq_eq] theorem natAbs_inj_of_nonpos_of_nonpos {a b : ℤ} (ha : a ≤ 0) (hb : b ≤ 0) : natAbs a = natAbs b ↔ a = b := by simpa only [Int.natAbs_neg, neg_inj] using natAbs_inj_of_nonneg_of_nonneg (neg_nonneg_of_nonpos ha) (neg_nonneg_of_nonpos hb) theorem natAbs_inj_of_nonneg_of_nonpos {a b : ℤ} (ha : 0 ≤ a) (hb : b ≤ 0) : natAbs a = natAbs b ↔ a = -b := by simpa only [Int.natAbs_neg] using natAbs_inj_of_nonneg_of_nonneg ha (neg_nonneg_of_nonpos hb) theorem natAbs_inj_of_nonpos_of_nonneg {a b : ℤ} (ha : a ≤ 0) (hb : 0 ≤ b) : natAbs a = natAbs b ↔ -a = b := by simpa only [Int.natAbs_neg] using natAbs_inj_of_nonneg_of_nonneg (neg_nonneg_of_nonpos ha) hb /-- A specialization of `abs_sub_le_of_nonneg_of_le` for working with the signed subtraction of natural numbers. -/ theorem natAbs_coe_sub_coe_le_of_le {a b n : ℕ} (a_le_n : a ≤ n) (b_le_n : b ≤ n) : natAbs (a - b : ℤ) ≤ n := by rw [← Nat.cast_le (α := ℤ), natCast_natAbs] exact abs_sub_le_of_nonneg_of_le (natCast_nonneg a) (ofNat_le.mpr a_le_n) (natCast_nonneg b) (ofNat_le.mpr b_le_n) /-- A specialization of `abs_sub_lt_of_nonneg_of_lt` for working with the signed subtraction of natural numbers. -/ theorem natAbs_coe_sub_coe_lt_of_lt {a b n : ℕ} (a_lt_n : a < n) (b_lt_n : b < n) : natAbs (a - b : ℤ) < n := by rw [← Nat.cast_lt (α := ℤ), natCast_natAbs] exact abs_sub_lt_of_nonneg_of_lt (natCast_nonneg a) (ofNat_lt.mpr a_lt_n) (natCast_nonneg b) (ofNat_lt.mpr b_lt_n) section Intervals open Set theorem strictMonoOn_natAbs : StrictMonoOn natAbs (Ici 0) := fun _ ha _ _ hab => natAbs_lt_natAbs_of_nonneg_of_lt ha hab theorem strictAntiOn_natAbs : StrictAntiOn natAbs (Iic 0) := fun a _ b hb hab => by simpa [Int.natAbs_neg] using natAbs_lt_natAbs_of_nonneg_of_lt (Right.nonneg_neg_iff.mpr hb) (neg_lt_neg_iff.mpr hab) theorem injOn_natAbs_Ici : InjOn natAbs (Ici 0) := strictMonoOn_natAbs.injOn theorem injOn_natAbs_Iic : InjOn natAbs (Iic 0) := strictAntiOn_natAbs.injOn end Intervals /-! ### bitwise ops This lemma is orphaned from `Data.Int.Bitwise` as it also requires material from `Data.Int.Order`. -/ @[simp] theorem div2_bit (b n) : div2 (bit b n) = n := by rw [bit_val, div2_val, add_comm, Int.add_mul_ediv_left, (_ : (_ / 2 : ℤ) = 0), zero_add] cases b · decide · change ofNat _ = _ rw [Nat.div_eq_of_lt] <;> simp · decide /-- Like `Int.ediv_emod_unique`, but permitting negative `b`. -/ theorem ediv_emod_unique'' {a b r q : Int} (h : b ≠ 0) : a / b = q ∧ a % b = r ↔ r + b * q = a ∧ 0 ≤ r ∧ r < |b| := by constructor · intro ⟨rfl, rfl⟩ exact ⟨emod_add_mul_ediv a b, emod_nonneg _ h, emod_lt_abs _ h⟩ · intro ⟨rfl, hz, hb⟩ constructor · rw [Int.add_mul_ediv_left r q h, ediv_eq_zero_of_lt_abs hz hb] simp · rw [add_mul_emod_self_left, ← emod_abs, emod_eq_of_lt hz hb] end Int
.lake/packages/mathlib/Mathlib/Data/Int/Star.lean
import Mathlib.Algebra.Order.Group.Abs import Mathlib.Algebra.Order.Monoid.Submonoid import Mathlib.Algebra.Order.Ring.Basic import Mathlib.Algebra.Order.Ring.Int import Mathlib.Algebra.Order.Star.Basic /-! # Star ordered ring structure on `ℤ` This file shows that `ℤ` is a `StarOrderedRing`. -/ open AddSubmonoid Set namespace Int @[simp] lemma addSubmonoid_closure_range_pow {n : ℕ} (hn : Even n) : closure (range fun x : ℤ ↦ x ^ n) = nonneg _ := by refine le_antisymm (closure_le.2 <| range_subset_iff.2 hn.pow_nonneg) fun x hx ↦ ?_ have : x = x.natAbs • 1 ^ n := by simpa [eq_comm (a := x)] using hx rw [this] exact nsmul_mem (subset_closure <| mem_range_self _) _ @[simp] lemma addSubmonoid_closure_range_mul_self : closure (range fun x : ℤ ↦ x * x) = nonneg _ := by simpa only [sq] using addSubmonoid_closure_range_pow even_two instance instStarOrderedRing : StarOrderedRing ℤ where le_iff a b := by simp [eq_comm, le_iff_exists_nonneg_add (a := a)] end Int
.lake/packages/mathlib/Mathlib/Data/Int/Interval.lean
import Mathlib.Algebra.Group.Embedding import Mathlib.Algebra.Ring.CharZero import Mathlib.Algebra.Ring.Int.Defs import Mathlib.Algebra.Order.Group.Unbundled.Int import Mathlib.Order.Interval.Finset.Basic /-! # Finite intervals of integers This file proves that `ℤ` is a `LocallyFiniteOrder` and calculates the cardinality of its intervals as finsets and fintypes. -/ assert_not_exists Field open Finset Int namespace Int instance instLocallyFiniteOrder : LocallyFiniteOrder ℤ where finsetIcc a b := (Finset.range (b + 1 - a).toNat).map <| Nat.castEmbedding.trans <| addLeftEmbedding a finsetIco a b := (Finset.range (b - a).toNat).map <| Nat.castEmbedding.trans <| addLeftEmbedding a finsetIoc a b := (Finset.range (b - a).toNat).map <| Nat.castEmbedding.trans <| addLeftEmbedding (a + 1) finsetIoo a b := (Finset.range (b - a - 1).toNat).map <| Nat.castEmbedding.trans <| addLeftEmbedding (a + 1) finset_mem_Icc a b x := by simp_rw [mem_map, mem_range, Function.Embedding.trans_apply, Nat.castEmbedding_apply, addLeftEmbedding_apply] constructor · omega · intro use (x - a).toNat omega finset_mem_Ico a b x := by simp_rw [mem_map, mem_range, Function.Embedding.trans_apply, Nat.castEmbedding_apply, addLeftEmbedding_apply] constructor · omega · intro use (x - a).toNat omega finset_mem_Ioc a b x := by simp_rw [mem_map, mem_range, Function.Embedding.trans_apply, Nat.castEmbedding_apply, addLeftEmbedding_apply] constructor · omega · intro use (x - (a + 1)).toNat omega finset_mem_Ioo a b x := by simp_rw [mem_map, mem_range, Function.Embedding.trans_apply, Nat.castEmbedding_apply, addLeftEmbedding_apply] constructor · omega · intro use (x - (a + 1)).toNat omega variable (a b : ℤ) theorem Icc_eq_finset_map : Icc a b = (Finset.range (b + 1 - a).toNat).map (Nat.castEmbedding.trans <| addLeftEmbedding a) := rfl theorem Ico_eq_finset_map : Ico a b = (Finset.range (b - a).toNat).map (Nat.castEmbedding.trans <| addLeftEmbedding a) := rfl theorem Ioc_eq_finset_map : Ioc a b = (Finset.range (b - a).toNat).map (Nat.castEmbedding.trans <| addLeftEmbedding (a + 1)) := rfl theorem Ioo_eq_finset_map : Ioo a b = (Finset.range (b - a - 1).toNat).map (Nat.castEmbedding.trans <| addLeftEmbedding (a + 1)) := rfl theorem uIcc_eq_finset_map : uIcc a b = (range (max a b + 1 - min a b).toNat).map (Nat.castEmbedding.trans <| addLeftEmbedding <| min a b) := rfl @[simp] theorem card_Icc : #(Icc a b) = (b + 1 - a).toNat := (card_map _).trans <| card_range _ @[simp] theorem card_Ico : #(Ico a b) = (b - a).toNat := (card_map _).trans <| card_range _ @[simp] theorem card_Ioc : #(Ioc a b) = (b - a).toNat := (card_map _).trans <| card_range _ @[simp] theorem card_Ioo : #(Ioo a b) = (b - a - 1).toNat := (card_map _).trans <| card_range _ @[simp] theorem card_uIcc : #(uIcc a b) = (b - a).natAbs + 1 := (card_map _).trans <| (Nat.cast_inj (R := ℤ)).mp <| by rw [card_range, Int.toNat_of_nonneg (sub_nonneg_of_le <| le_add_one min_le_max), Int.natCast_add, Int.natCast_natAbs, add_comm, add_sub_assoc, max_sub_min_eq_abs, add_comm, Int.ofNat_one] theorem card_Icc_of_le (h : a ≤ b + 1) : (#(Icc a b) : ℤ) = b + 1 - a := by rw [card_Icc, toNat_sub_of_le h] theorem card_Ico_of_le (h : a ≤ b) : (#(Ico a b) : ℤ) = b - a := by rw [card_Ico, toNat_sub_of_le h] theorem card_Ioc_of_le (h : a ≤ b) : (#(Ioc a b) : ℤ) = b - a := by rw [card_Ioc, toNat_sub_of_le h] theorem card_Ioo_of_lt (h : a < b) : (#(Ioo a b) : ℤ) = b - a - 1 := by rw [card_Ioo, sub_sub, toNat_sub_of_le h] theorem Icc_eq_pair : Finset.Icc a (a + 1) = {a, a + 1} := by ext simp omega theorem card_fintype_Icc_of_le (h : a ≤ b + 1) : (Fintype.card (Set.Icc a b) : ℤ) = b + 1 - a := by simp [h] theorem card_fintype_Ico_of_le (h : a ≤ b) : (Fintype.card (Set.Ico a b) : ℤ) = b - a := by simp [h] theorem card_fintype_Ioc_of_le (h : a ≤ b) : (Fintype.card (Set.Ioc a b) : ℤ) = b - a := by simp [h] theorem card_fintype_Ioo_of_lt (h : a < b) : (Fintype.card (Set.Ioo a b) : ℤ) = b - a - 1 := by simp [h] theorem image_Ico_emod (n a : ℤ) (h : 0 ≤ a) : (Ico n (n + a)).image (· % a) = Ico 0 a := by obtain rfl | ha := eq_or_lt_of_le h · simp ext i simp only [mem_image, mem_Ico] constructor · rintro ⟨i, _, rfl⟩ exact ⟨emod_nonneg i ha.ne', emod_lt_of_pos i ha⟩ intro hia have hn := Int.emod_add_mul_ediv n a obtain hi | hi := lt_or_ge i (n % a) · refine ⟨i + a * (n / a + 1), ⟨?_, ?_⟩, ?_⟩ · rw [add_comm (n / a), mul_add, mul_one, ← add_assoc] refine hn.symm.le.trans (add_le_add_right ?_ _) simpa only [zero_add] using add_le_add hia.left (Int.emod_lt_of_pos n ha).le · refine lt_of_lt_of_le (add_lt_add_right hi (a * (n / a + 1))) ?_ rw [mul_add, mul_one, ← add_assoc, hn] · rw [Int.add_mul_emod_self_left, Int.emod_eq_of_lt hia.left hia.right] · refine ⟨i + a * (n / a), ⟨?_, ?_⟩, ?_⟩ · exact hn.symm.le.trans (add_le_add_right hi _) · rw [add_comm n a] refine add_lt_add_of_lt_of_le hia.right (le_trans ?_ hn.le) simp only [le_add_iff_nonneg_left] exact Int.emod_nonneg n (ne_of_gt ha) · rw [Int.add_mul_emod_self_left, Int.emod_eq_of_lt hia.left hia.right] end Int section Nat lemma Finset.Icc_succ_succ (m n : ℕ) : Icc (-(m + 1) : ℤ) (n + 1) = Icc (-m : ℤ) n ∪ {(-(m + 1) : ℤ), (n + 1 : ℤ)} := by ext simp only [mem_Icc, union_insert, union_singleton, mem_insert] omega lemma Finset.Ico_succ_succ (m n : ℕ) : Ico (-(m + 1) : ℤ) (n + 1) = Ico (-m : ℤ) n ∪ {(-(m + 1) : ℤ), (n : ℤ)} := by ext simp only [mem_Ico, union_insert, union_singleton, mem_insert] omega lemma Finset.Ioc_succ_succ (m n : ℕ) : Ioc (-(m + 1) : ℤ) (n + 1) = Ioc (-m : ℤ) n ∪ {-(m : ℤ), (n + 1 : ℤ)} := by ext simp only [mem_Ioc, union_insert, union_singleton, mem_insert] omega lemma Finset.Ioo_succ_succ (m n : ℕ) : Ioo (-(m + 1) : ℤ) (n + 1) = Ioo (-m : ℤ) n ∪ {-(m : ℤ), (n : ℤ)} := by ext simp only [mem_Ioo, union_insert, union_singleton, mem_insert] omega end Nat
.lake/packages/mathlib/Mathlib/Data/Int/NatPrime.lean
import Mathlib.Data.Nat.Prime.Basic import Mathlib.Algebra.Group.Int.Defs import Mathlib.Data.Int.Basic /-! # Lemmas about `Nat.Prime` using `Int`s -/ open Nat namespace Int theorem not_prime_of_int_mul {a b : ℤ} {c : ℕ} (ha : a.natAbs ≠ 1) (hb : b.natAbs ≠ 1) (hc : a * b = (c : ℤ)) : ¬Nat.Prime c := not_prime_of_mul_eq (natAbs_mul_natAbs_eq hc) ha hb theorem succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : Nat.Prime p) {m n : ℤ} {k l : ℕ} (hpm : ↑(p ^ k) ∣ m) (hpn : ↑(p ^ l) ∣ n) (hpmn : ↑(p ^ (k + l + 1)) ∣ m * n) : ↑(p ^ (k + 1)) ∣ m ∨ ↑(p ^ (l + 1)) ∣ n := have hpm' : p ^ k ∣ m.natAbs := Int.natCast_dvd_natCast.1 <| Int.dvd_natAbs.2 hpm have hpn' : p ^ l ∣ n.natAbs := Int.natCast_dvd_natCast.1 <| Int.dvd_natAbs.2 hpn have hpmn' : p ^ (k + l + 1) ∣ m.natAbs * n.natAbs := by rw [← Int.natAbs_mul]; apply Int.natCast_dvd_natCast.1 <| Int.dvd_natAbs.2 hpmn let hsd := Nat.succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul p_prime hpm' hpn' hpmn' hsd.elim (fun hsd1 => Or.inl (by apply Int.dvd_natAbs.1; apply Int.natCast_dvd_natCast.2 hsd1)) fun hsd2 => Or.inr (by apply Int.dvd_natAbs.1; apply Int.natCast_dvd_natCast.2 hsd2) theorem Prime.dvd_natAbs_of_coe_dvd_sq {p : ℕ} (hp : p.Prime) (k : ℤ) (h : (p : ℤ) ∣ k ^ 2) : p ∣ k.natAbs := by apply @Nat.Prime.dvd_of_dvd_pow _ _ 2 hp rwa [sq, ← natAbs_mul, ← natCast_dvd, ← sq] end Int
.lake/packages/mathlib/Mathlib/Data/Int/Init.lean
import Batteries.Logic import Batteries.Tactic.Init import Mathlib.Data.Int.Notation import Mathlib.Data.Nat.Notation import Mathlib.Tactic.Lemma import Mathlib.Tactic.TypeStar /-! # Basic operations on the integers This file contains some basic lemmas about integers. See note [foundational algebra order theory]. This file should not depend on anything defined in Mathlib (except for notation), so that it can be upstreamed to Batteries easily. -/ open Nat namespace Int variable {a b c d m n : ℤ} protected theorem neg_eq_neg {a b : ℤ} (h : -a = -b) : a = b := Int.neg_inj.1 h /-! ### succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 lemma pred_succ (a : ℤ) : pred (succ a) = a := Int.add_sub_cancel _ _ lemma succ_pred (a : ℤ) : succ (pred a) = a := Int.sub_add_cancel _ _ lemma neg_succ (a : ℤ) : -succ a = pred (-a) := Int.neg_add lemma succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] lemma neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [← Int.neg_eq_comm.mp (neg_succ (-a)), Int.neg_neg] lemma pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] lemma pred_nat_succ (n : ℕ) : pred (Nat.succ n) = n := pred_succ n lemma neg_nat_succ (n : ℕ) : -(Nat.succ n : ℤ) = pred (-n) := neg_succ n lemma succ_neg_natCast_succ (n : ℕ) : succ (-Nat.succ n) = -n := succ_neg_succ n @[norm_cast] lemma natCast_pred_of_pos {n : ℕ} (h : 0 < n) : ((n - 1 : ℕ) : ℤ) = (n : ℤ) - 1 := by grind lemma lt_succ_self (a : ℤ) : a < succ a := by unfold succ; cutsat lemma pred_self_lt (a : ℤ) : pred a < a := by unfold pred; cutsat /-- Induction on integers: prove a proposition `p i` by proving the base case `p 0`, the upwards induction step `p i → p (i + 1)` and the downwards induction step `p (-i) → p (-i - 1)`. It is used as the default induction principle for the `induction` tactic. -/ @[elab_as_elim, induction_eliminator] protected lemma induction_on {motive : ℤ → Prop} (i : ℤ) (zero : motive 0) (succ : ∀ i : ℕ, motive i → motive (i + 1)) (pred : ∀ i : ℕ, motive (-i) → motive (-i - 1)) : motive i := by cases i with | ofNat i => induction i with | zero => exact zero | succ i ih => exact succ _ ih | negSucc i => suffices ∀ n : ℕ, motive (-n) from this (i + 1) intro n; induction n with | zero => simp [zero] | succ n ih => simpa [natCast_succ, Int.neg_add, Int.sub_eq_add_neg] using pred _ ih section inductionOn' variable {motive : ℤ → Sort*} (z b : ℤ) (zero : motive b) (succ : ∀ k, b ≤ k → motive k → motive (k + 1)) (pred : ∀ k ≤ b, motive k → motive (k - 1)) /-- Inductively define a function on `ℤ` by defining it at `b`, for the `succ` of a number greater than `b`, and the `pred` of a number less than `b`. -/ @[elab_as_elim] protected def inductionOn' : motive z := cast (congrArg motive <| show b + (z - b) = z by rw [Int.add_comm, z.sub_add_cancel b]) <| match z - b with | .ofNat n => pos n | .negSucc n => neg n where /-- The positive case of `Int.inductionOn'`. -/ pos : ∀ n : ℕ, motive (b + n) | 0 => cast (by simp) zero | n + 1 => cast (by rw [Int.add_assoc]; rfl) <| succ _ (Int.le_add_of_nonneg_right (natCast_nonneg _)) (pos n) /-- The negative case of `Int.inductionOn'`. -/ neg : ∀ n : ℕ, motive (b + -[n+1]) | 0 => pred _ Int.le_rfl zero | n + 1 => by refine cast (by cutsat) (pred _ (Int.le_of_lt ?_) (neg n)) cutsat variable {z b zero succ pred} lemma inductionOn'_self : b.inductionOn' b zero succ pred = zero := cast_eq_iff_heq.mpr <| .symm <| by rw [b.sub_self, ← cast_eq_iff_heq]; rfl lemma inductionOn'_sub_one (hz : z ≤ b) : (z - 1).inductionOn' b zero succ pred = pred z hz (z.inductionOn' b zero succ pred) := by apply cast_eq_iff_heq.mpr obtain ⟨n, hn⟩ := Int.eq_negSucc_of_lt_zero (show z - 1 - b < 0 by cutsat) rw [hn] obtain _ | n := n · change _ = -1 at hn have : z = b := by omega subst this; rw [inductionOn'_self]; exact heq_of_eq rfl · have : z = b + -[n+1] := by rw [Int.negSucc_eq] at hn ⊢; omega subst this refine (cast_heq _ _).trans ?_ congr symm rw [Int.inductionOn', cast_eq_iff_heq, show b + -[n+1] - b = -[n+1] by cutsat] end inductionOn' /-- Inductively define a function on `ℤ` by defining it on `ℕ` and extending it from `n` to `-n`. -/ @[elab_as_elim] protected def negInduction {motive : ℤ → Sort*} (nat : ∀ n : ℕ, motive n) (neg : (∀ n : ℕ, motive n) → ∀ n : ℕ, motive (-n)) : ∀ n : ℤ, motive n | .ofNat n => nat n | .negSucc n => neg nat <| n + 1 /-- See `Int.inductionOn'` for an induction in both directions. -/ @[elab_as_elim] protected lemma le_induction {m : ℤ} {motive : ∀ n, m ≤ n → Prop} (base : motive m m.le_refl) (succ : ∀ n hmn, motive n hmn → motive (n + 1) (le_add_one hmn)) : ∀ n hmn, motive n hmn := by refine fun n ↦ Int.inductionOn' n m ?_ ?_ ?_ <;> grind /-- See `Int.inductionOn'` for an induction in both directions. -/ @[elab_as_elim] protected lemma le_induction_down {m : ℤ} {motive : ∀ n, n ≤ m → Prop} (base : motive m m.le_refl) (pred : ∀ n hmn, motive n hmn → motive (n - 1) (by cutsat)) : ∀ n hmn, motive n hmn := fun n ↦ Int.inductionOn' n m (fun _ ↦ base) (fun k hle _ hle' ↦ by cutsat) fun k hle hi _ ↦ pred k hle (hi hle) section strongRec variable {motive : ℤ → Sort*} (lt : ∀ n < m, motive n) (ge : ∀ n ≥ m, (∀ k < n, motive k) → motive n) /-- A strong recursor for `Int` that specifies explicit values for integers below a threshold, and is analogous to `Nat.strongRec` for integers on or above the threshold. -/ @[elab_as_elim] protected def strongRec (n : ℤ) : motive n := by refine if hnm : n < m then lt n hnm else ge n (by cutsat) (n.inductionOn' m lt ?_ ?_) · intro _n _ ih l _ exact if hlm : l < m then lt l hlm else ge l (by omega) fun k _ ↦ ih k (by omega) · exact fun n _ hn l _ ↦ hn l (by omega) variable {lt ge} lemma strongRec_of_lt (hn : n < m) : m.strongRec lt ge n = lt n hn := dif_pos _ end strongRec /-! ### mul -/ /-! ### natAbs -/ alias natAbs_sq := natAbs_pow_two theorem sign_mul_self_eq_natAbs (a : Int) : sign a * a = natAbs a := sign_mul_self a /-! ### `/` -/ lemma natCast_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := natCast_ediv m n lemma ediv_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : ediv a b = -((-a - 1) / b + 1) := match a, b, eq_negSucc_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ => by rw [show (- -[m+1] : ℤ) = (m + 1 : ℤ) by rfl]; rw [Int.add_sub_cancel]; rfl /-! ### mod -/ @[simp, norm_cast] lemma natCast_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl lemma div_le_iff_of_dvd_of_pos (hb : 0 < b) (hba : b ∣ a) : a / b ≤ c ↔ a ≤ b * c := ediv_le_iff_of_dvd_of_pos hb hba lemma div_le_iff_of_dvd_of_neg (hb : b < 0) (hba : b ∣ a) : a / b ≤ c ↔ b * c ≤ a := ediv_le_iff_of_dvd_of_neg hb hba lemma div_lt_iff_of_dvd_of_pos (hb : 0 < b) (hba : b ∣ a) : a / b < c ↔ a < b * c := ediv_lt_iff_of_dvd_of_pos hb hba lemma div_lt_iff_of_dvd_of_neg (hb : b < 0) (hba : b ∣ a) : a / b < c ↔ b * c < a := ediv_lt_iff_of_dvd_of_neg hb hba lemma le_div_iff_of_dvd_of_pos (hc : 0 < c) (hcb : c ∣ b) : a ≤ b / c ↔ c * a ≤ b := le_ediv_iff_of_dvd_of_pos hc hcb lemma le_div_iff_of_dvd_of_neg (hc : c < 0) (hcb : c ∣ b) : a ≤ b / c ↔ b ≤ c * a := le_ediv_iff_of_dvd_of_neg hc hcb lemma lt_div_iff_of_dvd_of_pos (hc : 0 < c) (hcb : c ∣ b) : a < b / c ↔ c * a < b := lt_ediv_iff_of_dvd_of_pos hc hcb lemma lt_div_iff_of_dvd_of_neg (hc : c < 0) (hcb : c ∣ b) : a < b / c ↔ b < c * a := lt_ediv_iff_of_dvd_of_neg hc hcb lemma div_le_div_iff_of_dvd_of_pos_of_pos (hb : 0 < b) (hd : 0 < d) (hba : b ∣ a) (hdc : d ∣ c) : a / b ≤ c / d ↔ d * a ≤ c * b := ediv_le_ediv_iff_of_dvd_of_pos_of_pos hb hd hba hdc lemma div_le_div_iff_of_dvd_of_pos_of_neg (hb : 0 < b) (hd : d < 0) (hba : b ∣ a) (hdc : d ∣ c) : a / b ≤ c / d ↔ c * b ≤ d * a := ediv_le_ediv_iff_of_dvd_of_pos_of_neg hb hd hba hdc lemma div_le_div_iff_of_dvd_of_neg_of_pos (hb : b < 0) (hd : 0 < d) (hba : b ∣ a) (hdc : d ∣ c) : a / b ≤ c / d ↔ c * b ≤ d * a := ediv_le_ediv_iff_of_dvd_of_neg_of_pos hb hd hba hdc lemma div_le_div_iff_of_dvd_of_neg_of_neg (hb : b < 0) (hd : d < 0) (hba : b ∣ a) (hdc : d ∣ c) : a / b ≤ c / d ↔ d * a ≤ c * b := ediv_le_ediv_iff_of_dvd_of_neg_of_neg hb hd hba hdc lemma div_lt_div_iff_of_dvd_of_pos (hb : 0 < b) (hd : 0 < d) (hba : b ∣ a) (hdc : d ∣ c) : a / b < c / d ↔ d * a < c * b := ediv_lt_ediv_iff_of_dvd_of_pos hb hd hba hdc lemma div_lt_div_iff_of_dvd_of_pos_of_neg (hb : 0 < b) (hd : d < 0) (hba : b ∣ a) (hdc : d ∣ c) : a / b < c / d ↔ c * b < d * a := ediv_lt_ediv_iff_of_dvd_of_pos_of_neg hb hd hba hdc lemma div_lt_div_iff_of_dvd_of_neg_of_pos (hb : b < 0) (hd : 0 < d) (hba : b ∣ a) (hdc : d ∣ c) : a / b < c / d ↔ c * b < d * a := ediv_lt_ediv_iff_of_dvd_of_neg_of_pos hb hd hba hdc lemma div_lt_div_iff_of_dvd_of_neg_of_neg (hb : b < 0) (hd : d < 0) (hba : b ∣ a) (hdc : d ∣ c) : a / b < c / d ↔ d * a < c * b := ediv_lt_ediv_iff_of_dvd_of_neg_of_neg hb hd hba hdc /-! ### properties of `/` and `%` -/ lemma emod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 := emod_two_eq n /-! ### dvd -/ lemma dvd_mul_of_div_dvd (h : b ∣ a) (hdiv : a / b ∣ c) : a ∣ b * c := dvd_mul_of_ediv_dvd h hdiv lemma div_dvd_iff_dvd_mul (h : b ∣ a) (hb : b ≠ 0) : a / b ∣ c ↔ a ∣ b * c := ediv_dvd_iff_dvd_mul h hb lemma mul_dvd_of_dvd_div (hcb : c ∣ b) (h : a ∣ b / c) : c * a ∣ b := mul_dvd_of_dvd_ediv hcb h lemma dvd_div_of_mul_dvd (h : a * b ∣ c) : b ∣ c / a := dvd_ediv_of_mul_dvd h lemma dvd_div_iff_mul_dvd (hbc : c ∣ b) : a ∣ b / c ↔ c * a ∣ b := by simp [hbc] /-- If `n > 0` then `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)` for some `k`. -/ lemma exists_lt_and_lt_iff_not_dvd (m : ℤ) (hn : 0 < n) : (∃ k, n * k < m ∧ m < n * (k + 1)) ↔ ¬n ∣ m := (not_dvd_iff_lt_mul_succ m hn).symm lemma eq_mul_div_of_mul_eq_mul_of_dvd_left (hb : b ≠ 0) (hbc : b ∣ c) (h : b * a = c * d) : a = c / b * d := by obtain ⟨k, rfl⟩ := hbc rw [Int.mul_ediv_cancel_left _ hb] rwa [Int.mul_assoc, Int.mul_eq_mul_left_iff hb] at h lemma ofNat_add_negSucc_of_ge {m n : ℕ} (h : n.succ ≤ m) : ofNat m + -[n+1] = ofNat (m - n.succ) := by rw [negSucc_eq, ofNat_eq_natCast, ofNat_eq_natCast, ← Int.natCast_one, ← Int.natCast_add, ← Int.sub_eq_add_neg, ← Int.natCast_sub h] /-! #### `/` and ordering -/ lemma le_iff_pos_of_dvd (ha : 0 < a) (hab : a ∣ b) : a ≤ b ↔ 0 < b := ⟨Int.lt_of_lt_of_le ha, (Int.le_of_dvd · hab)⟩ lemma le_add_iff_lt_of_dvd_sub (ha : 0 < a) (hab : a ∣ c - b) : a + b ≤ c ↔ b < c := by rw [Int.add_le_iff_le_sub, ← Int.sub_pos, le_iff_pos_of_dvd ha hab] /-! ### sign -/ lemma sign_add_eq_of_sign_eq : ∀ {m n : ℤ}, m.sign = n.sign → (m + n).sign = n.sign := by have : (1 : ℤ) ≠ -1 := by decide rintro ((_ | m) | m) ((_ | n) | n) <;> simp [this, this.symm] <;> omega /-! ### toNat -/ /- The following lemma is non-confluent with ``` simp only [*, @Int.lt_toNat, CharP.cast_eq_zero, @Nat.cast_pred, Int.ofNat_toNat] ``` from the default simp set, which simplifies the LHS to `max i 0 - 1`. Therefore we mark this lemma as `@[simp high]`. -/ @[simp high] lemma toNat_pred_coe_of_pos {i : ℤ} (h : 0 < i) : ((i.toNat - 1 : ℕ) : ℤ) = i - 1 := by simp only [lt_toNat, Int.cast_ofNat_Int, h, natCast_pred_of_pos, Int.le_of_lt h, toNat_of_nonneg] lemma toNat_lt_of_ne_zero {n : ℕ} (hn : n ≠ 0) : m.toNat < n ↔ m < n := by cutsat @[deprecated (since := "2025-05-24")] alias toNat_lt'' := toNat_lt_of_ne_zero /-- The modulus of an integer by another as a natural. Uses the E-rounding convention. -/ def natMod (m n : ℤ) : ℕ := (m % n).toNat lemma natMod_lt {n : ℕ} (hn : n ≠ 0) : m.natMod n < n := (toNat_lt_of_ne_zero hn).2 <| emod_lt_of_pos _ <| by cutsat /-- For use in `Mathlib/Tactic/NormNum/Pow.lean` -/ @[simp] lemma pow_eq (m : ℤ) (n : ℕ) : m.pow n = m ^ n := rfl end Int
.lake/packages/mathlib/Mathlib/Data/Int/Basic.lean
import Mathlib.Data.Int.Init import Mathlib.Data.Nat.Basic import Mathlib.Logic.Nontrivial.Defs import Mathlib.Tactic.Conv import Mathlib.Tactic.Convert import Mathlib.Tactic.Lift import Mathlib.Tactic.OfNat /-! # Basic operations on the integers This file builds on `Data.Int.Init` by adding basic lemmas on integers. depending on Mathlib definitions. -/ open Nat namespace Int variable {a b c d m n : ℤ} -- TODO: Tag in Lean attribute [simp] natAbs_pos @[gcongr] alias ⟨_, GCongr.ofNat_le_ofNat⟩ := ofNat_le instance instNontrivial : Nontrivial ℤ := ⟨⟨0, 1, Int.zero_ne_one⟩⟩ @[simp] lemma ofNat_injective : Function.Injective ofNat := @Int.ofNat.inj section inductionOn' variable {C : ℤ → Sort*} (z b : ℤ) (H0 : C b) (Hs : ∀ k, b ≤ k → C k → C (k + 1)) (Hp : ∀ k ≤ b, C k → C (k - 1)) variable {z b H0 Hs Hp} lemma inductionOn'_add_one (hz : b ≤ z) : (z + 1).inductionOn' b H0 Hs Hp = Hs z hz (z.inductionOn' b H0 Hs Hp) := by apply cast_eq_iff_heq.mpr lift z - b to ℕ using Int.sub_nonneg.mpr hz with zb hzb rw [show z + 1 - b = zb + 1 by cutsat] have : b + zb = z := by omega subst this convert cast_heq _ _ rw [Int.inductionOn', cast_eq_iff_heq, ← hzb] end inductionOn' section strongRec variable {P : ℤ → Sort*} {lt : ∀ n < m, P n} {ge : ∀ n ≥ m, (∀ k < n, P k) → P n} lemma strongRec_of_ge : ∀ hn : m ≤ n, m.strongRec lt ge n = ge n hn fun k _ ↦ m.strongRec lt ge k := by refine m.strongRec (fun n hnm hmn ↦ (Int.not_lt.mpr hmn hnm).elim) (fun n _ ih hn ↦ ?_) n rw [Int.strongRec, dif_neg (Int.not_lt.mpr hn)] congr; revert ih refine n.inductionOn' m (fun _ ↦ ?_) (fun k hmk ih' ih ↦ ?_) (fun k hkm ih' _ ↦ ?_) <;> ext l hl · rw [inductionOn'_self, strongRec_of_lt hl] · rw [inductionOn'_add_one hmk]; split_ifs with hlm · rw [strongRec_of_lt hlm] · rw [ih' fun l hl ↦ ih l (Int.lt_trans hl k.lt_succ), ih _ hl] · rw [inductionOn'_sub_one hkm, ih'] exact fun l hlk hml ↦ (Int.not_lt.mpr hkm <| Int.lt_of_le_of_lt hml hlk).elim end strongRec /-! ### nat abs -/ lemma natAbs_surjective : natAbs.Surjective := fun n => ⟨n, natAbs_natCast n⟩ lemma pow_right_injective (h : 1 < a.natAbs) : ((a ^ ·) : ℕ → ℤ).Injective := by refine (?_ : (natAbs ∘ (a ^ · : ℕ → ℤ)).Injective).of_comp convert Nat.pow_right_injective h using 2 rw [Function.comp_apply, natAbs_pow] /-! ### dvd -/ @[norm_cast] theorem ofNat_dvd_natCast {x y : ℕ} : (ofNat(x) : ℤ) ∣ (y : ℤ) ↔ OfNat.ofNat x ∣ y := natCast_dvd_natCast @[norm_cast] theorem natCast_dvd_ofNat {x y : ℕ} : (x : ℤ) ∣ (ofNat(y) : ℤ) ↔ x ∣ OfNat.ofNat y := natCast_dvd_natCast lemma natCast_dvd {m : ℕ} : (m : ℤ) ∣ n ↔ m ∣ n.natAbs := by obtain hn | hn := natAbs_eq n <;> rw [hn] <;> simp [← natCast_dvd_natCast, Int.dvd_neg] lemma dvd_natCast {n : ℕ} : m ∣ (n : ℤ) ↔ m.natAbs ∣ n := by obtain hn | hn := natAbs_eq m <;> rw [hn] <;> simp [← natCast_dvd_natCast, Int.neg_dvd] lemma eq_zero_of_dvd_of_nonneg_of_lt (hm : 0 ≤ m) (hmn : m < n) (hnm : n ∣ m) : m = 0 := eq_zero_of_dvd_of_natAbs_lt_natAbs hnm (natAbs_lt_natAbs_of_nonneg_of_lt hm hmn) /-- If two integers are congruent to a sufficiently large modulus, they are equal. -/ lemma eq_of_mod_eq_of_natAbs_sub_lt_natAbs {a b c : ℤ} (h1 : a % b = c) (h2 : natAbs (a - c) < natAbs b) : a = c := Int.eq_of_sub_eq_zero (eq_zero_of_dvd_of_natAbs_lt_natAbs (dvd_self_sub_of_emod_eq h1) h2) lemma natAbs_le_of_dvd_ne_zero (hmn : m ∣ n) (hn : n ≠ 0) : natAbs m ≤ natAbs n := not_lt.mp (mt (eq_zero_of_dvd_of_natAbs_lt_natAbs hmn) hn) theorem gcd_emod (m n : ℤ) : (m % n).gcd n = m.gcd n := by conv_rhs => rw [← m.emod_add_mul_ediv n, gcd_add_mul_left_left] end Int
.lake/packages/mathlib/Mathlib/Data/Int/LeastGreatest.lean
import Mathlib.Algebra.Order.Group.OrderIso import Mathlib.Algebra.Ring.Int.Defs import Mathlib.Data.Nat.Find import Mathlib.Order.Bounds.Defs /-! # Least upper bound and greatest lower bound properties for integers In this file we prove that a bounded above nonempty set of integers has the greatest element, and a counterpart of this statement for the least element. ## Main definitions * `Int.leastOfBdd`: if `P : ℤ → Prop` is a decidable predicate, `b` is a lower bound of the set `{m | P m}`, and there exists `m : ℤ` such that `P m` (this time, no witness is required), then `Int.leastOfBdd` returns the least number `m` such that `P m`, together with proofs of `P m` and of the minimality. This definition is computable and does not rely on the axiom of choice. * `Int.greatestOfBdd`: a similar definition with all inequalities reversed. ## Main statements * `Int.exists_least_of_bdd`: if `P : ℤ → Prop` is a predicate such that the set `{m : P m}` is bounded below and nonempty, then this set has the least element. This lemma uses classical logic to avoid assumption `[DecidablePred P]`. See `Int.leastOfBdd` for a constructive counterpart. * `Int.coe_leastOfBdd_eq`: `(Int.leastOfBdd b Hb Hinh : ℤ)` does not depend on `b`. * `Int.exists_greatest_of_bdd`, `Int.coe_greatest_of_bdd_eq`: versions of the above lemmas with all inequalities reversed. ## Tags integer numbers, least element, greatest element -/ namespace Int /-- A computable version of `exists_least_of_bdd`: given a decidable predicate on the integers, with an explicit lower bound and a proof that it is somewhere true, return the least value for which the predicate is true. -/ def leastOfBdd {P : ℤ → Prop} [DecidablePred P] (b : ℤ) (Hb : ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : { lb : ℤ // P lb ∧ ∀ z : ℤ, P z → lb ≤ z } := have EX : ∃ n : ℕ, P (b + n) := let ⟨elt, Helt⟩ := Hinh match elt, le.dest (Hb _ Helt), Helt with | _, ⟨n, rfl⟩, Hn => ⟨n, Hn⟩ ⟨b + (Nat.find EX : ℤ), Nat.find_spec EX, fun z h => by obtain ⟨n, rfl⟩ := le.dest (Hb _ h); grw [Int.ofNat_le.2 <| Nat.find_min' EX h]⟩ /-- `Int.leastOfBdd` is the least integer satisfying a predicate which is false for all `z : ℤ` with `z < b` for some fixed `b : ℤ`. -/ lemma isLeast_coe_leastOfBdd {P : ℤ → Prop} [DecidablePred P] (b : ℤ) (Hb : ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : IsLeast {z | P z} (leastOfBdd b Hb Hinh : ℤ) := (leastOfBdd b Hb Hinh).2 /-- If `P : ℤ → Prop` is a predicate such that the set `{m : P m}` is bounded below and nonempty, then this set has the least element. This lemma uses classical logic to avoid assumption `[DecidablePred P]`. See `Int.leastOfBdd` for a constructive counterpart. -/ theorem exists_least_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ ∀ z : ℤ, P z → lb ≤ z := by classical let ⟨b, Hb⟩ := Hbdd let ⟨lb, H⟩ := leastOfBdd b Hb Hinh exact ⟨lb, H⟩ theorem coe_leastOfBdd_eq {P : ℤ → Prop} [DecidablePred P] {b b' : ℤ} (Hb : ∀ z : ℤ, P z → b ≤ z) (Hb' : ∀ z : ℤ, P z → b' ≤ z) (Hinh : ∃ z : ℤ, P z) : (leastOfBdd b Hb Hinh : ℤ) = leastOfBdd b' Hb' Hinh := by #adaptation_note /-- 2025-09-30 (https://github.com/leanprover/lean4/issues/10622) Used to be `grind` -/ rcases leastOfBdd b Hb Hinh with ⟨n, hn, h2n⟩ rcases leastOfBdd b' Hb' Hinh with ⟨n', hn', h2n'⟩ exact le_antisymm (h2n _ hn') (h2n' _ hn) /-- A computable version of `exists_greatest_of_bdd`: given a decidable predicate on the integers, with an explicit upper bound and a proof that it is somewhere true, return the greatest value for which the predicate is true. -/ def greatestOfBdd {P : ℤ → Prop} [DecidablePred P] (b : ℤ) (Hb : ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : { ub : ℤ // P ub ∧ ∀ z : ℤ, P z → z ≤ ub } := have Hbdd' : ∀ z : ℤ, P (-z) → -b ≤ z := fun _ h => neg_le.1 (Hb _ h) have Hinh' : ∃ z : ℤ, P (-z) := let ⟨elt, Helt⟩ := Hinh ⟨-elt, by rw [neg_neg]; exact Helt⟩ let ⟨lb, Plb, al⟩ := leastOfBdd (-b) Hbdd' Hinh' ⟨-lb, Plb, fun z h => le_neg.1 <| al _ <| by rwa [neg_neg]⟩ /-- `Int.greatestOfBdd` is the greatest integer satisfying a predicate which is false for all `z : ℤ` with `b < z` for some fixed `b : ℤ`. -/ lemma isGreatest_coe_greatestOfBdd {P : ℤ → Prop} [DecidablePred P] (b : ℤ) (Hb : ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : IsGreatest {z | P z} (greatestOfBdd b Hb Hinh : ℤ) := (greatestOfBdd b Hb Hinh).2 /-- If `P : ℤ → Prop` is a predicate such that the set `{m : P m}` is bounded above and nonempty, then this set has the greatest element. This lemma uses classical logic to avoid assumption `[DecidablePred P]`. See `Int.greatestOfBdd` for a constructive counterpart. -/ theorem exists_greatest_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ ∀ z : ℤ, P z → z ≤ ub := by classical let ⟨b, Hb⟩ := Hbdd let ⟨lb, H⟩ := greatestOfBdd b Hb Hinh exact ⟨lb, H⟩ theorem coe_greatestOfBdd_eq {P : ℤ → Prop} [DecidablePred P] {b b' : ℤ} (Hb : ∀ z : ℤ, P z → z ≤ b) (Hb' : ∀ z : ℤ, P z → z ≤ b') (Hinh : ∃ z : ℤ, P z) : (greatestOfBdd b Hb Hinh : ℤ) = greatestOfBdd b' Hb' Hinh := by #adaptation_note /-- 2025-09-30 (https://github.com/leanprover/lean4/issues/10622) Used to be `grind` -/ rcases greatestOfBdd b Hb Hinh with ⟨n, hn, h2n⟩ rcases greatestOfBdd b' Hb' Hinh with ⟨n', hn', h2n'⟩ exact le_antisymm (h2n' _ hn) (h2n _ hn') end Int
.lake/packages/mathlib/Mathlib/Data/Int/ConditionallyCompleteOrder.lean
import Mathlib.Order.ConditionallyCompleteLattice.Basic import Mathlib.Data.Int.LeastGreatest /-! ## `ℤ` forms a conditionally complete linear order The integers form a conditionally complete linear order. -/ open Int noncomputable section open scoped Classical in instance instConditionallyCompleteLinearOrder : ConditionallyCompleteLinearOrder ℤ where __ := instLinearOrder __ := LinearOrder.toLattice sSup s := if h : s.Nonempty ∧ BddAbove s then greatestOfBdd (Classical.choose h.2) (Classical.choose_spec h.2) h.1 else 0 sInf s := if h : s.Nonempty ∧ BddBelow s then leastOfBdd (Classical.choose h.2) (Classical.choose_spec h.2) h.1 else 0 le_csSup s n hs hns := by have : s.Nonempty ∧ BddAbove s := ⟨⟨n, hns⟩, hs⟩ simp only [dif_pos this] exact (greatestOfBdd _ _ _).2.2 n hns csSup_le s n hs hns := by have : s.Nonempty ∧ BddAbove s := ⟨hs, ⟨n, hns⟩⟩ simp only [dif_pos this] exact hns (greatestOfBdd _ (Classical.choose_spec this.2) _).2.1 csInf_le s n hs hns := by have : s.Nonempty ∧ BddBelow s := ⟨⟨n, hns⟩, hs⟩ simp only [dif_pos this] exact (leastOfBdd _ _ _).2.2 n hns le_csInf s n hs hns := by have : s.Nonempty ∧ BddBelow s := ⟨hs, ⟨n, hns⟩⟩ simp only [dif_pos this] exact hns (leastOfBdd _ (Classical.choose_spec this.2) _).2.1 csSup_of_not_bddAbove := fun s hs ↦ by simp [hs] csInf_of_not_bddBelow := fun s hs ↦ by simp [hs] namespace Int theorem csSup_eq_greatest_of_bdd {s : Set ℤ} [DecidablePred (· ∈ s)] (b : ℤ) (Hb : ∀ z ∈ s, z ≤ b) (Hinh : ∃ z : ℤ, z ∈ s) : sSup s = greatestOfBdd b Hb Hinh := by have : s.Nonempty ∧ BddAbove s := ⟨Hinh, b, Hb⟩ simp only [sSup, dif_pos this] convert (coe_greatestOfBdd_eq Hb (Classical.choose_spec (⟨b, Hb⟩ : BddAbove s)) Hinh).symm @[simp] theorem csSup_empty : sSup (∅ : Set ℤ) = 0 := dif_neg (by simp) theorem csSup_of_not_bdd_above {s : Set ℤ} (h : ¬BddAbove s) : sSup s = 0 := dif_neg (by simp [h]) theorem csInf_eq_least_of_bdd {s : Set ℤ} [DecidablePred (· ∈ s)] (b : ℤ) (Hb : ∀ z ∈ s, b ≤ z) (Hinh : ∃ z : ℤ, z ∈ s) : sInf s = leastOfBdd b Hb Hinh := by have : s.Nonempty ∧ BddBelow s := ⟨Hinh, b, Hb⟩ simp only [sInf, dif_pos this] convert (coe_leastOfBdd_eq Hb (Classical.choose_spec (⟨b, Hb⟩ : BddBelow s)) Hinh).symm @[simp] theorem csInf_empty : sInf (∅ : Set ℤ) = 0 := dif_neg (by simp) theorem csInf_of_not_bdd_below {s : Set ℤ} (h : ¬BddBelow s) : sInf s = 0 := dif_neg (by simp [h]) theorem csSup_mem {s : Set ℤ} (h1 : s.Nonempty) (h2 : BddAbove s) : sSup s ∈ s := by convert (greatestOfBdd _ (Classical.choose_spec h2) h1).2.1 exact dif_pos ⟨h1, h2⟩ theorem csInf_mem {s : Set ℤ} (h1 : s.Nonempty) (h2 : BddBelow s) : sInf s ∈ s := by convert (leastOfBdd _ (Classical.choose_spec h2) h1).2.1 exact dif_pos ⟨h1, h2⟩ end Int end -- this example tests that the `Lattice ℤ` instance is computable; -- i.e., that it is not found via the noncomputable instance in this file. example : Lattice ℤ := inferInstance