path
stringlengths
11
71
content
stringlengths
75
124k
Data\Multiset\Sections.lean
/- Copyright (c) 2018 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes HΓΆlzl -/ import Mathlib.Data.Multiset.Bind /-! # Sections of a multiset -/ assert_not_exists Ring namespace Multiset variable {Ξ± : Type*} section Sections /-- The sections of a multiset of multisets `s` consists of all those multisets which can be put in bijection with `s`, so each element is a member of the corresponding multiset. -/ def Sections (s : Multiset (Multiset Ξ±)) : Multiset (Multiset Ξ±) := Multiset.recOn s {0} (fun s _ c => s.bind fun a => c.map (Multiset.cons a)) fun aβ‚€ a₁ _ pi => by simp [map_bind, bind_bind aβ‚€ a₁, cons_swap] @[simp] theorem sections_zero : Sections (0 : Multiset (Multiset Ξ±)) = {0} := rfl @[simp] theorem sections_cons (s : Multiset (Multiset Ξ±)) (m : Multiset Ξ±) : Sections (m ::β‚˜ s) = m.bind fun a => (Sections s).map (Multiset.cons a) := recOn_cons m s theorem coe_sections : βˆ€ l : List (List Ξ±), Sections (l.map fun l : List Ξ± => (l : Multiset Ξ±) : Multiset (Multiset Ξ±)) = (l.sections.map fun l : List Ξ± => (l : Multiset Ξ±) : Multiset (Multiset Ξ±)) | [] => rfl | a :: l => by simp only [List.map_cons, List.sections] rw [← cons_coe, sections_cons, bind_map_comm, coe_sections l] simp [List.sections, (Β· ∘ Β·), List.bind] @[simp] theorem sections_add (s t : Multiset (Multiset Ξ±)) : Sections (s + t) = (Sections s).bind fun m => (Sections t).map (m + Β·) := Multiset.induction_on s (by simp) fun a s ih => by simp [ih, bind_assoc, map_bind, bind_map] theorem mem_sections {s : Multiset (Multiset Ξ±)} : βˆ€ {a}, a ∈ Sections s ↔ s.Rel (fun s a => a ∈ s) a := by induction s using Multiset.induction_on with | empty => simp | cons _ _ ih => simp [ih, rel_cons_left, eq_comm] theorem card_sections {s : Multiset (Multiset Ξ±)} : card (Sections s) = prod (s.map card) := Multiset.induction_on s (by simp) (by simp (config := { contextual := true })) end Sections end Multiset
Data\Multiset\Sort.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Data.List.Sort import Mathlib.Data.Multiset.Basic /-! # Construct a sorted list from a multiset. -/ namespace Multiset open List variable {Ξ± : Type*} section sort variable (r : Ξ± β†’ Ξ± β†’ Prop) [DecidableRel r] [IsTrans Ξ± r] [IsAntisymm Ξ± r] [IsTotal Ξ± r] /-- `sort s` constructs a sorted list from the multiset `s`. (Uses merge sort algorithm.) -/ def sort (s : Multiset Ξ±) : List Ξ± := Quot.liftOn s (mergeSort r) fun _ _ h => eq_of_perm_of_sorted ((perm_mergeSort _ _).trans <| h.trans (perm_mergeSort _ _).symm) (sorted_mergeSort r _) (sorted_mergeSort r _) @[simp] theorem coe_sort (l : List Ξ±) : sort r l = mergeSort r l := rfl @[simp] theorem sort_sorted (s : Multiset Ξ±) : Sorted r (sort r s) := Quot.inductionOn s fun _l => sorted_mergeSort r _ @[simp] theorem sort_eq (s : Multiset Ξ±) : ↑(sort r s) = s := Quot.inductionOn s fun _ => Quot.sound <| perm_mergeSort _ _ @[simp] theorem mem_sort {s : Multiset Ξ±} {a : Ξ±} : a ∈ sort r s ↔ a ∈ s := by rw [← mem_coe, sort_eq] @[simp] theorem length_sort {s : Multiset Ξ±} : (sort r s).length = card s := Quot.inductionOn s <| length_mergeSort _ @[simp] theorem sort_zero : sort r 0 = [] := List.mergeSort_nil r @[simp] theorem sort_singleton (a : Ξ±) : sort r {a} = [a] := List.mergeSort_singleton r a end sort -- TODO: use a sort order if available, gh-18166 unsafe instance [Repr Ξ±] : Repr (Multiset Ξ±) where reprPrec s _ := if Multiset.card s = 0 then "0" else Std.Format.bracket "{" (Std.Format.joinSep (s.unquot.map repr) ("," ++ Std.Format.line)) "}" end Multiset
Data\Multiset\Sum.lean
/- Copyright (c) 2022 YaΓ«l Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: YaΓ«l Dillies -/ import Mathlib.Data.Multiset.Nodup /-! # Disjoint sum of multisets This file defines the disjoint sum of two multisets as `Multiset (Ξ± βŠ• Ξ²)`. Beware not to confuse with the `Multiset.sum` operation which computes the additive sum. ## Main declarations * `Multiset.disjSum`: `s.disjSum t` is the disjoint sum of `s` and `t`. -/ open Sum namespace Multiset variable {Ξ± Ξ² : Type*} (s : Multiset Ξ±) (t : Multiset Ξ²) /-- Disjoint sum of multisets. -/ def disjSum : Multiset (Ξ± βŠ• Ξ²) := s.map inl + t.map inr @[simp] theorem zero_disjSum : (0 : Multiset Ξ±).disjSum t = t.map inr := zero_add _ @[simp] theorem disjSum_zero : s.disjSum (0 : Multiset Ξ²) = s.map inl := add_zero _ @[simp] theorem card_disjSum : Multiset.card (s.disjSum t) = Multiset.card s + Multiset.card t := by rw [disjSum, card_add, card_map, card_map] variable {s t} {s₁ sβ‚‚ : Multiset Ξ±} {t₁ tβ‚‚ : Multiset Ξ²} {a : Ξ±} {b : Ξ²} {x : Ξ± βŠ• Ξ²} theorem mem_disjSum : x ∈ s.disjSum t ↔ (βˆƒ a, a ∈ s ∧ inl a = x) ∨ βˆƒ b, b ∈ t ∧ inr b = x := by simp_rw [disjSum, mem_add, mem_map] @[simp] theorem inl_mem_disjSum : inl a ∈ s.disjSum t ↔ a ∈ s := by rw [mem_disjSum, or_iff_left] -- Porting note: Previous code for L62 was: simp only [exists_eq_right] Β· simp only [inl.injEq, exists_eq_right] rintro ⟨b, _, hb⟩ exact inr_ne_inl hb @[simp] theorem inr_mem_disjSum : inr b ∈ s.disjSum t ↔ b ∈ t := by rw [mem_disjSum, or_iff_right] -- Porting note: Previous code for L72 was: simp only [exists_eq_right] Β· simp only [inr.injEq, exists_eq_right] rintro ⟨a, _, ha⟩ exact inl_ne_inr ha theorem disjSum_mono (hs : s₁ ≀ sβ‚‚) (ht : t₁ ≀ tβ‚‚) : s₁.disjSum t₁ ≀ sβ‚‚.disjSum tβ‚‚ := add_le_add (map_le_map hs) (map_le_map ht) theorem disjSum_mono_left (t : Multiset Ξ²) : Monotone fun s : Multiset Ξ± => s.disjSum t := fun _ _ hs => add_le_add_right (map_le_map hs) _ theorem disjSum_mono_right (s : Multiset Ξ±) : Monotone (s.disjSum : Multiset Ξ² β†’ Multiset (Ξ± βŠ• Ξ²)) := fun _ _ ht => add_le_add_left (map_le_map ht) _ theorem disjSum_lt_disjSum_of_lt_of_le (hs : s₁ < sβ‚‚) (ht : t₁ ≀ tβ‚‚) : s₁.disjSum t₁ < sβ‚‚.disjSum tβ‚‚ := add_lt_add_of_lt_of_le (map_lt_map hs) (map_le_map ht) theorem disjSum_lt_disjSum_of_le_of_lt (hs : s₁ ≀ sβ‚‚) (ht : t₁ < tβ‚‚) : s₁.disjSum t₁ < sβ‚‚.disjSum tβ‚‚ := add_lt_add_of_le_of_lt (map_le_map hs) (map_lt_map ht) theorem disjSum_strictMono_left (t : Multiset Ξ²) : StrictMono fun s : Multiset Ξ± => s.disjSum t := fun _ _ hs => disjSum_lt_disjSum_of_lt_of_le hs le_rfl theorem disjSum_strictMono_right (s : Multiset Ξ±) : StrictMono (s.disjSum : Multiset Ξ² β†’ Multiset (Ξ± βŠ• Ξ²)) := fun _ _ => disjSum_lt_disjSum_of_le_of_lt le_rfl protected theorem Nodup.disjSum (hs : s.Nodup) (ht : t.Nodup) : (s.disjSum t).Nodup := by refine ((hs.map inl_injective).add_iff <| ht.map inr_injective).2 fun x hs ht => ?_ rw [Multiset.mem_map] at hs ht obtain ⟨a, _, rfl⟩ := hs obtain ⟨b, _, h⟩ := ht exact inr_ne_inl h end Multiset
Data\Multiset\Sym.lean
/- Copyright (c) 2023 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.Data.List.Sym /-! # Unordered tuples of elements of a multiset Defines `Multiset.sym` and the specialized `Multiset.sym2` for computing multisets of all unordered n-tuples from a given multiset. These are multiset versions of `Nat.multichoose`. ## Main declarations * `Multiset.sym2`: `xs.sym2` is the multiset of all unordered pairs of elements from `xs`, with multiplicity. The multiset's values are in `Sym2 Ξ±`. ## TODO * Once `List.Perm.sym` is defined, define ```lean protected def sym (n : Nat) (m : Multiset Ξ±) : Multiset (Sym Ξ± n) := m.liftOn (fun xs => xs.sym n) (List.perm.sym n) ``` and then use this to remove the `DecidableEq` assumption from `Finset.sym`. * `theorem injective_sym2 : Function.Injective (Multiset.sym2 : Multiset Ξ± β†’ _)` * `theorem strictMono_sym2 : StrictMono (Multiset.sym2 : Multiset Ξ± β†’ _)` -/ namespace Multiset variable {Ξ± Ξ² : Type*} section Sym2 /-- `m.sym2` is the multiset of all unordered pairs of elements from `m`, with multiplicity. If `m` has no duplicates then neither does `m.sym2`. -/ protected def sym2 (m : Multiset Ξ±) : Multiset (Sym2 Ξ±) := m.liftOn (fun xs => xs.sym2) fun _ _ h => by rw [coe_eq_coe]; exact h.sym2 @[simp] theorem sym2_coe (xs : List Ξ±) : (xs : Multiset Ξ±).sym2 = xs.sym2 := rfl @[simp] theorem sym2_eq_zero_iff {m : Multiset Ξ±} : m.sym2 = 0 ↔ m = 0 := m.inductionOn fun xs => by simp @[simp] theorem sym2_zero : (0 : Multiset Ξ±).sym2 = 0 := rfl theorem sym2_cons (a : Ξ±) (m : Multiset Ξ±) : (m.cons a).sym2 = ((m.cons a).map <| fun b => s(a, b)) + m.sym2 := m.inductionOn fun _ => rfl theorem sym2_map (f : Ξ± β†’ Ξ²) (m : Multiset Ξ±) : (m.map f).sym2 = m.sym2.map (Sym2.map f) := m.inductionOn fun xs => by simp [List.sym2_map] theorem mk_mem_sym2_iff {m : Multiset Ξ±} {a b : Ξ±} : s(a, b) ∈ m.sym2 ↔ a ∈ m ∧ b ∈ m := m.inductionOn fun xs => by simp [List.mk_mem_sym2_iff] theorem mem_sym2_iff {m : Multiset Ξ±} {z : Sym2 Ξ±} : z ∈ m.sym2 ↔ βˆ€ y ∈ z, y ∈ m := m.inductionOn fun xs => by simp [List.mem_sym2_iff] protected theorem Nodup.sym2 {m : Multiset Ξ±} (h : m.Nodup) : m.sym2.Nodup := m.inductionOn (fun _ h => List.Nodup.sym2 h) h open scoped List in @[simp, mono] theorem sym2_mono {m m' : Multiset Ξ±} (h : m ≀ m') : m.sym2 ≀ m'.sym2 := by refine Quotient.inductionOnβ‚‚ m m' (fun xs ys h => ?_) h suffices xs <+~ ys from this.sym2 simpa only [quot_mk_to_coe, coe_le, sym2_coe] using h theorem monotone_sym2 : Monotone (Multiset.sym2 : Multiset Ξ± β†’ _) := fun _ _ => sym2_mono theorem card_sym2 {m : Multiset Ξ±} : Multiset.card m.sym2 = Nat.choose (Multiset.card m + 1) 2 := by refine m.inductionOn fun xs => ?_ simp [List.length_sym2] theorem dedup_sym2 [DecidableEq Ξ±] (m : Multiset Ξ±) : m.sym2.dedup = m.dedup.sym2 := m.inductionOn fun xs => by simp [List.dedup_sym2] end Sym2 end Multiset
Data\Nat\BitIndices.lean
/- Copyright (c) 2024 Peter Nelson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Peter Nelson -/ import Mathlib.Data.List.Sort import Mathlib.Data.Nat.Bitwise import Mathlib.Algebra.BigOperators.Ring.List import Mathlib.Algebra.Order.BigOperators.Group.List import Mathlib.Algebra.Order.Sub.Defs import Mathlib.Algebra.Star.Order /-! # Bit Indices Given `n : β„•`, we define `Nat.bitIndices n`, which is the `List` of indices of `1`s in the binary expansion of `n`. If `s : Finset β„•` and `n = βˆ‘ i in s, 2^i`, then `Nat.bitIndices n` is the sorted list of elements of `s`. The lemma `twoPowSum_bitIndices` proves that summing `2 ^ i` over this list gives `n`. This is used in `Combinatorics.colex` to construct a bijection `equivBitIndices : β„• ≃ Finset β„•`. ## TODO Relate the material in this file to `Nat.digits` and `Nat.bits`. -/ open List namespace Nat variable {a n : β„•} /-- The function which maps each natural number `βˆ‘ i in s, 2^i` to the list of elements of `s` in increasing order. -/ def bitIndices (n : β„•) : List β„• := @binaryRec (fun _ ↦ List β„•) [] (fun b _ s ↦ b.casesOn (s.map (Β· + 1)) (0 :: s.map (Β· + 1))) n @[simp] theorem bitIndices_zero : bitIndices 0 = [] := by rfl @[simp] theorem bitIndices_one : bitIndices 1 = [0] := by rfl theorem bitIndices_bit_true (n : β„•) : bitIndices (bit true n) = 0 :: ((bitIndices n).map (Β· + 1)) := binaryRec_eq rfl _ _ theorem bitIndices_bit_false (n : β„•) : bitIndices (bit false n) = (bitIndices n).map (Β· + 1) := binaryRec_eq rfl _ _ @[simp] theorem bitIndices_two_mul_add_one (n : β„•) : bitIndices (2 * n + 1) = 0 :: (bitIndices n).map (Β· + 1) := by rw [← bitIndices_bit_true, bit_true] @[simp] theorem bitIndices_two_mul (n : β„•) : bitIndices (2 * n) = (bitIndices n).map (Β· + 1) := by rw [← bitIndices_bit_false, bit_false] @[simp] theorem bitIndices_sorted {n : β„•} : n.bitIndices.Sorted (Β· < Β·) := by induction' n using binaryRec with b n hs Β· simp suffices List.Pairwise (fun a b ↦ a < b) n.bitIndices by cases b <;> simpa [List.Sorted, bit_false, bit_true, List.pairwise_map] exact List.Pairwise.imp (by simp) hs @[simp] theorem bitIndices_two_pow_mul (k n : β„•) : bitIndices (2^k * n) = (bitIndices n).map (Β· + k) := by induction' k with k ih Β· simp rw [add_comm, pow_add, pow_one, mul_assoc, bitIndices_two_mul, ih, List.map_map, comp_add_right] simp [add_comm (a := 1)] @[simp] theorem bitIndices_two_pow (k : β„•) : bitIndices (2^k) = [k] := by rw [← mul_one (a := 2^k), bitIndices_two_pow_mul]; simp @[simp] theorem twoPowSum_bitIndices (n : β„•) : (n.bitIndices.map (fun i ↦ 2 ^ i)).sum = n := by induction' n using binaryRec with b n hs Β· simp have hrw : (fun i ↦ 2^i) ∘ (fun x ↦ x+1) = fun i ↦ 2 * 2 ^ i := by ext i; simp [pow_add, mul_comm] cases b Β· simpa [hrw, List.sum_map_mul_left] simp [hrw, List.sum_map_mul_left, hs, add_comm (a := 1)] /-- Together with `Nat.twoPowSum_bitIndices`, this implies a bijection between `β„•` and `Finset β„•`. See `Finset.equivBitIndices` for this bijection. -/ theorem bitIndices_twoPowsum {L : List β„•} (hL : List.Sorted (Β· < Β·) L) : (L.map (fun i ↦ 2^i)).sum.bitIndices = L := by cases' L with a L Β· simp obtain ⟨haL, hL⟩ := sorted_cons.1 hL simp_rw [Nat.lt_iff_add_one_le] at haL have h' : βˆƒ (Lβ‚€ : List β„•), Lβ‚€.Sorted (Β· < Β·) ∧ L = Lβ‚€.map (Β· + a + 1) := by refine ⟨L.map (Β· - (a+1)), ?_, ?_⟩ Β· rwa [Sorted, pairwise_map, Pairwise.and_mem, Pairwise.iff (S := fun x y ↦ x ∈ L ∧ y ∈ L ∧ x < y), ← Pairwise.and_mem] simp only [and_congr_right_iff] exact fun x y hx _ ↦ by rw [tsub_lt_tsub_iff_right (haL _ hx)] have h' : βˆ€ x ∈ L, ((fun x ↦ x + a + 1) ∘ (fun x ↦ x - (a + 1))) x = x := fun x hx ↦ by simp only [add_assoc, Function.comp_apply]; rw [tsub_add_cancel_of_le (haL _ hx)] simp [List.map_congr_left h'] obtain ⟨Lβ‚€, hLβ‚€, rfl⟩ := h' have _ : Lβ‚€.length < (a :: (Lβ‚€.map (Β· + a + 1))).length := by simp have hrw : (2^Β·) ∘ (Β· + a + 1) = fun i ↦ 2^a * (2 * 2^i) := by ext x; simp only [Function.comp_apply, pow_add, pow_one]; ac_rfl simp only [List.map_cons, List.map_map, List.sum_map_mul_left, List.sum_cons, hrw] nth_rw 1 [← mul_one (a := 2^a)] rw [← mul_add, bitIndices_two_pow_mul, add_comm, bitIndices_two_mul_add_one, bitIndices_twoPowsum hLβ‚€] simp [add_comm (a := 1), add_assoc] termination_by L.length theorem two_pow_le_of_mem_bitIndices (ha : a ∈ n.bitIndices) : 2^a ≀ n := by rw [← twoPowSum_bitIndices n] exact List.single_le_sum (by simp) _ <| mem_map_of_mem _ ha theorem not_mem_bitIndices_self (n : β„•) : n βˆ‰ n.bitIndices := fun h ↦ (lt_two_pow n).not_le <| two_pow_le_of_mem_bitIndices h end Nat
Data\Nat\Bits.lean
/- Copyright (c) 2022 Praneeth Kolichala. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Praneeth Kolichala -/ import Mathlib.Algebra.Group.Basic import Mathlib.Algebra.Group.Nat import Mathlib.Data.Nat.Defs import Mathlib.Init.Data.List.Basic import Mathlib.Tactic.Convert import Mathlib.Tactic.GeneralizeProofs import Mathlib.Tactic.Says /-! # Additional properties of binary recursion on `Nat` This file documents additional properties of binary recursion, which allows us to more easily work with operations which do depend on the number of leading zeros in the binary representation of `n`. For example, we can more easily work with `Nat.bits` and `Nat.size`. See also: `Nat.bitwise`, `Nat.pow` (for various lemmas about `size` and `shiftLeft`/`shiftRight`), and `Nat.digits`. -/ -- Once we're in the `Nat` namespace, `xor` will inconveniently resolve to `Nat.xor`. /-- `bxor` denotes the `xor` function i.e. the exclusive-or function on type `Bool`. -/ local notation "bxor" => _root_.xor namespace Nat universe u variable {m n : β„•} /-- `boddDiv2 n` returns a 2-tuple of type `(Bool, Nat)` where the `Bool` value indicates whether `n` is odd or not and the `Nat` value returns `⌊n/2βŒ‹` -/ def boddDiv2 : β„• β†’ Bool Γ— β„• | 0 => (false, 0) | succ n => match boddDiv2 n with | (false, m) => (true, m) | (true, m) => (false, succ m) /-- `div2 n = ⌊n/2βŒ‹` the greatest integer smaller than `n/2`-/ def div2 (n : β„•) : β„• := (boddDiv2 n).2 /-- `bodd n` returns `true` if `n` is odd-/ def bodd (n : β„•) : Bool := (boddDiv2 n).1 @[simp] lemma bodd_zero : bodd 0 = false := rfl lemma bodd_one : bodd 1 = true := rfl lemma bodd_two : bodd 2 = false := rfl @[simp] lemma bodd_succ (n : β„•) : bodd (succ n) = not (bodd n) := by simp only [bodd, boddDiv2] let ⟨b,m⟩ := boddDiv2 n cases b <;> rfl @[simp] lemma bodd_add (m n : β„•) : bodd (m + n) = bxor (bodd m) (bodd n) := by induction n case zero => simp case succ n ih => simp [← Nat.add_assoc, Bool.xor_not, ih] @[simp] lemma bodd_mul (m n : β„•) : bodd (m * n) = (bodd m && bodd n) := by induction' n with n IH Β· simp Β· simp only [mul_succ, bodd_add, IH, bodd_succ] cases bodd m <;> cases bodd n <;> rfl lemma mod_two_of_bodd (n : β„•) : n % 2 = cond (bodd n) 1 0 := by have := congr_arg bodd (mod_add_div n 2) simp? [not] at this says simp only [bodd_add, bodd_mul, bodd_succ, not, bodd_zero, Bool.false_and, Bool.bne_false] at this have _ : βˆ€ b, and false b = false := by intro b cases b <;> rfl have _ : βˆ€ b, bxor b false = b := by intro b cases b <;> rfl rw [← this] cases' mod_two_eq_zero_or_one n with h h <;> rw [h] <;> rfl @[simp] lemma div2_zero : div2 0 = 0 := rfl lemma div2_one : div2 1 = 0 := rfl lemma div2_two : div2 2 = 1 := rfl @[simp] lemma div2_succ (n : β„•) : div2 (succ n) = cond (bodd n) (succ (div2 n)) (div2 n) := by simp only [bodd, boddDiv2, div2] rcases boddDiv2 n with ⟨_|_, _⟩ <;> simp attribute [local simp] Nat.add_comm Nat.add_assoc Nat.add_left_comm Nat.mul_comm Nat.mul_assoc lemma bodd_add_div2 : βˆ€ n, cond (bodd n) 1 0 + 2 * div2 n = n | 0 => rfl | succ n => by simp only [bodd_succ, Bool.cond_not, div2_succ, Nat.mul_comm] refine Eq.trans ?_ (congr_arg succ (bodd_add_div2 n)) cases bodd n Β· simp Β· simp; omega lemma div2_val (n) : div2 n = n / 2 := by refine Nat.eq_of_mul_eq_mul_left (by decide) (Nat.add_left_cancel (Eq.trans ?_ (Nat.mod_add_div n 2).symm)) rw [mod_two_of_bodd, bodd_add_div2] /-- `bit b` appends the digit `b` to the binary representation of its natural number input. -/ def bit (b : Bool) : β„• β†’ β„• := cond b (2 * Β· + 1) (2 * Β·) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by cases b <;> rfl lemma bit_decomp (n : Nat) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans <| (Nat.add_comm _ _).trans <| bodd_add_div2 _ /-- For a predicate `C : Nat β†’ Sort*`, if instances can be constructed for natural numbers of the form `bit b n`, they can be constructed for any given natural number. -/ def bitCasesOn {C : Nat β†’ Sort u} (n) (h : βˆ€ b n, C (bit b n)) : C n := bit_decomp n β–Έ h _ _ lemma bit_zero : bit false 0 = 0 := rfl /-- `shiftLeft' b m n` performs a left shift of `m` `n` times and adds the bit `b` as the least significant bit each time. Returns the corresponding natural number-/ def shiftLeft' (b : Bool) (m : β„•) : β„• β†’ β„• | 0 => m | n + 1 => bit b (shiftLeft' b m n) @[simp] lemma shiftLeft'_false : βˆ€ n, shiftLeft' false m n = m <<< n | 0 => rfl | n + 1 => by have : 2 * (m * 2^n) = 2^(n+1)*m := by rw [Nat.mul_comm, Nat.mul_assoc, ← Nat.pow_succ]; simp simp [shiftLeft_eq, shiftLeft', bit_val, shiftLeft'_false, this] /-- Lean takes the unprimed name for `Nat.shiftLeft_eq m n : m <<< n = m * 2 ^ n`. -/ @[simp] lemma shiftLeft_eq' (m n : Nat) : shiftLeft m n = m <<< n := rfl @[simp] lemma shiftRight_eq (m n : Nat) : shiftRight m n = m >>> n := rfl lemma binaryRec_decreasing (h : n β‰  0) : div2 n < n := by rw [div2_val] apply (div_lt_iff_lt_mul <| succ_pos 1).2 have := Nat.mul_lt_mul_of_pos_left (lt_succ_self 1) (lt_of_le_of_ne n.zero_le h.symm) rwa [Nat.mul_one] at this /-- A recursion principle for `bit` representations of natural numbers. For a predicate `C : Nat β†’ Sort*`, if instances can be constructed for natural numbers of the form `bit b n`, they can be constructed for all natural numbers. -/ def binaryRec {C : Nat β†’ Sort u} (z : C 0) (f : βˆ€ b n, C n β†’ C (bit b n)) : βˆ€ n, C n := fun n => if n0 : n = 0 then by simp only [n0] exact z else by let n' := div2 n have _x : bit (bodd n) n' = n := by apply bit_decomp n rw [← _x] exact f (bodd n) n' (binaryRec z f n') decreasing_by exact binaryRec_decreasing n0 /-- `size n` : Returns the size of a natural number in bits i.e. the length of its binary representation -/ def size : β„• β†’ β„• := binaryRec 0 fun _ _ => succ /-- `bits n` returns a list of Bools which correspond to the binary representation of n, where the head of the list represents the least significant bit -/ def bits : β„• β†’ List Bool := binaryRec [] fun b _ IH => b :: IH /-- `ldiff a b` performs bitwise set difference. For each corresponding pair of bits taken as booleans, say `aα΅’` and `bα΅’`, it applies the boolean operation `aα΅’ ∧ Β¬bα΅’` to obtain the `iα΅—Κ°` bit of the result. -/ def ldiff : β„• β†’ β„• β†’ β„• := bitwise fun a b => a && not b @[simp] lemma binaryRec_zero {C : Nat β†’ Sort u} (z : C 0) (f : βˆ€ b n, C n β†’ C (bit b n)) : binaryRec z f 0 = z := by rw [binaryRec] rfl /-! bitwise ops -/ lemma bodd_bit (b n) : bodd (bit b n) = b := by rw [bit_val] simp only [Nat.mul_comm, Nat.add_comm, bodd_add, bodd_mul, bodd_succ, bodd_zero, Bool.not_false, Bool.not_true, Bool.and_false, Bool.xor_false] cases b <;> cases bodd n <;> rfl lemma div2_bit (b n) : div2 (bit b n) = n := by rw [bit_val, div2_val, Nat.add_comm, add_mul_div_left, div_eq_of_lt, Nat.zero_add] <;> cases b <;> decide lemma shiftLeft'_add (b m n) : βˆ€ k, shiftLeft' b m (n + k) = shiftLeft' b (shiftLeft' b m n) k | 0 => rfl | k + 1 => congr_arg (bit b) (shiftLeft'_add b m n k) lemma shiftLeft'_sub (b m) : βˆ€ {n k}, k ≀ n β†’ shiftLeft' b m (n - k) = (shiftLeft' b m n) >>> k | n, 0, _ => rfl | n + 1, k + 1, h => by rw [succ_sub_succ_eq_sub, shiftLeft', Nat.add_comm, shiftRight_add] simp only [shiftLeft'_sub, Nat.le_of_succ_le_succ h, shiftRight_succ, shiftRight_zero] simp [← div2_val, div2_bit] lemma shiftLeft_sub : βˆ€ (m : Nat) {n k}, k ≀ n β†’ m <<< (n - k) = (m <<< n) >>> k := fun _ _ _ hk => by simp only [← shiftLeft'_false, shiftLeft'_sub false _ hk] -- Not a `simp` lemma, as later `simp` will be able to prove this. lemma testBit_bit_zero (b n) : testBit (bit b n) 0 = b := by rw [testBit, bit] cases b Β· simp [← Nat.mul_two] Β· simp [← Nat.mul_two] lemma bodd_eq_one_and_ne_zero : βˆ€ n, bodd n = (1 &&& n != 0) | 0 => rfl | 1 => rfl | n + 2 => by simpa using bodd_eq_one_and_ne_zero n lemma testBit_bit_succ (m b n) : testBit (bit b n) (succ m) = testBit n m := by have : bodd (((bit b n) >>> 1) >>> m) = bodd (n >>> m) := by simp only [shiftRight_eq_div_pow] simp [← div2_val, div2_bit] rw [← shiftRight_add, Nat.add_comm] at this simp only [bodd_eq_one_and_ne_zero] at this exact this lemma binaryRec_eq {C : Nat β†’ Sort u} {z : C 0} {f : βˆ€ b n, C n β†’ C (bit b n)} (h : f false 0 z = z) (b n) : binaryRec z f (bit b n) = f b n (binaryRec z f n) := by rw [binaryRec] split_ifs with h' Β· generalize binaryRec z f (bit b n) = e revert e have bf := bodd_bit b n have n0 := div2_bit b n rw [h'] at bf n0 simp only [bodd_zero, div2_zero] at bf n0 subst bf n0 rw [binaryRec_zero] intros rw [h, eq_mpr_eq_cast, cast_eq] Β· simp only; generalize_proofs h revert h rw [bodd_bit, div2_bit] intros; simp only [eq_mpr_eq_cast, cast_eq] /-! ### `boddDiv2_eq` and `bodd` -/ @[simp] theorem boddDiv2_eq (n : β„•) : boddDiv2 n = (bodd n, div2 n) := rfl @[simp] theorem div2_bit0 (n) : div2 (2 * n) = n := div2_bit false n -- simp can prove this theorem div2_bit1 (n) : div2 (2 * n + 1) = n := div2_bit true n /-! ### `bit0` and `bit1` -/ theorem bit_add : βˆ€ (b : Bool) (n m : β„•), bit b (n + m) = bit false n + bit b m | true, _, _ => by dsimp [bit]; omega | false, _, _ => by dsimp [bit]; omega theorem bit_add' : βˆ€ (b : Bool) (n m : β„•), bit b (n + m) = bit b n + bit false m | true, _, _ => by dsimp [bit]; omega | false, _, _ => by dsimp [bit]; omega theorem bit_ne_zero (b) {n} (h : n β‰  0) : bit b n β‰  0 := by cases b <;> dsimp [bit] <;> omega @[simp] theorem bitCasesOn_bit {C : β„• β†’ Sort u} (H : βˆ€ b n, C (bit b n)) (b : Bool) (n : β„•) : bitCasesOn (bit b n) H = H b n := eq_of_heq <| (eq_rec_heq _ _).trans <| by rw [bodd_bit, div2_bit] @[simp] theorem bitCasesOn_bit0 {C : β„• β†’ Sort u} (H : βˆ€ b n, C (bit b n)) (n : β„•) : bitCasesOn (2 * n) H = H false n := bitCasesOn_bit H false n @[simp] theorem bitCasesOn_bit1 {C : β„• β†’ Sort u} (H : βˆ€ b n, C (bit b n)) (n : β„•) : bitCasesOn (2 * n + 1) H = H true n := bitCasesOn_bit H true n theorem bit_cases_on_injective {C : β„• β†’ Sort u} : Function.Injective fun H : βˆ€ b n, C (bit b n) => fun n => bitCasesOn n H := by intro H₁ Hβ‚‚ h ext b n simpa only [bitCasesOn_bit] using congr_fun h (bit b n) @[simp] theorem bit_cases_on_inj {C : β„• β†’ Sort u} (H₁ Hβ‚‚ : βˆ€ b n, C (bit b n)) : ((fun n => bitCasesOn n H₁) = fun n => bitCasesOn n Hβ‚‚) ↔ H₁ = Hβ‚‚ := bit_cases_on_injective.eq_iff theorem bit_eq_zero_iff {n : β„•} {b : Bool} : bit b n = 0 ↔ n = 0 ∧ b = false := by constructor Β· cases b <;> simp [Nat.bit]; omega Β· rintro ⟨rfl, rfl⟩ rfl lemma bit_le : βˆ€ (b : Bool) {m n : β„•}, m ≀ n β†’ bit b m ≀ bit b n | true, _, _, h => by dsimp [bit]; omega | false, _, _, h => by dsimp [bit]; omega lemma bit_lt_bit (a b) (h : m < n) : bit a m < bit b n := calc bit a m < 2 * n := by cases a <;> dsimp [bit] <;> omega _ ≀ bit b n := by cases b <;> dsimp [bit] <;> omega /-- The same as `binaryRec_eq`, but that one unfortunately requires `f` to be the identity when appending `false` to `0`. Here, we allow you to explicitly say that that case is not happening, i.e. supplying `n = 0 β†’ b = true`. -/ theorem binaryRec_eq' {C : β„• β†’ Sort*} {z : C 0} {f : βˆ€ b n, C n β†’ C (bit b n)} (b n) (h : f false 0 z = z ∨ (n = 0 β†’ b = true)) : binaryRec z f (bit b n) = f b n (binaryRec z f n) := by rw [binaryRec] split_ifs with h' Β· rcases bit_eq_zero_iff.mp h' with ⟨rfl, rfl⟩ rw [binaryRec_zero] simp only [imp_false, or_false_iff, eq_self_iff_true, not_true] at h exact h.symm Β· dsimp only [] generalize_proofs e revert e rw [bodd_bit, div2_bit] intros rfl /-- The same as `binaryRec`, but the induction step can assume that if `n=0`, the bit being appended is `true`-/ @[elab_as_elim] def binaryRec' {C : β„• β†’ Sort*} (z : C 0) (f : βˆ€ b n, (n = 0 β†’ b = true) β†’ C n β†’ C (bit b n)) : βˆ€ n, C n := binaryRec z fun b n ih => if h : n = 0 β†’ b = true then f b n h ih else by convert z rw [bit_eq_zero_iff] simpa using h /-- The same as `binaryRec`, but special casing both 0 and 1 as base cases -/ @[elab_as_elim] def binaryRecFromOne {C : β„• β†’ Sort*} (zβ‚€ : C 0) (z₁ : C 1) (f : βˆ€ b n, n β‰  0 β†’ C n β†’ C (bit b n)) : βˆ€ n, C n := binaryRec' zβ‚€ fun b n h ih => if h' : n = 0 then by rw [h', h h'] exact z₁ else f b n h' ih @[simp] theorem zero_bits : bits 0 = [] := by simp [Nat.bits] @[simp] theorem bits_append_bit (n : β„•) (b : Bool) (hn : n = 0 β†’ b = true) : (bit b n).bits = b :: n.bits := by rw [Nat.bits, binaryRec_eq'] simpa @[simp] theorem bit0_bits (n : β„•) (hn : n β‰  0) : (2 * n).bits = false :: n.bits := bits_append_bit n false fun hn' => absurd hn' hn @[simp] theorem bit1_bits (n : β„•) : (2 * n + 1).bits = true :: n.bits := bits_append_bit n true fun _ => rfl @[simp] theorem one_bits : Nat.bits 1 = [true] := by convert bit1_bits 0 -- TODO Find somewhere this can live. -- example : bits 3423 = [true, true, true, true, true, false, true, false, true, false, true, true] -- := by norm_num theorem bodd_eq_bits_head (n : β„•) : n.bodd = n.bits.headI := by induction' n using Nat.binaryRec' with b n h _; Β· simp simp [bodd_bit, bits_append_bit _ _ h] theorem div2_bits_eq_tail (n : β„•) : n.div2.bits = n.bits.tail := by induction' n using Nat.binaryRec' with b n h _; Β· simp simp [div2_bit, bits_append_bit _ _ h] end Nat
Data\Nat\Bitwise.lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Alex Keizer -/ import Mathlib.Data.List.GetD import Mathlib.Data.Nat.Bits import Mathlib.Algebra.Ring.Nat import Mathlib.Order.Basic import Mathlib.Tactic.AdaptationNote import Mathlib.Tactic.Common /-! # Bitwise operations on natural numbers In the first half of this file, we provide theorems for reasoning about natural numbers from their bitwise properties. In the second half of this file, we show properties of the bitwise operations `lor`, `land` and `xor`, which are defined in core. ## Main results * `eq_of_testBit_eq`: two natural numbers are equal if they have equal bits at every position. * `exists_most_significant_bit`: if `n β‰  0`, then there is some position `i` that contains the most significant `1`-bit of `n`. * `lt_of_testBit`: if `n` and `m` are numbers and `i` is a position such that the `i`-th bit of of `n` is zero, the `i`-th bit of `m` is one, and all more significant bits are equal, then `n < m`. ## Future work There is another way to express bitwise properties of natural number: `digits 2`. The two ways should be connected. ## Keywords bitwise, and, or, xor -/ open Function namespace Nat section variable {f : Bool β†’ Bool β†’ Bool} @[simp] lemma bitwise_zero_left (m : Nat) : bitwise f 0 m = if f false true then m else 0 := by simp [bitwise] @[simp] lemma bitwise_zero_right (n : Nat) : bitwise f n 0 = if f true false then n else 0 := by unfold bitwise simp only [ite_self, decide_False, Nat.zero_div, ite_true, ite_eq_right_iff] rintro ⟨⟩ split_ifs <;> rfl lemma bitwise_zero : bitwise f 0 0 = 0 := by simp only [bitwise_zero_right, ite_self] lemma bitwise_of_ne_zero {n m : Nat} (hn : n β‰  0) (hm : m β‰  0) : bitwise f n m = bit (f (bodd n) (bodd m)) (bitwise f (n / 2) (m / 2)) := by conv_lhs => unfold bitwise have mod_two_iff_bod x : (x % 2 = 1 : Bool) = bodd x := by simp only [mod_two_of_bodd, cond]; cases bodd x <;> rfl simp only [hn, hm, mod_two_iff_bod, ite_false, bit, two_mul, Bool.cond_eq_ite] split_ifs <;> rfl theorem binaryRec_of_ne_zero {C : Nat β†’ Sort*} (z : C 0) (f : βˆ€ b n, C n β†’ C (bit b n)) {n} (h : n β‰  0) : binaryRec z f n = bit_decomp n β–Έ f (bodd n) (div2 n) (binaryRec z f (div2 n)) := by rw [Eq.rec_eq_cast] rw [binaryRec] dsimp only rw [dif_neg h, eq_mpr_eq_cast] @[simp] lemma bitwise_bit {f : Bool β†’ Bool β†’ Bool} (h : f false false = false := by rfl) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := by conv_lhs => unfold bitwise #adaptation_note /-- nightly-2024-03-16: simp was -- simp (config := { unfoldPartialApp := true }) only [bit, bit1, bit0, Bool.cond_eq_ite] -/ simp only [bit, ite_apply, Bool.cond_eq_ite] have h2 x : (x + x + 1) % 2 = 1 := by rw [← two_mul, add_comm]; apply add_mul_mod_self_left have h4 x : (x + x + 1) / 2 = x := by rw [← two_mul, add_comm]; simp [add_mul_div_left] cases a <;> cases b <;> simp [h2, h4] <;> split_ifs <;> simp_all (config := {decide := true}) [two_mul] lemma bit_mod_two (a : Bool) (x : β„•) : bit a x % 2 = if a then 1 else 0 := by #adaptation_note /-- nightly-2024-03-16: simp was -- simp (config := { unfoldPartialApp := true }) only [bit, bit1, bit0, ← mul_two, -- Bool.cond_eq_ite] -/ simp only [bit, ite_apply, ← mul_two, Bool.cond_eq_ite] split_ifs <;> simp [Nat.add_mod] @[simp] lemma bit_mod_two_eq_zero_iff (a x) : bit a x % 2 = 0 ↔ !a := by rw [bit_mod_two]; split_ifs <;> simp_all @[simp] lemma bit_mod_two_eq_one_iff (a x) : bit a x % 2 = 1 ↔ a := by rw [bit_mod_two]; split_ifs <;> simp_all @[simp] theorem lor_bit : βˆ€ a m b n, bit a m ||| bit b n = bit (a || b) (m ||| n) := bitwise_bit @[simp] theorem land_bit : βˆ€ a m b n, bit a m &&& bit b n = bit (a && b) (m &&& n) := bitwise_bit @[simp] theorem ldiff_bit : βˆ€ a m b n, ldiff (bit a m) (bit b n) = bit (a && not b) (ldiff m n) := bitwise_bit @[simp] theorem xor_bit : βˆ€ a m b n, bit a m ^^^ bit b n = bit (bne a b) (m ^^^ n) := bitwise_bit attribute [simp] Nat.testBit_bitwise theorem testBit_lor : βˆ€ m n k, testBit (m ||| n) k = (testBit m k || testBit n k) := testBit_bitwise rfl theorem testBit_land : βˆ€ m n k, testBit (m &&& n) k = (testBit m k && testBit n k) := testBit_bitwise rfl @[simp] theorem testBit_ldiff : βˆ€ m n k, testBit (ldiff m n) k = (testBit m k && not (testBit n k)) := testBit_bitwise rfl attribute [simp] testBit_xor end @[simp] theorem bit_false : bit false = (2 * Β·) := rfl @[simp] theorem bit_true : bit true = (2 * Β· + 1) := rfl @[simp] theorem bit_eq_zero {n : β„•} {b : Bool} : n.bit b = 0 ↔ n = 0 ∧ b = false := by cases b <;> simp [bit, Nat.mul_eq_zero] theorem bit_ne_zero_iff {n : β„•} {b : Bool} : n.bit b β‰  0 ↔ n = 0 β†’ b = true := by simpa only [not_and, Bool.not_eq_false] using (@bit_eq_zero n b).not /-- An alternative for `bitwise_bit` which replaces the `f false false = false` assumption with assumptions that neither `bit a m` nor `bit b n` are `0` (albeit, phrased as the implications `m = 0 β†’ a = true` and `n = 0 β†’ b = true`) -/ lemma bitwise_bit' {f : Bool β†’ Bool β†’ Bool} (a : Bool) (m : Nat) (b : Bool) (n : Nat) (ham : m = 0 β†’ a = true) (hbn : n = 0 β†’ b = true) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := by conv_lhs => unfold bitwise rw [← bit_ne_zero_iff] at ham hbn simp only [ham, hbn, bit_mod_two_eq_one_iff, Bool.decide_coe, ← div2_val, div2_bit, ne_eq, ite_false] conv_rhs => simp only [bit, two_mul, Bool.cond_eq_ite] split_ifs with hf <;> rfl lemma bitwise_eq_binaryRec (f : Bool β†’ Bool β†’ Bool) : bitwise f = binaryRec (fun n => cond (f false true) n 0) fun a m Ia => binaryRec (cond (f true false) (bit a m) 0) fun b n _ => bit (f a b) (Ia n) := by funext x y induction x using binaryRec' generalizing y with | z => simp only [bitwise_zero_left, binaryRec_zero, Bool.cond_eq_ite] | f xb x hxb ih => rw [← bit_ne_zero_iff] at hxb simp_rw [binaryRec_of_ne_zero _ _ hxb, bodd_bit, div2_bit, eq_rec_constant] induction y using binaryRec' with | z => simp only [bitwise_zero_right, binaryRec_zero, Bool.cond_eq_ite] | f yb y hyb => rw [← bit_ne_zero_iff] at hyb simp_rw [binaryRec_of_ne_zero _ _ hyb, bitwise_of_ne_zero hxb hyb, bodd_bit, ← div2_val, div2_bit, eq_rec_constant, ih] theorem zero_of_testBit_eq_false {n : β„•} (h : βˆ€ i, testBit n i = false) : n = 0 := by induction' n using Nat.binaryRec with b n hn Β· rfl Β· have : b = false := by simpa using h 0 rw [this, bit_false, hn fun i => by rw [← h (i + 1), testBit_bit_succ]] theorem testBit_eq_false_of_lt {n i} (h : n < 2 ^ i) : n.testBit i = false := by simp [testBit, shiftRight_eq_div_pow, Nat.div_eq_of_lt h] /-- The ith bit is the ith element of `n.bits`. -/ theorem testBit_eq_inth (n i : β„•) : n.testBit i = n.bits.getI i := by induction' i with i ih generalizing n Β· simp only [testBit, zero_eq, shiftRight_zero, one_and_eq_mod_two, mod_two_of_bodd, bodd_eq_bits_head, List.getI_zero_eq_headI] cases List.headI (bits n) <;> rfl conv_lhs => rw [← bit_decomp n] rw [testBit_bit_succ, ih n.div2, div2_bits_eq_tail] cases n.bits <;> simp theorem exists_most_significant_bit {n : β„•} (h : n β‰  0) : βˆƒ i, testBit n i = true ∧ βˆ€ j, i < j β†’ testBit n j = false := by induction' n using Nat.binaryRec with b n hn Β· exact False.elim (h rfl) by_cases h' : n = 0 Β· subst h' rw [show b = true by revert h cases b <;> simp] refine ⟨0, ⟨by rw [testBit_bit_zero], fun j hj => ?_⟩⟩ obtain ⟨j', rfl⟩ := exists_eq_succ_of_ne_zero (ne_of_gt hj) rw [testBit_bit_succ, zero_testBit] Β· obtain ⟨k, ⟨hk, hk'⟩⟩ := hn h' refine ⟨k + 1, ⟨by rw [testBit_bit_succ, hk], fun j hj => ?_⟩⟩ obtain ⟨j', rfl⟩ := exists_eq_succ_of_ne_zero (show j β‰  0 by intro x; subst x; simp at hj) exact (testBit_bit_succ _ _ _).trans (hk' _ (lt_of_succ_lt_succ hj)) theorem lt_of_testBit {n m : β„•} (i : β„•) (hn : testBit n i = false) (hm : testBit m i = true) (hnm : βˆ€ j, i < j β†’ testBit n j = testBit m j) : n < m := by induction' n using Nat.binaryRec with b n hn' generalizing i m Β· rw [Nat.pos_iff_ne_zero] rintro rfl simp at hm induction' m using Nat.binaryRec with b' m hm' generalizing i Β· exact False.elim (Bool.false_ne_true ((zero_testBit i).symm.trans hm)) by_cases hi : i = 0 Β· subst hi simp only [testBit_bit_zero] at hn hm have : n = m := eq_of_testBit_eq fun i => by convert hnm (i + 1) (Nat.zero_lt_succ _) using 1 <;> rw [testBit_bit_succ] rw [hn, hm, this, bit_false, bit_true] exact Nat.lt_succ_self _ Β· obtain ⟨i', rfl⟩ := exists_eq_succ_of_ne_zero hi simp only [testBit_bit_succ] at hn hm have := hn' _ hn hm fun j hj => by convert hnm j.succ (succ_lt_succ hj) using 1 <;> rw [testBit_bit_succ] have this' : 2 * n < 2 * m := Nat.mul_lt_mul_of_le_of_lt (le_refl _) this Nat.two_pos cases b <;> cases b' <;> simp only [bit_false, bit_true] Β· exact this' Β· exact Nat.lt_add_right 1 this' Β· calc 2 * n + 1 < 2 * n + 2 := lt.base _ _ ≀ 2 * m := mul_le_mul_left 2 this Β· exact Nat.succ_lt_succ this' @[simp] theorem testBit_two_pow_self (n : β„•) : testBit (2 ^ n) n = true := by rw [testBit, shiftRight_eq_div_pow, Nat.div_self (Nat.pow_pos Nat.zero_lt_two)] simp theorem testBit_two_pow_of_ne {n m : β„•} (hm : n β‰  m) : testBit (2 ^ n) m = false := by rw [testBit, shiftRight_eq_div_pow] cases' hm.lt_or_lt with hm hm Β· rw [Nat.div_eq_of_lt] Β· simp Β· exact Nat.pow_lt_pow_right Nat.one_lt_two hm Β· rw [Nat.pow_div hm.le Nat.two_pos, ← Nat.sub_add_cancel (succ_le_of_lt <| Nat.sub_pos_of_lt hm)] -- Porting note: XXX why does this make it work? rw [(rfl : succ 0 = 1)] simp [pow_succ, and_one_is_mod, mul_mod_left] theorem testBit_two_pow (n m : β„•) : testBit (2 ^ n) m = (n = m) := by by_cases h : n = m Β· cases h simp Β· rw [testBit_two_pow_of_ne h] simp [h] theorem bitwise_swap {f : Bool β†’ Bool β†’ Bool} : bitwise (Function.swap f) = Function.swap (bitwise f) := by funext m n simp only [Function.swap] induction' m using Nat.strongInductionOn with m ih generalizing n cases' m with m <;> cases' n with n <;> try rw [bitwise_zero_left, bitwise_zero_right] Β· specialize ih ((m+1) / 2) (div_lt_self' ..) simp [bitwise_of_ne_zero, ih] /-- If `f` is a commutative operation on bools such that `f false false = false`, then `bitwise f` is also commutative. -/ theorem bitwise_comm {f : Bool β†’ Bool β†’ Bool} (hf : βˆ€ b b', f b b' = f b' b) (n m : β„•) : bitwise f n m = bitwise f m n := suffices bitwise f = swap (bitwise f) by conv_lhs => rw [this] calc bitwise f = bitwise (swap f) := congr_arg _ <| funext fun _ => funext <| hf _ _ = swap (bitwise f) := bitwise_swap theorem lor_comm (n m : β„•) : n ||| m = m ||| n := bitwise_comm Bool.or_comm n m theorem land_comm (n m : β„•) : n &&& m = m &&& n := bitwise_comm Bool.and_comm n m protected lemma xor_comm (n m : β„•) : n ^^^ m = m ^^^ n := bitwise_comm (Bool.bne_eq_xor β–Έ Bool.xor_comm) n m lemma and_two_pow (n i : β„•) : n &&& 2 ^ i = (n.testBit i).toNat * 2 ^ i := by refine eq_of_testBit_eq fun j => ?_ obtain rfl | hij := Decidable.eq_or_ne i j <;> cases' h : n.testBit i Β· simp [h] Β· simp [h] Β· simp [h, testBit_two_pow_of_ne hij] Β· simp [h, testBit_two_pow_of_ne hij] lemma two_pow_and (n i : β„•) : 2 ^ i &&& n = 2 ^ i * (n.testBit i).toNat := by rw [mul_comm, land_comm, and_two_pow] @[simp] theorem zero_xor (n : β„•) : 0 ^^^ n = n := by simp [HXor.hXor, Xor.xor, xor] @[simp] theorem xor_zero (n : β„•) : n ^^^ 0 = n := by simp [HXor.hXor, Xor.xor, xor] /-- Proving associativity of bitwise operations in general essentially boils down to a huge case distinction, so it is shorter to use this tactic instead of proving it in the general case. -/ macro "bitwise_assoc_tac" : tactic => set_option hygiene false in `(tactic| ( induction' n using Nat.binaryRec with b n hn generalizing m k Β· simp induction' m using Nat.binaryRec with b' m hm Β· simp induction' k using Nat.binaryRec with b'' k hk -- porting note (#10745): was `simp [hn]` -- This is necessary because these are simp lemmas in mathlib <;> simp [hn, Bool.or_assoc, Bool.and_assoc, Bool.bne_eq_xor])) protected lemma xor_assoc (n m k : β„•) : (n ^^^ m) ^^^ k = n ^^^ (m ^^^ k) := by bitwise_assoc_tac theorem land_assoc (n m k : β„•) : (n &&& m) &&& k = n &&& (m &&& k) := by bitwise_assoc_tac theorem lor_assoc (n m k : β„•) : (n ||| m) ||| k = n ||| (m ||| k) := by bitwise_assoc_tac @[simp] theorem xor_self (n : β„•) : n ^^^ n = 0 := zero_of_testBit_eq_false fun i => by simp -- These lemmas match `mul_inv_cancel_right` and `mul_inv_cancel_left`. theorem xor_cancel_right (n m : β„•) : (m ^^^ n) ^^^ n = m := by rw [Nat.xor_assoc, xor_self, xor_zero] theorem xor_cancel_left (n m : β„•) : n ^^^ (n ^^^ m) = m := by rw [← Nat.xor_assoc, xor_self, zero_xor] theorem xor_right_injective {n : β„•} : Function.Injective (HXor.hXor n : β„• β†’ β„•) := fun m m' h => by rw [← xor_cancel_left n m, ← xor_cancel_left n m', h] theorem xor_left_injective {n : β„•} : Function.Injective fun m => m ^^^ n := fun m m' (h : m ^^^ n = m' ^^^ n) => by rw [← xor_cancel_right n m, ← xor_cancel_right n m', h] @[simp] theorem xor_right_inj {n m m' : β„•} : n ^^^ m = n ^^^ m' ↔ m = m' := xor_right_injective.eq_iff @[simp] theorem xor_left_inj {n m m' : β„•} : m ^^^ n = m' ^^^ n ↔ m = m' := xor_left_injective.eq_iff @[simp] theorem xor_eq_zero {n m : β„•} : n ^^^ m = 0 ↔ n = m := by rw [← xor_self n, xor_right_inj, eq_comm] theorem xor_ne_zero {n m : β„•} : n ^^^ m β‰  0 ↔ n β‰  m := xor_eq_zero.not theorem xor_trichotomy {a b c : β„•} (h : a β‰  b ^^^ c) : b ^^^ c < a ∨ a ^^^ c < b ∨ a ^^^ b < c := by set v := a ^^^ (b ^^^ c) with hv -- The xor of any two of `a`, `b`, `c` is the xor of `v` and the third. have hab : a ^^^ b = c ^^^ v := by rw [hv] conv_rhs => rw [Nat.xor_comm] simp [Nat.xor_assoc] have hac : a ^^^ c = b ^^^ v := by rw [hv] conv_rhs => right rw [← Nat.xor_comm] rw [← Nat.xor_assoc, ← Nat.xor_assoc, xor_self, zero_xor, Nat.xor_comm] have hbc : b ^^^ c = a ^^^ v := by simp [hv, ← Nat.xor_assoc] -- If `i` is the position of the most significant bit of `v`, then at least one of `a`, `b`, `c` -- has a one bit at position `i`. obtain ⟨i, ⟨hi, hi'⟩⟩ := exists_most_significant_bit (xor_ne_zero.2 h) have : testBit a i = true ∨ testBit b i = true ∨ testBit c i = true := by contrapose! hi simp only [Bool.eq_false_eq_not_eq_true, Ne, testBit_xor, Bool.bne_eq_xor] at hi ⊒ rw [hi.1, hi.2.1, hi.2.2, Bool.xor_false, Bool.xor_false] -- If, say, `a` has a one bit at position `i`, then `a xor v` has a zero bit at position `i`, but -- the same bits as `a` in positions greater than `j`, so `a xor v < a`. rcases this with (h | h | h) on_goal 1 => left; rw [hbc] on_goal 2 => right; left; rw [hac] on_goal 3 => right; right; rw [hab] all_goals exact lt_of_testBit i (by simp [h, hi]) h fun j hj => by simp [hi' _ hj] theorem lt_xor_cases {a b c : β„•} (h : a < b ^^^ c) : a ^^^ c < b ∨ a ^^^ b < c := (or_iff_right fun h' => (h.asymm h').elim).1 <| xor_trichotomy h.ne @[simp] theorem bit_lt_two_pow_succ_iff {b x n} : bit b x < 2 ^ (n + 1) ↔ x < 2 ^ n := by cases b <;> simp <;> omega /-- If `x` and `y` fit within `n` bits, then the result of any bitwise operation on `x` and `y` also fits within `n` bits -/ theorem bitwise_lt {f x y n} (hx : x < 2 ^ n) (hy : y < 2 ^ n) : bitwise f x y < 2 ^ n := by induction x using Nat.binaryRec' generalizing n y with | z => simp only [bitwise_zero_left] split <;> assumption | @f bx nx hnx ih => cases y using Nat.binaryRec' with | z => simp only [bitwise_zero_right] split <;> assumption | f Β«byΒ» ny hny => rw [bitwise_bit' _ _ _ _ hnx hny] cases n <;> simp_all lemma shiftLeft_lt {x n m : β„•} (h : x < 2 ^ n) : x <<< m < 2 ^ (n + m) := by simp only [Nat.pow_add, shiftLeft_eq, Nat.mul_lt_mul_right (Nat.two_pow_pos _), h] /-- Note that the LHS is the expression used within `Std.BitVec.append`, hence the name. -/ lemma append_lt {x y n m} (hx : x < 2 ^ n) (hy : y < 2 ^ m) : y <<< n ||| x < 2 ^ (n + m) := by apply bitwise_lt Β· rw [add_comm]; apply shiftLeft_lt hy Β· apply lt_of_lt_of_le hx <| Nat.pow_le_pow_right (le_succ _) (le_add_right _ _) end Nat
Data\Nat\ChineseRemainder.lean
/- Copyright (c) 2023 Shogo Saito. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Shogo Saito. Adapted for mathlib by Hunter Monroe -/ import Mathlib.Algebra.BigOperators.Ring.List import Mathlib.Data.Nat.ModEq import Mathlib.Data.Nat.GCD.BigOperators /-! # Chinese Remainder Theorem This file provides definitions and theorems for the Chinese Remainder Theorem. These are used in GΓΆdel's Beta function, which is used in proving GΓΆdel's incompleteness theorems. ## Main result - `chineseRemainderOfList`: Definition of the Chinese remainder of a list ## Tags Chinese Remainder Theorem, GΓΆdel, beta function -/ namespace Nat variable {ΞΉ : Type*} lemma modEq_list_prod_iff {a b} {l : List β„•} (co : l.Pairwise Coprime) : a ≑ b [MOD l.prod] ↔ βˆ€ i, a ≑ b [MOD l.get i] := by induction' l with m l ih Β· simp [modEq_one] Β· have : Coprime m l.prod := coprime_list_prod_right_iff.mpr (List.pairwise_cons.mp co).1 simp only [List.prod_cons, ← modEq_and_modEq_iff_modEq_mul this, ih (List.Pairwise.of_cons co), List.length_cons] constructor Β· rintro ⟨h0, hs⟩ i cases i using Fin.cases <;> simp_all Β· intro h; exact ⟨h 0, fun i => h i.succ⟩ lemma modEq_list_prod_iff' {a b} {s : ΞΉ β†’ β„•} {l : List ΞΉ} (co : l.Pairwise (Coprime on s)) : a ≑ b [MOD (l.map s).prod] ↔ βˆ€ i ∈ l, a ≑ b [MOD s i] := by induction' l with i l ih Β· simp [modEq_one] Β· have : Coprime (s i) (l.map s).prod := by simp only [coprime_list_prod_right_iff, List.mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iffβ‚‚] intro j hj exact (List.pairwise_cons.mp co).1 j hj simp [← modEq_and_modEq_iff_modEq_mul this, ih (List.Pairwise.of_cons co)] variable (a s : ΞΉ β†’ β„•) /-- The natural number less than `(l.map s).prod` congruent to `a i` mod `s i` for all `i ∈ l`. -/ def chineseRemainderOfList : (l : List ΞΉ) β†’ l.Pairwise (Coprime on s) β†’ { k // βˆ€ i ∈ l, k ≑ a i [MOD s i] } | [], _ => ⟨0, by simp⟩ | i :: l, co => by have : Coprime (s i) (l.map s).prod := by simp only [coprime_list_prod_right_iff, List.mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iffβ‚‚] intro j hj exact (List.pairwise_cons.mp co).1 j hj have ih := chineseRemainderOfList l co.of_cons have k := chineseRemainder this (a i) ih use k simp only [List.mem_cons, forall_eq_or_imp, k.prop.1, true_and] intro j hj exact ((modEq_list_prod_iff' co.of_cons).mp k.prop.2 j hj).trans (ih.prop j hj) @[simp] theorem chineseRemainderOfList_nil : (chineseRemainderOfList a s [] List.Pairwise.nil : β„•) = 0 := rfl theorem chineseRemainderOfList_lt_prod (l : List ΞΉ) (co : l.Pairwise (Coprime on s)) (hs : βˆ€ i ∈ l, s i β‰  0) : chineseRemainderOfList a s l co < (l.map s).prod := by cases l with | nil => simp | cons i l => simp only [chineseRemainderOfList, List.map_cons, List.prod_cons] have : Coprime (s i) (l.map s).prod := by simp only [coprime_list_prod_right_iff, List.mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iffβ‚‚] intro j hj exact (List.pairwise_cons.mp co).1 j hj refine chineseRemainder_lt_mul this (a i) (chineseRemainderOfList a s l co.of_cons) (hs i (List.mem_cons_self _ l)) ?_ simp only [ne_eq, List.prod_eq_zero_iff, List.mem_map, not_exists, not_and] intro j hj exact hs j (List.mem_cons_of_mem _ hj) theorem chineseRemainderOfList_modEq_unique (l : List ΞΉ) (co : l.Pairwise (Coprime on s)) {z} (hz : βˆ€ i ∈ l, z ≑ a i [MOD s i]) : z ≑ chineseRemainderOfList a s l co [MOD (l.map s).prod] := by induction' l with i l ih Β· simp [modEq_one] Β· simp only [List.map_cons, List.prod_cons, chineseRemainderOfList] have : Coprime (s i) (l.map s).prod := by simp only [coprime_list_prod_right_iff, List.mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iffβ‚‚] intro j hj exact (List.pairwise_cons.mp co).1 j hj exact chineseRemainder_modEq_unique this (hz i (List.mem_cons_self _ _)) (ih co.of_cons (fun j hj => hz j (List.mem_cons_of_mem _ hj))) theorem chineseRemainderOfList_perm {l l' : List ΞΉ} (hl : l.Perm l') (hs : βˆ€ i ∈ l, s i β‰  0) (co : l.Pairwise (Coprime on s)) : (chineseRemainderOfList a s l co : β„•) = chineseRemainderOfList a s l' (co.perm hl coprime_comm.mpr) := by let z := chineseRemainderOfList a s l' (co.perm hl coprime_comm.mpr) have hlp : (l.map s).prod = (l'.map s).prod := List.Perm.prod_eq (List.Perm.map s hl) exact (chineseRemainderOfList_modEq_unique a s l co (z := z) (fun i hi => z.prop i (hl.symm.mem_iff.mpr hi))).symm.eq_of_lt_of_lt (chineseRemainderOfList_lt_prod _ _ _ _ hs) (by rw [hlp] exact chineseRemainderOfList_lt_prod _ _ _ _ (by simpa [List.Perm.mem_iff hl.symm] using hs)) /-- The natural number less than `(m.map s).prod` congruent to `a i` mod `s i` for all `i ∈ m`. -/ def chineseRemainderOfMultiset {m : Multiset ΞΉ} : m.Nodup β†’ (βˆ€ i ∈ m, s i β‰  0) β†’ Set.Pairwise {x | x ∈ m} (Coprime on s) β†’ { k // βˆ€ i ∈ m, k ≑ a i [MOD s i] } := Quotient.recOn m (fun l nod _ co => chineseRemainderOfList a s l (List.Nodup.pairwise_of_forall_ne nod co)) (fun l l' (pp : l.Perm l') ↦ funext fun nod' : l'.Nodup => have nod : l.Nodup := pp.symm.nodup_iff.mp nod' funext fun hs' : βˆ€ i ∈ l', s i β‰  0 => have hs : βˆ€ i ∈ l, s i β‰  0 := by simpa [List.Perm.mem_iff pp] using hs' funext fun co' : Set.Pairwise {x | x ∈ l'} (Coprime on s) => have co : Set.Pairwise {x | x ∈ l} (Coprime on s) := by simpa [List.Perm.mem_iff pp] using co' have lco : l.Pairwise (Coprime on s) := List.Nodup.pairwise_of_forall_ne nod co have : βˆ€ {m' e nod'' hs'' co''}, @Eq.ndrec (Multiset ΞΉ) l (fun m ↦ m.Nodup β†’ (βˆ€ i ∈ m, s i β‰  0) β†’ Set.Pairwise {x | x ∈ m} (Coprime on s) β†’ { k // βˆ€ i ∈ m, k ≑ a i [MOD s i] }) (fun nod _ co ↦ chineseRemainderOfList a s l (List.Nodup.pairwise_of_forall_ne nod co)) m' e nod'' hs'' co'' = (chineseRemainderOfList a s l lco : β„•) := by rintro _ rfl _ _ _; rfl by ext; exact this.trans <| chineseRemainderOfList_perm a s pp hs lco) theorem chineseRemainderOfMultiset_lt_prod {m : Multiset ΞΉ} (nod : m.Nodup) (hs : βˆ€ i ∈ m, s i β‰  0) (pp : Set.Pairwise {x | x ∈ m} (Coprime on s)) : chineseRemainderOfMultiset a s nod hs pp < (m.map s).prod := by induction' m using Quot.ind with l unfold chineseRemainderOfMultiset simpa using chineseRemainderOfList_lt_prod a s l (List.Nodup.pairwise_of_forall_ne nod pp) (by simpa using hs) /-- The natural number less than `∏ i ∈ t, s i` congruent to `a i` mod `s i` for all `i ∈ t`. -/ def chineseRemainderOfFinset (t : Finset ΞΉ) (hs : βˆ€ i ∈ t, s i β‰  0) (pp : Set.Pairwise t (Coprime on s)) : { k // βˆ€ i ∈ t, k ≑ a i [MOD s i] } := by simpa using chineseRemainderOfMultiset a s t.nodup (by simpa using hs) (by simpa using pp) theorem chineseRemainderOfFinset_lt_prod {t : Finset ΞΉ} (hs : βˆ€ i ∈ t, s i β‰  0) (pp : Set.Pairwise t (Coprime on s)) : chineseRemainderOfFinset a s t hs pp < ∏ i ∈ t, s i := by simpa [chineseRemainderOfFinset] using chineseRemainderOfMultiset_lt_prod a s t.nodup (by simpa using hs) (by simpa using pp) end Nat
Data\Nat\Count.lean
/- Copyright (c) 2021 Vladimir Goryachev. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: YaΓ«l Dillies, Vladimir Goryachev, Kyle Miller, Scott Morrison, Eric Rodriguez -/ import Mathlib.SetTheory.Cardinal.Basic /-! # Counting on β„• This file defines the `count` function, which gives, for any predicate on the natural numbers, "how many numbers under `k` satisfy this predicate?". We then prove several expected lemmas about `count`, relating it to the cardinality of other objects, and helping to evaluate it for specific `k`. -/ open Finset namespace Nat variable (p : β„• β†’ Prop) section Count variable [DecidablePred p] /-- Count the number of naturals `k < n` satisfying `p k`. -/ def count (n : β„•) : β„• := (List.range n).countP p @[simp] theorem count_zero : count p 0 = 0 := by rw [count, List.range_zero, List.countP, List.countP.go] /-- A fintype instance for the set relevant to `Nat.count`. Locally an instance in locale `count` -/ def CountSet.fintype (n : β„•) : Fintype { i // i < n ∧ p i } := by apply Fintype.ofFinset ((Finset.range n).filter p) intro x rw [mem_filter, mem_range] rfl scoped[Count] attribute [instance] Nat.CountSet.fintype open Count theorem count_eq_card_filter_range (n : β„•) : count p n = ((range n).filter p).card := by rw [count, List.countP_eq_length_filter] rfl /-- `count p n` can be expressed as the cardinality of `{k // k < n ∧ p k}`. -/ theorem count_eq_card_fintype (n : β„•) : count p n = Fintype.card { k : β„• // k < n ∧ p k } := by rw [count_eq_card_filter_range, ← Fintype.card_ofFinset, ← CountSet.fintype] rfl theorem count_succ (n : β„•) : count p (n + 1) = count p n + if p n then 1 else 0 := by split_ifs with h <;> simp [count, List.range_succ, h] @[mono] theorem count_monotone : Monotone (count p) := monotone_nat_of_le_succ fun n ↦ by by_cases h : p n <;> simp [count_succ, h] theorem count_add (a b : β„•) : count p (a + b) = count p a + count (fun k ↦ p (a + k)) b := by have : Disjoint ((range a).filter p) (((range b).map <| addLeftEmbedding a).filter p) := by apply disjoint_filter_filter rw [Finset.disjoint_left] simp_rw [mem_map, mem_range, addLeftEmbedding_apply] rintro x hx ⟨c, _, rfl⟩ exact (self_le_add_right _ _).not_lt hx simp_rw [count_eq_card_filter_range, range_add, filter_union, card_union_of_disjoint this, filter_map, addLeftEmbedding, card_map] rfl theorem count_add' (a b : β„•) : count p (a + b) = count (fun k ↦ p (k + b)) a + count p b := by rw [add_comm, count_add, add_comm] simp_rw [add_comm b] theorem count_one : count p 1 = if p 0 then 1 else 0 := by simp [count_succ] theorem count_succ' (n : β„•) : count p (n + 1) = count (fun k ↦ p (k + 1)) n + if p 0 then 1 else 0 := by rw [count_add', count_one] variable {p} @[simp] theorem count_lt_count_succ_iff {n : β„•} : count p n < count p (n + 1) ↔ p n := by by_cases h : p n <;> simp [count_succ, h] theorem count_succ_eq_succ_count_iff {n : β„•} : count p (n + 1) = count p n + 1 ↔ p n := by by_cases h : p n <;> simp [h, count_succ] theorem count_succ_eq_count_iff {n : β„•} : count p (n + 1) = count p n ↔ Β¬p n := by by_cases h : p n <;> simp [h, count_succ] alias ⟨_, count_succ_eq_succ_count⟩ := count_succ_eq_succ_count_iff alias ⟨_, count_succ_eq_count⟩ := count_succ_eq_count_iff theorem count_le_cardinal (n : β„•) : (count p n : Cardinal) ≀ Cardinal.mk { k | p k } := by rw [count_eq_card_fintype, ← Cardinal.mk_fintype] exact Cardinal.mk_subtype_mono fun x hx ↦ hx.2 theorem lt_of_count_lt_count {a b : β„•} (h : count p a < count p b) : a < b := (count_monotone p).reflect_lt h theorem count_strict_mono {m n : β„•} (hm : p m) (hmn : m < n) : count p m < count p n := (count_lt_count_succ_iff.2 hm).trans_le <| count_monotone _ (Nat.succ_le_iff.2 hmn) theorem count_injective {m n : β„•} (hm : p m) (hn : p n) (heq : count p m = count p n) : m = n := by by_contra! h : m β‰  n wlog hmn : m < n Β· exact this hn hm heq.symm h.symm (h.lt_or_lt.resolve_left hmn) Β· simpa [heq] using count_strict_mono hm hmn theorem count_le_card (hp : (setOf p).Finite) (n : β„•) : count p n ≀ hp.toFinset.card := by rw [count_eq_card_filter_range] exact Finset.card_mono fun x hx ↦ hp.mem_toFinset.2 (mem_filter.1 hx).2 theorem count_lt_card {n : β„•} (hp : (setOf p).Finite) (hpn : p n) : count p n < hp.toFinset.card := (count_lt_count_succ_iff.2 hpn).trans_le (count_le_card hp _) theorem count_of_forall {n : β„•} (hp : βˆ€ n' < n, p n') : count p n = n := by rw [count_eq_card_filter_range, filter_true_of_mem, card_range] Β· simpa only [Finset.mem_range] @[simp] theorem count_true (n : β„•) : count (fun _ ↦ True) n = n := count_of_forall fun _ _ ↦ trivial theorem count_of_forall_not {n : β„•} (hp : βˆ€ n' < n, Β¬p n') : count p n = 0 := by rw [count_eq_card_filter_range, filter_false_of_mem, card_empty] Β· simpa only [Finset.mem_range] @[simp] theorem count_false (n : β„•) : count (fun _ ↦ False) n = 0 := count_of_forall_not fun _ _ ↦ id variable {q : β„• β†’ Prop} variable [DecidablePred q] theorem count_mono_left {n : β„•} (hpq : βˆ€ k, p k β†’ q k) : count p n ≀ count q n := by simp only [count_eq_card_filter_range] exact card_le_card ((range n).monotone_filter_right hpq) end Count end Nat
Data\Nat\Defs.lean
/- Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import Mathlib.Logic.Function.Basic import Mathlib.Logic.Nontrivial.Defs import Mathlib.Tactic.Cases import Mathlib.Tactic.GCongr.Core import Mathlib.Tactic.PushNeg import Mathlib.Util.AssertExists import Batteries.Data.Nat.Basic /-! # Basic operations on the natural numbers This file contains: * some basic lemmas about natural numbers * extra recursors: * `leRecOn`, `le_induction`: recursion and induction principles starting at non-zero numbers * `decreasing_induction`: recursion growing downwards * `le_rec_on'`, `decreasing_induction'`: versions with slightly weaker assumptions * `strong_rec'`: recursion based on strong inequalities * decidability instances on predicates about the natural numbers See note [foundational algebra order theory]. ## TODO Split this file into: * `Data.Nat.Init` (or maybe `Data.Nat.Batteries`?) for lemmas that could go to Batteries * `Data.Nat.Basic` for the lemmas that require mathlib definitions -/ library_note "foundational algebra order theory"/-- Batteries has a home-baked development of the algebraic and order theoretic theory of `β„•` and `β„€ which, in particular, is not typeclass-mediated. This is useful to set up the algebra and finiteness libraries in mathlib (naturals and integers show up as indices/offsets in lists, cardinality in finsets, powers in groups, ...). Less basic uses of `β„•` and `β„€` should however use the typeclass-mediated development. The relevant files are: * `Data.Nat.Defs` for the continuation of the home-baked development on `β„•` * `Data.Int.Defs` for the continuation of the home-baked development on `β„€` * `Algebra.Group.Nat` for the monoid instances on `β„•` * `Algebra.Group.Int` for the group instance on `β„€` * `Algebra.Ring.Nat` for the semiring instance on `β„•` * `Algebra.Ring.Int` for the ring instance on `β„€` * `Algebra.Order.Group.Nat` for the ordered monoid instance on `β„•` * `Algebra.Order.Group.Int` for the ordered group instance on `β„€` * `Algebra.Order.Ring.Nat` for the ordered semiring instance on `β„•` * `Algebra.Order.Ring.Int` for the ordered ring instance on `β„€` -/ /- We don't want to import the algebraic hierarchy in this file. -/ assert_not_exists Monoid open Function namespace Nat variable {a b c d m n k : β„•} {p q : β„• β†’ Prop} -- TODO: Move the `LinearOrder β„•` instance to `Order.Nat` (#13092). instance instLinearOrder : LinearOrder β„• where le := Nat.le le_refl := @Nat.le_refl le_trans := @Nat.le_trans le_antisymm := @Nat.le_antisymm le_total := @Nat.le_total lt := Nat.lt lt_iff_le_not_le := @Nat.lt_iff_le_not_le decidableLT := inferInstance decidableLE := inferInstance decidableEq := inferInstance instance instNontrivial : Nontrivial β„• := ⟨⟨0, 1, Nat.zero_ne_one⟩⟩ @[simp] theorem default_eq_zero : default = 0 := rfl attribute [gcongr] Nat.succ_le_succ attribute [simp] Nat.not_lt_zero Nat.succ_ne_zero Nat.succ_ne_self Nat.zero_ne_one Nat.one_ne_zero Nat.min_eq_left Nat.min_eq_right Nat.max_eq_left Nat.max_eq_right -- Nat.zero_ne_bit1 Nat.bit1_ne_zero Nat.bit0_ne_one Nat.one_ne_bit0 Nat.bit0_ne_bit1 -- Nat.bit1_ne_bit0 attribute [simp] Nat.min_eq_left Nat.min_eq_right /-! ### `succ`, `pred` -/ lemma succ_pos' : 0 < succ n := succ_pos n alias succ_inj := succ_inj' lemma succ_injective : Injective Nat.succ := @succ.inj lemma succ_ne_succ : succ m β‰  succ n ↔ m β‰  n := succ_injective.ne_iff -- Porting note: no longer a simp lemma, as simp can prove this lemma succ_succ_ne_one (n : β„•) : n.succ.succ β‰  1 := by simp lemma one_lt_succ_succ (n : β„•) : 1 < n.succ.succ := succ_lt_succ <| succ_pos n -- Moved to Batteries alias _root_.LT.lt.nat_succ_le := succ_le_of_lt lemma not_succ_lt_self : Β¬ succ n < n := Nat.not_lt_of_ge n.le_succ lemma succ_le_iff : succ m ≀ n ↔ m < n := ⟨lt_of_succ_le, succ_le_of_lt⟩ lemma le_succ_iff : m ≀ n.succ ↔ m ≀ n ∨ m = n.succ := by refine ⟨fun hmn ↦ (Nat.lt_or_eq_of_le hmn).imp_left le_of_lt_succ, ?_⟩ rintro (hmn | rfl) Β· exact le_succ_of_le hmn Β· exact Nat.le_refl _ alias ⟨of_le_succ, _⟩ := le_succ_iff lemma lt_iff_le_pred : βˆ€ {n}, 0 < n β†’ (m < n ↔ m ≀ n - 1) | _ + 1, _ => Nat.lt_succ_iff lemma le_of_pred_lt : βˆ€ {m}, pred m < n β†’ m ≀ n | 0 => Nat.le_of_lt | _ + 1 => id lemma lt_iff_add_one_le : m < n ↔ m + 1 ≀ n := by rw [succ_le_iff] -- A flipped version of `lt_add_one_iff`. lemma lt_one_add_iff : m < 1 + n ↔ m ≀ n := by simp only [Nat.add_comm, Nat.lt_succ_iff] lemma one_add_le_iff : 1 + m ≀ n ↔ m < n := by simp only [Nat.add_comm, add_one_le_iff] lemma one_le_iff_ne_zero : 1 ≀ n ↔ n β‰  0 := Nat.pos_iff_ne_zero lemma one_lt_iff_ne_zero_and_ne_one : βˆ€ {n : β„•}, 1 < n ↔ n β‰  0 ∧ n β‰  1 | 0 => by decide | 1 => by decide | n + 2 => by omega lemma le_one_iff_eq_zero_or_eq_one : βˆ€ {n : β„•}, n ≀ 1 ↔ n = 0 ∨ n = 1 := by simp [le_succ_iff] @[simp] lemma lt_one_iff : n < 1 ↔ n = 0 := Nat.lt_succ_iff.trans $ by rw [le_zero_eq] lemma one_le_of_lt (h : a < b) : 1 ≀ b := Nat.lt_of_le_of_lt (Nat.zero_le _) h @[simp] lemma min_eq_zero_iff : min m n = 0 ↔ m = 0 ∨ n = 0 := by omega @[simp] lemma max_eq_zero_iff : max m n = 0 ↔ m = 0 ∧ n = 0 := by omega -- Moved to Batteries lemma pred_one_add (n : β„•) : pred (1 + n) = n := by rw [Nat.add_comm, add_one, Nat.pred_succ] lemma pred_eq_self_iff : n.pred = n ↔ n = 0 := by cases n <;> simp [(Nat.succ_ne_self _).symm] lemma pred_eq_of_eq_succ (H : m = n.succ) : m.pred = n := by simp [H] @[simp] lemma pred_eq_succ_iff : n - 1 = m + 1 ↔ n = m + 2 := by cases n <;> constructor <;> rintro ⟨⟩ <;> rfl lemma forall_lt_succ : (βˆ€ m < n + 1, p m) ↔ (βˆ€ m < n, p m) ∧ p n := by simp only [Nat.lt_succ_iff, Nat.le_iff_lt_or_eq, or_comm, forall_eq_or_imp, and_comm] lemma exists_lt_succ : (βˆƒ m < n + 1, p m) ↔ (βˆƒ m < n, p m) ∨ p n := by rw [← not_iff_not] push_neg exact forall_lt_succ lemma two_lt_of_ne : βˆ€ {n}, n β‰  0 β†’ n β‰  1 β†’ n β‰  2 β†’ 2 < n | 0, h, _, _ => (h rfl).elim | 1, _, h, _ => (h rfl).elim | 2, _, _, h => (h rfl).elim -- Porting note: was `by decide` | n + 3, _, _, _ => le_add_left 3 n /-! ### `pred` -/ @[simp] lemma add_succ_sub_one (m n : β„•) : m + succ n - 1 = m + n := rfl @[simp] lemma succ_add_sub_one (n m : β„•) : succ m + n - 1 = m + n := by rw [succ_add, Nat.add_one_sub_one] lemma pred_sub (n m : β„•) : pred n - m = pred (n - m) := by rw [← Nat.sub_one, Nat.sub_sub, one_add, sub_succ] lemma self_add_sub_one : βˆ€ n, n + (n - 1) = 2 * n - 1 | 0 => rfl | n + 1 => by rw [Nat.two_mul]; exact (add_succ_sub_one (Nat.succ _) _).symm lemma sub_one_add_self (n : β„•) : (n - 1) + n = 2 * n - 1 := Nat.add_comm _ n β–Έ self_add_sub_one n lemma self_add_pred (n : β„•) : n + pred n = (2 * n).pred := self_add_sub_one n lemma pred_add_self (n : β„•) : pred n + n = (2 * n).pred := sub_one_add_self n lemma pred_le_iff : pred m ≀ n ↔ m ≀ succ n := ⟨le_succ_of_pred_le, by cases m; exacts [fun _ ↦ zero_le n, le_of_succ_le_succ]⟩ lemma lt_of_lt_pred (h : m < n - 1) : m < n := by omega lemma le_add_pred_of_pos (a : β„•) (hb : b β‰  0) : a ≀ b + (a - 1) := by omega /-! ### `add` -/ attribute [simp] le_add_left le_add_right Nat.lt_add_left_iff_pos Nat.lt_add_right_iff_pos Nat.add_le_add_iff_left Nat.add_le_add_iff_right Nat.add_lt_add_iff_left Nat.add_lt_add_iff_right not_lt_zero -- We want to use these two lemmas earlier than the lemmas simp can prove them with @[simp, nolint simpNF] protected alias add_left_inj := Nat.add_right_cancel_iff @[simp, nolint simpNF] protected alias add_right_inj := Nat.add_left_cancel_iff -- Sometimes a bare `Nat.add` or similar appears as a consequence of unfolding during pattern -- matching. These lemmas package them back up as typeclass mediated operations. -- TODO: This is a duplicate of `Nat.add_eq` @[simp] lemma add_def : Nat.add m n = m + n := rfl -- We want to use these two lemmas earlier than the lemmas simp can prove them with @[simp, nolint simpNF] protected lemma add_eq_left : a + b = a ↔ b = 0 := by omega @[simp, nolint simpNF] protected lemma add_eq_right : a + b = b ↔ a = 0 := by omega lemma two_le_iff : βˆ€ n, 2 ≀ n ↔ n β‰  0 ∧ n β‰  1 | 0 => by simp | 1 => by simp | n + 2 => by simp lemma add_eq_max_iff : m + n = max m n ↔ m = 0 ∨ n = 0 := by omega lemma add_eq_min_iff : m + n = min m n ↔ m = 0 ∧ n = 0 := by omega -- We want to use this lemma earlier than the lemma simp can prove it with @[simp, nolint simpNF] protected lemma add_eq_zero : m + n = 0 ↔ m = 0 ∧ n = 0 := by omega lemma add_pos_iff_pos_or_pos : 0 < m + n ↔ 0 < m ∨ 0 < n := by omega lemma add_eq_one_iff : m + n = 1 ↔ m = 0 ∧ n = 1 ∨ m = 1 ∧ n = 0 := by cases n <;> simp [← Nat.add_assoc, succ_inj'] lemma add_eq_two_iff : m + n = 2 ↔ m = 0 ∧ n = 2 ∨ m = 1 ∧ n = 1 ∨ m = 2 ∧ n = 0 := by omega lemma add_eq_three_iff : m + n = 3 ↔ m = 0 ∧ n = 3 ∨ m = 1 ∧ n = 2 ∨ m = 2 ∧ n = 1 ∨ m = 3 ∧ n = 0 := by omega lemma le_add_one_iff : m ≀ n + 1 ↔ m ≀ n ∨ m = n + 1 := by rw [Nat.le_iff_lt_or_eq, Nat.lt_add_one_iff] lemma le_and_le_add_one_iff : n ≀ m ∧ m ≀ n + 1 ↔ m = n ∨ m = n + 1 := by rw [le_add_one_iff, and_or_left, ← Nat.le_antisymm_iff, eq_comm, and_iff_right_of_imp] rintro rfl exact n.le_succ lemma add_succ_lt_add (hab : a < b) (hcd : c < d) : a + c + 1 < b + d := by rw [Nat.add_assoc]; exact Nat.add_lt_add_of_lt_of_le hab (Nat.succ_le_iff.2 hcd) theorem le_or_le_of_add_eq_add_pred (h : a + c = b + d - 1) : b ≀ a ∨ d ≀ c := by rcases le_or_lt b a with h' | h' <;> [left; right] Β· exact h' Β· replace h' := Nat.add_lt_add_right h' c rw [h] at h' rcases d.eq_zero_or_pos with hn | hn Β· rw [hn] exact zero_le c rw [d.add_sub_assoc (Nat.succ_le_of_lt hn), Nat.add_lt_add_iff_left] at h' exact Nat.le_of_pred_lt h' /-! ### `sub` -/ attribute [simp] Nat.sub_eq_zero_of_le Nat.sub_le_iff_le_add Nat.add_sub_cancel_left Nat.add_sub_cancel_right /-- A version of `Nat.sub_succ` in the form `_ - 1` instead of `Nat.pred _`. -/ lemma sub_succ' (m n : β„•) : m - n.succ = m - n - 1 := rfl protected lemma sub_eq_of_eq_add' (h : a = b + c) : a - b = c := by rw [h, Nat.add_sub_cancel_left] protected lemma eq_sub_of_add_eq (h : c + b = a) : c = a - b := (Nat.sub_eq_of_eq_add h.symm).symm protected lemma eq_sub_of_add_eq' (h : b + c = a) : c = a - b := (Nat.sub_eq_of_eq_add' h.symm).symm protected lemma lt_sub_iff_add_lt : a < c - b ↔ a + b < c := ⟨add_lt_of_lt_sub, lt_sub_of_add_lt⟩ protected lemma lt_sub_iff_add_lt' : a < c - b ↔ b + a < c := by omega protected lemma sub_lt_iff_lt_add (hba : b ≀ a) : a - b < c ↔ a < b + c := by omega protected lemma sub_lt_iff_lt_add' (hba : b ≀ a) : a - b < c ↔ a < c + b := by omega protected lemma sub_sub_sub_cancel_right (h : c ≀ b) : a - c - (b - c) = a - b := by omega protected lemma add_sub_sub_cancel (h : c ≀ a) : a + b - (a - c) = b + c := by omega protected lemma sub_add_sub_cancel (hab : b ≀ a) (hcb : c ≀ b) : a - b + (b - c) = a - c := by omega lemma lt_pred_iff : a < pred b ↔ succ a < b := Nat.lt_sub_iff_add_lt (b := 1) protected lemma sub_lt_sub_iff_right (h : c ≀ a) : a - c < b - c ↔ a < b := by omega /-! ### `mul` -/ @[simp] lemma mul_def : Nat.mul m n = m * n := rfl -- Porting note: removing `simp` attribute protected lemma zero_eq_mul : 0 = m * n ↔ m = 0 ∨ n = 0 := by rw [eq_comm, Nat.mul_eq_zero] lemma two_mul_ne_two_mul_add_one : 2 * n β‰  2 * m + 1 := mt (congrArg (Β· % 2)) (by rw [Nat.add_comm, add_mul_mod_self_left, mul_mod_right, mod_eq_of_lt] <;> simp) -- TODO: Replace `Nat.mul_right_cancel_iff` with `Nat.mul_left_inj` protected lemma mul_left_inj (ha : a β‰  0) : b * a = c * a ↔ b = c := Nat.mul_right_cancel_iff (Nat.pos_iff_ne_zero.2 ha) _ _ -- TODO: Replace `Nat.mul_left_cancel_iff` with `Nat.mul_right_inj` protected lemma mul_right_inj (ha : a β‰  0) : a * b = a * c ↔ b = c := Nat.mul_left_cancel_iff (Nat.pos_iff_ne_zero.2 ha) _ _ protected lemma mul_ne_mul_left (ha : a β‰  0) : b * a β‰  c * a ↔ b β‰  c := not_congr (Nat.mul_left_inj ha) protected lemma mul_ne_mul_right (ha : a β‰  0) : a * b β‰  a * c ↔ b β‰  c := not_congr (Nat.mul_right_inj ha) lemma mul_eq_left (ha : a β‰  0) : a * b = a ↔ b = 1 := by simpa using Nat.mul_right_inj ha (c := 1) lemma mul_eq_right (hb : b β‰  0) : a * b = b ↔ a = 1 := by simpa using Nat.mul_left_inj hb (c := 1) -- TODO: Deprecate lemma mul_right_eq_self_iff (ha : 0 < a) : a * b = a ↔ b = 1 := mul_eq_left $ ne_of_gt ha lemma mul_left_eq_self_iff (hb : 0 < b) : a * b = b ↔ a = 1 := mul_eq_right $ ne_of_gt hb protected lemma le_of_mul_le_mul_right (h : a * c ≀ b * c) (hc : 0 < c) : a ≀ b := Nat.le_of_mul_le_mul_left (by simpa [Nat.mul_comm]) hc protected alias mul_sub := Nat.mul_sub_left_distrib protected alias sub_mul := Nat.mul_sub_right_distrib set_option push_neg.use_distrib true in /-- The product of two natural numbers is greater than 1 if and only if at least one of them is greater than 1 and both are positive. -/ lemma one_lt_mul_iff : 1 < m * n ↔ 0 < m ∧ 0 < n ∧ (1 < m ∨ 1 < n) := by constructor <;> intro h Β· by_contra h'; push_neg at h'; simp [Nat.le_zero] at h' obtain rfl | rfl | h' := h' Β· simp at h Β· simp at h Β· exact Nat.not_lt_of_le (Nat.mul_le_mul h'.1 h'.2) h Β· obtain hm | hn := h.2.2 Β· exact Nat.mul_lt_mul_of_lt_of_le' hm h.2.1 Nat.zero_lt_one Β· exact Nat.mul_lt_mul_of_le_of_lt h.1 hn h.1 lemma eq_one_of_mul_eq_one_right (H : m * n = 1) : m = 1 := eq_one_of_dvd_one ⟨n, H.symm⟩ lemma eq_one_of_mul_eq_one_left (H : m * n = 1) : n = 1 := eq_one_of_mul_eq_one_right (n := m) (by rwa [Nat.mul_comm]) @[simp] protected lemma lt_mul_iff_one_lt_left (hb : 0 < b) : b < a * b ↔ 1 < a := by simpa using Nat.mul_lt_mul_right (b := 1) hb @[simp] protected lemma lt_mul_iff_one_lt_right (ha : 0 < a) : a < a * b ↔ 1 < b := by simpa using Nat.mul_lt_mul_left (b := 1) ha lemma eq_zero_of_double_le (h : 2 * n ≀ n) : n = 0 := by omega lemma eq_zero_of_mul_le (hb : 2 ≀ n) (h : n * m ≀ m) : m = 0 := eq_zero_of_double_le <| Nat.le_trans (Nat.mul_le_mul_right _ hb) h lemma succ_mul_pos (m : β„•) (hn : 0 < n) : 0 < succ m * n := Nat.mul_pos m.succ_pos hn lemma mul_self_le_mul_self (h : m ≀ n) : m * m ≀ n * n := Nat.mul_le_mul h h lemma mul_lt_mul'' (hac : a < c) (hbd : b < d) : a * b < c * d := Nat.mul_lt_mul_of_lt_of_le hac (Nat.le_of_lt hbd) $ by omega lemma mul_self_lt_mul_self (h : m < n) : m * m < n * n := mul_lt_mul'' h h lemma mul_self_le_mul_self_iff : m * m ≀ n * n ↔ m ≀ n := ⟨fun h => Nat.le_of_not_lt fun h' => Nat.not_le_of_gt (mul_self_lt_mul_self h') h, mul_self_le_mul_self⟩ lemma mul_self_lt_mul_self_iff : m * m < n * n ↔ m < n := by simp only [← Nat.not_le, mul_self_le_mul_self_iff] lemma le_mul_self : βˆ€ n : β„•, n ≀ n * n | 0 => Nat.le_refl _ | n + 1 => by simp [Nat.mul_add] lemma mul_self_inj : m * m = n * n ↔ m = n := by simp [Nat.le_antisymm_iff, mul_self_le_mul_self_iff] @[simp] lemma lt_mul_self_iff : βˆ€ {n : β„•}, n < n * n ↔ 1 < n | 0 => by simp | n + 1 => Nat.lt_mul_iff_one_lt_left n.succ_pos lemma add_sub_one_le_mul (ha : a β‰  0) (hb : b β‰  0) : a + b - 1 ≀ a * b := by cases a Β· cases ha rfl Β· rw [succ_add, Nat.add_one_sub_one, succ_mul] exact Nat.add_le_add_right (Nat.le_mul_of_pos_right _ $ Nat.pos_iff_ne_zero.2 hb) _ protected lemma add_le_mul {a : β„•} (ha : 2 ≀ a) : βˆ€ {b : β„•} (_ : 2 ≀ b), a + b ≀ a * b | 2, _ => by omega | b + 3, _ => by have := Nat.add_le_mul ha (Nat.le_add_left _ b); rw [mul_succ]; omega /-! ### `div` -/ attribute [simp] Nat.div_self lemma div_le_iff_le_mul_add_pred (hb : 0 < b) : a / b ≀ c ↔ a ≀ b * c + (b - 1) := by rw [← Nat.lt_succ_iff, div_lt_iff_lt_mul hb, succ_mul, Nat.mul_comm] cases hb <;> exact Nat.lt_succ_iff /-- A version of `Nat.div_lt_self` using successors, rather than additional hypotheses. -/ lemma div_lt_self' (a b : β„•) : (a + 1) / (b + 2) < a + 1 := Nat.div_lt_self (Nat.succ_pos _) (Nat.succ_lt_succ (Nat.succ_pos _)) lemma le_div_iff_mul_le' (hb : 0 < b) : a ≀ c / b ↔ a * b ≀ c := le_div_iff_mul_le hb lemma div_lt_iff_lt_mul' (hb : 0 < b) : a / b < c ↔ a < c * b := by simp only [← Nat.not_le, le_div_iff_mul_le' hb] lemma one_le_div_iff (hb : 0 < b) : 1 ≀ a / b ↔ b ≀ a := by rw [le_div_iff_mul_le hb, Nat.one_mul] lemma div_lt_one_iff (hb : 0 < b) : a / b < 1 ↔ a < b := by simp only [← Nat.not_le, one_le_div_iff hb] @[gcongr] protected lemma div_le_div_right (h : a ≀ b) : a / c ≀ b / c := (c.eq_zero_or_pos.elim fun hc ↦ by simp [hc]) fun hc ↦ (le_div_iff_mul_le' hc).2 <| Nat.le_trans (Nat.div_mul_le_self _ _) h lemma lt_of_div_lt_div (h : a / c < b / c) : a < b := Nat.lt_of_not_le fun hab ↦ Nat.not_le_of_lt h $ Nat.div_le_div_right hab protected lemma div_pos (hba : b ≀ a) (hb : 0 < b) : 0 < a / b := Nat.pos_of_ne_zero fun h ↦ Nat.lt_irrefl a $ calc a = a % b := by simpa [h] using (mod_add_div a b).symm _ < b := mod_lt a hb _ ≀ a := hba lemma lt_mul_of_div_lt (h : a / c < b) (hc : 0 < c) : a < b * c := Nat.lt_of_not_ge <| Nat.not_le_of_gt h ∘ (Nat.le_div_iff_mul_le hc).2 lemma mul_div_le_mul_div_assoc (a b c : β„•) : a * (b / c) ≀ a * b / c := if hc0 : c = 0 then by simp [hc0] else (Nat.le_div_iff_mul_le (Nat.pos_of_ne_zero hc0)).2 (by rw [Nat.mul_assoc]; exact Nat.mul_le_mul_left _ (Nat.div_mul_le_self _ _)) protected lemma eq_mul_of_div_eq_left (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [Nat.mul_comm, Nat.eq_mul_of_div_eq_right H1 H2] protected lemma mul_div_cancel_left' (Hd : a ∣ b) : a * (b / a) = b := by rw [Nat.mul_comm, Nat.div_mul_cancel Hd] lemma lt_div_mul_add (hb : 0 < b) : a < a / b * b + b := by rw [← Nat.succ_mul, ← Nat.div_lt_iff_lt_mul hb]; exact Nat.lt_succ_self _ @[simp] protected lemma div_left_inj (hda : d ∣ a) (hdb : d ∣ b) : a / d = b / d ↔ a = b := by refine ⟨fun h ↦ ?_, congrArg fun b ↦ b / d⟩ rw [← Nat.mul_div_cancel' hda, ← Nat.mul_div_cancel' hdb, h] lemma div_mul_div_comm : b ∣ a β†’ d ∣ c β†’ (a / b) * (c / d) = (a * c) / (b * d) := by rintro ⟨x, rfl⟩ ⟨y, rfl⟩ obtain rfl | hb := b.eq_zero_or_pos Β· simp obtain rfl | hd := d.eq_zero_or_pos Β· simp rw [Nat.mul_div_cancel_left _ hb, Nat.mul_div_cancel_left _ hd, Nat.mul_assoc b, Nat.mul_left_comm x, ← Nat.mul_assoc b, Nat.mul_div_cancel_left _ (Nat.mul_pos hb hd)] protected lemma mul_div_mul_comm (hba : b ∣ a) (hdc : d ∣ c) : a * c / (b * d) = a / b * (c / d) := (div_mul_div_comm hba hdc).symm @[deprecated (since := "2024-05-29")] alias mul_div_mul_comm_of_dvd_dvd := Nat.mul_div_mul_comm lemma eq_zero_of_le_div (hn : 2 ≀ n) (h : m ≀ m / n) : m = 0 := eq_zero_of_mul_le hn <| by rw [Nat.mul_comm]; exact (Nat.le_div_iff_mul_le' (Nat.lt_of_lt_of_le (by decide) hn)).1 h lemma div_mul_div_le_div (a b c : β„•) : a / c * b / a ≀ b / c := by obtain rfl | ha := Nat.eq_zero_or_pos a Β· simp Β· calc a / c * b / a ≀ b * a / c / a := Nat.div_le_div_right (by rw [Nat.mul_comm]; exact mul_div_le_mul_div_assoc _ _ _) _ = b / c := by rw [Nat.div_div_eq_div_mul, Nat.mul_comm b, Nat.mul_comm c, Nat.mul_div_mul_left _ _ ha] lemma eq_zero_of_le_half (h : n ≀ n / 2) : n = 0 := eq_zero_of_le_div (Nat.le_refl _) h lemma le_half_of_half_lt_sub (h : a / 2 < a - b) : b ≀ a / 2 := by rw [Nat.le_div_iff_mul_le Nat.two_pos] rw [Nat.div_lt_iff_lt_mul Nat.two_pos, Nat.sub_mul, Nat.lt_sub_iff_add_lt, Nat.mul_two a] at h exact Nat.le_of_lt (Nat.lt_of_add_lt_add_left h) lemma half_le_of_sub_le_half (h : a - b ≀ a / 2) : a / 2 ≀ b := by rw [Nat.le_div_iff_mul_le Nat.two_pos, Nat.sub_mul, Nat.sub_le_iff_le_add, Nat.mul_two, Nat.add_le_add_iff_left] at h rw [← Nat.mul_div_left b Nat.two_pos] exact Nat.div_le_div_right h protected lemma div_le_of_le_mul' (h : m ≀ k * n) : m / k ≀ n := by obtain rfl | hk := k.eq_zero_or_pos Β· simp Β· refine Nat.le_of_mul_le_mul_left ?_ hk calc k * (m / k) ≀ m % k + k * (m / k) := Nat.le_add_left _ _ _ = m := mod_add_div _ _ _ ≀ k * n := h protected lemma div_le_div_of_mul_le_mul (hd : d β‰  0) (hdc : d ∣ c) (h : a * d ≀ c * b) : a / b ≀ c / d := Nat.div_le_of_le_mul' $ by rwa [← Nat.mul_div_assoc _ hdc, Nat.le_div_iff_mul_le (Nat.pos_iff_ne_zero.2 hd), b.mul_comm] protected lemma div_le_self' (m n : β„•) : m / n ≀ m := by obtain rfl | hn := n.eq_zero_or_pos Β· simp Β· refine Nat.div_le_of_le_mul' ?_ calc m = 1 * m := by rw [Nat.one_mul] _ ≀ n * m := Nat.mul_le_mul_right _ hn lemma two_mul_odd_div_two (hn : n % 2 = 1) : 2 * (n / 2) = n - 1 := by conv => rhs; rw [← Nat.mod_add_div n 2, hn, Nat.add_sub_cancel_left] @[gcongr] lemma div_le_div_left (hcb : c ≀ b) (hc : 0 < c) : a / b ≀ a / c := (Nat.le_div_iff_mul_le hc).2 <| Nat.le_trans (Nat.mul_le_mul_left _ hcb) (div_mul_le_self _ _) lemma div_eq_self : m / n = m ↔ m = 0 ∨ n = 1 := by constructor Β· intro match n with | 0 => simp_all | 1 => right; rfl | n+2 => left have : m / (n + 2) ≀ m / 2 := div_le_div_left (by simp) (by decide) refine eq_zero_of_le_half ?_ simp_all Β· rintro (rfl | rfl) <;> simp lemma div_eq_sub_mod_div : m / n = (m - m % n) / n := by obtain rfl | hn := n.eq_zero_or_pos Β· rw [Nat.div_zero, Nat.div_zero] Β· have : m - m % n = n * (m / n) := by rw [Nat.sub_eq_iff_eq_add (Nat.mod_le _ _), Nat.add_comm, mod_add_div] rw [this, mul_div_right _ hn] protected lemma eq_div_of_mul_eq_left (hc : c β‰  0) (h : a * c = b) : a = b / c := by rw [← h, Nat.mul_div_cancel _ (Nat.pos_iff_ne_zero.2 hc)] protected lemma eq_div_of_mul_eq_right (hc : c β‰  0) (h : c * a = b) : a = b / c := by rw [← h, Nat.mul_div_cancel_left _ (Nat.pos_iff_ne_zero.2 hc)] protected lemma mul_le_of_le_div (k x y : β„•) (h : x ≀ y / k) : x * k ≀ y := by if hk : k = 0 then rw [hk, Nat.mul_zero]; exact zero_le _ else rwa [← le_div_iff_mul_le (Nat.pos_iff_ne_zero.2 hk)] protected lemma div_mul_div_le (a b c d : β„•) : (a / b) * (c / d) ≀ (a * c) / (b * d) := by if hb : b = 0 then simp [hb] else if hd : d = 0 then simp [hd] else have hbd : b * d β‰  0 := Nat.mul_ne_zero hb hd rw [le_div_iff_mul_le (Nat.pos_of_ne_zero hbd)] transitivity ((a / b) * b) * ((c / d) * d) Β· apply Nat.le_of_eq; simp only [Nat.mul_assoc, Nat.mul_left_comm] Β· apply Nat.mul_le_mul <;> apply div_mul_le_self /-! ### `pow` #### TODO * Rename `Nat.pow_le_pow_of_le_left` to `Nat.pow_le_pow_left`, protect it, remove the alias * Rename `Nat.pow_le_pow_of_le_right` to `Nat.pow_le_pow_right`, protect it, remove the alias -/ protected lemma pow_lt_pow_left (h : a < b) : βˆ€ {n : β„•}, n β‰  0 β†’ a ^ n < b ^ n | 1, _ => by simpa | n + 2, _ => Nat.mul_lt_mul_of_lt_of_le (Nat.pow_lt_pow_left h n.succ_ne_zero) (Nat.le_of_lt h) (zero_lt_of_lt h) protected lemma pow_lt_pow_right (ha : 1 < a) (h : m < n) : a ^ m < a ^ n := (Nat.pow_lt_pow_iff_right ha).2 h protected lemma pow_le_pow_iff_left {n : β„•} (hn : n β‰  0) : a ^ n ≀ b ^ n ↔ a ≀ b where mp := by simpa only [← Nat.not_le, Decidable.not_imp_not] using (Nat.pow_lt_pow_left Β· hn) mpr h := Nat.pow_le_pow_left h _ protected lemma pow_lt_pow_iff_left (hn : n β‰  0) : a ^ n < b ^ n ↔ a < b := by simp only [← Nat.not_le, Nat.pow_le_pow_iff_left hn] @[deprecated (since := "2023-12-23")] alias pow_lt_pow_of_lt_left := Nat.pow_lt_pow_left @[deprecated (since := "2023-12-23")] alias pow_le_iff_le_left := Nat.pow_le_pow_iff_left lemma pow_left_injective (hn : n β‰  0) : Injective (fun a : β„• ↦ a ^ n) := by simp [Injective, le_antisymm_iff, Nat.pow_le_pow_iff_left hn] protected lemma pow_right_injective (ha : 2 ≀ a) : Injective (a ^ Β·) := by simp [Injective, le_antisymm_iff, Nat.pow_le_pow_iff_right ha] -- We want to use this lemma earlier than the lemma simp can prove it with @[simp, nolint simpNF] protected lemma pow_eq_zero {a : β„•} : βˆ€ {n : β„•}, a ^ n = 0 ↔ a = 0 ∧ n β‰  0 | 0 => by simp | n + 1 => by rw [Nat.pow_succ, mul_eq_zero, Nat.pow_eq_zero]; omega /-- For `a > 1`, `a ^ b = a` iff `b = 1`. -/ lemma pow_eq_self_iff {a b : β„•} (ha : 1 < a) : a ^ b = a ↔ b = 1 := (Nat.pow_right_injective ha).eq_iff' a.pow_one lemma le_self_pow (hn : n β‰  0) : βˆ€ a : β„•, a ≀ a ^ n | 0 => zero_le _ | a + 1 => by simpa using Nat.pow_le_pow_right a.succ_pos (Nat.one_le_iff_ne_zero.2 hn) lemma lt_pow_self (ha : 1 < a) : βˆ€ n : β„•, n < a ^ n | 0 => by simp | n + 1 => calc n + 1 < a ^ n + 1 := Nat.add_lt_add_right (lt_pow_self ha _) _ _ ≀ a ^ (n + 1) := Nat.pow_lt_pow_succ ha lemma lt_two_pow (n : β„•) : n < 2 ^ n := lt_pow_self (by decide) n lemma one_le_pow (n m : β„•) (h : 0 < m) : 1 ≀ m ^ n := by simpa using Nat.pow_le_pow_of_le_left h n lemma one_le_pow' (n m : β„•) : 1 ≀ (m + 1) ^ n := one_le_pow n (m + 1) (succ_pos m) lemma one_lt_pow (hn : n β‰  0) (ha : 1 < a) : 1 < a ^ n := by simpa using Nat.pow_lt_pow_left ha hn lemma two_pow_succ (n : β„•) : 2 ^ (n + 1) = 2 ^ n + 2 ^ n := by simp [Nat.pow_succ, Nat.mul_two] lemma one_lt_pow' (n m : β„•) : 1 < (m + 2) ^ (n + 1) := one_lt_pow n.succ_ne_zero (Nat.lt_of_sub_eq_succ rfl) @[simp] lemma one_lt_pow_iff {n : β„•} (hn : n β‰  0) : βˆ€ {a}, 1 < a ^ n ↔ 1 < a | 0 => by simp [Nat.zero_pow (Nat.pos_of_ne_zero hn)] | 1 => by simp | a + 2 => by simp [one_lt_pow hn] -- one_lt_pow_iff_of_nonneg (zero_le _) h lemma one_lt_two_pow' (n : β„•) : 1 < 2 ^ (n + 1) := one_lt_pow n.succ_ne_zero (by decide) lemma mul_lt_mul_pow_succ (ha : 0 < a) (hb : 1 < b) : n * b < a * b ^ (n + 1) := by rw [Nat.pow_succ, ← Nat.mul_assoc, Nat.mul_lt_mul_right (Nat.lt_trans Nat.zero_lt_one hb)] exact Nat.lt_of_le_of_lt (Nat.le_mul_of_pos_left _ ha) ((Nat.mul_lt_mul_left ha).2 $ Nat.lt_pow_self hb _) lemma sq_sub_sq (a b : β„•) : a ^ 2 - b ^ 2 = (a + b) * (a - b) := by simpa [Nat.pow_succ] using Nat.mul_self_sub_mul_self_eq a b alias pow_two_sub_pow_two := sq_sub_sq protected lemma div_pow (h : a ∣ b) : (b / a) ^ c = b ^ c / a ^ c := by obtain rfl | hc := c.eq_zero_or_pos Β· simp obtain rfl | ha := a.eq_zero_or_pos Β· simp [Nat.zero_pow hc] refine (Nat.div_eq_of_eq_mul_right (pos_pow_of_pos c ha) ?_).symm rw [← Nat.mul_pow, Nat.mul_div_cancel_left' h] /-! ### Recursion and induction principles This section is here due to dependencies -- the lemmas here require some of the lemmas proved above, and some of the results in later sections depend on the definitions in this section. -/ -- Porting note: The type ascriptions of these two lemmas need to be changed, -- as mathport wrote a lambda that wasn't there in mathlib3, that prevents `simp` applying them. @[simp] lemma rec_zero {C : β„• β†’ Sort*} (h0 : C 0) (h : βˆ€ n, C n β†’ C (n + 1)) : Nat.rec h0 h 0 = h0 := rfl lemma rec_add_one {C : β„• β†’ Sort*} (h0 : C 0) (h : βˆ€ n, C n β†’ C (n + 1)) (n : β„•) : Nat.rec h0 h (n + 1) = h n (Nat.rec h0 h n) := rfl @[simp] lemma rec_one {C : β„• β†’ Sort*} (h0 : C 0) (h : βˆ€ n, C n β†’ C (n + 1)) : Nat.rec (motive := C) h0 h 1 = h 0 h0 := rfl /-- Recursion starting at a non-zero number: given a map `C k β†’ C (k+1)` for each `k β‰₯ n`, there is a map from `C n` to each `C m`, `n ≀ m`. This is a version of `Nat.le.rec` that works for `Sort u`. Similarly to `Nat.le.rec`, it can be used as ``` induction hle using Nat.leRec with | refl => sorry | le_succ_of_le hle ih => sorry ``` -/ @[elab_as_elim] def leRec {n} {motive : (m : β„•) β†’ n ≀ m β†’ Sort*} (refl : motive n le_rfl) (le_succ_of_le : βˆ€ ⦃k⦄ (h : n ≀ k), motive k h β†’ motive (k + 1) (le_succ_of_le h)) : βˆ€ {m} (h : n ≀ m), motive m h | 0, H => Nat.eq_zero_of_le_zero H β–Έ refl | m + 1, H => (le_succ_iff.1 H).by_cases (fun h : n ≀ m ↦ le_succ_of_le h <| leRec refl le_succ_of_le h) (fun h : n = m + 1 ↦ h β–Έ refl) -- This verifies the signatures of the recursor matches the builtin one, as promised in the -- above. theorem leRec_eq_leRec : @Nat.leRec.{0} = @Nat.le.rec := rfl @[simp] lemma leRec_self {n} {motive : (m : β„•) β†’ n ≀ m β†’ Sort*} (refl : motive n le_rfl) (le_succ_of_le : βˆ€ ⦃k⦄ (h : n ≀ k), motive k h β†’ motive (k + 1) (le_succ_of_le h)) : (leRec (motive := motive) refl le_succ_of_le le_rfl : motive n le_rfl) = refl := by cases n <;> simp [leRec, Or.by_cases, dif_neg] @[simp] lemma leRec_succ {n} {motive : (m : β„•) β†’ n ≀ m β†’ Sort*} (refl : motive n le_rfl) (le_succ_of_le : βˆ€ ⦃k⦄ (h : n ≀ k), motive k h β†’ motive (k + 1) (le_succ_of_le h)) (h1 : n ≀ m) {h2 : n ≀ m + 1} : (leRec (motive := motive) refl le_succ_of_le h2) = le_succ_of_le h1 (leRec (motive := motive) refl le_succ_of_le h1) := by conv => lhs rw [leRec, Or.by_cases, dif_pos h1] lemma leRec_succ' {n} {motive : (m : β„•) β†’ n ≀ m β†’ Sort*} (refl le_succ_of_le) : (leRec (motive := motive) refl le_succ_of_le (le_succ _)) = le_succ_of_le _ refl := by rw [leRec_succ, leRec_self] lemma leRec_trans {n m k} {motive : (m : β„•) β†’ n ≀ m β†’ Sort*} (refl le_succ_of_le) (hnm : n ≀ m) (hmk : m ≀ k) : leRec (motive := motive) refl le_succ_of_le (Nat.le_trans hnm hmk) = leRec (leRec refl (fun _ h => le_succ_of_le h) hnm) (fun _ h => le_succ_of_le <| Nat.le_trans hnm h) hmk := by induction hmk with | refl => rw [leRec_self] | step hmk ih => rw [leRec_succ _ _ (Nat.le_trans hnm hmk), ih, leRec_succ] lemma leRec_succ_left {motive : (m : β„•) β†’ n ≀ m β†’ Sort*} (refl le_succ_of_le) {m} (h1 : n ≀ m) (h2 : n + 1 ≀ m) : -- the `@` is needed for this to elaborate, even though we only provide explicit arguments! @leRec _ _ (le_succ_of_le le_rfl refl) (fun k h ih => le_succ_of_le (le_of_succ_le h) ih) _ h2 = leRec (motive := motive) refl le_succ_of_le h1 := by rw [leRec_trans _ _ (le_succ n) h2, leRec_succ'] /-- Recursion starting at a non-zero number: given a map `C k β†’ C (k+1)` for each `k β‰₯ n`, there is a map from `C n` to each `C m`, `n ≀ m`. Prefer `Nat.leRec`, which can be used as `induction h using Nat.leRec`. -/ @[elab_as_elim, deprecated Nat.leRec (since := "2024-07-05")] def leRecOn' {C : β„• β†’ Sort*} : βˆ€ {m}, n ≀ m β†’ (βˆ€ ⦃k⦄, n ≀ k β†’ C k β†’ C (k + 1)) β†’ C n β†’ C m := fun h of_succ self => Nat.leRec self of_succ h /-- Recursion starting at a non-zero number: given a map `C k β†’ C (k + 1)` for each `k`, there is a map from `C n` to each `C m`, `n ≀ m`. For a version where the assumption is only made when `k β‰₯ n`, see `Nat.leRec`. -/ @[elab_as_elim] def leRecOn {C : β„• β†’ Sort*} {n : β„•} : βˆ€ {m}, n ≀ m β†’ (βˆ€ {k}, C k β†’ C (k + 1)) β†’ C n β†’ C m := fun h of_succ self => Nat.leRec self (fun _ _ => @of_succ _) h lemma leRecOn_self {C : β„• β†’ Sort*} {n} {next : βˆ€ {k}, C k β†’ C (k + 1)} (x : C n) : (leRecOn n.le_refl next x : C n) = x := leRec_self _ _ lemma leRecOn_succ {C : β„• β†’ Sort*} {n m} (h1 : n ≀ m) {h2 : n ≀ m + 1} {next} (x : C n) : (leRecOn h2 next x : C (m + 1)) = next (leRecOn h1 next x : C m) := leRec_succ _ _ _ lemma leRecOn_succ' {C : β„• β†’ Sort*} {n} {h : n ≀ n + 1} {next : βˆ€ {k}, C k β†’ C (k + 1)} (x : C n) : (leRecOn h next x : C (n + 1)) = next x := leRec_succ' _ _ lemma leRecOn_trans {C : β„• β†’ Sort*} {n m k} (hnm : n ≀ m) (hmk : m ≀ k) {next} (x : C n) : (leRecOn (Nat.le_trans hnm hmk) (@next) x : C k) = leRecOn hmk (@next) (leRecOn hnm (@next) x) := leRec_trans _ _ _ _ lemma leRecOn_succ_left {C : β„• β†’ Sort*} {n m} {next : βˆ€ {k}, C k β†’ C (k + 1)} (x : C n) (h1 : n ≀ m) (h2 : n + 1 ≀ m) : (leRecOn h2 next (next x) : C m) = (leRecOn h1 next x : C m) := leRec_succ_left (motive := fun n _ => C n) _ (fun _ _ => @next _) _ _ lemma leRecOn_injective {C : β„• β†’ Sort*} {n m} (hnm : n ≀ m) (next : βˆ€ {k}, C k β†’ C (k + 1)) (Hnext : βˆ€ n, Injective (@next n)) : Injective (@leRecOn C n m hnm next) := by induction hnm with | refl => intro x y H rwa [leRecOn_self, leRecOn_self] at H | step hnm ih => intro x y H rw [leRecOn_succ hnm, leRecOn_succ hnm] at H exact ih (Hnext _ H) lemma leRecOn_surjective {C : β„• β†’ Sort*} {n m} (hnm : n ≀ m) (next : βˆ€ {k}, C k β†’ C (k + 1)) (Hnext : βˆ€ n, Surjective (@next n)) : Surjective (@leRecOn C n m hnm next) := by induction hnm with | refl => intro x refine ⟨x, ?_⟩ rw [leRecOn_self] | step hnm ih => intro x obtain ⟨w, rfl⟩ := Hnext _ x obtain ⟨x, rfl⟩ := ih w refine ⟨x, ?_⟩ rw [leRecOn_succ] /-- Recursion principle based on `<`. -/ @[elab_as_elim] protected def strongRec' {p : β„• β†’ Sort*} (H : βˆ€ n, (βˆ€ m, m < n β†’ p m) β†’ p n) : βˆ€ n : β„•, p n | n => H n fun m _ ↦ Nat.strongRec' H m /-- Recursion principle based on `<` applied to some natural number. -/ @[elab_as_elim] def strongRecOn' {P : β„• β†’ Sort*} (n : β„•) (h : βˆ€ n, (βˆ€ m, m < n β†’ P m) β†’ P n) : P n := Nat.strongRec' h n lemma strongRecOn'_beta {P : β„• β†’ Sort*} {h} : (strongRecOn' n h : P n) = h n fun m _ ↦ (strongRecOn' m h : P m) := by simp only [strongRecOn']; rw [Nat.strongRec'] /-- Induction principle starting at a non-zero number. To use in an induction proof, the syntax is `induction n, hn using Nat.le_induction` (or the same for `induction'`). This is an alias of `Nat.leRec`, specialized to `Prop`. -/ @[elab_as_elim] lemma le_induction {m : β„•} {P : βˆ€ n, m ≀ n β†’ Prop} (base : P m m.le_refl) (succ : βˆ€ n hmn, P n hmn β†’ P (n + 1) (le_succ_of_le hmn)) : βˆ€ n hmn, P n hmn := @Nat.leRec (motive := P) base succ /-- Decreasing induction: if `P (k+1)` implies `P k` for all `k < n`, then `P n` implies `P m` for all `m ≀ n`. Also works for functions to `Sort*`. For a version also assuming `m ≀ k`, see `Nat.decreasingInduction'`. -/ @[elab_as_elim] def decreasingInduction {n} {motive : (m : β„•) β†’ m ≀ n β†’ Sort*} (of_succ : βˆ€ k (h : k < n), motive (k + 1) h β†’ motive k (le_of_succ_le h)) (self : motive n le_rfl) {m} (mn : m ≀ n) : motive m mn := by induction mn using leRec with | refl => exact self | @le_succ_of_le k _ ih => apply ih (fun i hi => of_succ i (le_succ_of_le hi)) (of_succ k (lt_succ_self _) self) @[simp] lemma decreasingInduction_self {n} {motive : (m : β„•) β†’ m ≀ n β†’ Sort*} (of_succ self) : (decreasingInduction (motive := motive) of_succ self le_rfl) = self := by dsimp only [decreasingInduction] rw [leRec_self] lemma decreasingInduction_succ {n} {motive : (m : β„•) β†’ m ≀ n + 1 β†’ Sort*} (of_succ self) (mn : m ≀ n) (msn : m ≀ n + 1) : (decreasingInduction (motive := motive) of_succ self msn : motive m msn) = decreasingInduction (motive := fun m h => motive m (le_succ_of_le h)) (fun i hi => of_succ _ _) (of_succ _ _ self) mn := by dsimp only [decreasingInduction]; rw [leRec_succ] @[simp] lemma decreasingInduction_succ' {n} {motive : (m : β„•) β†’ m ≀ n + 1 β†’ Sort*} (of_succ self) : decreasingInduction (motive := motive) of_succ self n.le_succ = of_succ _ _ self := by dsimp only [decreasingInduction]; rw [leRec_succ'] lemma decreasingInduction_trans {motive : (m : β„•) β†’ m ≀ k β†’ Sort*} (hmn : m ≀ n) (hnk : n ≀ k) (of_succ self) : (decreasingInduction (motive := motive) of_succ self (Nat.le_trans hmn hnk) : motive m _) = decreasingInduction (fun n ih => of_succ _ _) (decreasingInduction of_succ self hnk) hmn := by induction hnk with | refl => rw [decreasingInduction_self] | step hnk ih => rw [decreasingInduction_succ _ _ (Nat.le_trans hmn hnk), ih, decreasingInduction_succ] lemma decreasingInduction_succ_left {motive : (m : β„•) β†’ m ≀ n β†’ Sort*} (of_succ self) (smn : m + 1 ≀ n) (mn : m ≀ n) : decreasingInduction (motive := motive) of_succ self mn = of_succ m smn (decreasingInduction of_succ self smn) := by rw [Subsingleton.elim mn (Nat.le_trans (le_succ m) smn), decreasingInduction_trans, decreasingInduction_succ'] /-- Given `P : β„• β†’ β„• β†’ Sort*`, if for all `m n : β„•` we can extend `P` from the rectangle strictly below `(m, n)` to `P m n`, then we have `P n m` for all `n m : β„•`. Note that for non-`Prop` output it is preferable to use the equation compiler directly if possible, since this produces equation lemmas. -/ @[elab_as_elim] def strongSubRecursion {P : β„• β†’ β„• β†’ Sort*} (H : βˆ€ m n, (βˆ€ x y, x < m β†’ y < n β†’ P x y) β†’ P m n) : βˆ€ n m : β„•, P n m | n, m => H n m fun x y _ _ ↦ strongSubRecursion H x y /-- Given `P : β„• β†’ β„• β†’ Sort*`, if we have `P m 0` and `P 0 n` for all `m n : β„•`, and for any `m n : β„•` we can extend `P` from `(m, n + 1)` and `(m + 1, n)` to `(m + 1, n + 1)` then we have `P m n` for all `m n : β„•`. Note that for non-`Prop` output it is preferable to use the equation compiler directly if possible, since this produces equation lemmas. -/ @[elab_as_elim] def pincerRecursion {P : β„• β†’ β„• β†’ Sort*} (Ha0 : βˆ€ m : β„•, P m 0) (H0b : βˆ€ n : β„•, P 0 n) (H : βˆ€ x y : β„•, P x y.succ β†’ P x.succ y β†’ P x.succ y.succ) : βˆ€ n m : β„•, P n m | m, 0 => Ha0 m | 0, n => H0b n | Nat.succ m, Nat.succ n => H _ _ (pincerRecursion Ha0 H0b H _ _) (pincerRecursion Ha0 H0b H _ _) /-- Decreasing induction: if `P (k+1)` implies `P k` for all `m ≀ k < n`, then `P n` implies `P m`. Also works for functions to `Sort*`. Weakens the assumptions of `Nat.decreasingInduction`. -/ @[elab_as_elim] def decreasingInduction' {P : β„• β†’ Sort*} (h : βˆ€ k < n, m ≀ k β†’ P (k + 1) β†’ P k) (mn : m ≀ n) (hP : P n) : P m := by induction mn using decreasingInduction with | self => exact hP | of_succ k hk ih => exact h _ (lt_of_succ_le hk) le_rfl (ih fun k' hk' h'' => h k' hk' <| le_of_succ_le h'') /-- Given a predicate on two naturals `P : β„• β†’ β„• β†’ Prop`, `P a b` is true for all `a < b` if `P (a + 1) (a + 1)` is true for all `a`, `P 0 (b + 1)` is true for all `b` and for all `a < b`, `P (a + 1) b` is true and `P a (b + 1)` is true implies `P (a + 1) (b + 1)` is true. -/ @[elab_as_elim] theorem diag_induction (P : β„• β†’ β„• β†’ Prop) (ha : βˆ€ a, P (a + 1) (a + 1)) (hb : βˆ€ b, P 0 (b + 1)) (hd : βˆ€ a b, a < b β†’ P (a + 1) b β†’ P a (b + 1) β†’ P (a + 1) (b + 1)) : βˆ€ a b, a < b β†’ P a b | 0, b + 1, _ => hb _ | a + 1, b + 1, h => by apply hd _ _ (Nat.add_lt_add_iff_right.1 h) Β· have this : a + 1 = b ∨ a + 1 < b := by omega have wf : (a + 1) + b < (a + 1) + (b + 1) := by simp rcases this with (rfl | h) Β· exact ha _ apply diag_induction P ha hb hd (a + 1) b h have _ : a + (b + 1) < (a + 1) + (b + 1) := by simp apply diag_induction P ha hb hd a (b + 1) apply Nat.lt_of_le_of_lt (Nat.le_succ _) h termination_by a b _c => a + b decreasing_by all_goals assumption /-- A subset of `β„•` containing `k : β„•` and closed under `Nat.succ` contains every `n β‰₯ k`. -/ lemma set_induction_bounded {S : Set β„•} (hk : k ∈ S) (h_ind : βˆ€ k : β„•, k ∈ S β†’ k + 1 ∈ S) (hnk : k ≀ n) : n ∈ S := @leRecOn (fun n => n ∈ S) k n hnk @h_ind hk /-- A subset of `β„•` containing zero and closed under `Nat.succ` contains all of `β„•`. -/ lemma set_induction {S : Set β„•} (hb : 0 ∈ S) (h_ind : βˆ€ k : β„•, k ∈ S β†’ k + 1 ∈ S) (n : β„•) : n ∈ S := set_induction_bounded hb h_ind (zero_le n) /-! ### `mod`, `dvd` -/ attribute [simp] Nat.dvd_zero @[simp] lemma mod_two_ne_one : Β¬n % 2 = 1 ↔ n % 2 = 0 := by cases' mod_two_eq_zero_or_one n with h h <;> simp [h] @[simp] lemma mod_two_ne_zero : Β¬n % 2 = 0 ↔ n % 2 = 1 := by cases' mod_two_eq_zero_or_one n with h h <;> simp [h] @[deprecated mod_mul_right_div_self (since := "2024-05-29")] lemma div_mod_eq_mod_mul_div (a b c : β„•) : a / b % c = a % (b * c) / b := (mod_mul_right_div_self a b c).symm protected lemma lt_div_iff_mul_lt (hdn : d ∣ n) (a : β„•) : a < n / d ↔ d * a < n := by obtain rfl | hd := d.eq_zero_or_pos Β· simp [Nat.zero_dvd.1 hdn] Β· rw [← Nat.mul_lt_mul_left hd, ← Nat.eq_mul_of_div_eq_right hdn rfl] lemma mul_div_eq_iff_dvd {n d : β„•} : d * (n / d) = n ↔ d ∣ n := calc d * (n / d) = n ↔ d * (n / d) = d * (n / d) + (n % d) := by rw [div_add_mod] _ ↔ d ∣ n := by rw [eq_comm, Nat.add_eq_left, dvd_iff_mod_eq_zero] lemma mul_div_lt_iff_not_dvd : d * (n / d) < n ↔ Β¬ d ∣ n := by simp [Nat.lt_iff_le_and_ne, mul_div_eq_iff_dvd, mul_div_le] lemma div_eq_iff_eq_of_dvd_dvd (hn : n β‰  0) (ha : a ∣ n) (hb : b ∣ n) : n / a = n / b ↔ a = b := by constructor <;> intro h Β· rw [← Nat.mul_right_inj hn] apply Nat.eq_mul_of_div_eq_left (Nat.dvd_trans hb (Nat.dvd_mul_right _ _)) rw [eq_comm, Nat.mul_comm, Nat.mul_div_assoc _ hb] exact Nat.eq_mul_of_div_eq_right ha h Β· rw [h] protected lemma div_eq_zero_iff (hb : 0 < b) : a / b = 0 ↔ a < b where mp h := by rw [← mod_add_div a b, h, Nat.mul_zero, Nat.add_zero]; exact mod_lt _ hb mpr h := by rw [← Nat.mul_right_inj (Nat.ne_of_gt hb), ← Nat.add_left_cancel_iff, mod_add_div, mod_eq_of_lt h, Nat.mul_zero, Nat.add_zero] protected lemma div_ne_zero_iff (hb : b β‰  0) : a / b β‰  0 ↔ b ≀ a := by rw [ne_eq, Nat.div_eq_zero_iff (Nat.pos_of_ne_zero hb), not_lt] protected lemma div_pos_iff (hb : b β‰  0) : 0 < a / b ↔ b ≀ a := by rw [Nat.pos_iff_ne_zero, Nat.div_ne_zero_iff hb] lemma le_iff_ne_zero_of_dvd (ha : a β‰  0) (hab : a ∣ b) : a ≀ b ↔ b β‰  0 where mp := by rw [← Nat.pos_iff_ne_zero] at ha ⊒; exact Nat.lt_of_lt_of_le ha mpr hb := Nat.le_of_dvd (Nat.pos_iff_ne_zero.2 hb) hab lemma div_ne_zero_iff_of_dvd (hba : b ∣ a) : a / b β‰  0 ↔ a β‰  0 ∧ b β‰  0 := by obtain rfl | hb := eq_or_ne b 0 <;> simp [Nat.div_ne_zero_iff, Nat.le_iff_ne_zero_of_dvd, *] @[simp] lemma mul_mod_mod (a b c : β„•) : (a * (b % c)) % c = a * b % c := by rw [mul_mod, mod_mod, ← mul_mod] @[simp] lemma mod_mul_mod (a b c : β„•) : (a % c * b) % c = a * b % c := by rw [mul_mod, mod_mod, ← mul_mod] lemma pow_mod (a b n : β„•) : a ^ b % n = (a % n) ^ b % n := by induction b with | zero => rfl | succ b ih => simp [Nat.pow_succ, Nat.mul_mod, ih] lemma not_pos_pow_dvd : βˆ€ {a n : β„•} (_ : 1 < a) (_ : 1 < n), Β¬ a ^ n ∣ a | succ a, succ n, hp, hk, h => have : succ a * succ a ^ n ∣ succ a * 1 := by simpa [pow_succ'] using h have : succ a ^ n ∣ 1 := Nat.dvd_of_mul_dvd_mul_left (succ_pos _) this have he : succ a ^ n = 1 := eq_one_of_dvd_one this have : n < succ a ^ n := lt_pow_self hp n have : n < 1 := by rwa [he] at this have : n = 0 := Nat.eq_zero_of_le_zero <| le_of_lt_succ this have : 1 < 1 := by rwa [this] at hk absurd this (by decide) lemma lt_of_pow_dvd_right (hb : b β‰  0) (ha : 2 ≀ a) (h : a ^ n ∣ b) : n < b := by rw [← Nat.pow_lt_pow_iff_right (succ_le_iff.1 ha)] exact Nat.lt_of_le_of_lt (le_of_dvd (Nat.pos_iff_ne_zero.2 hb) h) (lt_pow_self ha _) lemma div_dvd_of_dvd (h : n ∣ m) : m / n ∣ m := ⟨n, (Nat.div_mul_cancel h).symm⟩ protected lemma div_div_self (h : n ∣ m) (hm : m β‰  0) : m / (m / n) = n := by rcases h with ⟨_, rfl⟩ rw [Nat.mul_ne_zero_iff] at hm rw [mul_div_right _ (Nat.pos_of_ne_zero hm.1), mul_div_left _ (Nat.pos_of_ne_zero hm.2)] lemma not_dvd_of_pos_of_lt (h1 : 0 < n) (h2 : n < m) : Β¬m ∣ n := by rintro ⟨k, rfl⟩ rcases Nat.eq_zero_or_pos k with (rfl | hk) Β· exact Nat.lt_irrefl 0 h1 Β· exact Nat.not_lt.2 (Nat.le_mul_of_pos_right _ hk) h2 lemma eq_of_dvd_of_lt_two_mul (ha : a β‰  0) (hdvd : b ∣ a) (hlt : a < 2 * b) : a = b := by obtain ⟨_ | _ | c, rfl⟩ := hdvd Β· simp at ha Β· exact Nat.mul_one _ Β· rw [Nat.mul_comm] at hlt cases Nat.not_le_of_lt hlt (Nat.mul_le_mul_right _ (by omega)) lemma mod_eq_iff_lt (hn : n β‰  0) : m % n = m ↔ m < n := ⟨fun h ↦ by rw [← h]; exact mod_lt _ $ Nat.pos_iff_ne_zero.2 hn, mod_eq_of_lt⟩ @[simp] lemma mod_succ_eq_iff_lt : m % n.succ = m ↔ m < n.succ := mod_eq_iff_lt (succ_ne_zero _) @[simp] lemma mod_succ (n : β„•) : n % n.succ = n := mod_eq_of_lt n.lt_succ_self -- Porting note `Nat.div_add_mod` is now in core. lemma mod_add_div' (a b : β„•) : a % b + a / b * b = a := by rw [Nat.mul_comm]; exact mod_add_div _ _ lemma div_add_mod' (a b : β„•) : a / b * b + a % b = a := by rw [Nat.mul_comm]; exact div_add_mod _ _ /-- See also `Nat.divModEquiv` for a similar statement as an `Equiv`. -/ protected lemma div_mod_unique (h : 0 < b) : a / b = d ∧ a % b = c ↔ c + b * d = a ∧ c < b := ⟨fun ⟨e₁, eβ‚‚βŸ© ↦ e₁ β–Έ eβ‚‚ β–Έ ⟨mod_add_div _ _, mod_lt _ h⟩, fun ⟨h₁, hβ‚‚βŸ© ↦ h₁ β–Έ by rw [add_mul_div_left _ _ h, add_mul_mod_self_left]; simp [div_eq_of_lt, mod_eq_of_lt, hβ‚‚]⟩ /-- If `m` and `n` are equal mod `k`, `m - n` is zero mod `k`. -/ lemma sub_mod_eq_zero_of_mod_eq (h : m % k = n % k) : (m - n) % k = 0 := by rw [← Nat.mod_add_div m k, ← Nat.mod_add_div n k, ← h, ← Nat.sub_sub, Nat.add_sub_cancel_left, ← k.mul_sub, Nat.mul_mod_right] @[simp] lemma one_mod (n : β„•) : 1 % (n + 2) = 1 := Nat.mod_eq_of_lt (Nat.add_lt_add_right n.succ_pos 1) lemma one_mod_of_ne_one : βˆ€ {n : β„•}, n β‰  1 β†’ 1 % n = 1 | 0, _ | (n + 2), _ => by simp lemma dvd_sub_mod (k : β„•) : n ∣ k - k % n := ⟨k / n, Nat.sub_eq_of_eq_add (Nat.div_add_mod k n).symm⟩ lemma add_mod_eq_ite : (m + n) % k = if k ≀ m % k + n % k then m % k + n % k - k else m % k + n % k := by cases k Β· simp rw [Nat.add_mod] split_ifs with h Β· rw [Nat.mod_eq_sub_mod h, Nat.mod_eq_of_lt] exact (Nat.sub_lt_iff_lt_add h).mpr (Nat.add_lt_add (m.mod_lt (zero_lt_succ _)) (n.mod_lt (zero_lt_succ _))) Β· exact Nat.mod_eq_of_lt (Nat.lt_of_not_ge h) /-- `m` is not divisible by `n` if it is between `n * k` and `n * (k + 1)` for some `k`. -/ theorem not_dvd_of_between_consec_multiples (h1 : n * k < m) (h2 : m < n * (k + 1)) : Β¬n ∣ m := by rintro ⟨d, rfl⟩ have := Nat.lt_of_mul_lt_mul_left h1 have := Nat.lt_of_mul_lt_mul_left h2 omega -- TODO: Replace `Nat.dvd_add_iff_left` protected lemma dvd_add_left (h : a ∣ c) : a ∣ b + c ↔ a ∣ b := (Nat.dvd_add_iff_left h).symm protected lemma dvd_add_right (h : a ∣ b) : a ∣ b + c ↔ a ∣ c := (Nat.dvd_add_iff_right h).symm /-- special case of `mul_dvd_mul_iff_left` for `β„•`. Duplicated here to keep simple imports for this file. -/ protected lemma mul_dvd_mul_iff_left (ha : 0 < a) : a * b ∣ a * c ↔ b ∣ c := exists_congr fun d ↦ by rw [Nat.mul_assoc, Nat.mul_right_inj $ ne_of_gt ha] /-- special case of `mul_dvd_mul_iff_right` for `β„•`. Duplicated here to keep simple imports for this file. -/ protected lemma mul_dvd_mul_iff_right (hc : 0 < c) : a * c ∣ b * c ↔ a ∣ b := exists_congr fun d ↦ by rw [Nat.mul_right_comm, Nat.mul_left_inj $ ne_of_gt hc] -- Moved to Batteries lemma add_mod_eq_add_mod_right (c : β„•) (H : a % d = b % d) : (a + c) % d = (b + c) % d := by rw [← mod_add_mod, ← mod_add_mod b, H] lemma add_mod_eq_add_mod_left (c : β„•) (H : a % d = b % d) : (c + a) % d = (c + b) % d := by rw [Nat.add_comm, add_mod_eq_add_mod_right _ H, Nat.add_comm] -- Moved to Batteries lemma mul_dvd_of_dvd_div (hcb : c ∣ b) (h : a ∣ b / c) : c * a ∣ b := have ⟨d, hd⟩ := h ⟨d, by simpa [Nat.mul_comm, Nat.mul_left_comm] using Nat.eq_mul_of_div_eq_left hcb hd⟩ lemma eq_of_dvd_of_div_eq_one (hab : a ∣ b) (h : b / a = 1) : a = b := by rw [← Nat.div_mul_cancel hab, h, Nat.one_mul] lemma eq_zero_of_dvd_of_div_eq_zero (hab : a ∣ b) (h : b / a = 0) : b = 0 := by rw [← Nat.div_mul_cancel hab, h, Nat.zero_mul] @[gcongr] protected theorem div_le_div {a b c d : β„•} (h1 : a ≀ b) (h2 : d ≀ c) (h3 : d β‰  0) : a / c ≀ b / d := calc a / c ≀ b / c := Nat.div_le_div_right h1 _ ≀ b / d := Nat.div_le_div_left h2 (Nat.pos_of_ne_zero h3) -- Moved to Batteries lemma lt_mul_div_succ (a : β„•) (hb : 0 < b) : a < b * (a / b + 1) := by rw [Nat.mul_comm, ← Nat.div_lt_iff_lt_mul' hb] exact lt_succ_self _ -- TODO: Batteries claimed this name but flipped the order of multiplication lemma mul_add_mod' (a b c : β„•) : (a * b + c) % b = c % b := by rw [Nat.mul_comm, Nat.mul_add_mod] lemma mul_add_mod_of_lt (h : c < b) : (a * b + c) % b = c := by rw [Nat.mul_add_mod', Nat.mod_eq_of_lt h] set_option linter.deprecated false in @[simp] protected theorem not_two_dvd_bit1 (n : β„•) : Β¬2 ∣ 2 * n + 1 := by omega /-- A natural number `m` divides the sum `m + n` if and only if `m` divides `n`.-/ @[simp] protected lemma dvd_add_self_left : m ∣ m + n ↔ m ∣ n := Nat.dvd_add_right (Nat.dvd_refl m) /-- A natural number `m` divides the sum `n + m` if and only if `m` divides `n`.-/ @[simp] protected lemma dvd_add_self_right : m ∣ n + m ↔ m ∣ n := Nat.dvd_add_left (Nat.dvd_refl m) -- TODO: update `Nat.dvd_sub` in core lemma dvd_sub' (h₁ : k ∣ m) (hβ‚‚ : k ∣ n) : k ∣ m - n := by rcases le_total n m with H | H Β· exact dvd_sub H h₁ hβ‚‚ Β· rw [Nat.sub_eq_zero_iff_le.mpr H] exact Nat.dvd_zero k lemma succ_div : βˆ€ a b : β„•, (a + 1) / b = a / b + if b ∣ a + 1 then 1 else 0 | a, 0 => by simp | 0, 1 => by simp | 0, b + 2 => by have hb2 : b + 2 > 1 := by simp simp [ne_of_gt hb2, div_eq_of_lt hb2] | a + 1, b + 1 => by rw [Nat.div_eq] conv_rhs => rw [Nat.div_eq] by_cases hb_eq_a : b = a + 1 Β· simp [hb_eq_a, Nat.le_refl, Nat.not_succ_le_self, Nat.dvd_refl] by_cases hb_le_a1 : b ≀ a + 1 Β· have hb_le_a : b ≀ a := le_of_lt_succ (lt_of_le_of_ne hb_le_a1 hb_eq_a) have h₁ : 0 < b + 1 ∧ b + 1 ≀ a + 1 + 1 := ⟨succ_pos _, Nat.add_le_add_iff_right.2 hb_le_a1⟩ have hβ‚‚ : 0 < b + 1 ∧ b + 1 ≀ a + 1 := ⟨succ_pos _, Nat.add_le_add_iff_right.2 hb_le_a⟩ have dvd_iff : b + 1 ∣ a - b + 1 ↔ b + 1 ∣ a + 1 + 1 := by rw [Nat.dvd_add_iff_left (Nat.dvd_refl (b + 1)), ← Nat.add_sub_add_right a 1 b, Nat.add_comm (_ - _), Nat.add_assoc, Nat.sub_add_cancel (succ_le_succ hb_le_a), Nat.add_comm 1] have wf : a - b < a + 1 := lt_succ_of_le (Nat.sub_le _ _) rw [if_pos h₁, if_pos hβ‚‚, Nat.add_sub_add_right, Nat.add_sub_add_right, Nat.add_comm a, Nat.add_sub_assoc hb_le_a, Nat.add_comm 1, have := wf succ_div (a - b)] simp [dvd_iff, Nat.add_comm 1, Nat.add_assoc] Β· have hba : Β¬b ≀ a := not_le_of_gt (lt_trans (lt_succ_self a) (lt_of_not_ge hb_le_a1)) have hb_dvd_a : Β¬b + 1 ∣ a + 2 := fun h => hb_le_a1 (le_of_succ_le_succ (le_of_dvd (succ_pos _) h)) simp [hba, hb_le_a1, hb_dvd_a] lemma succ_div_of_dvd (hba : b ∣ a + 1) : (a + 1) / b = a / b + 1 := by rw [succ_div, if_pos hba] lemma succ_div_of_not_dvd (hba : Β¬b ∣ a + 1) : (a + 1) / b = a / b := by rw [succ_div, if_neg hba, Nat.add_zero] lemma dvd_iff_div_mul_eq (n d : β„•) : d ∣ n ↔ n / d * d = n := ⟨fun h => Nat.div_mul_cancel h, fun h => by rw [← h]; exact Nat.dvd_mul_left _ _⟩ lemma dvd_iff_le_div_mul (n d : β„•) : d ∣ n ↔ n ≀ n / d * d := ((dvd_iff_div_mul_eq _ _).trans le_antisymm_iff).trans (and_iff_right (div_mul_le_self n d)) lemma dvd_iff_dvd_dvd (n d : β„•) : d ∣ n ↔ βˆ€ k : β„•, k ∣ d β†’ k ∣ n := ⟨fun h _ hkd => Nat.dvd_trans hkd h, fun h => h _ (Nat.dvd_refl _)⟩ lemma dvd_div_of_mul_dvd (h : a * b ∣ c) : b ∣ c / a := if ha : a = 0 then by simp [ha] else have ha : 0 < a := Nat.pos_of_ne_zero ha have h1 : βˆƒ d, c = a * b * d := h let ⟨d, hd⟩ := h1 have h2 : c / a = b * d := Nat.div_eq_of_eq_mul_right ha (by simpa [Nat.mul_assoc] using hd) show βˆƒ d, c / a = b * d from ⟨d, h2⟩ @[simp] lemma dvd_div_iff_mul_dvd (hbc : c ∣ b) : a ∣ b / c ↔ c * a ∣ b := ⟨fun h => mul_dvd_of_dvd_div hbc h, fun h => dvd_div_of_mul_dvd h⟩ @[deprecated (since := "2024-06-18")] alias dvd_div_iff := dvd_div_iff_mul_dvd lemma dvd_mul_of_div_dvd (h : b ∣ a) (hdiv : a / b ∣ c) : a ∣ b * c := by obtain ⟨e, rfl⟩ := hdiv rw [← Nat.mul_assoc, Nat.mul_comm _ (a / b), Nat.div_mul_cancel h] exact Nat.dvd_mul_right a e @[simp] lemma div_dvd_iff_dvd_mul (h : b ∣ a) (hb : b β‰  0) : a / b ∣ c ↔ a ∣ b * c := exists_congr <| fun d => by have := Nat.dvd_trans (Nat.dvd_mul_left _ d) (Nat.mul_dvd_mul_left d h) rw [eq_comm, Nat.mul_comm, ← Nat.mul_div_assoc d h, Nat.div_eq_iff_eq_mul_right (Nat.pos_of_ne_zero hb) this, Nat.mul_comm, eq_comm] @[simp] lemma div_div_div_eq_div (dvd : b ∣ a) (dvd2 : a ∣ c) : c / (a / b) / b = c / a := match a, b, c with | 0, _, _ => by simp | a + 1, 0, _ => by simp at dvd | a + 1, c + 1, _ => by have a_split : a + 1 β‰  0 := succ_ne_zero a have c_split : c + 1 β‰  0 := succ_ne_zero c rcases dvd2 with ⟨k, rfl⟩ rcases dvd with ⟨k2, pr⟩ have k2_nonzero : k2 β‰  0 := fun k2_zero => by simp [k2_zero] at pr rw [Nat.mul_div_cancel_left k (Nat.pos_of_ne_zero a_split), pr, Nat.mul_div_cancel_left k2 (Nat.pos_of_ne_zero c_split), Nat.mul_comm ((c + 1) * k2) k, ← Nat.mul_assoc k (c + 1) k2, Nat.mul_div_cancel _ (Nat.pos_of_ne_zero k2_nonzero), Nat.mul_div_cancel _ (Nat.pos_of_ne_zero c_split)] /-- If a small natural number is divisible by a larger natural number, the small number is zero. -/ lemma eq_zero_of_dvd_of_lt (w : a ∣ b) (h : b < a) : b = 0 := Nat.eq_zero_of_dvd_of_div_eq_zero w ((Nat.div_eq_zero_iff (lt_of_le_of_lt (zero_le b) h)).mpr h) lemma le_of_lt_add_of_dvd (h : a < b + n) : n ∣ a β†’ n ∣ b β†’ a ≀ b := by rintro ⟨a, rfl⟩ ⟨b, rfl⟩ rw [← mul_succ] at h exact Nat.mul_le_mul_left _ (Nat.lt_succ_iff.1 <| Nat.lt_of_mul_lt_mul_left h) /-- `n` is not divisible by `a` iff it is between `a * k` and `a * (k + 1)` for some `k`. -/ lemma not_dvd_iff_between_consec_multiples (n : β„•) {a : β„•} (ha : 0 < a) : (βˆƒ k : β„•, a * k < n ∧ n < a * (k + 1)) ↔ Β¬a ∣ n := by refine ⟨fun ⟨k, hk1, hk2⟩ => not_dvd_of_between_consec_multiples hk1 hk2, fun han => ⟨n / a, ⟨lt_of_le_of_ne (mul_div_le n a) ?_, lt_mul_div_succ _ ha⟩⟩⟩ exact mt (⟨n / a, Eq.symm ·⟩) han /-- Two natural numbers are equal if and only if they have the same multiples. -/ lemma dvd_right_iff_eq : (βˆ€ a : β„•, m ∣ a ↔ n ∣ a) ↔ m = n := ⟨fun h => Nat.dvd_antisymm ((h _).mpr (Nat.dvd_refl _)) ((h _).mp (Nat.dvd_refl _)), fun h n => by rw [h]⟩ /-- Two natural numbers are equal if and only if they have the same divisors. -/ lemma dvd_left_iff_eq : (βˆ€ a : β„•, a ∣ m ↔ a ∣ n) ↔ m = n := ⟨fun h => Nat.dvd_antisymm ((h _).mp (Nat.dvd_refl _)) ((h _).mpr (Nat.dvd_refl _)), fun h n => by rw [h]⟩ /-- `dvd` is injective in the left argument -/ lemma dvd_left_injective : Function.Injective ((Β· ∣ Β·) : β„• β†’ β„• β†’ Prop) := fun _ _ h => dvd_right_iff_eq.mp fun a => iff_of_eq (congr_fun h a) lemma div_lt_div_of_lt_of_dvd {a b d : β„•} (hdb : d ∣ b) (h : a < b) : a / d < b / d := by rw [Nat.lt_div_iff_mul_lt hdb] exact lt_of_le_of_lt (mul_div_le a d) h /-! ### `sqrt` See [Wikipedia, *Methods of computing square roots*] (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2)). -/ private lemma iter_fp_bound (n k : β„•) : let iter_next (n guess : β„•) := (guess + n / guess) / 2; sqrt.iter n k ≀ iter_next n (sqrt.iter n k) := by intro iter_next unfold sqrt.iter if h : (k + n / k) / 2 < k then simpa [if_pos h] using iter_fp_bound _ _ else simpa [if_neg h] using Nat.le_of_not_lt h private lemma AM_GM : {a b : β„•} β†’ (4 * a * b ≀ (a + b) * (a + b)) | 0, _ => by rw [Nat.mul_zero, Nat.zero_mul]; exact zero_le _ | _, 0 => by rw [Nat.mul_zero]; exact zero_le _ | a + 1, b + 1 => by simpa only [Nat.mul_add, Nat.add_mul, show (4 : β„•) = 1 + 1 + 1 + 1 from rfl, Nat.one_mul, Nat.mul_one, Nat.add_assoc, Nat.add_left_comm, Nat.add_le_add_iff_left] using Nat.add_le_add_right (@AM_GM a b) 4 -- These two lemmas seem like they belong to `Batteries.Data.Nat.Basic`. lemma sqrt.iter_sq_le (n guess : β„•) : sqrt.iter n guess * sqrt.iter n guess ≀ n := by unfold sqrt.iter let next := (guess + n / guess) / 2 if h : next < guess then simpa only [dif_pos h] using sqrt.iter_sq_le n next else simp only [dif_neg h] apply Nat.mul_le_of_le_div apply Nat.le_of_add_le_add_left (a := guess) rw [← Nat.mul_two, ← le_div_iff_mul_le] Β· exact Nat.le_of_not_lt h Β· exact Nat.zero_lt_two lemma sqrt.lt_iter_succ_sq (n guess : β„•) (hn : n < (guess + 1) * (guess + 1)) : n < (sqrt.iter n guess + 1) * (sqrt.iter n guess + 1) := by unfold sqrt.iter -- m was `next` let m := (guess + n / guess) / 2 dsimp split_ifs with h Β· suffices n < (m + 1) * (m + 1) by simpa only [dif_pos h] using sqrt.lt_iter_succ_sq n m this refine Nat.lt_of_mul_lt_mul_left ?_ (a := 4 * (guess * guess)) apply Nat.lt_of_le_of_lt AM_GM rw [show (4 : β„•) = 2 * 2 from rfl] rw [Nat.mul_mul_mul_comm 2, Nat.mul_mul_mul_comm (2 * guess)] refine Nat.mul_self_lt_mul_self (?_ : _ < _ * ((_ / 2) + 1)) rw [← add_div_right _ (by decide), Nat.mul_comm 2, Nat.mul_assoc, show guess + n / guess + 2 = (guess + n / guess + 1) + 1 from rfl] have aux_lemma {a : β„•} : a ≀ 2 * ((a + 1) / 2) := by omega refine lt_of_lt_of_le ?_ (Nat.mul_le_mul_left _ aux_lemma) rw [Nat.add_assoc, Nat.mul_add] exact Nat.add_lt_add_left (lt_mul_div_succ _ (lt_of_le_of_lt (Nat.zero_le m) h)) _ Β· simpa only [dif_neg h] using hn -- Porting note: the implementation of `Nat.sqrt` in `Batteries` no longer needs `sqrt_aux`. private def IsSqrt (n q : β„•) : Prop := q * q ≀ n ∧ n < (q + 1) * (q + 1) -- Porting note: as the definition of square root has changed, -- the proof of `sqrt_isSqrt` is attempted from scratch. /- Sketch of proof: Up to rounding, in terms of the definition of `sqrt.iter`, * By AM-GM inequality, `nextΒ² β‰₯ n` giving one of the bounds. * When we terminated, we have `guess β‰₯ next` from which we deduce the other bound `n β‰₯ nextΒ²`. To turn this into a lean proof we need to manipulate, use properties of natural number division etc. -/ private lemma sqrt_isSqrt (n : β„•) : IsSqrt n (sqrt n) := by match n with | 0 => simp [IsSqrt, sqrt] | 1 => simp [IsSqrt, sqrt] | n + 2 => have h : Β¬ (n + 2) ≀ 1 := by simp simp only [IsSqrt, sqrt, h, ite_false] refine ⟨sqrt.iter_sq_le _ _, sqrt.lt_iter_succ_sq _ _ ?_⟩ simp only [Nat.mul_add, Nat.add_mul, Nat.one_mul, Nat.mul_one, ← Nat.add_assoc] rw [Nat.lt_add_one_iff, Nat.add_assoc, ← Nat.mul_two] refine le_trans (Nat.le_of_eq (div_add_mod' (n + 2) 2).symm) ?_ rw [Nat.add_comm, Nat.add_le_add_iff_right, add_mod_right] simp only [Nat.zero_lt_two, add_div_right, succ_mul_succ] refine le_trans (b := 1) ?_ ?_ Β· exact (lt_succ.1 <| mod_lt n Nat.zero_lt_two) Β· exact Nat.le_add_left _ _ lemma sqrt_le (n : β„•) : sqrt n * sqrt n ≀ n := (sqrt_isSqrt n).left lemma sqrt_le' (n : β„•) : sqrt n ^ 2 ≀ n := by simpa [Nat.pow_two] using sqrt_le n lemma lt_succ_sqrt (n : β„•) : n < succ (sqrt n) * succ (sqrt n) := (sqrt_isSqrt n).right lemma lt_succ_sqrt' (n : β„•) : n < succ (sqrt n) ^ 2 := by simpa [Nat.pow_two] using lt_succ_sqrt n lemma sqrt_le_add (n : β„•) : n ≀ sqrt n * sqrt n + sqrt n + sqrt n := by rw [← succ_mul]; exact le_of_lt_succ (lt_succ_sqrt n) lemma le_sqrt : m ≀ sqrt n ↔ m * m ≀ n := ⟨fun h ↦ le_trans (mul_self_le_mul_self h) (sqrt_le n), fun h ↦ le_of_lt_succ <| Nat.mul_self_lt_mul_self_iff.1 <| lt_of_le_of_lt h (lt_succ_sqrt n)⟩ lemma le_sqrt' : m ≀ sqrt n ↔ m ^ 2 ≀ n := by simpa only [Nat.pow_two] using le_sqrt lemma sqrt_lt : sqrt m < n ↔ m < n * n := by simp only [← not_le, le_sqrt] lemma sqrt_lt' : sqrt m < n ↔ m < n ^ 2 := by simp only [← not_le, le_sqrt'] lemma sqrt_le_self (n : β„•) : sqrt n ≀ n := le_trans (le_mul_self _) (sqrt_le n) lemma sqrt_le_sqrt (h : m ≀ n) : sqrt m ≀ sqrt n := le_sqrt.2 (le_trans (sqrt_le _) h) @[simp] lemma sqrt_zero : sqrt 0 = 0 := rfl @[simp] lemma sqrt_one : sqrt 1 = 1 := rfl lemma sqrt_eq_zero : sqrt n = 0 ↔ n = 0 := ⟨fun h ↦ Nat.eq_zero_of_le_zero <| le_of_lt_succ <| (@sqrt_lt n 1).1 <| by rw [h]; decide, by rintro rfl; simp⟩ lemma eq_sqrt : a = sqrt n ↔ a * a ≀ n ∧ n < (a + 1) * (a + 1) := ⟨fun e ↦ e.symm β–Έ sqrt_isSqrt n, fun ⟨h₁, hβ‚‚βŸ© ↦ le_antisymm (le_sqrt.2 h₁) (le_of_lt_succ <| sqrt_lt.2 hβ‚‚)⟩ lemma eq_sqrt' : a = sqrt n ↔ a ^ 2 ≀ n ∧ n < (a + 1) ^ 2 := by simpa only [Nat.pow_two] using eq_sqrt lemma le_three_of_sqrt_eq_one (h : sqrt n = 1) : n ≀ 3 := le_of_lt_succ <| (@sqrt_lt n 2).1 <| by rw [h]; decide lemma sqrt_lt_self (h : 1 < n) : sqrt n < n := sqrt_lt.2 <| by have := Nat.mul_lt_mul_of_pos_left h (lt_of_succ_lt h); rwa [Nat.mul_one] at this lemma sqrt_pos : 0 < sqrt n ↔ 0 < n := le_sqrt lemma sqrt_add_eq (n : β„•) (h : a ≀ n + n) : sqrt (n * n + a) = n := le_antisymm (le_of_lt_succ <| sqrt_lt.2 <| by rw [succ_mul, mul_succ, add_succ, Nat.add_assoc] exact lt_succ_of_le (Nat.add_le_add_left h _)) (le_sqrt.2 <| Nat.le_add_right _ _) lemma sqrt_add_eq' (n : β„•) (h : a ≀ n + n) : sqrt (n ^ 2 + a) = n := by simpa [Nat.pow_two] using sqrt_add_eq n h lemma sqrt_eq (n : β„•) : sqrt (n * n) = n := sqrt_add_eq n (zero_le _) lemma sqrt_eq' (n : β„•) : sqrt (n ^ 2) = n := sqrt_add_eq' n (zero_le _) lemma sqrt_succ_le_succ_sqrt (n : β„•) : sqrt n.succ ≀ n.sqrt.succ := le_of_lt_succ <| sqrt_lt.2 <| lt_succ_of_le <| succ_le_succ <| le_trans (sqrt_le_add n) <| Nat.add_le_add_right (by refine add_le_add (Nat.mul_le_mul_right _ ?_) ?_ <;> exact Nat.le_add_right _ 2) _ lemma exists_mul_self (x : β„•) : (βˆƒ n, n * n = x) ↔ sqrt x * sqrt x = x := ⟨fun ⟨n, hn⟩ ↦ by rw [← hn, sqrt_eq], fun h ↦ ⟨sqrt x, h⟩⟩ lemma exists_mul_self' (x : β„•) : (βˆƒ n, n ^ 2 = x) ↔ sqrt x ^ 2 = x := by simpa only [Nat.pow_two] using exists_mul_self x lemma sqrt_mul_sqrt_lt_succ (n : β„•) : sqrt n * sqrt n < n + 1 := Nat.lt_succ_iff.mpr (sqrt_le _) lemma sqrt_mul_sqrt_lt_succ' (n : β„•) : sqrt n ^ 2 < n + 1 := Nat.lt_succ_iff.mpr (sqrt_le' _) lemma succ_le_succ_sqrt (n : β„•) : n + 1 ≀ (sqrt n + 1) * (sqrt n + 1) := le_of_pred_lt (lt_succ_sqrt _) lemma succ_le_succ_sqrt' (n : β„•) : n + 1 ≀ (sqrt n + 1) ^ 2 := le_of_pred_lt (lt_succ_sqrt' _) /-- There are no perfect squares strictly between mΒ² and (m+1)Β² -/ lemma not_exists_sq (hl : m * m < n) (hr : n < (m + 1) * (m + 1)) : Β¬βˆƒ t, t * t = n := by rintro ⟨t, rfl⟩ have h1 : m < t := Nat.mul_self_lt_mul_self_iff.1 hl have h2 : t < m + 1 := Nat.mul_self_lt_mul_self_iff.1 hr exact (not_lt_of_ge <| le_of_lt_succ h2) h1 lemma not_exists_sq' : m ^ 2 < n β†’ n < (m + 1) ^ 2 β†’ Β¬βˆƒ t, t ^ 2 = n := by simpa only [Nat.pow_two] using not_exists_sq /-! ### Decidability of predicates -/ instance decidableLoHi (lo hi : β„•) (P : β„• β†’ Prop) [H : DecidablePred P] : Decidable (βˆ€ x, lo ≀ x β†’ x < hi β†’ P x) := decidable_of_iff (βˆ€ x < hi - lo, P (lo + x)) $ by refine ⟨fun al x hl hh ↦ ?_, fun al x h ↦ al _ (Nat.le_add_right _ _) (Nat.lt_sub_iff_add_lt'.1 h)⟩ have := al (x - lo) ((Nat.sub_lt_sub_iff_right hl).2 hh) rwa [Nat.add_sub_cancel' hl] at this instance decidableLoHiLe (lo hi : β„•) (P : β„• β†’ Prop) [DecidablePred P] : Decidable (βˆ€ x, lo ≀ x β†’ x ≀ hi β†’ P x) := decidable_of_iff (βˆ€ x, lo ≀ x β†’ x < hi + 1 β†’ P x) <| forallβ‚‚_congr fun _ _ ↦ imp_congr Nat.lt_succ_iff Iff.rfl end Nat
Data\Nat\Digits.lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Shing Tak Lam, Mario Carneiro -/ 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.Data.List.Indexes import Mathlib.Data.List.Palindrome import Mathlib.Tactic.IntervalCases import Mathlib.Tactic.Linarith import Mathlib.Tactic.Ring /-! # 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. -/ 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) : β„• β†’ List β„• | 0 => [] | n + 1 => ((n + 1) % b) :: digitsAux b h ((n + 1) / b) decreasing_by exact Nat.div_lt_self (Nat.succ_pos _) h @[simp] theorem digitsAux_zero (b : β„•) (h : 2 ≀ b) : digitsAux b h 0 = [] := by rw [digitsAux] 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] /-- `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 norm_num) @[simp] theorem digits_zero (b : β„•) : digits b 0 = [] := by rcases b with (_ | ⟨_ | ⟨_⟩⟩) <;> simp [digits, digitsAux0, digitsAux1] -- @[simp] -- Porting note (#10618): simp can prove this 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 -- @[simp] -- Porting note (#10685): 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 d L ih Β· rfl Β· dsimp [ofDigits] rw [ih] theorem ofDigits_eq_sum_map_with_index_aux (b : β„•) (l : List β„•) : ((List.range l.length).zipWith ((fun i a : β„• => a * b ^ (i + 1))) l).sum = b * ((List.range l.length).zipWith (fun i a => a * b ^ i) l).sum := by suffices (List.range l.length).zipWith (fun i a : β„• => a * b ^ (i + 1)) l = (List.range l.length).zipWith (fun i a => b * (a * b ^ i)) l by simp [this] congr; ext; simp [pow_succ]; 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_enum_map, List.enum_eq_zip_range, List.map_uncurry_zip_eq_zipWith, ofDigits_eq_foldr] induction' L with hd tl hl Β· simp Β· simpa [List.range_succ_eq_map, List.zipWith_map_left, ofDigits_eq_sum_map_with_index_aux] using Or.inl hl @[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 hd tl IH Β· simp [ofDigits] Β· rw [ofDigits, List.cons_append, ofDigits, IH, List.length_cons, pow_succ'] ring @[norm_cast] theorem coe_ofDigits (Ξ± : Type*) [Semiring Ξ±] (b : β„•) (L : List β„•) : ((ofDigits b L : β„•) : Ξ±) = ofDigits (b : Ξ±) L := by induction' L with d L ih Β· simp [ofDigits] Β· dsimp [ofDigits]; push_cast; rw [ih] @[norm_cast] theorem coe_int_ofDigits (b : β„•) (L : List β„•) : ((ofDigits b L : β„•) : β„€) = ofDigits (b : β„€) L := by induction' L with d L _ Β· rfl Β· dsimp [ofDigits]; push_cast; simp only 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 d L ih Β· dsimp [ofDigits] simp Β· 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 cases' b with b Β· cases' n with n Β· rfl Β· change ofDigits 0 [n + 1] = n + 1 dsimp [ofDigits] Β· cases' b with b Β· induction' n with n ih Β· rfl Β· rw [Nat.zero_add] at ih ⊒ simp only [ih, add_comm 1, ofDigits_one_cons, Nat.cast_id, digits_one_succ] Β· apply Nat.strongInductionOn n _ clear n intro n h cases n Β· rw [digits_zero] rfl Β· simp only [Nat.succ_eq_add_one, 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 _ _ ih Β· rfl Β· 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) := by rcases b with (_ | _ | b) Β· rw [digits_zero_succ' w, Nat.mod_zero, Nat.div_zero, Nat.digits_zero_zero] Β· norm_num at h rcases n with (_ | n) Β· norm_num at w Β· simp only [digits_add_two_add_one, ne_eq] 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 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 Β· have hb0 : b β‰  0 := (Nat.succ_le_iff.1 hb).ne_bot simp [h, log_eq_zero_iff, ← Nat.div_eq_zero_iff hb0.bot_lt] Β· 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 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 rename β„• => m simp only [zero_add, digits_one, List.getLast_replicate_succ m 1] exact Nat.one_ne_zero revert hm apply Nat.strongInductionOn m intro n IH 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 (le_of_not_lt hnb) (zero_lt_succ (succ b)) 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 /-- 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, ofDigits] | cons hd₁ tl₁ ih₁ => induction l2 generalizing tl₁ with | nil => simp_all | cons hdβ‚‚ tlβ‚‚ ihβ‚‚ => simp_all only [List.length_cons, succ_eq_add_one, ofDigits_cons, add_left_inj, eq_comm, List.zipWith_cons_cons, add_eq] 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 apply Nat.strongInductionOn m intro n IH d hd cases' 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 simp) -- Porting note: Previous code (single line) contained linarith. -- . exact IH _ (Nat.div_lt_self (Nat.succ_pos _) (by linarith)) hd Β· 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 hd tl IH Β· simp [ofDigits] Β· 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 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] 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' _ _ h) β–Έ (getLast_digit_ne_zero _ <| digits_ne_nil_iff_ne_zero.mp h) 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_lt 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 @[mono] theorem ofDigits_monotone {p q : β„•} (L : List β„•) (h : p ≀ q) : ofDigits p L ≀ ofDigits q L := by induction' L with _ _ hi Β· rfl Β· 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 n Β· exact digits_zero _ β–Έ Nat.le_refl (List.sum []) Β· induction' p with p Β· rw [digits_zero_succ, List.sum_cons, List.sum_nil, add_zero] Β· 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 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 /-- 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 hd tl Β· simp [ofDigits] Β· refine Eq.trans (add_mul_div_left hd _ hpos) ?_ rw [Nat.div_eq_of_lt <| w₁ _ <| List.mem_cons_self _ _, zero_add] rfl /-- 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 i hi Β· simp Β· 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 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 hd tl ih Β· simp [ofDigits] Β· 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.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, one_eq_succ_zero, Nat.sub_add_cancel <| zero_lt_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 b n h ih Β· simp Β· rfl 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 d L ih Β· change k ∣ 0 - 0 simp Β· 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 d L ih Β· rfl Β· 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, Int.ModEq] 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 omega] 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 d L ih Β· rfl Β· 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 modEq_three_digits_sum (n : β„•) : n ≑ (digits 10 n).sum [MOD 3] := modEq_digits_sum 3 10 (by norm_num) n theorem modEq_nine_digits_sum (n : β„•) : n ≑ (digits 10 n).sum [MOD 9] := modEq_digits_sum 9 10 (by norm_num) n 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_int_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 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 norm_num) n theorem nine_dvd_iff (n : β„•) : 9 ∣ n ↔ 9 ∣ (digits 10 n).sum := dvd_iff_dvd_digits_sum 9 10 (by norm_num) 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 norm_num) 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 /-! ### `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, List.length]; 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 @[deprecated (since := "2024-02-19")] alias to_digits_core_lens_eq_aux:= toDigitsCore_lens_eq_aux 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 => if hnb : (n / b) = 0 then simp only [hnb, if_true, List.length] else generalize hx : Nat.digitChar (n % b) = x simp only [hx, hnb, if_false] at ih simp only [hnb, if_false] specialize ih (n / b) c (x :: tl) rw [← ih] have lens_eq : (x :: (c :: tl)).length = (c :: x :: tl).length := by simp apply toDigitsCore_lens_eq_aux exact lens_eq @[deprecated (since := "2024-02-19")] alias to_digits_core_lens_eq:= toDigitsCore_lens_eq 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 greater than one, it can be used for binary, decimal, and hex. -/ lemma toDigitsCore_length (b : Nat) (h : 2 <= b) (f n e : Nat) (hlt : n < b ^ e) (h_e_pos : 0 < e) : (Nat.toDigitsCore b f n []).length <= e := by induction f generalizing n e hlt h_e_pos with simp only [Nat.toDigitsCore, List.length, Nat.zero_le] | succ f ih => cases e with | zero => exact False.elim (Nat.lt_irrefl 0 h_e_pos) | succ e => if h_pred_pos : 0 < e then have _ : 0 < b := Nat.lt_trans (by decide) h specialize ih (n / b) e (nat_repr_len_aux n b e β€Ή0 < bβ€Ί hlt) h_pred_pos if hdiv_ten : n / b = 0 then simp only [hdiv_ten]; exact Nat.le.step h_pred_pos else simp only [hdiv_ten, toDigitsCore_lens_eq b f (n / b) (Nat.digitChar <| n % b), if_false] exact Nat.succ_le_succ ih else obtain rfl : e = 0 := Nat.eq_zero_of_not_pos h_pred_pos have _ : b ^ 1 = b := by simp only [Nat.pow_succ, pow_zero, Nat.one_mul] have _ : n < b := β€Ήb ^ 1 = bβ€Ί β–Έ hlt simp [(@Nat.div_eq_of_lt n b β€Ήn < bβ€Ί : n / b = 0)] @[deprecated (since := "2024-02-19")] alias to_digits_core_length := 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 cases n with (intro e0 he; simp only [Nat.repr, Nat.toDigits, String.length, List.asString]) | zero => assumption | succ n => if hterm : n.succ / 10 = 0 then simp only [hterm, Nat.toDigitsCore]; assumption else exact toDigitsCore_length 10 (by decide) (Nat.succ n + 1) (Nat.succ n) e he e0 /-! ### `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 := lt_iff_add_one_le.mpr (le_trans (add_le_add_right (lt_iff_add_one_le.mp n0) 1) nb) refine ⟨?_, b2, n0⟩ rw [Nat.digits_def' b2 n0, Nat.mod_eq_of_lt nb, (Nat.div_eq_zero_iff ((zero_le n).trans_lt nb)).2 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
Data\Nat\Dist.lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jeremy Avigad -/ import Mathlib.Algebra.Order.Ring.Nat /-! # Distance function on β„• This file defines a simple distance function on naturals from truncated subtraction. -/ namespace Nat /-- Distance (absolute value of difference) between natural numbers. -/ def dist (n m : β„•) := n - m + (m - n) theorem dist_comm (n m : β„•) : dist n m = dist m n := by simp [dist, add_comm] @[simp] theorem dist_self (n : β„•) : dist n n = 0 := by simp [dist, tsub_self] theorem eq_of_dist_eq_zero {n m : β„•} (h : dist n m = 0) : n = m := have : n - m = 0 := Nat.eq_zero_of_add_eq_zero_right h have : n ≀ m := tsub_eq_zero_iff_le.mp this have : m - n = 0 := Nat.eq_zero_of_add_eq_zero_left h have : m ≀ n := tsub_eq_zero_iff_le.mp this le_antisymm β€Ήn ≀ mβ€Ί β€Ήm ≀ nβ€Ί theorem dist_eq_zero {n m : β„•} (h : n = m) : dist n m = 0 := by rw [h, dist_self] theorem dist_eq_sub_of_le {n m : β„•} (h : n ≀ m) : dist n m = m - n := by rw [dist, tsub_eq_zero_iff_le.mpr h, zero_add] theorem dist_eq_sub_of_le_right {n m : β„•} (h : m ≀ n) : dist n m = n - m := by rw [dist_comm]; apply dist_eq_sub_of_le h theorem dist_tri_left (n m : β„•) : m ≀ dist n m + n := le_trans le_tsub_add (add_le_add_right (Nat.le_add_left _ _) _) theorem dist_tri_right (n m : β„•) : m ≀ n + dist n m := by rw [add_comm]; apply dist_tri_left theorem dist_tri_left' (n m : β„•) : n ≀ dist n m + m := by rw [dist_comm]; apply dist_tri_left theorem dist_tri_right' (n m : β„•) : n ≀ m + dist n m := by rw [dist_comm]; apply dist_tri_right theorem dist_zero_right (n : β„•) : dist n 0 = n := Eq.trans (dist_eq_sub_of_le_right (zero_le n)) (tsub_zero n) theorem dist_zero_left (n : β„•) : dist 0 n = n := Eq.trans (dist_eq_sub_of_le (zero_le n)) (tsub_zero n) theorem dist_add_add_right (n k m : β„•) : dist (n + k) (m + k) = dist n m := calc dist (n + k) (m + k) = n + k - (m + k) + (m + k - (n + k)) := rfl _ = n - m + (m + k - (n + k)) := by rw [@add_tsub_add_eq_tsub_right] _ = n - m + (m - n) := by rw [@add_tsub_add_eq_tsub_right] theorem dist_add_add_left (k n m : β„•) : dist (k + n) (k + m) = dist n m := by rw [add_comm k n, add_comm k m]; apply dist_add_add_right theorem dist_eq_intro {n m k l : β„•} (h : n + m = k + l) : dist n k = dist l m := calc dist n k = dist (n + m) (k + m) := by rw [dist_add_add_right] _ = dist (k + l) (k + m) := by rw [h] _ = dist l m := by rw [dist_add_add_left] theorem dist.triangle_inequality (n m k : β„•) : dist n k ≀ dist n m + dist m k := by have : dist n m + dist m k = n - m + (m - k) + (k - m + (m - n)) := by simp [dist, add_comm, add_left_comm, add_assoc] rw [this, dist] exact add_le_add tsub_le_tsub_add_tsub tsub_le_tsub_add_tsub theorem dist_mul_right (n k m : β„•) : dist (n * k) (m * k) = dist n m * k := by rw [dist, dist, right_distrib, tsub_mul n, tsub_mul m] theorem dist_mul_left (k n m : β„•) : dist (k * n) (k * m) = k * dist n m := by rw [mul_comm k n, mul_comm k m, dist_mul_right, mul_comm] theorem dist_eq_max_sub_min {i j : β„•} : dist i j = (max i j) - min i j := Or.elim (lt_or_ge i j) (by intro h; rw [max_eq_right_of_lt h, min_eq_left_of_lt h, dist_eq_sub_of_le (Nat.le_of_lt h)]) (by intro h; rw [max_eq_left h, min_eq_right h, dist_eq_sub_of_le_right h]) theorem dist_succ_succ {i j : Nat} : dist (succ i) (succ j) = dist i j := by simp [dist, succ_sub_succ] theorem dist_pos_of_ne {i j : Nat} : i β‰  j β†’ 0 < dist i j := fun hne => Nat.ltByCases (fun h : i < j => by rw [dist_eq_sub_of_le (le_of_lt h)]; apply tsub_pos_of_lt h) (fun h : i = j => by contradiction) fun h : i > j => by rw [dist_eq_sub_of_le_right (le_of_lt h)]; apply tsub_pos_of_lt h end Nat
Data\Nat\EvenOddRec.lean
/- Copyright (c) 2022 Stuart Presnell. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stuart Presnell -/ import Mathlib.Algebra.Ring.Parity import Mathlib.Data.Nat.Bits /-! # A recursion principle based on even and odd numbers. -/ namespace Nat /-- Recursion principle on even and odd numbers: if we have `P 0`, and for all `i : β„•` we can extend from `P i` to both `P (2 * i)` and `P (2 * i + 1)`, then we have `P n` for all `n : β„•`. This is nothing more than a wrapper around `Nat.binaryRec`, to avoid having to switch to dealing with `bit0` and `bit1`. -/ @[elab_as_elim] def evenOddRec {P : β„• β†’ Sort*} (h0 : P 0) (h_even : βˆ€ n, P n β†’ P (2 * n)) (h_odd : βˆ€ n, P n β†’ P (2 * n + 1)) (n : β„•) : P n := binaryRec h0 (fun | false, i, hi => (h_even i hi : P (2 * i)) | true, i, hi => (h_odd i hi : P (2 * i + 1))) n @[simp] theorem evenOddRec_zero {P : β„• β†’ Sort*} (h0 : P 0) (h_even : βˆ€ i, P i β†’ P (2 * i)) (h_odd : βˆ€ i, P i β†’ P (2 * i + 1)) : evenOddRec h0 h_even h_odd 0 = h0 := binaryRec_zero _ _ @[simp] theorem evenOddRec_even {P : β„• β†’ Sort*} (h0 : P 0) (h_even : βˆ€ i, P i β†’ P (2 * i)) (h_odd : βˆ€ i, P i β†’ P (2 * i + 1)) (H : h_even 0 h0 = h0) (n : β„•) : (2 * n).evenOddRec h0 h_even h_odd = h_even n (evenOddRec h0 h_even h_odd n) := by apply binaryRec_eq' false n simp [H] @[simp] theorem evenOddRec_odd {P : β„• β†’ Sort*} (h0 : P 0) (h_even : βˆ€ i, P i β†’ P (2 * i)) (h_odd : βˆ€ i, P i β†’ P (2 * i + 1)) (H : h_even 0 h0 = h0) (n : β„•) : (2 * n + 1).evenOddRec h0 h_even h_odd = h_odd n (evenOddRec h0 h_even h_odd n) := by apply binaryRec_eq' true n simp [H] /-- Strong recursion principle on even and odd numbers: if for all `i : β„•` we can prove `P (2 * i)` from `P j` for all `j < 2 * i` and we can prove `P (2 * i + 1)` from `P j` for all `j < 2 * i + 1`, then we have `P n` for all `n : β„•`. -/ @[elab_as_elim] noncomputable def evenOddStrongRec {P : β„• β†’ Sort*} (h_even : βˆ€ n : β„•, (βˆ€ k < 2 * n, P k) β†’ P (2 * n)) (h_odd : βˆ€ n : β„•, (βˆ€ k < 2 * n + 1, P k) β†’ P (2 * n + 1)) (n : β„•) : P n := n.strongRecOn fun m ih => m.even_or_odd'.choose_spec.by_cases (fun h => h.symm β–Έ h_even m.even_or_odd'.choose <| h β–Έ ih) (fun h => h.symm β–Έ h_odd m.even_or_odd'.choose <| h β–Έ ih) end Nat
Data\Nat\Factors.lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import Mathlib.Algebra.BigOperators.Ring.List import Mathlib.Data.Nat.Prime.Defs import Mathlib.Data.List.Prime import Mathlib.Data.List.Sort /-! # Prime numbers This file deals with the factors of natural numbers. ## Important declarations - `Nat.factors n`: the prime factorization of `n` - `Nat.factors_unique`: uniqueness of the prime factorisation -/ open Bool Subtype open Nat namespace Nat attribute [instance 0] instBEqNat /-- `primeFactorsList n` is the prime factorization of `n`, listed in increasing order. -/ def primeFactorsList : β„• β†’ List β„• | 0 => [] | 1 => [] | k + 2 => let m := minFac (k + 2) m :: primeFactorsList ((k + 2) / m) decreasing_by show (k + 2) / m < (k + 2); exact factors_lemma @[deprecated (since := "2024-06-14")] alias factors := primeFactorsList @[simp] theorem primeFactorsList_zero : primeFactorsList 0 = [] := by rw [primeFactorsList] @[simp] theorem primeFactorsList_one : primeFactorsList 1 = [] := by rw [primeFactorsList] @[simp] theorem primeFactorsList_two : primeFactorsList 2 = [2] := by simp [primeFactorsList] theorem prime_of_mem_primeFactorsList {n : β„•} : βˆ€ {p : β„•}, p ∈ primeFactorsList n β†’ Prime p := by match n with | 0 => simp | 1 => simp | k + 2 => intro p h let m := minFac (k + 2) have : (k + 2) / m < (k + 2) := factors_lemma have h₁ : p = m ∨ p ∈ primeFactorsList ((k + 2) / m) := List.mem_cons.1 (by rwa [primeFactorsList] at h) exact Or.casesOn h₁ (fun hβ‚‚ => hβ‚‚.symm β–Έ minFac_prime (by simp)) prime_of_mem_primeFactorsList theorem pos_of_mem_primeFactorsList {n p : β„•} (h : p ∈ primeFactorsList n) : 0 < p := Prime.pos (prime_of_mem_primeFactorsList h) theorem prod_primeFactorsList : βˆ€ {n}, n β‰  0 β†’ List.prod (primeFactorsList n) = n | 0 => by simp | 1 => by simp | k + 2 => fun _ => let m := minFac (k + 2) have : (k + 2) / m < (k + 2) := factors_lemma show (primeFactorsList (k + 2)).prod = (k + 2) by have h₁ : (k + 2) / m β‰  0 := fun h => by have : (k + 2) = 0 * m := (Nat.div_eq_iff_eq_mul_left (minFac_pos _) (minFac_dvd _)).1 h rw [zero_mul] at this; exact (show k + 2 β‰  0 by simp) this rw [primeFactorsList, List.prod_cons, prod_primeFactorsList h₁, Nat.mul_div_cancel' (minFac_dvd _)] theorem primeFactorsList_prime {p : β„•} (hp : Nat.Prime p) : p.primeFactorsList = [p] := by have : p = p - 2 + 2 := (Nat.sub_add_cancel hp.two_le).symm rw [this, primeFactorsList] simp only [Eq.symm this] have : Nat.minFac p = p := (Nat.prime_def_minFac.mp hp).2 simp only [this, primeFactorsList, Nat.div_self (Nat.Prime.pos hp)] theorem primeFactorsList_chain {n : β„•} : βˆ€ {a}, (βˆ€ p, Prime p β†’ p ∣ n β†’ a ≀ p) β†’ List.Chain (Β· ≀ Β·) a (primeFactorsList n) := by match n with | 0 => simp | 1 => simp | k + 2 => intro a h let m := minFac (k + 2) have : (k + 2) / m < (k + 2) := factors_lemma rw [primeFactorsList] refine List.Chain.cons ((le_minFac.2 h).resolve_left (by simp)) (primeFactorsList_chain ?_) exact fun p pp d => minFac_le_of_dvd pp.two_le (d.trans <| div_dvd_of_dvd <| minFac_dvd _) theorem primeFactorsList_chain_2 (n) : List.Chain (Β· ≀ Β·) 2 (primeFactorsList n) := primeFactorsList_chain fun _ pp _ => pp.two_le theorem primeFactorsList_chain' (n) : List.Chain' (Β· ≀ Β·) (primeFactorsList n) := @List.Chain'.tail _ _ (_ :: _) (primeFactorsList_chain_2 _) theorem primeFactorsList_sorted (n : β„•) : List.Sorted (Β· ≀ Β·) (primeFactorsList n) := List.chain'_iff_pairwise.1 (primeFactorsList_chain' _) /-- `primeFactorsList` can be constructed inductively by extracting `minFac`, for sufficiently large `n`. -/ theorem primeFactorsList_add_two (n : β„•) : primeFactorsList (n + 2) = minFac (n + 2) :: primeFactorsList ((n + 2) / minFac (n + 2)) := by rw [primeFactorsList] @[simp] theorem primeFactorsList_eq_nil (n : β„•) : n.primeFactorsList = [] ↔ n = 0 ∨ n = 1 := by constructor <;> intro h Β· rcases n with (_ | _ | n) Β· exact Or.inl rfl Β· exact Or.inr rfl Β· rw [primeFactorsList] at h injection h Β· rcases h with (rfl | rfl) Β· exact primeFactorsList_zero Β· exact primeFactorsList_one open scoped List in theorem eq_of_perm_primeFactorsList {a b : β„•} (ha : a β‰  0) (hb : b β‰  0) (h : a.primeFactorsList ~ b.primeFactorsList) : a = b := by simpa [prod_primeFactorsList ha, prod_primeFactorsList hb] using List.Perm.prod_eq h section open List theorem mem_primeFactorsList_iff_dvd {n p : β„•} (hn : n β‰  0) (hp : Prime p) : p ∈ primeFactorsList n ↔ p ∣ n where mp h := prod_primeFactorsList hn β–Έ List.dvd_prod h mpr h := mem_list_primes_of_dvd_prod (prime_iff.mp hp) (fun _ h ↦ prime_iff.mp (prime_of_mem_primeFactorsList h)) ((prod_primeFactorsList hn).symm β–Έ h) theorem dvd_of_mem_primeFactorsList {n p : β„•} (h : p ∈ n.primeFactorsList) : p ∣ n := by rcases n.eq_zero_or_pos with (rfl | hn) Β· exact dvd_zero p Β· rwa [← mem_primeFactorsList_iff_dvd hn.ne' (prime_of_mem_primeFactorsList h)] theorem mem_primeFactorsList {n p} (hn : n β‰  0) : p ∈ primeFactorsList n ↔ Prime p ∧ p ∣ n := ⟨fun h => ⟨prime_of_mem_primeFactorsList h, dvd_of_mem_primeFactorsList h⟩, fun ⟨hprime, hdvd⟩ => (mem_primeFactorsList_iff_dvd hn hprime).mpr hdvd⟩ @[simp] lemma mem_primeFactorsList' {n p} : p ∈ n.primeFactorsList ↔ p.Prime ∧ p ∣ n ∧ n β‰  0 := by cases n <;> simp [mem_primeFactorsList, *] theorem le_of_mem_primeFactorsList {n p : β„•} (h : p ∈ n.primeFactorsList) : p ≀ n := by rcases n.eq_zero_or_pos with (rfl | hn) Β· rw [primeFactorsList_zero] at h cases h Β· exact le_of_dvd hn (dvd_of_mem_primeFactorsList h) /-- **Fundamental theorem of arithmetic**-/ theorem primeFactorsList_unique {n : β„•} {l : List β„•} (h₁ : prod l = n) (hβ‚‚ : βˆ€ p ∈ l, Prime p) : l ~ primeFactorsList n := by refine perm_of_prod_eq_prod ?_ ?_ ?_ Β· rw [h₁] refine (prod_primeFactorsList ?_).symm rintro rfl rw [prod_eq_zero_iff] at h₁ exact Prime.ne_zero (hβ‚‚ 0 h₁) rfl Β· simp_rw [← prime_iff] exact hβ‚‚ Β· simp_rw [← prime_iff] exact fun p => prime_of_mem_primeFactorsList theorem Prime.primeFactorsList_pow {p : β„•} (hp : p.Prime) (n : β„•) : (p ^ n).primeFactorsList = List.replicate n p := by symm rw [← List.replicate_perm] apply Nat.primeFactorsList_unique (List.prod_replicate n p) intro q hq rwa [eq_of_mem_replicate hq] theorem eq_prime_pow_of_unique_prime_dvd {n p : β„•} (hpos : n β‰  0) (h : βˆ€ {d}, Nat.Prime d β†’ d ∣ n β†’ d = p) : n = p ^ n.primeFactorsList.length := by set k := n.primeFactorsList.length rw [← prod_primeFactorsList hpos, ← prod_replicate k p, eq_replicate_of_mem fun d hd => h (prime_of_mem_primeFactorsList hd) (dvd_of_mem_primeFactorsList hd)] /-- For positive `a` and `b`, the prime factors of `a * b` are the union of those of `a` and `b` -/ theorem perm_primeFactorsList_mul {a b : β„•} (ha : a β‰  0) (hb : b β‰  0) : (a * b).primeFactorsList ~ a.primeFactorsList ++ b.primeFactorsList := by refine (primeFactorsList_unique ?_ ?_).symm Β· rw [List.prod_append, prod_primeFactorsList ha, prod_primeFactorsList hb] Β· intro p hp rw [List.mem_append] at hp cases' hp with hp' hp' <;> exact prime_of_mem_primeFactorsList hp' /-- For coprime `a` and `b`, the prime factors of `a * b` are the union of those of `a` and `b` -/ theorem perm_primeFactorsList_mul_of_coprime {a b : β„•} (hab : Coprime a b) : (a * b).primeFactorsList ~ a.primeFactorsList ++ b.primeFactorsList := by rcases a.eq_zero_or_pos with (rfl | ha) Β· simp [(coprime_zero_left _).mp hab] rcases b.eq_zero_or_pos with (rfl | hb) Β· simp [(coprime_zero_right _).mp hab] exact perm_primeFactorsList_mul ha.ne' hb.ne' theorem primeFactorsList_sublist_right {n k : β„•} (h : k β‰  0) : n.primeFactorsList <+ (n * k).primeFactorsList := by cases' n with hn Β· simp [zero_mul] apply sublist_of_subperm_of_sorted _ (primeFactorsList_sorted _) (primeFactorsList_sorted _) simp only [(perm_primeFactorsList_mul (Nat.succ_ne_zero _) h).subperm_left] exact (sublist_append_left _ _).subperm theorem primeFactorsList_sublist_of_dvd {n k : β„•} (h : n ∣ k) (h' : k β‰  0) : n.primeFactorsList <+ k.primeFactorsList := by obtain ⟨a, rfl⟩ := h exact primeFactorsList_sublist_right (right_ne_zero_of_mul h') theorem primeFactorsList_subset_right {n k : β„•} (h : k β‰  0) : n.primeFactorsList βŠ† (n * k).primeFactorsList := (primeFactorsList_sublist_right h).subset theorem primeFactorsList_subset_of_dvd {n k : β„•} (h : n ∣ k) (h' : k β‰  0) : n.primeFactorsList βŠ† k.primeFactorsList := (primeFactorsList_sublist_of_dvd h h').subset theorem dvd_of_primeFactorsList_subperm {a b : β„•} (ha : a β‰  0) (h : a.primeFactorsList <+~ b.primeFactorsList) : a ∣ b := by rcases b.eq_zero_or_pos with (rfl | hb) Β· exact dvd_zero _ rcases a with (_ | _ | a) Β· exact (ha rfl).elim Β· exact one_dvd _ -- Porting note: previous proof --use (b.primeFactorsList.diff a.succ.succ.primeFactorsList).prod use (@List.diff _ instBEqOfDecidableEq b.primeFactorsList a.succ.succ.primeFactorsList).prod nth_rw 1 [← Nat.prod_primeFactorsList ha] rw [← List.prod_append, List.Perm.prod_eq <| List.subperm_append_diff_self_of_count_le <| List.subperm_ext_iff.mp h, Nat.prod_primeFactorsList hb.ne'] theorem replicate_subperm_primeFactorsList_iff {a b n : β„•} (ha : Prime a) (hb : b β‰  0) : replicate n a <+~ primeFactorsList b ↔ a ^ n ∣ b := by induction n generalizing b with | zero => simp | succ n ih => constructor Β· rw [List.subperm_iff] rintro ⟨u, hu1, hu2⟩ rw [← Nat.prod_primeFactorsList hb, ← hu1.prod_eq, ← prod_replicate] exact hu2.prod_dvd_prod Β· rintro ⟨c, rfl⟩ rw [Ne, pow_succ', mul_assoc, mul_eq_zero, _root_.not_or] at hb rw [pow_succ', mul_assoc, replicate_succ, (Nat.perm_primeFactorsList_mul hb.1 hb.2).subperm_left, primeFactorsList_prime ha, singleton_append, subperm_cons, ih hb.2] exact dvd_mul_right _ _ end theorem mem_primeFactorsList_mul {a b : β„•} (ha : a β‰  0) (hb : b β‰  0) {p : β„•} : p ∈ (a * b).primeFactorsList ↔ p ∈ a.primeFactorsList ∨ p ∈ b.primeFactorsList := by rw [mem_primeFactorsList (mul_ne_zero ha hb), mem_primeFactorsList ha, mem_primeFactorsList hb, ← and_or_left] simpa only [and_congr_right_iff] using Prime.dvd_mul /-- The sets of factors of coprime `a` and `b` are disjoint -/ theorem coprime_primeFactorsList_disjoint {a b : β„•} (hab : a.Coprime b) : List.Disjoint a.primeFactorsList b.primeFactorsList := by intro q hqa hqb apply not_prime_one rw [← eq_one_of_dvd_coprimes hab (dvd_of_mem_primeFactorsList hqa) (dvd_of_mem_primeFactorsList hqb)] exact prime_of_mem_primeFactorsList hqa theorem mem_primeFactorsList_mul_of_coprime {a b : β„•} (hab : Coprime a b) (p : β„•) : p ∈ (a * b).primeFactorsList ↔ p ∈ a.primeFactorsList βˆͺ b.primeFactorsList := by rcases a.eq_zero_or_pos with (rfl | ha) Β· simp [(coprime_zero_left _).mp hab] rcases b.eq_zero_or_pos with (rfl | hb) Β· simp [(coprime_zero_right _).mp hab] rw [mem_primeFactorsList_mul ha.ne' hb.ne', List.mem_union_iff] open List /-- If `p` is a prime factor of `a` then `p` is also a prime factor of `a * b` for any `b > 0` -/ theorem mem_primeFactorsList_mul_left {p a b : β„•} (hpa : p ∈ a.primeFactorsList) (hb : b β‰  0) : p ∈ (a * b).primeFactorsList := by rcases eq_or_ne a 0 with (rfl | ha) Β· simp at hpa apply (mem_primeFactorsList_mul ha hb).2 (Or.inl hpa) /-- If `p` is a prime factor of `b` then `p` is also a prime factor of `a * b` for any `a > 0` -/ theorem mem_primeFactorsList_mul_right {p a b : β„•} (hpb : p ∈ b.primeFactorsList) (ha : a β‰  0) : p ∈ (a * b).primeFactorsList := by rw [mul_comm] exact mem_primeFactorsList_mul_left hpb ha theorem eq_two_pow_or_exists_odd_prime_and_dvd (n : β„•) : (βˆƒ k : β„•, n = 2 ^ k) ∨ βˆƒ p, Nat.Prime p ∧ p ∣ n ∧ Odd p := (eq_or_ne n 0).elim (fun hn => Or.inr ⟨3, prime_three, hn.symm β–Έ dvd_zero 3, ⟨1, rfl⟩⟩) fun hn => or_iff_not_imp_right.mpr fun H => ⟨n.primeFactorsList.length, eq_prime_pow_of_unique_prime_dvd hn fun {_} hprime hdvd => hprime.eq_two_or_odd'.resolve_right fun hodd => H ⟨_, hprime, hdvd, hodd⟩⟩ theorem four_dvd_or_exists_odd_prime_and_dvd_of_two_lt {n : β„•} (n2 : 2 < n) : 4 ∣ n ∨ βˆƒ p, Prime p ∧ p ∣ n ∧ Odd p := by obtain ⟨_ | _ | k, rfl⟩ | ⟨p, hp, hdvd, hodd⟩ := n.eq_two_pow_or_exists_odd_prime_and_dvd Β· contradiction Β· contradiction Β· simp [Nat.pow_succ, mul_assoc] Β· exact Or.inr ⟨p, hp, hdvd, hodd⟩ end Nat assert_not_exists Multiset
Data\Nat\Find.lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Johannes HΓΆlzl, Mario Carneiro -/ import Mathlib.Data.Nat.Defs import Batteries.WF /-! # `Nat.find` and `Nat.findGreatest` -/ variable {a b c d m n k : β„•} {p q : β„• β†’ Prop} namespace Nat section Find /-! ### `Nat.find` -/ private def lbp (m n : β„•) : Prop := m = n + 1 ∧ βˆ€ k ≀ n, Β¬p k variable [DecidablePred p] (H : βˆƒ n, p n) private def wf_lbp : WellFounded (@lbp p) := ⟨let ⟨n, pn⟩ := H suffices βˆ€ m k, n ≀ k + m β†’ Acc lbp k from fun a => this _ _ (Nat.le_add_left _ _) fun m => Nat.recOn m (fun k kn => ⟨_, fun y r => match y, r with | _, ⟨rfl, a⟩ => absurd pn (a _ kn)⟩) fun m IH k kn => ⟨_, fun y r => match y, r with | _, ⟨rfl, _a⟩ => IH _ (by rw [Nat.add_right_comm]; exact kn)⟩⟩ protected def findX : { n // p n ∧ βˆ€ m < n, Β¬p m } := @WellFounded.fix _ (fun k => (βˆ€ n < k, Β¬p n) β†’ { n // p n ∧ βˆ€ m < n, Β¬p m }) lbp (wf_lbp H) (fun m IH al => if pm : p m then ⟨m, pm, al⟩ else have : βˆ€ n ≀ m, Β¬p n := fun n h => Or.elim (Nat.lt_or_eq_of_le h) (al n) fun e => by rw [e]; exact pm IH _ ⟨rfl, this⟩ fun n h => this n <| Nat.le_of_succ_le_succ h) 0 fun n h => absurd h (Nat.not_lt_zero _) /-- If `p` is a (decidable) predicate on `β„•` and `hp : βˆƒ (n : β„•), p n` is a proof that there exists some natural number satisfying `p`, then `Nat.find hp` is the smallest natural number satisfying `p`. Note that `Nat.find` is protected, meaning that you can't just write `find`, even if the `Nat` namespace is open. The API for `Nat.find` is: * `Nat.find_spec` is the proof that `Nat.find hp` satisfies `p`. * `Nat.find_min` is the proof that if `m < Nat.find hp` then `m` does not satisfy `p`. * `Nat.find_min'` is the proof that if `m` does satisfy `p` then `Nat.find hp ≀ m`. -/ protected def find : β„• := (Nat.findX H).1 protected theorem find_spec : p (Nat.find H) := (Nat.findX H).2.left protected theorem find_min : βˆ€ {m : β„•}, m < Nat.find H β†’ Β¬p m := @(Nat.findX H).2.right protected theorem find_min' {m : β„•} (h : p m) : Nat.find H ≀ m := Nat.le_of_not_lt fun l => Nat.find_min H l h lemma find_eq_iff (h : βˆƒ n : β„•, p n) : Nat.find h = m ↔ p m ∧ βˆ€ n < m, Β¬ p n := by constructor Β· rintro rfl exact ⟨Nat.find_spec h, fun _ ↦ Nat.find_min h⟩ Β· rintro ⟨hm, hlt⟩ exact le_antisymm (Nat.find_min' h hm) (not_lt.1 <| imp_not_comm.1 (hlt _) <| Nat.find_spec h) @[simp] lemma find_lt_iff (h : βˆƒ n : β„•, p n) (n : β„•) : Nat.find h < n ↔ βˆƒ m < n, p m := ⟨fun h2 ↦ ⟨Nat.find h, h2, Nat.find_spec h⟩, fun ⟨_, hmn, hm⟩ ↦ Nat.lt_of_le_of_lt (Nat.find_min' h hm) hmn⟩ @[simp] lemma find_le_iff (h : βˆƒ n : β„•, p n) (n : β„•) : Nat.find h ≀ n ↔ βˆƒ m ≀ n, p m := by simp only [exists_prop, ← Nat.lt_succ_iff, find_lt_iff] @[simp] lemma le_find_iff (h : βˆƒ n : β„•, p n) (n : β„•) : n ≀ Nat.find h ↔ βˆ€ m < n, Β¬ p m := by simp only [← not_lt, find_lt_iff, not_exists, not_and] @[simp] lemma lt_find_iff (h : βˆƒ n : β„•, p n) (n : β„•) : n < Nat.find h ↔ βˆ€ m ≀ n, Β¬ p m := by simp only [← succ_le_iff, le_find_iff, succ_le_succ_iff] @[simp] lemma find_eq_zero (h : βˆƒ n : β„•, p n) : Nat.find h = 0 ↔ p 0 := by simp [find_eq_iff] variable [DecidablePred q] in lemma find_mono (h : βˆ€ n, q n β†’ p n) {hp : βˆƒ n, p n} {hq : βˆƒ n, q n} : Nat.find hp ≀ Nat.find hq := Nat.find_min' _ (h _ (Nat.find_spec hq)) lemma find_le {h : βˆƒ n, p n} (hn : p n) : Nat.find h ≀ n := (Nat.find_le_iff _ _).2 ⟨n, le_refl _, hn⟩ lemma find_comp_succ (h₁ : βˆƒ n, p n) (hβ‚‚ : βˆƒ n, p (n + 1)) (h0 : Β¬ p 0) : Nat.find h₁ = Nat.find hβ‚‚ + 1 := by refine (find_eq_iff _).2 ⟨Nat.find_spec hβ‚‚, fun n hn ↦ ?_⟩ cases n exacts [h0, @Nat.find_min (fun n ↦ p (n + 1)) _ hβ‚‚ _ (succ_lt_succ_iff.1 hn)] -- Porting note (#10618): removing `simp` attribute as `simp` can prove it lemma find_pos (h : βˆƒ n : β„•, p n) : 0 < Nat.find h ↔ Β¬p 0 := Nat.pos_iff_ne_zero.trans (Nat.find_eq_zero _).not lemma find_add {hβ‚˜ : βˆƒ m, p (m + n)} {hβ‚™ : βˆƒ n, p n} (hn : n ≀ Nat.find hβ‚™) : Nat.find hβ‚˜ + n = Nat.find hβ‚™ := by refine le_antisymm ((le_find_iff _ _).2 fun m hm hpm => Nat.not_le.2 hm ?_) ?_ Β· have hnm : n ≀ m := le_trans hn (find_le hpm) refine Nat.add_le_of_le_sub hnm (find_le ?_) rwa [Nat.sub_add_cancel hnm] Β· rw [← Nat.sub_le_iff_le_add] refine (le_find_iff _ _).2 fun m hm hpm => Nat.not_le.2 hm ?_ rw [Nat.sub_le_iff_le_add] exact find_le hpm end Find /-! ### `Nat.findGreatest` -/ section FindGreatest /-- `Nat.findGreatest P n` is the largest `i ≀ bound` such that `P i` holds, or `0` if no such `i` exists -/ def findGreatest (P : β„• β†’ Prop) [DecidablePred P] : β„• β†’ β„• | 0 => 0 | n + 1 => if P (n + 1) then n + 1 else Nat.findGreatest P n variable {P Q : β„• β†’ Prop} [DecidablePred P] {n : β„•} @[simp] lemma findGreatest_zero : Nat.findGreatest P 0 = 0 := rfl lemma findGreatest_succ (n : β„•) : Nat.findGreatest P (n + 1) = if P (n + 1) then n + 1 else Nat.findGreatest P n := rfl @[simp] lemma findGreatest_eq : βˆ€ {n}, P n β†’ Nat.findGreatest P n = n | 0, _ => rfl | n + 1, h => by simp [Nat.findGreatest, h] @[simp] lemma findGreatest_of_not (h : Β¬ P (n + 1)) : findGreatest P (n + 1) = findGreatest P n := by simp [Nat.findGreatest, h] lemma findGreatest_eq_iff : Nat.findGreatest P k = m ↔ m ≀ k ∧ (m β‰  0 β†’ P m) ∧ βˆ€ ⦃n⦄, m < n β†’ n ≀ k β†’ Β¬P n := by induction' k with k ihk generalizing m Β· rw [eq_comm, Iff.comm] simp only [zero_eq, Nat.le_zero, ne_eq, findGreatest_zero, and_iff_left_iff_imp] rintro rfl exact ⟨fun h ↦ (h rfl).elim, fun n hlt heq ↦ by omega⟩ Β· by_cases hk : P (k + 1) Β· rw [findGreatest_eq hk] constructor Β· rintro rfl exact ⟨le_refl _, fun _ ↦ hk, fun n hlt hle ↦ by omega⟩ Β· rintro ⟨hle, h0, hm⟩ rcases Decidable.eq_or_lt_of_le hle with (rfl | hlt) exacts [rfl, (hm hlt (le_refl _) hk).elim] Β· rw [findGreatest_of_not hk, ihk] constructor Β· rintro ⟨hle, hP, hm⟩ refine ⟨le_trans hle k.le_succ, hP, fun n hlt hle ↦ ?_⟩ rcases Decidable.eq_or_lt_of_le hle with (rfl | hlt') exacts [hk, hm hlt <| Nat.lt_succ_iff.1 hlt'] Β· rintro ⟨hle, hP, hm⟩ refine ⟨Nat.lt_succ_iff.1 (lt_of_le_of_ne hle ?_), hP, fun n hlt hle ↦ hm hlt (le_trans hle k.le_succ)⟩ rintro rfl exact hk (hP k.succ_ne_zero) lemma findGreatest_eq_zero_iff : Nat.findGreatest P k = 0 ↔ βˆ€ ⦃n⦄, 0 < n β†’ n ≀ k β†’ Β¬P n := by simp [findGreatest_eq_iff] @[simp] lemma findGreatest_pos : 0 < Nat.findGreatest P k ↔ βˆƒ n, 0 < n ∧ n ≀ k ∧ P n := by rw [Nat.pos_iff_ne_zero, Ne, findGreatest_eq_zero_iff]; push_neg; rfl lemma findGreatest_spec (hmb : m ≀ n) (hm : P m) : P (Nat.findGreatest P n) := by by_cases h : Nat.findGreatest P n = 0 Β· cases m Β· rwa [h] exact ((findGreatest_eq_zero_iff.1 h) (zero_lt_succ _) hmb hm).elim Β· exact (findGreatest_eq_iff.1 rfl).2.1 h lemma findGreatest_le (n : β„•) : Nat.findGreatest P n ≀ n := (findGreatest_eq_iff.1 rfl).1 lemma le_findGreatest (hmb : m ≀ n) (hm : P m) : m ≀ Nat.findGreatest P n := le_of_not_lt fun hlt => (findGreatest_eq_iff.1 rfl).2.2 hlt hmb hm lemma findGreatest_mono_right (P : β„• β†’ Prop) [DecidablePred P] {m n} (hmn : m ≀ n) : Nat.findGreatest P m ≀ Nat.findGreatest P n := by induction' hmn with k hmk ih Β· simp rw [findGreatest_succ] split_ifs Β· exact le_trans ih $ le_trans (findGreatest_le _) (le_succ _) Β· exact ih lemma findGreatest_mono_left [DecidablePred Q] (hPQ : βˆ€ n, P n β†’ Q n) (n : β„•) : Nat.findGreatest P n ≀ Nat.findGreatest Q n := by induction' n with n hn Β· rfl by_cases h : P (n + 1) Β· rw [findGreatest_eq h, findGreatest_eq (hPQ _ h)] Β· rw [findGreatest_of_not h] exact le_trans hn (Nat.findGreatest_mono_right _ <| le_succ _) lemma findGreatest_mono [DecidablePred Q] (hPQ : βˆ€ n, P n β†’ Q n) (hmn : m ≀ n) : Nat.findGreatest P m ≀ Nat.findGreatest Q n := le_trans (Nat.findGreatest_mono_right _ hmn) (findGreatest_mono_left hPQ _) theorem findGreatest_is_greatest (hk : Nat.findGreatest P n < k) (hkb : k ≀ n) : Β¬P k := (findGreatest_eq_iff.1 rfl).2.2 hk hkb theorem findGreatest_of_ne_zero (h : Nat.findGreatest P n = m) (h0 : m β‰  0) : P m := (findGreatest_eq_iff.1 h).2.1 h0 end FindGreatest
Data\Nat\Hyperoperation.lean
/- Copyright (c) 2023 Mark Andrew Gerads. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mark Andrew Gerads, Junyan Xu, Eric Wieser -/ import Mathlib.Tactic.Ring /-! # Hyperoperation sequence This file defines the Hyperoperation sequence. `hyperoperation 0 m k = k + 1` `hyperoperation 1 m k = m + k` `hyperoperation 2 m k = m * k` `hyperoperation 3 m k = m ^ k` `hyperoperation (n + 3) m 0 = 1` `hyperoperation (n + 1) m (k + 1) = hyperoperation n m (hyperoperation (n + 1) m k)` ## References * <https://en.wikipedia.org/wiki/Hyperoperation> ## Tags hyperoperation -/ /-- Implementation of the hyperoperation sequence where `hyperoperation n m k` is the `n`th hyperoperation between `m` and `k`. -/ def hyperoperation : β„• β†’ β„• β†’ β„• β†’ β„• | 0, _, k => k + 1 | 1, m, 0 => m | 2, _, 0 => 0 | _ + 3, _, 0 => 1 | n + 1, m, k + 1 => hyperoperation n m (hyperoperation (n + 1) m k) -- Basic hyperoperation lemmas @[simp] theorem hyperoperation_zero (m : β„•) : hyperoperation 0 m = Nat.succ := funext fun k => by rw [hyperoperation, Nat.succ_eq_add_one] theorem hyperoperation_ge_three_eq_one (n m : β„•) : hyperoperation (n + 3) m 0 = 1 := by rw [hyperoperation] theorem hyperoperation_recursion (n m k : β„•) : hyperoperation (n + 1) m (k + 1) = hyperoperation n m (hyperoperation (n + 1) m k) := by rw [hyperoperation] -- Interesting hyperoperation lemmas @[simp] theorem hyperoperation_one : hyperoperation 1 = (Β· + Β·) := by ext m k induction' k with bn bih Β· rw [Nat.add_zero m, hyperoperation] Β· rw [hyperoperation_recursion, bih, hyperoperation_zero] exact Nat.add_assoc m bn 1 @[simp] theorem hyperoperation_two : hyperoperation 2 = (Β· * Β·) := by ext m k induction' k with bn bih Β· rw [hyperoperation] exact (Nat.mul_zero m).symm Β· rw [hyperoperation_recursion, hyperoperation_one, bih] -- Porting note: was `ring` dsimp only nth_rewrite 1 [← mul_one m] rw [← mul_add, add_comm] @[simp] theorem hyperoperation_three : hyperoperation 3 = (Β· ^ Β·) := by ext m k induction' k with bn bih Β· rw [hyperoperation_ge_three_eq_one] exact (pow_zero m).symm Β· rw [hyperoperation_recursion, hyperoperation_two, bih] exact (pow_succ' m bn).symm theorem hyperoperation_ge_two_eq_self (n m : β„•) : hyperoperation (n + 2) m 1 = m := by induction' n with nn nih Β· rw [hyperoperation_two] ring Β· rw [hyperoperation_recursion, hyperoperation_ge_three_eq_one, nih] theorem hyperoperation_two_two_eq_four (n : β„•) : hyperoperation (n + 1) 2 2 = 4 := by induction' n with nn nih Β· rw [hyperoperation_one] Β· rw [hyperoperation_recursion, hyperoperation_ge_two_eq_self, nih] theorem hyperoperation_ge_three_one (n : β„•) : βˆ€ k : β„•, hyperoperation (n + 3) 1 k = 1 := by induction' n with nn nih Β· intro k rw [hyperoperation_three] dsimp rw [one_pow] Β· intro k cases k Β· rw [hyperoperation_ge_three_eq_one] Β· rw [hyperoperation_recursion, nih] theorem hyperoperation_ge_four_zero (n k : β„•) : hyperoperation (n + 4) 0 k = if Even k then 1 else 0 := by induction' k with kk kih Β· rw [hyperoperation_ge_three_eq_one] simp only [Nat.zero_eq, even_zero, if_true] Β· rw [hyperoperation_recursion] rw [kih] simp_rw [Nat.even_add_one] split_ifs Β· exact hyperoperation_ge_two_eq_self (n + 1) 0 Β· exact hyperoperation_ge_three_eq_one n 0
Data\Nat\Lattice.lean
/- Copyright (c) 2018 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes HΓΆlzl, Floris van Doorn, Gabriel Ebner, Yury Kudryashov -/ import Mathlib.Order.ConditionallyCompleteLattice.Finset import Mathlib.Order.Interval.Finset.Nat /-! # Conditionally complete linear order structure on `β„•` In this file we * define a `ConditionallyCompleteLinearOrderBot` structure on `β„•`; * prove a few lemmas about `iSup`/`iInf`/`Set.iUnion`/`Set.iInter` and natural numbers. -/ assert_not_exists MonoidWithZero open Set namespace Nat open scoped Classical noncomputable instance : InfSet β„• := ⟨fun s ↦ if h : βˆƒ n, n ∈ s then @Nat.find (fun n ↦ n ∈ s) _ h else 0⟩ noncomputable instance : SupSet β„• := ⟨fun s ↦ if h : βˆƒ n, βˆ€ a ∈ s, a ≀ n then @Nat.find (fun n ↦ βˆ€ a ∈ s, a ≀ n) _ h else 0⟩ theorem sInf_def {s : Set β„•} (h : s.Nonempty) : sInf s = @Nat.find (fun n ↦ n ∈ s) _ h := dif_pos _ theorem sSup_def {s : Set β„•} (h : βˆƒ n, βˆ€ a ∈ s, a ≀ n) : sSup s = @Nat.find (fun n ↦ βˆ€ a ∈ s, a ≀ n) _ h := dif_pos _ theorem _root_.Set.Infinite.Nat.sSup_eq_zero {s : Set β„•} (h : s.Infinite) : sSup s = 0 := dif_neg fun ⟨n, hn⟩ ↦ let ⟨k, hks, hk⟩ := h.exists_gt n (hn k hks).not_lt hk @[simp] theorem sInf_eq_zero {s : Set β„•} : sInf s = 0 ↔ 0 ∈ s ∨ s = βˆ… := by cases eq_empty_or_nonempty s with | inl h => subst h simp only [or_true_iff, eq_self_iff_true, iff_true_iff, iInf, InfSet.sInf, mem_empty_iff_false, exists_false, dif_neg, not_false_iff] | inr h => simp only [h.ne_empty, or_false_iff, Nat.sInf_def, h, Nat.find_eq_zero] @[simp] theorem sInf_empty : sInf βˆ… = 0 := by rw [sInf_eq_zero] right rfl @[simp] theorem iInf_of_empty {ΞΉ : Sort*} [IsEmpty ΞΉ] (f : ΞΉ β†’ β„•) : iInf f = 0 := by rw [iInf_of_isEmpty, sInf_empty] /-- This combines `Nat.iInf_of_empty` with `ciInf_const`. -/ @[simp] lemma iInf_const_zero {ΞΉ : Sort*} : β¨… i : ΞΉ, 0 = 0 := (isEmpty_or_nonempty ΞΉ).elim (fun h ↦ by simp) fun h ↦ sInf_eq_zero.2 <| by simp theorem sInf_mem {s : Set β„•} (h : s.Nonempty) : sInf s ∈ s := by rw [Nat.sInf_def h] exact Nat.find_spec h theorem not_mem_of_lt_sInf {s : Set β„•} {m : β„•} (hm : m < sInf s) : m βˆ‰ s := by cases eq_empty_or_nonempty s with | inl h => subst h; apply not_mem_empty | inr h => rw [Nat.sInf_def h] at hm; exact Nat.find_min h hm protected theorem sInf_le {s : Set β„•} {m : β„•} (hm : m ∈ s) : sInf s ≀ m := by rw [Nat.sInf_def ⟨m, hm⟩] exact Nat.find_min' ⟨m, hm⟩ hm theorem nonempty_of_pos_sInf {s : Set β„•} (h : 0 < sInf s) : s.Nonempty := by by_contra contra rw [Set.not_nonempty_iff_eq_empty] at contra have h' : sInf s β‰  0 := ne_of_gt h apply h' rw [Nat.sInf_eq_zero] right assumption theorem nonempty_of_sInf_eq_succ {s : Set β„•} {k : β„•} (h : sInf s = k + 1) : s.Nonempty := nonempty_of_pos_sInf (h.symm β–Έ succ_pos k : sInf s > 0) theorem eq_Ici_of_nonempty_of_upward_closed {s : Set β„•} (hs : s.Nonempty) (hs' : βˆ€ k₁ kβ‚‚ : β„•, k₁ ≀ kβ‚‚ β†’ k₁ ∈ s β†’ kβ‚‚ ∈ s) : s = Ici (sInf s) := ext fun n ↦ ⟨fun H ↦ Nat.sInf_le H, fun H ↦ hs' (sInf s) n H (sInf_mem hs)⟩ theorem sInf_upward_closed_eq_succ_iff {s : Set β„•} (hs : βˆ€ k₁ kβ‚‚ : β„•, k₁ ≀ kβ‚‚ β†’ k₁ ∈ s β†’ kβ‚‚ ∈ s) (k : β„•) : sInf s = k + 1 ↔ k + 1 ∈ s ∧ k βˆ‰ s := by constructor Β· intro H rw [eq_Ici_of_nonempty_of_upward_closed (nonempty_of_sInf_eq_succ _) hs, H, mem_Ici, mem_Ici] Β· exact ⟨le_rfl, k.not_succ_le_self⟩ Β· exact k Β· assumption Β· rintro ⟨H, H'⟩ rw [sInf_def (⟨_, H⟩ : s.Nonempty), find_eq_iff] exact ⟨H, fun n hnk hns ↦ H' <| hs n k (Nat.lt_succ_iff.mp hnk) hns⟩ /-- This instance is necessary, otherwise the lattice operations would be derived via `ConditionallyCompleteLinearOrderBot` and marked as noncomputable. -/ instance : Lattice β„• := LinearOrder.toLattice noncomputable instance : ConditionallyCompleteLinearOrderBot β„• := { (inferInstance : OrderBot β„•), (LinearOrder.toLattice : Lattice β„•), (inferInstance : LinearOrder β„•) with -- sup := sSup -- Porting note: removed, unnecessary? -- inf := sInf -- Porting note: removed, unnecessary? le_csSup := fun s a hb ha ↦ by rw [sSup_def hb]; revert a ha; exact @Nat.find_spec _ _ hb csSup_le := fun s a _ ha ↦ by rw [sSup_def ⟨a, ha⟩]; exact Nat.find_min' _ ha le_csInf := fun s a hs hb ↦ by rw [sInf_def hs]; exact hb (@Nat.find_spec (fun n ↦ n ∈ s) _ _) csInf_le := fun s a _ ha ↦ by rw [sInf_def ⟨a, ha⟩]; exact Nat.find_min' _ ha csSup_empty := by simp only [sSup_def, Set.mem_empty_iff_false, forall_const, forall_prop_of_false, not_false_iff, exists_const] apply bot_unique (Nat.find_min' _ _) trivial csSup_of_not_bddAbove := by intro s hs simp only [mem_univ, forall_true_left, sSup, mem_empty_iff_false, IsEmpty.forall_iff, forall_const, exists_const, dite_true] rw [dif_neg] Β· exact le_antisymm (zero_le _) (find_le trivial) Β· exact hs csInf_of_not_bddBelow := fun s hs ↦ by simp at hs } theorem sSup_mem {s : Set β„•} (h₁ : s.Nonempty) (hβ‚‚ : BddAbove s) : sSup s ∈ s := let ⟨k, hk⟩ := hβ‚‚ h₁.csSup_mem ((finite_le_nat k).subset hk) theorem sInf_add {n : β„•} {p : β„• β†’ Prop} (hn : n ≀ sInf { m | p m }) : sInf { m | p (m + n) } + n = sInf { m | p m } := by obtain h | ⟨m, hm⟩ := { m | p (m + n) }.eq_empty_or_nonempty Β· rw [h, Nat.sInf_empty, zero_add] obtain hnp | hnp := hn.eq_or_lt Β· exact hnp suffices hp : p (sInf { m | p m } - n + n) from (h.subset hp).elim rw [Nat.sub_add_cancel hn] exact csInf_mem (nonempty_of_pos_sInf <| n.zero_le.trans_lt hnp) Β· have hp : βˆƒ n, n ∈ { m | p m } := ⟨_, hm⟩ rw [Nat.sInf_def ⟨m, hm⟩, Nat.sInf_def hp] rw [Nat.sInf_def hp] at hn exact find_add hn theorem sInf_add' {n : β„•} {p : β„• β†’ Prop} (h : 0 < sInf { m | p m }) : sInf { m | p m } + n = sInf { m | p (m - n) } := by suffices h₁ : n ≀ sInf {m | p (m - n)} by convert sInf_add h₁ simp_rw [Nat.add_sub_cancel_right] obtain ⟨m, hm⟩ := nonempty_of_pos_sInf h refine le_csInf ⟨m + n, ?_⟩ fun b hb ↦ le_of_not_lt fun hbn ↦ ne_of_mem_of_not_mem ?_ (not_mem_of_lt_sInf h) (Nat.sub_eq_zero_of_le hbn.le) Β· dsimp rwa [Nat.add_sub_cancel_right] Β· exact hb section variable {Ξ± : Type*} [CompleteLattice Ξ±] theorem iSup_lt_succ (u : β„• β†’ Ξ±) (n : β„•) : ⨆ k < n + 1, u k = (⨆ k < n, u k) βŠ” u n := by simp [Nat.lt_succ_iff_lt_or_eq, iSup_or, iSup_sup_eq] theorem iSup_lt_succ' (u : β„• β†’ Ξ±) (n : β„•) : ⨆ k < n + 1, u k = u 0 βŠ” ⨆ k < n, u (k + 1) := by rw [← sup_iSup_nat_succ] simp theorem iInf_lt_succ (u : β„• β†’ Ξ±) (n : β„•) : β¨… k < n + 1, u k = (β¨… k < n, u k) βŠ“ u n := @iSup_lt_succ Ξ±α΅’α΅ˆ _ _ _ theorem iInf_lt_succ' (u : β„• β†’ Ξ±) (n : β„•) : β¨… k < n + 1, u k = u 0 βŠ“ β¨… k < n, u (k + 1) := @iSup_lt_succ' Ξ±α΅’α΅ˆ _ _ _ theorem iSup_le_succ (u : β„• β†’ Ξ±) (n : β„•) : ⨆ k ≀ n + 1, u k = (⨆ k ≀ n, u k) βŠ” u (n + 1) := by simp_rw [← Nat.lt_succ_iff, iSup_lt_succ] theorem iSup_le_succ' (u : β„• β†’ Ξ±) (n : β„•) : ⨆ k ≀ n + 1, u k = u 0 βŠ” ⨆ k ≀ n, u (k + 1) := by simp_rw [← Nat.lt_succ_iff, iSup_lt_succ'] theorem iInf_le_succ (u : β„• β†’ Ξ±) (n : β„•) : β¨… k ≀ n + 1, u k = (β¨… k ≀ n, u k) βŠ“ u (n + 1) := @iSup_le_succ Ξ±α΅’α΅ˆ _ _ _ theorem iInf_le_succ' (u : β„• β†’ Ξ±) (n : β„•) : β¨… k ≀ n + 1, u k = u 0 βŠ“ β¨… k ≀ n, u (k + 1) := @iSup_le_succ' Ξ±α΅’α΅ˆ _ _ _ end end Nat namespace Set variable {Ξ± : Type*} theorem biUnion_lt_succ (u : β„• β†’ Set Ξ±) (n : β„•) : ⋃ k < n + 1, u k = (⋃ k < n, u k) βˆͺ u n := Nat.iSup_lt_succ u n theorem biUnion_lt_succ' (u : β„• β†’ Set Ξ±) (n : β„•) : ⋃ k < n + 1, u k = u 0 βˆͺ ⋃ k < n, u (k + 1) := Nat.iSup_lt_succ' u n theorem biInter_lt_succ (u : β„• β†’ Set Ξ±) (n : β„•) : β‹‚ k < n + 1, u k = (β‹‚ k < n, u k) ∩ u n := Nat.iInf_lt_succ u n theorem biInter_lt_succ' (u : β„• β†’ Set Ξ±) (n : β„•) : β‹‚ k < n + 1, u k = u 0 ∩ β‹‚ k < n, u (k + 1) := Nat.iInf_lt_succ' u n theorem biUnion_le_succ (u : β„• β†’ Set Ξ±) (n : β„•) : ⋃ k ≀ n + 1, u k = (⋃ k ≀ n, u k) βˆͺ u (n + 1) := Nat.iSup_le_succ u n theorem biUnion_le_succ' (u : β„• β†’ Set Ξ±) (n : β„•) : ⋃ k ≀ n + 1, u k = u 0 βˆͺ ⋃ k ≀ n, u (k + 1) := Nat.iSup_le_succ' u n theorem biInter_le_succ (u : β„• β†’ Set Ξ±) (n : β„•) : β‹‚ k ≀ n + 1, u k = (β‹‚ k ≀ n, u k) ∩ u (n + 1) := Nat.iInf_le_succ u n theorem biInter_le_succ' (u : β„• β†’ Set Ξ±) (n : β„•) : β‹‚ k ≀ n + 1, u k = u 0 ∩ β‹‚ k ≀ n, u (k + 1) := Nat.iInf_le_succ' u n end Set
Data\Nat\Log.lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, YaΓ«l Dillies -/ import Mathlib.Data.Nat.Defs import Mathlib.Init.Data.Nat.Lemmas import Mathlib.Order.Interval.Set.Basic import Mathlib.Tactic.Bound.Attribute import Mathlib.Tactic.Monotonicity.Attr /-! # Natural number logarithms This file defines two `β„•`-valued analogs of the logarithm of `n` with base `b`: * `log b n`: Lower logarithm, or floor **log**. Greatest `k` such that `b^k ≀ n`. * `clog b n`: Upper logarithm, or **c**eil **log**. Least `k` such that `n ≀ b^k`. These are interesting because, for `1 < b`, `Nat.log b` and `Nat.clog b` are respectively right and left adjoints of `Nat.pow b`. See `pow_le_iff_le_log` and `le_pow_iff_clog_le`. -/ namespace Nat /-! ### Floor logarithm -/ /-- `log b n`, is the logarithm of natural number `n` in base `b`. It returns the largest `k : β„•` such that `b^k ≀ n`, so if `b^k = n`, it returns exactly `k`. -/ @[pp_nodot] def log (b : β„•) : β„• β†’ β„• | n => if h : b ≀ n ∧ 1 < b then log b (n / b) + 1 else 0 decreasing_by -- putting this in the def triggers the `unusedHavesSuffices` linter: -- https://github.com/leanprover-community/batteries/issues/428 have : n / b < n := div_lt_self ((Nat.zero_lt_one.trans h.2).trans_le h.1) h.2 decreasing_trivial @[simp] theorem log_eq_zero_iff {b n : β„•} : log b n = 0 ↔ n < b ∨ b ≀ 1 := by rw [log, dite_eq_right_iff] simp only [Nat.add_eq_zero_iff, Nat.one_ne_zero, and_false, imp_false, not_and_or, not_le, not_lt] theorem log_of_lt {b n : β„•} (hb : n < b) : log b n = 0 := log_eq_zero_iff.2 (Or.inl hb) theorem log_of_left_le_one {b : β„•} (hb : b ≀ 1) (n) : log b n = 0 := log_eq_zero_iff.2 (Or.inr hb) @[simp] theorem log_pos_iff {b n : β„•} : 0 < log b n ↔ b ≀ n ∧ 1 < b := by rw [Nat.pos_iff_ne_zero, Ne, log_eq_zero_iff, not_or, not_lt, not_le] @[bound] theorem log_pos {b n : β„•} (hb : 1 < b) (hbn : b ≀ n) : 0 < log b n := log_pos_iff.2 ⟨hbn, hb⟩ theorem log_of_one_lt_of_le {b n : β„•} (h : 1 < b) (hn : b ≀ n) : log b n = log b (n / b) + 1 := by rw [log] exact if_pos ⟨hn, h⟩ @[simp] lemma log_zero_left : βˆ€ n, log 0 n = 0 := log_of_left_le_one $ Nat.zero_le _ @[simp] theorem log_zero_right (b : β„•) : log b 0 = 0 := log_eq_zero_iff.2 (le_total 1 b) @[simp] theorem log_one_left : βˆ€ n, log 1 n = 0 := log_of_left_le_one le_rfl @[simp] theorem log_one_right (b : β„•) : log b 1 = 0 := log_eq_zero_iff.2 (lt_or_le _ _) /-- `pow b` and `log b` (almost) form a Galois connection. See also `Nat.pow_le_of_le_log` and `Nat.le_log_of_pow_le` for individual implications under weaker assumptions. -/ theorem pow_le_iff_le_log {b : β„•} (hb : 1 < b) {x y : β„•} (hy : y β‰  0) : b ^ x ≀ y ↔ x ≀ log b y := by induction' y using Nat.strong_induction_on with y ih generalizing x cases x with | zero => dsimp; omega | succ x => rw [log]; split_ifs with h Β· have b_pos : 0 < b := lt_of_succ_lt hb rw [Nat.add_le_add_iff_right, ← ih (y / b) (div_lt_self (Nat.pos_iff_ne_zero.2 hy) hb) (Nat.div_pos h.1 b_pos).ne', le_div_iff_mul_le b_pos, pow_succ', Nat.mul_comm] Β· exact iff_of_false (fun hby => h ⟨(le_self_pow x.succ_ne_zero _).trans hby, hb⟩) (not_succ_le_zero _) theorem lt_pow_iff_log_lt {b : β„•} (hb : 1 < b) {x y : β„•} (hy : y β‰  0) : y < b ^ x ↔ log b y < x := lt_iff_lt_of_le_iff_le (pow_le_iff_le_log hb hy) theorem pow_le_of_le_log {b x y : β„•} (hy : y β‰  0) (h : x ≀ log b y) : b ^ x ≀ y := by refine (le_or_lt b 1).elim (fun hb => ?_) fun hb => (pow_le_iff_le_log hb hy).2 h rw [log_of_left_le_one hb, Nat.le_zero] at h rwa [h, Nat.pow_zero, one_le_iff_ne_zero] theorem le_log_of_pow_le {b x y : β„•} (hb : 1 < b) (h : b ^ x ≀ y) : x ≀ log b y := by rcases ne_or_eq y 0 with (hy | rfl) exacts [(pow_le_iff_le_log hb hy).1 h, (h.not_lt (Nat.pow_pos (Nat.zero_lt_one.trans hb))).elim] theorem pow_log_le_self (b : β„•) {x : β„•} (hx : x β‰  0) : b ^ log b x ≀ x := pow_le_of_le_log hx le_rfl theorem log_lt_of_lt_pow {b x y : β„•} (hy : y β‰  0) : y < b ^ x β†’ log b y < x := lt_imp_lt_of_le_imp_le (pow_le_of_le_log hy) theorem lt_pow_of_log_lt {b x y : β„•} (hb : 1 < b) : log b y < x β†’ y < b ^ x := lt_imp_lt_of_le_imp_le (le_log_of_pow_le hb) theorem lt_pow_succ_log_self {b : β„•} (hb : 1 < b) (x : β„•) : x < b ^ (log b x).succ := lt_pow_of_log_lt hb (lt_succ_self _) theorem log_eq_iff {b m n : β„•} (h : m β‰  0 ∨ 1 < b ∧ n β‰  0) : log b n = m ↔ b ^ m ≀ n ∧ n < b ^ (m + 1) := by rcases em (1 < b ∧ n β‰  0) with (⟨hb, hn⟩ | hbn) Β· rw [le_antisymm_iff, ← Nat.lt_succ_iff, ← pow_le_iff_le_log, ← lt_pow_iff_log_lt, and_comm] <;> assumption have hm : m β‰  0 := h.resolve_right hbn rw [not_and_or, not_lt, Ne, not_not] at hbn rcases hbn with (hb | rfl) Β· obtain rfl | rfl := le_one_iff_eq_zero_or_eq_one.1 hb any_goals simp only [ne_eq, zero_eq, reduceSucc, lt_self_iff_false, not_lt_zero, false_and, or_false] at h simp [h, eq_comm (a := 0), Nat.zero_pow (Nat.pos_iff_ne_zero.2 _)] <;> omega Β· simp [@eq_comm _ 0, hm] theorem log_eq_of_pow_le_of_lt_pow {b m n : β„•} (h₁ : b ^ m ≀ n) (hβ‚‚ : n < b ^ (m + 1)) : log b n = m := by rcases eq_or_ne m 0 with (rfl | hm) Β· rw [Nat.pow_one] at hβ‚‚ exact log_of_lt hβ‚‚ Β· exact (log_eq_iff (Or.inl hm)).2 ⟨h₁, hβ‚‚βŸ© theorem log_pow {b : β„•} (hb : 1 < b) (x : β„•) : log b (b ^ x) = x := log_eq_of_pow_le_of_lt_pow le_rfl (Nat.pow_lt_pow_right hb x.lt_succ_self) theorem log_eq_one_iff' {b n : β„•} : log b n = 1 ↔ b ≀ n ∧ n < b * b := by rw [log_eq_iff (Or.inl Nat.one_ne_zero), Nat.pow_add, Nat.pow_one] theorem log_eq_one_iff {b n : β„•} : log b n = 1 ↔ n < b * b ∧ 1 < b ∧ b ≀ n := log_eq_one_iff'.trans ⟨fun h => ⟨h.2, lt_mul_self_iff.1 (h.1.trans_lt h.2), h.1⟩, fun h => ⟨h.2.2, h.1⟩⟩ theorem log_mul_base {b n : β„•} (hb : 1 < b) (hn : n β‰  0) : log b (n * b) = log b n + 1 := by apply log_eq_of_pow_le_of_lt_pow <;> rw [pow_succ', Nat.mul_comm b] exacts [Nat.mul_le_mul_right _ (pow_log_le_self _ hn), (Nat.mul_lt_mul_right (Nat.zero_lt_one.trans hb)).2 (lt_pow_succ_log_self hb _)] theorem pow_log_le_add_one (b : β„•) : βˆ€ x, b ^ log b x ≀ x + 1 | 0 => by rw [log_zero_right, Nat.pow_zero] | x + 1 => (pow_log_le_self b x.succ_ne_zero).trans (x + 1).le_succ theorem log_monotone {b : β„•} : Monotone (log b) := by refine monotone_nat_of_le_succ fun n => ?_ rcases le_or_lt b 1 with hb | hb Β· rw [log_of_left_le_one hb] exact zero_le _ Β· exact le_log_of_pow_le hb (pow_log_le_add_one _ _) @[mono] theorem log_mono_right {b n m : β„•} (h : n ≀ m) : log b n ≀ log b m := log_monotone h @[mono] theorem log_anti_left {b c n : β„•} (hc : 1 < c) (hb : c ≀ b) : log b n ≀ log c n := by rcases eq_or_ne n 0 with (rfl | hn); Β· rw [log_zero_right, log_zero_right] apply le_log_of_pow_le hc calc c ^ log b n ≀ b ^ log b n := Nat.pow_le_pow_left hb _ _ ≀ n := pow_log_le_self _ hn theorem log_antitone_left {n : β„•} : AntitoneOn (fun b => log b n) (Set.Ioi 1) := fun _ hc _ _ hb => log_anti_left (Set.mem_Iio.1 hc) hb @[simp] theorem log_div_base (b n : β„•) : log b (n / b) = log b n - 1 := by rcases le_or_lt b 1 with hb | hb Β· rw [log_of_left_le_one hb, log_of_left_le_one hb, Nat.zero_sub] cases' lt_or_le n b with h h Β· rw [div_eq_of_lt h, log_of_lt h, log_zero_right] rw [log_of_one_lt_of_le hb h, Nat.add_sub_cancel_right] @[simp] theorem log_div_mul_self (b n : β„•) : log b (n / b * b) = log b n := by rcases le_or_lt b 1 with hb | hb Β· rw [log_of_left_le_one hb, log_of_left_le_one hb] cases' lt_or_le n b with h h Β· rw [div_eq_of_lt h, Nat.zero_mul, log_zero_right, log_of_lt h] rw [log_mul_base hb (Nat.div_pos h (by omega)).ne', log_div_base, Nat.sub_add_cancel (succ_le_iff.2 <| log_pos hb h)] theorem add_pred_div_lt {b n : β„•} (hb : 1 < b) (hn : 2 ≀ n) : (n + b - 1) / b < n := by rw [div_lt_iff_lt_mul (by omega), ← succ_le_iff, ← pred_eq_sub_one, succ_pred_eq_of_pos (by omega)] exact Nat.add_le_mul hn hb /-! ### Ceil logarithm -/ /-- `clog b n`, is the upper logarithm of natural number `n` in base `b`. It returns the smallest `k : β„•` such that `n ≀ b^k`, so if `b^k = n`, it returns exactly `k`. -/ @[pp_nodot] def clog (b : β„•) : β„• β†’ β„• | n => if h : 1 < b ∧ 1 < n then clog b ((n + b - 1) / b) + 1 else 0 decreasing_by -- putting this in the def triggers the `unusedHavesSuffices` linter: -- https://github.com/leanprover-community/batteries/issues/428 have : (n + b - 1) / b < n := add_pred_div_lt h.1 h.2 decreasing_trivial theorem clog_of_left_le_one {b : β„•} (hb : b ≀ 1) (n : β„•) : clog b n = 0 := by rw [clog, dif_neg fun h : 1 < b ∧ 1 < n => h.1.not_le hb] theorem clog_of_right_le_one {n : β„•} (hn : n ≀ 1) (b : β„•) : clog b n = 0 := by rw [clog, dif_neg fun h : 1 < b ∧ 1 < n => h.2.not_le hn] @[simp] lemma clog_zero_left (n : β„•) : clog 0 n = 0 := clog_of_left_le_one (Nat.zero_le _) _ @[simp] lemma clog_zero_right (b : β„•) : clog b 0 = 0 := clog_of_right_le_one (Nat.zero_le _) _ @[simp] theorem clog_one_left (n : β„•) : clog 1 n = 0 := clog_of_left_le_one le_rfl _ @[simp] theorem clog_one_right (b : β„•) : clog b 1 = 0 := clog_of_right_le_one le_rfl _ theorem clog_of_two_le {b n : β„•} (hb : 1 < b) (hn : 2 ≀ n) : clog b n = clog b ((n + b - 1) / b) + 1 := by rw [clog, dif_pos (⟨hb, hn⟩ : 1 < b ∧ 1 < n)] theorem clog_pos {b n : β„•} (hb : 1 < b) (hn : 2 ≀ n) : 0 < clog b n := by rw [clog_of_two_le hb hn] exact zero_lt_succ _ theorem clog_eq_one {b n : β„•} (hn : 2 ≀ n) (h : n ≀ b) : clog b n = 1 := by rw [clog_of_two_le (hn.trans h) hn, clog_of_right_le_one] rw [← Nat.lt_succ_iff, Nat.div_lt_iff_lt_mul] <;> omega /-- `clog b` and `pow b` form a Galois connection. -/ theorem le_pow_iff_clog_le {b : β„•} (hb : 1 < b) {x y : β„•} : x ≀ b ^ y ↔ clog b x ≀ y := by induction' x using Nat.strong_induction_on with x ih generalizing y cases y Β· rw [Nat.pow_zero] refine ⟨fun h => (clog_of_right_le_one h b).le, ?_⟩ simp_rw [← not_lt] contrapose! exact clog_pos hb have b_pos : 0 < b := zero_lt_of_lt hb rw [clog]; split_ifs with h Β· rw [Nat.add_le_add_iff_right, ← ih ((x + b - 1) / b) (add_pred_div_lt hb h.2), Nat.div_le_iff_le_mul_add_pred b_pos, Nat.mul_comm b, ← Nat.pow_succ, Nat.add_sub_assoc (Nat.succ_le_of_lt b_pos), Nat.add_le_add_iff_right] Β· exact iff_of_true ((not_lt.1 (not_and.1 h hb)).trans <| succ_le_of_lt <| Nat.pow_pos b_pos) (zero_le _) theorem pow_lt_iff_lt_clog {b : β„•} (hb : 1 < b) {x y : β„•} : b ^ y < x ↔ y < clog b x := lt_iff_lt_of_le_iff_le (le_pow_iff_clog_le hb) theorem clog_pow (b x : β„•) (hb : 1 < b) : clog b (b ^ x) = x := eq_of_forall_ge_iff fun z ↦ by rw [← le_pow_iff_clog_le hb, Nat.pow_le_pow_iff_right hb] theorem pow_pred_clog_lt_self {b : β„•} (hb : 1 < b) {x : β„•} (hx : 1 < x) : b ^ (clog b x).pred < x := by rw [← not_le, le_pow_iff_clog_le hb, not_le] exact pred_lt (clog_pos hb hx).ne' theorem le_pow_clog {b : β„•} (hb : 1 < b) (x : β„•) : x ≀ b ^ clog b x := (le_pow_iff_clog_le hb).2 le_rfl @[mono] theorem clog_mono_right (b : β„•) {n m : β„•} (h : n ≀ m) : clog b n ≀ clog b m := by rcases le_or_lt b 1 with hb | hb Β· rw [clog_of_left_le_one hb] exact zero_le _ Β· rw [← le_pow_iff_clog_le hb] exact h.trans (le_pow_clog hb _) @[mono] theorem clog_anti_left {b c n : β„•} (hc : 1 < c) (hb : c ≀ b) : clog b n ≀ clog c n := by rw [← le_pow_iff_clog_le (lt_of_lt_of_le hc hb)] calc n ≀ c ^ clog c n := le_pow_clog hc _ _ ≀ b ^ clog c n := Nat.pow_le_pow_left hb _ theorem clog_monotone (b : β„•) : Monotone (clog b) := fun _ _ => clog_mono_right _ theorem clog_antitone_left {n : β„•} : AntitoneOn (fun b : β„• => clog b n) (Set.Ioi 1) := fun _ hc _ _ hb => clog_anti_left (Set.mem_Iio.1 hc) hb theorem log_le_clog (b n : β„•) : log b n ≀ clog b n := by obtain hb | hb := le_or_lt b 1 Β· rw [log_of_left_le_one hb] exact zero_le _ cases n with | zero => rw [log_zero_right] exact zero_le _ | succ n => exact (Nat.pow_le_pow_iff_right hb).1 ((pow_log_le_self b n.succ_ne_zero).trans <| le_pow_clog hb _) end Nat
Data\Nat\MaxPowDiv.lean
/- Copyright (c) 2023 Matthew Robert Ballard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Matthew Robert Ballard -/ import Mathlib.Algebra.Divisibility.Units import Mathlib.Algebra.Order.Ring.Nat import Mathlib.Tactic.Common /-! # The maximal power of one natural number dividing another Here we introduce `p.maxPowDiv n` which returns the maximal `k : β„•` for which `p ^ k ∣ n` with the convention that `maxPowDiv 1 n = 0` for all `n`. We prove enough about `maxPowDiv` in this file to show equality with `Nat.padicValNat` in `padicValNat.padicValNat_eq_maxPowDiv`. The implementation of `maxPowDiv` improves on the speed of `padicValNat`. -/ namespace Nat open Nat /-- Tail recursive function which returns the largest `k : β„•` such that `p ^ k ∣ n` for any `p : β„•`. `padicValNat_eq_maxPowDiv` allows the code generator to use this definition for `padicValNat` -/ def maxPowDiv (p n : β„•) : β„• := go 0 p n where go (k p n : β„•) : β„• := if 1 < p ∧ 0 < n ∧ n % p = 0 then go (k+1) p (n / p) else k termination_by n decreasing_by apply Nat.div_lt_self <;> tauto attribute [inherit_doc maxPowDiv] maxPowDiv.go end Nat namespace Nat.maxPowDiv theorem go_succ {k p n : β„•} : go (k+1) p n = go k p n + 1 := by induction k, p, n using go.induct case case1 h ih => unfold go simp only [if_pos h] exact ih case case2 h => unfold go simp only [if_neg h] @[simp] theorem zero_base {n : β„•} : maxPowDiv 0 n = 0 := by dsimp [maxPowDiv] rw [maxPowDiv.go] simp @[simp] theorem zero {p : β„•} : maxPowDiv p 0 = 0 := by dsimp [maxPowDiv] rw [maxPowDiv.go] simp theorem base_mul_eq_succ {p n : β„•} (hp : 1 < p) (hn : 0 < n) : p.maxPowDiv (p*n) = p.maxPowDiv n + 1 := by have : 0 < p := lt_trans (b := 1) (by simp) hp dsimp [maxPowDiv] rw [maxPowDiv.go, if_pos, mul_div_right _ this] Β· apply go_succ Β· refine ⟨hp, ?_, by simp⟩ apply Nat.mul_pos this hn theorem base_pow_mul {p n exp : β„•} (hp : 1 < p) (hn : 0 < n) : p.maxPowDiv (p ^ exp * n) = p.maxPowDiv n + exp := by match exp with | 0 => simp | e + 1 => rw [Nat.pow_succ, mul_assoc, mul_comm, mul_assoc, base_mul_eq_succ hp, mul_comm, base_pow_mul hp hn] Β· ac_rfl Β· apply Nat.mul_pos hn <| pow_pos (pos_of_gt hp) e theorem pow_dvd (p n : β„•) : p ^ (p.maxPowDiv n) ∣ n := by dsimp [maxPowDiv] rw [go] by_cases h : (1 < p ∧ 0 < n ∧ n % p = 0) Β· have : n / p < n := by apply Nat.div_lt_self <;> aesop rw [if_pos h] have ⟨c,hc⟩ := pow_dvd p (n / p) rw [go_succ, pow_succ] nth_rw 2 [← mod_add_div' n p] rw [h.right.right, zero_add] exact ⟨c,by nth_rw 1 [hc]; ac_rfl⟩ Β· rw [if_neg h] simp theorem le_of_dvd {p n pow : β„•} (hp : 1 < p) (hn : 0 < n) (h : p ^ pow ∣ n) : pow ≀ p.maxPowDiv n := by have ⟨c, hc⟩ := h have : 0 < c := by apply Nat.pos_of_ne_zero intro h' rw [h',mul_zero] at hc exact not_eq_zero_of_lt hn hc simp [hc, base_pow_mul hp this] end maxPowDiv end Nat
Data\Nat\ModEq.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Algebra.Ring.Regular import Mathlib.Data.Int.GCD import Mathlib.Data.Int.Order.Lemmas import Mathlib.Tactic.NormNum.Basic /-! # Congruences modulo a natural number This file defines the equivalence relation `a ≑ b [MOD n]` on the natural numbers, and proves basic properties about it such as the Chinese Remainder Theorem `modEq_and_modEq_iff_modEq_mul`. ## Notations `a ≑ b [MOD n]` is notation for `nat.ModEq n a b`, which is defined to mean `a % n = b % n`. ## Tags ModEq, congruence, mod, MOD, modulo -/ assert_not_exists Function.support namespace Nat /-- Modular equality. `n.ModEq a b`, or `a ≑ b [MOD n]`, means that `a - b` is a multiple of `n`. -/ def ModEq (n a b : β„•) := a % n = b % n @[inherit_doc] notation:50 a " ≑ " b " [MOD " n "]" => ModEq n a b variable {m n a b c d : β„•} -- Porting note: This instance should be derivable automatically instance : Decidable (ModEq n a b) := decEq (a % n) (b % n) namespace ModEq @[refl] protected theorem refl (a : β„•) : a ≑ a [MOD n] := rfl protected theorem rfl : a ≑ a [MOD n] := ModEq.refl _ instance : IsRefl _ (ModEq n) := ⟨ModEq.refl⟩ @[symm] protected theorem symm : a ≑ b [MOD n] β†’ b ≑ a [MOD n] := Eq.symm @[trans] protected theorem trans : a ≑ b [MOD n] β†’ b ≑ c [MOD n] β†’ a ≑ c [MOD n] := Eq.trans instance : Trans (ModEq n) (ModEq n) (ModEq n) where trans := Nat.ModEq.trans protected theorem comm : a ≑ b [MOD n] ↔ b ≑ a [MOD n] := ⟨ModEq.symm, ModEq.symm⟩ end ModEq theorem modEq_zero_iff_dvd : a ≑ 0 [MOD n] ↔ n ∣ a := by rw [ModEq, zero_mod, dvd_iff_mod_eq_zero] theorem _root_.Dvd.dvd.modEq_zero_nat (h : n ∣ a) : a ≑ 0 [MOD n] := modEq_zero_iff_dvd.2 h theorem _root_.Dvd.dvd.zero_modEq_nat (h : n ∣ a) : 0 ≑ a [MOD n] := h.modEq_zero_nat.symm theorem modEq_iff_dvd : a ≑ b [MOD n] ↔ (n : β„€) ∣ b - a := by rw [ModEq, eq_comm, ← Int.natCast_inj, Int.natCast_mod, Int.natCast_mod, Int.emod_eq_emod_iff_emod_sub_eq_zero, Int.dvd_iff_emod_eq_zero] alias ⟨ModEq.dvd, modEq_of_dvd⟩ := modEq_iff_dvd /-- A variant of `modEq_iff_dvd` with `Nat` divisibility -/ theorem modEq_iff_dvd' (h : a ≀ b) : a ≑ b [MOD n] ↔ n ∣ b - a := by rw [modEq_iff_dvd, ← Int.natCast_dvd_natCast, Int.ofNat_sub h] theorem mod_modEq (a n) : a % n ≑ a [MOD n] := mod_mod _ _ namespace ModEq lemma of_dvd (d : m ∣ n) (h : a ≑ b [MOD n]) : a ≑ b [MOD m] := modEq_of_dvd <| d.natCast.trans h.dvd protected theorem mul_left' (c : β„•) (h : a ≑ b [MOD n]) : c * a ≑ c * b [MOD c * n] := by unfold ModEq at *; rw [mul_mod_mul_left, mul_mod_mul_left, h] @[gcongr] protected theorem mul_left (c : β„•) (h : a ≑ b [MOD n]) : c * a ≑ c * b [MOD n] := (h.mul_left' _).of_dvd (dvd_mul_left _ _) protected theorem mul_right' (c : β„•) (h : a ≑ b [MOD n]) : a * c ≑ b * c [MOD n * c] := by rw [mul_comm a, mul_comm b, mul_comm n]; exact h.mul_left' c @[gcongr] protected theorem mul_right (c : β„•) (h : a ≑ b [MOD n]) : a * c ≑ b * c [MOD n] := by rw [mul_comm a, mul_comm b]; exact h.mul_left c @[gcongr] protected theorem mul (h₁ : a ≑ b [MOD n]) (hβ‚‚ : c ≑ d [MOD n]) : a * c ≑ b * d [MOD n] := (hβ‚‚.mul_left _).trans (h₁.mul_right _) @[gcongr] protected theorem pow (m : β„•) (h : a ≑ b [MOD n]) : a ^ m ≑ b ^ m [MOD n] := by induction m with | zero => rfl | succ d hd => rw [Nat.pow_succ, Nat.pow_succ] exact hd.mul h @[gcongr] protected theorem add (h₁ : a ≑ b [MOD n]) (hβ‚‚ : c ≑ d [MOD n]) : a + c ≑ b + d [MOD n] := by rw [modEq_iff_dvd, Int.ofNat_add, Int.ofNat_add, add_sub_add_comm] exact dvd_add h₁.dvd hβ‚‚.dvd @[gcongr] protected theorem add_left (c : β„•) (h : a ≑ b [MOD n]) : c + a ≑ c + b [MOD n] := ModEq.rfl.add h @[gcongr] protected theorem add_right (c : β„•) (h : a ≑ b [MOD n]) : a + c ≑ b + c [MOD n] := h.add ModEq.rfl protected theorem add_left_cancel (h₁ : a ≑ b [MOD n]) (hβ‚‚ : a + c ≑ b + d [MOD n]) : c ≑ d [MOD n] := by simp only [modEq_iff_dvd, Int.ofNat_add] at * rw [add_sub_add_comm] at hβ‚‚ convert _root_.dvd_sub hβ‚‚ h₁ using 1 rw [add_sub_cancel_left] protected theorem add_left_cancel' (c : β„•) (h : c + a ≑ c + b [MOD n]) : a ≑ b [MOD n] := ModEq.rfl.add_left_cancel h protected theorem add_right_cancel (h₁ : c ≑ d [MOD n]) (hβ‚‚ : a + c ≑ b + d [MOD n]) : a ≑ b [MOD n] := by rw [add_comm a, add_comm b] at hβ‚‚ exact h₁.add_left_cancel hβ‚‚ protected theorem add_right_cancel' (c : β„•) (h : a + c ≑ b + c [MOD n]) : a ≑ b [MOD n] := ModEq.rfl.add_right_cancel h /-- Cancel left multiplication on both sides of the `≑` and in the modulus. For cancelling left multiplication in the modulus, see `Nat.ModEq.of_mul_left`. -/ protected theorem mul_left_cancel' {a b c m : β„•} (hc : c β‰  0) : c * a ≑ c * b [MOD c * m] β†’ a ≑ b [MOD m] := by simp [modEq_iff_dvd, ← mul_sub, mul_dvd_mul_iff_left (by simp [hc] : (c : β„€) β‰  0)] protected theorem mul_left_cancel_iff' {a b c m : β„•} (hc : c β‰  0) : c * a ≑ c * b [MOD c * m] ↔ a ≑ b [MOD m] := ⟨ModEq.mul_left_cancel' hc, ModEq.mul_left' _⟩ /-- Cancel right multiplication on both sides of the `≑` and in the modulus. For cancelling right multiplication in the modulus, see `Nat.ModEq.of_mul_right`. -/ protected theorem mul_right_cancel' {a b c m : β„•} (hc : c β‰  0) : a * c ≑ b * c [MOD m * c] β†’ a ≑ b [MOD m] := by simp [modEq_iff_dvd, ← sub_mul, mul_dvd_mul_iff_right (by simp [hc] : (c : β„€) β‰  0)] protected theorem mul_right_cancel_iff' {a b c m : β„•} (hc : c β‰  0) : a * c ≑ b * c [MOD m * c] ↔ a ≑ b [MOD m] := ⟨ModEq.mul_right_cancel' hc, ModEq.mul_right' _⟩ /-- Cancel left multiplication in the modulus. For cancelling left multiplication on both sides of the `≑`, see `nat.modeq.mul_left_cancel'`. -/ lemma of_mul_left (m : β„•) (h : a ≑ b [MOD m * n]) : a ≑ b [MOD n] := by rw [modEq_iff_dvd] at * exact (dvd_mul_left (n : β„€) (m : β„€)).trans h /-- Cancel right multiplication in the modulus. For cancelling right multiplication on both sides of the `≑`, see `nat.modeq.mul_right_cancel'`. -/ lemma of_mul_right (m : β„•) : a ≑ b [MOD n * m] β†’ a ≑ b [MOD n] := mul_comm m n β–Έ of_mul_left _ theorem of_div (h : a / c ≑ b / c [MOD m / c]) (ha : c ∣ a) (ha : c ∣ b) (ha : c ∣ m) : a ≑ b [MOD m] := by convert h.mul_left' c <;> rwa [Nat.mul_div_cancel'] end ModEq lemma modEq_sub (h : b ≀ a) : a ≑ b [MOD a - b] := (modEq_of_dvd <| by rw [Int.ofNat_sub h]).symm lemma modEq_one : a ≑ b [MOD 1] := modEq_of_dvd <| one_dvd _ @[simp] lemma modEq_zero_iff : a ≑ b [MOD 0] ↔ a = b := by rw [ModEq, mod_zero, mod_zero] @[simp] lemma add_modEq_left : n + a ≑ a [MOD n] := by rw [ModEq, add_mod_left] @[simp] lemma add_modEq_right : a + n ≑ a [MOD n] := by rw [ModEq, add_mod_right] namespace ModEq theorem le_of_lt_add (h1 : a ≑ b [MOD m]) (h2 : a < b + m) : a ≀ b := (le_total a b).elim id fun h3 => Nat.le_of_sub_eq_zero (eq_zero_of_dvd_of_lt ((modEq_iff_dvd' h3).mp h1.symm) ((tsub_lt_iff_left h3).mpr h2)) theorem add_le_of_lt (h1 : a ≑ b [MOD m]) (h2 : a < b) : a + m ≀ b := le_of_lt_add (add_modEq_right.trans h1) (add_lt_add_right h2 m) theorem dvd_iff (h : a ≑ b [MOD m]) (hdm : d ∣ m) : d ∣ a ↔ d ∣ b := by simp only [← modEq_zero_iff_dvd] replace h := h.of_dvd hdm exact ⟨h.symm.trans, h.trans⟩ theorem gcd_eq (h : a ≑ b [MOD m]) : gcd a m = gcd b m := by have h1 := gcd_dvd_right a m have h2 := gcd_dvd_right b m exact dvd_antisymm (dvd_gcd ((h.dvd_iff h1).mp (gcd_dvd_left a m)) h1) (dvd_gcd ((h.dvd_iff h2).mpr (gcd_dvd_left b m)) h2) lemma eq_of_abs_lt (h : a ≑ b [MOD m]) (h2 : |(b : β„€) - a| < m) : a = b := by apply Int.ofNat.inj rw [eq_comm, ← sub_eq_zero] exact Int.eq_zero_of_abs_lt_dvd h.dvd h2 lemma eq_of_lt_of_lt (h : a ≑ b [MOD m]) (ha : a < m) (hb : b < m) : a = b := h.eq_of_abs_lt <| abs_sub_lt_iff.2 ⟨(sub_le_self _ <| Int.natCast_nonneg _).trans_lt <| Int.ofNat_lt.2 hb, (sub_le_self _ <| Int.natCast_nonneg _).trans_lt <| Int.ofNat_lt.2 ha⟩ /-- To cancel a common factor `c` from a `ModEq` we must divide the modulus `m` by `gcd m c` -/ lemma cancel_left_div_gcd (hm : 0 < m) (h : c * a ≑ c * b [MOD m]) : a ≑ b [MOD m / gcd m c] := by let d := gcd m c have hmd := gcd_dvd_left m c have hcd := gcd_dvd_right m c rw [modEq_iff_dvd] refine @Int.dvd_of_dvd_mul_right_of_gcd_one (m / d) (c / d) (b - a) ?_ ?_ Β· show (m / d : β„€) ∣ c / d * (b - a) rw [mul_comm, ← Int.mul_ediv_assoc (b - a) (Int.natCast_dvd_natCast.mpr hcd), mul_comm] apply Int.ediv_dvd_ediv (Int.natCast_dvd_natCast.mpr hmd) rw [mul_sub] exact modEq_iff_dvd.mp h Β· show Int.gcd (m / d) (c / d) = 1 simp only [← Int.natCast_div, Int.gcd_natCast_natCast (m / d) (c / d), gcd_div hmd hcd, Nat.div_self (gcd_pos_of_pos_left c hm)] /-- To cancel a common factor `c` from a `ModEq` we must divide the modulus `m` by `gcd m c` -/ lemma cancel_right_div_gcd (hm : 0 < m) (h : a * c ≑ b * c [MOD m]) : a ≑ b [MOD m / gcd m c] := by apply cancel_left_div_gcd hm simpa [mul_comm] using h lemma cancel_left_div_gcd' (hm : 0 < m) (hcd : c ≑ d [MOD m]) (h : c * a ≑ d * b [MOD m]) : a ≑ b [MOD m / gcd m c] := (h.trans <| hcd.symm.mul_right b).cancel_left_div_gcd hm lemma cancel_right_div_gcd' (hm : 0 < m) (hcd : c ≑ d [MOD m]) (h : a * c ≑ b * d [MOD m]) : a ≑ b [MOD m / gcd m c] := (h.trans <| hcd.symm.mul_left b).cancel_right_div_gcd hm /-- A common factor that's coprime with the modulus can be cancelled from a `ModEq` -/ lemma cancel_left_of_coprime (hmc : gcd m c = 1) (h : c * a ≑ c * b [MOD m]) : a ≑ b [MOD m] := by rcases m.eq_zero_or_pos with (rfl | hm) Β· simp only [gcd_zero_left] at hmc simp only [gcd_zero_left, hmc, one_mul, modEq_zero_iff] at h subst h rfl simpa [hmc] using h.cancel_left_div_gcd hm /-- A common factor that's coprime with the modulus can be cancelled from a `ModEq` -/ lemma cancel_right_of_coprime (hmc : gcd m c = 1) (h : a * c ≑ b * c [MOD m]) : a ≑ b [MOD m] := cancel_left_of_coprime hmc <| by simpa [mul_comm] using h end ModEq /-- The natural number less than `lcm n m` congruent to `a` mod `n` and `b` mod `m` -/ def chineseRemainder' (h : a ≑ b [MOD gcd n m]) : { k // k ≑ a [MOD n] ∧ k ≑ b [MOD m] } := if hn : n = 0 then ⟨a, by rw [hn, gcd_zero_left] at h; constructor Β· rfl Β· exact h⟩ else if hm : m = 0 then ⟨b, by rw [hm, gcd_zero_right] at h; constructor Β· exact h.symm Β· rfl⟩ else ⟨let (c, d) := xgcd n m; Int.toNat ((n * c * b + m * d * a) / gcd n m % lcm n m), by rw [xgcd_val] dsimp rw [modEq_iff_dvd, modEq_iff_dvd, Int.toNat_of_nonneg (Int.emod_nonneg _ (Int.natCast_ne_zero.2 (lcm_ne_zero hn hm)))] have hnonzero : (gcd n m : β„€) β‰  0 := by norm_cast rw [Nat.gcd_eq_zero_iff, not_and] exact fun _ => hm have hcoedvd : βˆ€ t, (gcd n m : β„€) ∣ t * (b - a) := fun t => h.dvd.mul_left _ have := gcd_eq_gcd_ab n m constructor <;> rw [Int.emod_def, ← sub_add] <;> refine dvd_add ?_ (dvd_mul_of_dvd_left ?_ _) <;> try norm_cast Β· rw [← sub_eq_iff_eq_add'] at this rw [← this, sub_mul, ← add_sub_assoc, add_comm, add_sub_assoc, ← mul_sub, Int.add_ediv_of_dvd_left, Int.mul_ediv_cancel_left _ hnonzero, Int.mul_ediv_assoc _ h.dvd, ← sub_sub, sub_self, zero_sub, dvd_neg, mul_assoc] Β· exact dvd_mul_right _ _ norm_cast exact dvd_mul_right _ _ Β· exact dvd_lcm_left n m Β· rw [← sub_eq_iff_eq_add] at this rw [← this, sub_mul, sub_add, ← mul_sub, Int.sub_ediv_of_dvd, Int.mul_ediv_cancel_left _ hnonzero, Int.mul_ediv_assoc _ h.dvd, ← sub_add, sub_self, zero_add, mul_assoc] Β· exact dvd_mul_right _ _ Β· exact hcoedvd _ Β· exact dvd_lcm_right n m⟩ /-- The natural number less than `n*m` congruent to `a` mod `n` and `b` mod `m` -/ def chineseRemainder (co : n.Coprime m) (a b : β„•) : { k // k ≑ a [MOD n] ∧ k ≑ b [MOD m] } := chineseRemainder' (by convert @modEq_one a b) theorem chineseRemainder'_lt_lcm (h : a ≑ b [MOD gcd n m]) (hn : n β‰  0) (hm : m β‰  0) : ↑(chineseRemainder' h) < lcm n m := by dsimp only [chineseRemainder'] rw [dif_neg hn, dif_neg hm, Subtype.coe_mk, xgcd_val, ← Int.toNat_natCast (lcm n m)] have lcm_pos := Int.natCast_pos.mpr (Nat.pos_of_ne_zero (lcm_ne_zero hn hm)) exact (Int.toNat_lt_toNat lcm_pos).mpr (Int.emod_lt_of_pos _ lcm_pos) theorem chineseRemainder_lt_mul (co : n.Coprime m) (a b : β„•) (hn : n β‰  0) (hm : m β‰  0) : ↑(chineseRemainder co a b) < n * m := lt_of_lt_of_le (chineseRemainder'_lt_lcm _ hn hm) (le_of_eq co.lcm_eq_mul) theorem mod_lcm (hn : a ≑ b [MOD n]) (hm : a ≑ b [MOD m]) : a ≑ b [MOD lcm n m] := Nat.modEq_iff_dvd.mpr <| Int.lcm_dvd (Nat.modEq_iff_dvd.mp hn) (Nat.modEq_iff_dvd.mp hm) theorem chineseRemainder_modEq_unique (co : n.Coprime m) {a b z} (hzan : z ≑ a [MOD n]) (hzbm : z ≑ b [MOD m]) : z ≑ chineseRemainder co a b [MOD n*m] := by simpa [Nat.Coprime.lcm_eq_mul co] using mod_lcm (hzan.trans ((chineseRemainder co a b).prop.1).symm) (hzbm.trans ((chineseRemainder co a b).prop.2).symm) theorem modEq_and_modEq_iff_modEq_mul {a b m n : β„•} (hmn : m.Coprime n) : a ≑ b [MOD m] ∧ a ≑ b [MOD n] ↔ a ≑ b [MOD m * n] := ⟨fun h => by rw [Nat.modEq_iff_dvd, Nat.modEq_iff_dvd, ← Int.dvd_natAbs, Int.natCast_dvd_natCast, ← Int.dvd_natAbs, Int.natCast_dvd_natCast] at h rw [Nat.modEq_iff_dvd, ← Int.dvd_natAbs, Int.natCast_dvd_natCast] exact hmn.mul_dvd_of_dvd_of_dvd h.1 h.2, fun h => ⟨h.of_mul_right _, h.of_mul_left _⟩⟩ theorem coprime_of_mul_modEq_one (b : β„•) {a n : β„•} (h : a * b ≑ 1 [MOD n]) : a.Coprime n := by obtain ⟨g, hh⟩ := Nat.gcd_dvd_right a n rw [Nat.coprime_iff_gcd_eq_one, ← Nat.dvd_one, ← Nat.modEq_zero_iff_dvd] calc 1 ≑ a * b [MOD a.gcd n] := (hh β–Έ h).symm.of_mul_right g _ ≑ 0 * b [MOD a.gcd n] := (Nat.modEq_zero_iff_dvd.mpr (Nat.gcd_dvd_left _ _)).mul_right b _ = 0 := by rw [zero_mul] theorem add_mod_add_ite (a b c : β„•) : ((a + b) % c + if c ≀ a % c + b % c then c else 0) = a % c + b % c := have : (a + b) % c = (a % c + b % c) % c := ((mod_modEq _ _).add <| mod_modEq _ _).symm if hc0 : c = 0 then by simp [hc0, Nat.mod_zero] else by rw [this] split_ifs with h Β· have h2 : (a % c + b % c) / c < 2 := Nat.div_lt_of_lt_mul (by rw [mul_two] exact add_lt_add (Nat.mod_lt _ (Nat.pos_of_ne_zero hc0)) (Nat.mod_lt _ (Nat.pos_of_ne_zero hc0))) have h0 : 0 < (a % c + b % c) / c := Nat.div_pos h (Nat.pos_of_ne_zero hc0) rw [← @add_right_cancel_iff _ _ _ (c * ((a % c + b % c) / c)), add_comm _ c, add_assoc, mod_add_div, le_antisymm (le_of_lt_succ h2) h0, mul_one, add_comm] Β· rw [Nat.mod_eq_of_lt (lt_of_not_ge h), add_zero] theorem add_mod_of_add_mod_lt {a b c : β„•} (hc : a % c + b % c < c) : (a + b) % c = a % c + b % c := by rw [← add_mod_add_ite, if_neg (not_le_of_lt hc), add_zero] theorem add_mod_add_of_le_add_mod {a b c : β„•} (hc : c ≀ a % c + b % c) : (a + b) % c + c = a % c + b % c := by rw [← add_mod_add_ite, if_pos hc] theorem add_div {a b c : β„•} (hc0 : 0 < c) : (a + b) / c = a / c + b / c + if c ≀ a % c + b % c then 1 else 0 := by rw [← mul_right_inj' hc0.ne', ← @add_left_cancel_iff _ _ _ ((a + b) % c + a % c + b % c)] suffices (a + b) % c + c * ((a + b) / c) + a % c + b % c = (a % c + c * (a / c) + (b % c + c * (b / c)) + c * if c ≀ a % c + b % c then 1 else 0) + (a + b) % c by simpa only [mul_add, add_comm, add_left_comm, add_assoc] rw [mod_add_div, mod_add_div, mod_add_div, mul_ite, add_assoc, add_assoc] conv_lhs => rw [← add_mod_add_ite] simp only [mul_one, mul_zero] ac_rfl theorem add_div_eq_of_add_mod_lt {a b c : β„•} (hc : a % c + b % c < c) : (a + b) / c = a / c + b / c := if hc0 : c = 0 then by simp [hc0] else by rw [add_div (Nat.pos_of_ne_zero hc0), if_neg (not_le_of_lt hc), add_zero] protected theorem add_div_of_dvd_right {a b c : β„•} (hca : c ∣ a) : (a + b) / c = a / c + b / c := if h : c = 0 then by simp [h] else add_div_eq_of_add_mod_lt (by rw [Nat.mod_eq_zero_of_dvd hca, zero_add] exact Nat.mod_lt _ (pos_iff_ne_zero.mpr h)) protected theorem add_div_of_dvd_left {a b c : β„•} (hca : c ∣ b) : (a + b) / c = a / c + b / c := by rwa [add_comm, Nat.add_div_of_dvd_right, add_comm] theorem add_div_eq_of_le_mod_add_mod {a b c : β„•} (hc : c ≀ a % c + b % c) (hc0 : 0 < c) : (a + b) / c = a / c + b / c + 1 := by rw [add_div hc0, if_pos hc] theorem add_div_le_add_div (a b c : β„•) : a / c + b / c ≀ (a + b) / c := if hc0 : c = 0 then by simp [hc0] else by rw [Nat.add_div (Nat.pos_of_ne_zero hc0)]; exact Nat.le_add_right _ _ theorem le_mod_add_mod_of_dvd_add_of_not_dvd {a b c : β„•} (h : c ∣ a + b) (ha : Β¬c ∣ a) : c ≀ a % c + b % c := by_contradiction fun hc => by have : (a + b) % c = a % c + b % c := add_mod_of_add_mod_lt (lt_of_not_ge hc) simp_all [dvd_iff_mod_eq_zero] theorem odd_mul_odd {n m : β„•} : n % 2 = 1 β†’ m % 2 = 1 β†’ n * m % 2 = 1 := by simpa [Nat.ModEq] using @ModEq.mul 2 n 1 m 1 theorem odd_mul_odd_div_two {m n : β„•} (hm1 : m % 2 = 1) (hn1 : n % 2 = 1) : m * n / 2 = m * (n / 2) + m / 2 := have hm0 : 0 < m := Nat.pos_of_ne_zero fun h => by simp_all have hn0 : 0 < n := Nat.pos_of_ne_zero fun h => by simp_all mul_right_injectiveβ‚€ two_ne_zero <| by dsimp rw [mul_add, two_mul_odd_div_two hm1, mul_left_comm, two_mul_odd_div_two hn1, two_mul_odd_div_two (Nat.odd_mul_odd hm1 hn1), mul_tsub, mul_one, ← add_tsub_assoc_of_le (succ_le_of_lt hm0), tsub_add_cancel_of_le (le_mul_of_one_le_right (Nat.zero_le _) hn0)] theorem odd_of_mod_four_eq_one {n : β„•} : n % 4 = 1 β†’ n % 2 = 1 := by simpa [ModEq, show 2 * 2 = 4 by norm_num] using @ModEq.of_mul_left 2 n 1 2 theorem odd_of_mod_four_eq_three {n : β„•} : n % 4 = 3 β†’ n % 2 = 1 := by simpa [ModEq, show 2 * 2 = 4 by norm_num, show 3 % 4 = 3 by norm_num] using @ModEq.of_mul_left 2 n 3 2 /-- A natural number is odd iff it has residue `1` or `3` mod `4`-/ theorem odd_mod_four_iff {n : β„•} : n % 2 = 1 ↔ n % 4 = 1 ∨ n % 4 = 3 := have help : βˆ€ m : β„•, m < 4 β†’ m % 2 = 1 β†’ m = 1 ∨ m = 3 := by decide ⟨fun hn => help (n % 4) (mod_lt n (by norm_num)) <| (mod_mod_of_dvd n (by decide : 2 ∣ 4)).trans hn, fun h => Or.elim h odd_of_mod_four_eq_one odd_of_mod_four_eq_three⟩ lemma mod_eq_of_modEq {a b n} (h : a ≑ b [MOD n]) (hb : b < n) : a % n = b := Eq.trans h (mod_eq_of_lt hb) end Nat
Data\Nat\Multiplicity.lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.Algebra.BigOperators.Intervals import Mathlib.Algebra.GeomSum import Mathlib.Algebra.Order.Ring.Abs import Mathlib.Data.Nat.Bitwise import Mathlib.Data.Nat.Log import Mathlib.Data.Nat.Prime.Defs import Mathlib.Data.Nat.Digits import Mathlib.RingTheory.Multiplicity /-! # Natural number multiplicity This file contains lemmas about the multiplicity function (the maximum prime power dividing a number) when applied to naturals, in particular calculating it for factorials and binomial coefficients. ## Multiplicity calculations * `Nat.Prime.multiplicity_factorial`: Legendre's Theorem. The multiplicity of `p` in `n!` is `n / p + ... + n / p ^ b` for any `b` such that `n / p ^ (b + 1) = 0`. See `padicValNat_factorial` for this result stated in the language of `p`-adic valuations and `sub_one_mul_padicValNat_factorial` for a related result. * `Nat.Prime.multiplicity_factorial_mul`: The multiplicity of `p` in `(p * n)!` is `n` more than that of `n!`. * `Nat.Prime.multiplicity_choose`: Kummer's Theorem. The multiplicity of `p` in `n.choose k` is the number of carries when `k` and `n - k` are added in base `p`. See `padicValNat_choose` for the same result but stated in the language of `p`-adic valuations and `sub_one_mul_padicValNat_choose_eq_sub_sum_digits` for a related result. ## Other declarations * `Nat.multiplicity_eq_card_pow_dvd`: The multiplicity of `m` in `n` is the number of positive natural numbers `i` such that `m ^ i` divides `n`. * `Nat.multiplicity_two_factorial_lt`: The multiplicity of `2` in `n!` is strictly less than `n`. * `Nat.Prime.multiplicity_something`: Specialization of `multiplicity.something` to a prime in the naturals. Avoids having to provide `p β‰  1` and other trivialities, along with translating between `Prime` and `Nat.Prime`. ## Tags Legendre, p-adic -/ open Finset Nat multiplicity open Nat namespace Nat /-- The multiplicity of `m` in `n` is the number of positive natural numbers `i` such that `m ^ i` divides `n`. This set is expressed by filtering `Ico 1 b` where `b` is any bound greater than `log m n`. -/ theorem multiplicity_eq_card_pow_dvd {m n b : β„•} (hm : m β‰  1) (hn : 0 < n) (hb : log m n < b) : multiplicity m n = ↑((Finset.Ico 1 b).filter fun i => m ^ i ∣ n).card := calc multiplicity m n = ↑(Ico 1 <| (multiplicity m n).get (finite_nat_iff.2 ⟨hm, hn⟩) + 1).card := by simp _ = ↑((Finset.Ico 1 b).filter fun i => m ^ i ∣ n).card := congr_arg _ <| congr_arg card <| Finset.ext fun i => by rw [mem_filter, mem_Ico, mem_Ico, Nat.lt_succ_iff, ← @PartENat.coe_le_coe i, PartENat.natCast_get, ← pow_dvd_iff_le_multiplicity, and_right_comm] refine (and_iff_left_of_imp fun h => lt_of_le_of_lt ?_ hb).symm cases' m with m Β· rw [zero_pow, zero_dvd_iff] at h exacts [(hn.ne' h.2).elim, one_le_iff_ne_zero.1 h.1] exact le_log_of_pow_le (one_lt_iff_ne_zero_and_ne_one.2 ⟨m.succ_ne_zero, hm⟩) (le_of_dvd hn h.2) namespace Prime theorem multiplicity_one {p : β„•} (hp : p.Prime) : multiplicity p 1 = 0 := multiplicity.one_right hp.prime.not_unit theorem multiplicity_mul {p m n : β„•} (hp : p.Prime) : multiplicity p (m * n) = multiplicity p m + multiplicity p n := multiplicity.mul hp.prime theorem multiplicity_pow {p m n : β„•} (hp : p.Prime) : multiplicity p (m ^ n) = n β€’ multiplicity p m := multiplicity.pow hp.prime theorem multiplicity_self {p : β„•} (hp : p.Prime) : multiplicity p p = 1 := multiplicity.multiplicity_self hp.prime.not_unit hp.ne_zero theorem multiplicity_pow_self {p n : β„•} (hp : p.Prime) : multiplicity p (p ^ n) = n := multiplicity.multiplicity_pow_self hp.ne_zero hp.prime.not_unit n /-- **Legendre's Theorem** The multiplicity of a prime in `n!` is the sum of the quotients `n / p ^ i`. This sum is expressed over the finset `Ico 1 b` where `b` is any bound greater than `log p n`. -/ theorem multiplicity_factorial {p : β„•} (hp : p.Prime) : βˆ€ {n b : β„•}, log p n < b β†’ multiplicity p n ! = (βˆ‘ i ∈ Ico 1 b, n / p ^ i : β„•) | 0, b, _ => by simp [Ico, hp.multiplicity_one] | n + 1, b, hb => calc multiplicity p (n + 1)! = multiplicity p n ! + multiplicity p (n + 1) := by rw [factorial_succ, hp.multiplicity_mul, add_comm] _ = (βˆ‘ i ∈ Ico 1 b, n / p ^ i : β„•) + ((Finset.Ico 1 b).filter fun i => p ^ i ∣ n + 1).card := by rw [multiplicity_factorial hp ((log_mono_right <| le_succ _).trans_lt hb), ← multiplicity_eq_card_pow_dvd hp.ne_one (succ_pos _) hb] _ = (βˆ‘ i ∈ Ico 1 b, (n / p ^ i + if p ^ i ∣ n + 1 then 1 else 0) : β„•) := by rw [sum_add_distrib, sum_boole] simp _ = (βˆ‘ i ∈ Ico 1 b, (n + 1) / p ^ i : β„•) := congr_arg _ <| Finset.sum_congr rfl fun _ _ => (succ_div _ _).symm /-- For a prime number `p`, taking `(p - 1)` times the multiplicity of `p` in `n!` equals `n` minus the sum of base `p` digits of `n`. -/ theorem sub_one_mul_multiplicity_factorial {n p : β„•} (hp : p.Prime) : (p - 1) * (multiplicity p n !).get (finite_nat_iff.mpr ⟨hp.ne_one, factorial_pos n⟩) = n - (p.digits n).sum := by simp only [multiplicity_factorial hp <| lt_succ_of_lt <| lt.base (log p n), ← Finset.sum_Ico_add' _ 0 _ 1, Ico_zero_eq_range, ← sub_one_mul_sum_log_div_pow_eq_sub_sum_digits] rfl /-- The multiplicity of `p` in `(p * (n + 1))!` is one more than the sum of the multiplicities of `p` in `(p * n)!` and `n + 1`. -/ theorem multiplicity_factorial_mul_succ {n p : β„•} (hp : p.Prime) : multiplicity p (p * (n + 1))! = multiplicity p (p * n)! + multiplicity p (n + 1) + 1 := by have hp' := hp.prime have h0 : 2 ≀ p := hp.two_le have h1 : 1 ≀ p * n + 1 := Nat.le_add_left _ _ have h2 : p * n + 1 ≀ p * (n + 1) := by linarith have h3 : p * n + 1 ≀ p * (n + 1) + 1 := by omega have hm : multiplicity p (p * n)! β‰  ⊀ := by rw [Ne, eq_top_iff_not_finite, Classical.not_not, finite_nat_iff] exact ⟨hp.ne_one, factorial_pos _⟩ revert hm have h4 : βˆ€ m ∈ Ico (p * n + 1) (p * (n + 1)), multiplicity p m = 0 := by intro m hm rw [multiplicity_eq_zero, ← not_dvd_iff_between_consec_multiples _ hp.pos] rw [mem_Ico] at hm exact ⟨n, lt_of_succ_le hm.1, hm.2⟩ simp_rw [← prod_Ico_id_eq_factorial, multiplicity.Finset.prod hp', ← sum_Ico_consecutive _ h1 h3, add_assoc] intro h rw [PartENat.add_left_cancel_iff h, sum_Ico_succ_top h2, multiplicity.mul hp', hp.multiplicity_self, sum_congr rfl h4, sum_const_zero, zero_add, add_comm (1 : PartENat)] /-- The multiplicity of `p` in `(p * n)!` is `n` more than that of `n!`. -/ theorem multiplicity_factorial_mul {n p : β„•} (hp : p.Prime) : multiplicity p (p * n)! = multiplicity p n ! + n := by induction' n with n ih Β· simp Β· simp only [succ_eq_add_one, multiplicity.mul, hp, hp.prime, ih, multiplicity_factorial_mul_succ, ← add_assoc, Nat.cast_one, Nat.cast_add, factorial_succ] congr 1 rw [add_comm, add_assoc] /-- A prime power divides `n!` iff it is at most the sum of the quotients `n / p ^ i`. This sum is expressed over the set `Ico 1 b` where `b` is any bound greater than `log p n` -/ theorem pow_dvd_factorial_iff {p : β„•} {n r b : β„•} (hp : p.Prime) (hbn : log p n < b) : p ^ r ∣ n ! ↔ r ≀ βˆ‘ i ∈ Ico 1 b, n / p ^ i := by rw [← PartENat.coe_le_coe, ← hp.multiplicity_factorial hbn, ← pow_dvd_iff_le_multiplicity] theorem multiplicity_factorial_le_div_pred {p : β„•} (hp : p.Prime) (n : β„•) : multiplicity p n ! ≀ (n / (p - 1) : β„•) := by rw [hp.multiplicity_factorial (lt_succ_self _), PartENat.coe_le_coe] exact Nat.geom_sum_Ico_le hp.two_le _ _ theorem multiplicity_choose_aux {p n b k : β„•} (hp : p.Prime) (hkn : k ≀ n) : βˆ‘ i ∈ Finset.Ico 1 b, n / p ^ i = ((βˆ‘ i ∈ Finset.Ico 1 b, k / p ^ i) + βˆ‘ i ∈ Finset.Ico 1 b, (n - k) / p ^ i) + ((Finset.Ico 1 b).filter fun i => p ^ i ≀ k % p ^ i + (n - k) % p ^ i).card := calc βˆ‘ i ∈ Finset.Ico 1 b, n / p ^ i = βˆ‘ i ∈ Finset.Ico 1 b, (k + (n - k)) / p ^ i := by simp only [add_tsub_cancel_of_le hkn] _ = βˆ‘ i ∈ Finset.Ico 1 b, (k / p ^ i + (n - k) / p ^ i + if p ^ i ≀ k % p ^ i + (n - k) % p ^ i then 1 else 0) := by simp only [Nat.add_div (pow_pos hp.pos _)] _ = _ := by simp [sum_add_distrib, sum_boole] /-- The multiplicity of `p` in `choose (n + k) k` is the number of carries when `k` and `n` are added in base `p`. The set is expressed by filtering `Ico 1 b` where `b` is any bound greater than `log p (n + k)`. -/ theorem multiplicity_choose' {p n k b : β„•} (hp : p.Prime) (hnb : log p (n + k) < b) : multiplicity p (choose (n + k) k) = ((Ico 1 b).filter fun i => p ^ i ≀ k % p ^ i + n % p ^ i).card := by have h₁ : multiplicity p (choose (n + k) k) + multiplicity p (k ! * n !) = ((Finset.Ico 1 b).filter fun i => p ^ i ≀ k % p ^ i + n % p ^ i).card + multiplicity p (k ! * n !) := by rw [← hp.multiplicity_mul, ← mul_assoc] have := (add_tsub_cancel_right n k) β–Έ choose_mul_factorial_mul_factorial (le_add_left k n) rw [this, hp.multiplicity_factorial hnb, hp.multiplicity_mul, hp.multiplicity_factorial ((log_mono_right (le_add_left k n)).trans_lt hnb), hp.multiplicity_factorial ((log_mono_right (le_add_left n k)).trans_lt (add_comm n k β–Έ hnb)), multiplicity_choose_aux hp (le_add_left k n)] simp [add_comm] refine (PartENat.add_right_cancel_iff ?_).1 h₁ apply PartENat.ne_top_iff_dom.2 exact finite_nat_iff.2 ⟨hp.ne_one, mul_pos (factorial_pos k) (factorial_pos n)⟩ /-- The multiplicity of `p` in `choose n k` is the number of carries when `k` and `n - k` are added in base `p`. The set is expressed by filtering `Ico 1 b` where `b` is any bound greater than `log p n`. -/ theorem multiplicity_choose {p n k b : β„•} (hp : p.Prime) (hkn : k ≀ n) (hnb : log p n < b) : multiplicity p (choose n k) = ((Ico 1 b).filter fun i => p ^ i ≀ k % p ^ i + (n - k) % p ^ i).card := by have := Nat.sub_add_cancel hkn convert @multiplicity_choose' p (n - k) k b hp _ Β· rw [this] exact this.symm β–Έ hnb /-- A lower bound on the multiplicity of `p` in `choose n k`. -/ theorem multiplicity_le_multiplicity_choose_add {p : β„•} (hp : p.Prime) : βˆ€ n k : β„•, multiplicity p n ≀ multiplicity p (choose n k) + multiplicity p k | _, 0 => by simp | 0, _ + 1 => by simp | n + 1, k + 1 => by rw [← hp.multiplicity_mul] refine multiplicity_le_multiplicity_of_dvd_right ?_ rw [← succ_mul_choose_eq] exact dvd_mul_right _ _ variable {p n k : β„•} theorem multiplicity_choose_prime_pow_add_multiplicity (hp : p.Prime) (hkn : k ≀ p ^ n) (hk0 : k β‰  0) : multiplicity p (choose (p ^ n) k) + multiplicity p k = n := le_antisymm (by have hdisj : Disjoint ((Ico 1 n.succ).filter fun i => p ^ i ≀ k % p ^ i + (p ^ n - k) % p ^ i) ((Ico 1 n.succ).filter fun i => p ^ i ∣ k) := by simp (config := { contextual := true }) [disjoint_right, *, dvd_iff_mod_eq_zero, Nat.mod_lt _ (pow_pos hp.pos _)] rw [multiplicity_choose hp hkn (lt_succ_self _), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) hk0.bot_lt (lt_succ_of_le (log_mono_right hkn)), ← Nat.cast_add, PartENat.coe_le_coe, log_pow hp.one_lt, ← card_union_of_disjoint hdisj, filter_union_right] have filter_le_Ico := (Ico 1 n.succ).card_filter_le fun x => p ^ x ≀ k % p ^ x + (p ^ n - k) % p ^ x ∨ p ^ x ∣ k rwa [card_Ico 1 n.succ] at filter_le_Ico) (by rw [← hp.multiplicity_pow_self]; exact multiplicity_le_multiplicity_choose_add hp _ _) theorem multiplicity_choose_prime_pow {p n k : β„•} (hp : p.Prime) (hkn : k ≀ p ^ n) (hk0 : k β‰  0) : multiplicity p (choose (p ^ n) k) = ↑(n - (multiplicity p k).get (finite_nat_iff.2 ⟨hp.ne_one, hk0.bot_lt⟩)) := PartENat.eq_natCast_sub_of_add_eq_natCast <| multiplicity_choose_prime_pow_add_multiplicity hp hkn hk0 theorem dvd_choose_pow (hp : Prime p) (hk : k β‰  0) (hkp : k β‰  p ^ n) : p ∣ (p ^ n).choose k := by obtain hkp | hkp := hkp.symm.lt_or_lt Β· simp [choose_eq_zero_of_lt hkp] refine multiplicity_ne_zero.1 fun h => hkp.not_le <| Nat.le_of_dvd hk.bot_lt ?_ have H := hp.multiplicity_choose_prime_pow_add_multiplicity hkp.le hk rw [h, zero_add, eq_coe_iff] at H exact H.1 theorem dvd_choose_pow_iff (hp : Prime p) : p ∣ (p ^ n).choose k ↔ k β‰  0 ∧ k β‰  p ^ n := by refine ⟨fun h => ⟨?_, ?_⟩, fun h => dvd_choose_pow hp h.1 h.2⟩ <;> rintro rfl <;> simp [hp.ne_one] at h end Prime theorem multiplicity_two_factorial_lt : βˆ€ {n : β„•} (_ : n β‰  0), multiplicity 2 n ! < n := by have h2 := prime_two.prime refine binaryRec ?_ ?_ Β· exact fun h => False.elim <| h rfl Β· intro b n ih h by_cases hn : n = 0 Β· subst hn simp only [ne_eq, bit_eq_zero, true_and, Bool.not_eq_false] at h simp only [h, bit_true, factorial, mul_one, Nat.isUnit_iff, cast_one] rw [Prime.multiplicity_one] Β· simp [zero_lt_one] Β· decide have : multiplicity 2 (2 * n)! < (2 * n : β„•) := by rw [prime_two.multiplicity_factorial_mul] refine (PartENat.add_lt_add_right (ih hn) (PartENat.natCast_ne_top _)).trans_le ?_ rw [two_mul] norm_cast cases b Β· simpa Β· suffices multiplicity 2 (2 * n + 1) + multiplicity 2 (2 * n)! < ↑(2 * n) + 1 by simpa [multiplicity.mul, h2, prime_two, bit, factorial] rw [multiplicity_eq_zero.2 (two_not_dvd_two_mul_add_one n), zero_add] refine this.trans ?_ exact mod_cast lt_succ_self _ end Nat
Data\Nat\Notation.lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura -/ /-! # Notation `β„•` for the natural numbers. -/ @[inherit_doc] notation "β„•" => Nat
Data\Nat\Nth.lean
/- Copyright (c) 2021 Vladimir Goryachev. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: YaΓ«l Dillies, Vladimir Goryachev, Kyle Miller, Scott Morrison, Eric Rodriguez -/ import Mathlib.Data.List.GetD import Mathlib.Data.Nat.Count import Mathlib.Data.Nat.SuccPred import Mathlib.Order.Interval.Set.Monotone import Mathlib.Order.OrderIsoNat /-! # The `n`th Number Satisfying a Predicate This file defines a function for "what is the `n`th number that satisifies a given predicate `p`", and provides lemmas that deal with this function and its connection to `Nat.count`. ## Main definitions * `Nat.nth p n`: The `n`-th natural `k` (zero-indexed) such that `p k`. If there is no such natural (that is, `p` is true for at most `n` naturals), then `Nat.nth p n = 0`. ## Main results * `Nat.nth_eq_orderEmbOfFin`: For a finitely-often true `p`, gives the cardinality of the set of numbers satisfying `p` above particular values of `nth p` * `Nat.gc_count_nth`: Establishes a Galois connection between `Nat.nth p` and `Nat.count p`. * `Nat.nth_eq_orderIsoOfNat`: For an infinitely-often true predicate, `nth` agrees with the order-isomorphism of the subtype to the natural numbers. There has been some discussion on the subject of whether both of `nth` and `Nat.Subtype.orderIsoOfNat` should exist. See discussion [here](https://github.com/leanprover-community/mathlib/pull/9457#pullrequestreview-767221180). Future work should address how lemmas that use these should be written. -/ open Finset namespace Nat variable (p : β„• β†’ Prop) /-- Find the `n`-th natural number satisfying `p` (indexed from `0`, so `nth p 0` is the first natural number satisfying `p`), or `0` if there is no such number. See also `Subtype.orderIsoOfNat` for the order isomorphism with β„• when `p` is infinitely often true. -/ noncomputable def nth (p : β„• β†’ Prop) (n : β„•) : β„• := by classical exact if h : Set.Finite (setOf p) then (h.toFinset.sort (Β· ≀ Β·)).getD n 0 else @Nat.Subtype.orderIsoOfNat (setOf p) (Set.Infinite.to_subtype h) n variable {p} /-! ### Lemmas about `Nat.nth` on a finite set -/ theorem nth_of_card_le (hf : (setOf p).Finite) {n : β„•} (hn : hf.toFinset.card ≀ n) : nth p n = 0 := by rw [nth, dif_pos hf, List.getD_eq_default]; rwa [Finset.length_sort] theorem nth_eq_getD_sort (h : (setOf p).Finite) (n : β„•) : nth p n = (h.toFinset.sort (Β· ≀ Β·)).getD n 0 := dif_pos h theorem nth_eq_orderEmbOfFin (hf : (setOf p).Finite) {n : β„•} (hn : n < hf.toFinset.card) : nth p n = hf.toFinset.orderEmbOfFin rfl ⟨n, hn⟩ := by rw [nth_eq_getD_sort hf, Finset.orderEmbOfFin_apply, List.getD_eq_get] theorem nth_strictMonoOn (hf : (setOf p).Finite) : StrictMonoOn (nth p) (Set.Iio hf.toFinset.card) := by rintro m (hm : m < _) n (hn : n < _) h simp only [nth_eq_orderEmbOfFin, *] exact OrderEmbedding.strictMono _ h theorem nth_lt_nth_of_lt_card (hf : (setOf p).Finite) {m n : β„•} (h : m < n) (hn : n < hf.toFinset.card) : nth p m < nth p n := nth_strictMonoOn hf (h.trans hn) hn h theorem nth_le_nth_of_lt_card (hf : (setOf p).Finite) {m n : β„•} (h : m ≀ n) (hn : n < hf.toFinset.card) : nth p m ≀ nth p n := (nth_strictMonoOn hf).monotoneOn (h.trans_lt hn) hn h theorem lt_of_nth_lt_nth_of_lt_card (hf : (setOf p).Finite) {m n : β„•} (h : nth p m < nth p n) (hm : m < hf.toFinset.card) : m < n := not_le.1 fun hle => h.not_le <| nth_le_nth_of_lt_card hf hle hm theorem le_of_nth_le_nth_of_lt_card (hf : (setOf p).Finite) {m n : β„•} (h : nth p m ≀ nth p n) (hm : m < hf.toFinset.card) : m ≀ n := not_lt.1 fun hlt => h.not_lt <| nth_lt_nth_of_lt_card hf hlt hm theorem nth_injOn (hf : (setOf p).Finite) : (Set.Iio hf.toFinset.card).InjOn (nth p) := (nth_strictMonoOn hf).injOn theorem range_nth_of_finite (hf : (setOf p).Finite) : Set.range (nth p) = insert 0 (setOf p) := by simpa only [← List.getD_eq_getElem?_getD, ← nth_eq_getD_sort hf, mem_sort, Set.Finite.mem_toFinset] using Set.range_list_getD (hf.toFinset.sort (Β· ≀ Β·)) 0 @[simp] theorem image_nth_Iio_card (hf : (setOf p).Finite) : nth p '' Set.Iio hf.toFinset.card = setOf p := calc nth p '' Set.Iio hf.toFinset.card = Set.range (hf.toFinset.orderEmbOfFin rfl) := by ext x simp only [Set.mem_image, Set.mem_range, Fin.exists_iff, ← nth_eq_orderEmbOfFin hf, Set.mem_Iio, exists_prop] _ = setOf p := by rw [range_orderEmbOfFin, Set.Finite.coe_toFinset] theorem nth_mem_of_lt_card {n : β„•} (hf : (setOf p).Finite) (hlt : n < hf.toFinset.card) : p (nth p n) := (image_nth_Iio_card hf).subset <| Set.mem_image_of_mem _ hlt theorem exists_lt_card_finite_nth_eq (hf : (setOf p).Finite) {x} (h : p x) : βˆƒ n, n < hf.toFinset.card ∧ nth p n = x := by rwa [← @Set.mem_setOf_eq _ _ p, ← image_nth_Iio_card hf] at h /-! ### Lemmas about `Nat.nth` on an infinite set -/ /-- When `s` is an infinite set, `nth` agrees with `Nat.Subtype.orderIsoOfNat`. -/ theorem nth_apply_eq_orderIsoOfNat (hf : (setOf p).Infinite) (n : β„•) : nth p n = @Nat.Subtype.orderIsoOfNat (setOf p) hf.to_subtype n := by rw [nth, dif_neg hf] /-- When `s` is an infinite set, `nth` agrees with `Nat.Subtype.orderIsoOfNat`. -/ theorem nth_eq_orderIsoOfNat (hf : (setOf p).Infinite) : nth p = (↑) ∘ @Nat.Subtype.orderIsoOfNat (setOf p) hf.to_subtype := funext <| nth_apply_eq_orderIsoOfNat hf theorem nth_strictMono (hf : (setOf p).Infinite) : StrictMono (nth p) := by rw [nth_eq_orderIsoOfNat hf] exact (Subtype.strictMono_coe _).comp (OrderIso.strictMono _) theorem nth_injective (hf : (setOf p).Infinite) : Function.Injective (nth p) := (nth_strictMono hf).injective theorem nth_monotone (hf : (setOf p).Infinite) : Monotone (nth p) := (nth_strictMono hf).monotone theorem nth_lt_nth (hf : (setOf p).Infinite) {k n} : nth p k < nth p n ↔ k < n := (nth_strictMono hf).lt_iff_lt theorem nth_le_nth (hf : (setOf p).Infinite) {k n} : nth p k ≀ nth p n ↔ k ≀ n := (nth_strictMono hf).le_iff_le theorem range_nth_of_infinite (hf : (setOf p).Infinite) : Set.range (nth p) = setOf p := by rw [nth_eq_orderIsoOfNat hf] haveI := hf.to_subtype -- Porting note: added `classical`; probably, Lean 3 found instance by unification classical exact Nat.Subtype.coe_comp_ofNat_range theorem nth_mem_of_infinite (hf : (setOf p).Infinite) (n : β„•) : p (nth p n) := Set.range_subset_iff.1 (range_nth_of_infinite hf).le n /-! ### Lemmas that work for finite and infinite sets -/ theorem exists_lt_card_nth_eq {x} (h : p x) : βˆƒ n, (βˆ€ hf : (setOf p).Finite, n < hf.toFinset.card) ∧ nth p n = x := by refine (setOf p).finite_or_infinite.elim (fun hf => ?_) fun hf => ?_ Β· rcases exists_lt_card_finite_nth_eq hf h with ⟨n, hn, hx⟩ exact ⟨n, fun _ => hn, hx⟩ Β· rw [← @Set.mem_setOf_eq _ _ p, ← range_nth_of_infinite hf] at h rcases h with ⟨n, hx⟩ exact ⟨n, fun hf' => absurd hf' hf, hx⟩ theorem subset_range_nth : setOf p βŠ† Set.range (nth p) := fun x (hx : p x) => let ⟨n, _, hn⟩ := exists_lt_card_nth_eq hx ⟨n, hn⟩ theorem range_nth_subset : Set.range (nth p) βŠ† insert 0 (setOf p) := (setOf p).finite_or_infinite.elim (fun h => (range_nth_of_finite h).subset) fun h => (range_nth_of_infinite h).trans_subset (Set.subset_insert _ _) theorem nth_mem (n : β„•) (h : βˆ€ hf : (setOf p).Finite, n < hf.toFinset.card) : p (nth p n) := (setOf p).finite_or_infinite.elim (fun hf => nth_mem_of_lt_card hf (h hf)) fun h => nth_mem_of_infinite h n theorem nth_lt_nth' {m n : β„•} (hlt : m < n) (h : βˆ€ hf : (setOf p).Finite, n < hf.toFinset.card) : nth p m < nth p n := (setOf p).finite_or_infinite.elim (fun hf => nth_lt_nth_of_lt_card hf hlt (h _)) fun hf => (nth_lt_nth hf).2 hlt theorem nth_le_nth' {m n : β„•} (hle : m ≀ n) (h : βˆ€ hf : (setOf p).Finite, n < hf.toFinset.card) : nth p m ≀ nth p n := (setOf p).finite_or_infinite.elim (fun hf => nth_le_nth_of_lt_card hf hle (h _)) fun hf => (nth_le_nth hf).2 hle theorem le_nth {n : β„•} (h : βˆ€ hf : (setOf p).Finite, n < hf.toFinset.card) : n ≀ nth p n := (setOf p).finite_or_infinite.elim (fun hf => ((nth_strictMonoOn hf).mono <| Set.Iic_subset_Iio.2 (h _)).Iic_id_le _ le_rfl) fun hf => (nth_strictMono hf).id_le _ theorem isLeast_nth {n} (h : βˆ€ hf : (setOf p).Finite, n < hf.toFinset.card) : IsLeast {i | p i ∧ βˆ€ k < n, nth p k < i} (nth p n) := ⟨⟨nth_mem n h, fun _k hk => nth_lt_nth' hk h⟩, fun _x hx => let ⟨k, hk, hkx⟩ := exists_lt_card_nth_eq hx.1 (lt_or_le k n).elim (fun hlt => absurd hkx (hx.2 _ hlt).ne) fun hle => hkx β–Έ nth_le_nth' hle hk⟩ theorem isLeast_nth_of_lt_card {n : β„•} (hf : (setOf p).Finite) (hn : n < hf.toFinset.card) : IsLeast {i | p i ∧ βˆ€ k < n, nth p k < i} (nth p n) := isLeast_nth fun _ => hn theorem isLeast_nth_of_infinite (hf : (setOf p).Infinite) (n : β„•) : IsLeast {i | p i ∧ βˆ€ k < n, nth p k < i} (nth p n) := isLeast_nth fun h => absurd h hf /-- An alternative recursive definition of `Nat.nth`: `Nat.nth s n` is the infimum of `x ∈ s` such that `Nat.nth s k < x` for all `k < n`, if this set is nonempty. We do not assume that the set is nonempty because we use the same "garbage value" `0` both for `sInf` on `β„•` and for `Nat.nth s n` for `n β‰₯ card s`. -/ theorem nth_eq_sInf (p : β„• β†’ Prop) (n : β„•) : nth p n = sInf {x | p x ∧ βˆ€ k < n, nth p k < x} := by by_cases hn : βˆ€ hf : (setOf p).Finite, n < hf.toFinset.card Β· exact (isLeast_nth hn).csInf_eq.symm Β· push_neg at hn rcases hn with ⟨hf, hn⟩ rw [nth_of_card_le _ hn] refine ((congr_arg sInf <| Set.eq_empty_of_forall_not_mem fun k hk => ?_).trans sInf_empty).symm rcases exists_lt_card_nth_eq hk.1 with ⟨k, hlt, rfl⟩ exact (hk.2 _ ((hlt hf).trans_le hn)).false theorem nth_zero : nth p 0 = sInf (setOf p) := by rw [nth_eq_sInf]; simp @[simp] theorem nth_zero_of_zero (h : p 0) : nth p 0 = 0 := by simp [nth_zero, h] theorem nth_zero_of_exists [DecidablePred p] (h : βˆƒ n, p n) : nth p 0 = Nat.find h := by rw [nth_zero]; convert Nat.sInf_def h theorem nth_eq_zero {n} : nth p n = 0 ↔ p 0 ∧ n = 0 ∨ βˆƒ hf : (setOf p).Finite, hf.toFinset.card ≀ n := by refine ⟨fun h => ?_, ?_⟩ Β· simp only [or_iff_not_imp_right, not_exists, not_le] exact fun hn => ⟨h β–Έ nth_mem _ hn, nonpos_iff_eq_zero.1 <| h β–Έ le_nth hn⟩ Β· rintro (⟨hβ‚€, rfl⟩ | ⟨hf, hle⟩) exacts [nth_zero_of_zero hβ‚€, nth_of_card_le hf hle] theorem nth_eq_zero_mono (hβ‚€ : Β¬p 0) {a b : β„•} (hab : a ≀ b) (ha : nth p a = 0) : nth p b = 0 := by simp only [nth_eq_zero, hβ‚€, false_and_iff, false_or_iff] at ha ⊒ exact ha.imp fun hf hle => hle.trans hab theorem le_nth_of_lt_nth_succ {k a : β„•} (h : a < nth p (k + 1)) (ha : p a) : a ≀ nth p k := by cases' (setOf p).finite_or_infinite with hf hf Β· rcases exists_lt_card_finite_nth_eq hf ha with ⟨n, hn, rfl⟩ cases' lt_or_le (k + 1) hf.toFinset.card with hk hk Β· rwa [(nth_strictMonoOn hf).lt_iff_lt hn hk, Nat.lt_succ_iff, ← (nth_strictMonoOn hf).le_iff_le hn (k.lt_succ_self.trans hk)] at h Β· rw [nth_of_card_le _ hk] at h exact absurd h (zero_le _).not_lt Β· rcases subset_range_nth ha with ⟨n, rfl⟩ rwa [nth_lt_nth hf, Nat.lt_succ_iff, ← nth_le_nth hf] at h section Count variable (p) [DecidablePred p] @[simp] theorem count_nth_zero : count p (nth p 0) = 0 := by rw [count_eq_card_filter_range, card_eq_zero, filter_eq_empty_iff, nth_zero] exact fun n h₁ hβ‚‚ => (mem_range.1 h₁).not_le (Nat.sInf_le hβ‚‚) theorem filter_range_nth_subset_insert (k : β„•) : (range (nth p (k + 1))).filter p βŠ† insert (nth p k) ((range (nth p k)).filter p) := by intro a ha simp only [mem_insert, mem_filter, mem_range] at ha ⊒ exact (le_nth_of_lt_nth_succ ha.1 ha.2).eq_or_lt.imp_right fun h => ⟨h, ha.2⟩ variable {p} theorem filter_range_nth_eq_insert {k : β„•} (hlt : βˆ€ hf : (setOf p).Finite, k + 1 < hf.toFinset.card) : (range (nth p (k + 1))).filter p = insert (nth p k) ((range (nth p k)).filter p) := by refine (filter_range_nth_subset_insert p k).antisymm fun a ha => ?_ simp only [mem_insert, mem_filter, mem_range] at ha ⊒ have : nth p k < nth p (k + 1) := nth_lt_nth' k.lt_succ_self hlt rcases ha with (rfl | ⟨hlt, hpa⟩) Β· exact ⟨this, nth_mem _ fun hf => k.lt_succ_self.trans (hlt hf)⟩ Β· exact ⟨hlt.trans this, hpa⟩ theorem filter_range_nth_eq_insert_of_finite (hf : (setOf p).Finite) {k : β„•} (hlt : k + 1 < hf.toFinset.card) : (range (nth p (k + 1))).filter p = insert (nth p k) ((range (nth p k)).filter p) := filter_range_nth_eq_insert fun _ => hlt theorem filter_range_nth_eq_insert_of_infinite (hp : (setOf p).Infinite) (k : β„•) : (range (nth p (k + 1))).filter p = insert (nth p k) ((range (nth p k)).filter p) := filter_range_nth_eq_insert fun hf => absurd hf hp theorem count_nth {n : β„•} (hn : βˆ€ hf : (setOf p).Finite, n < hf.toFinset.card) : count p (nth p n) = n := by induction' n with k ihk Β· exact count_nth_zero _ Β· rw [count_eq_card_filter_range, filter_range_nth_eq_insert hn, card_insert_of_not_mem, ← count_eq_card_filter_range, ihk fun hf => lt_of_succ_lt (hn hf)] simp theorem count_nth_of_lt_card_finite {n : β„•} (hp : (setOf p).Finite) (hlt : n < hp.toFinset.card) : count p (nth p n) = n := count_nth fun _ => hlt theorem count_nth_of_infinite (hp : (setOf p).Infinite) (n : β„•) : count p (nth p n) = n := count_nth fun hf => absurd hf hp theorem count_nth_succ {n : β„•} (hn : βˆ€ hf : (setOf p).Finite, n < hf.toFinset.card) : count p (nth p n + 1) = n + 1 := by rw [count_succ, count_nth hn, if_pos (nth_mem _ hn)] @[simp] theorem nth_count {n : β„•} (hpn : p n) : nth p (count p n) = n := have : βˆ€ hf : (setOf p).Finite, count p n < hf.toFinset.card := fun hf => count_lt_card hf hpn count_injective (nth_mem _ this) hpn (count_nth this) theorem nth_lt_of_lt_count {n k : β„•} (h : k < count p n) : nth p k < n := by refine (count_monotone p).reflect_lt ?_ rwa [count_nth] exact fun hf => h.trans_le (count_le_card hf n) theorem le_nth_of_count_le {n k : β„•} (h : n ≀ nth p k) : count p n ≀ k := not_lt.1 fun hlt => h.not_lt <| nth_lt_of_lt_count hlt variable (p) theorem nth_count_eq_sInf (n : β„•) : nth p (count p n) = sInf {i : β„• | p i ∧ n ≀ i} := by refine (nth_eq_sInf _ _).trans (congr_arg sInf ?_) refine Set.ext fun a => and_congr_right fun hpa => ?_ refine ⟨fun h => not_lt.1 fun ha => ?_, fun hn k hk => lt_of_lt_of_le (nth_lt_of_lt_count hk) hn⟩ have hn : nth p (count p a) < a := h _ (count_strict_mono hpa ha) rwa [nth_count hpa, lt_self_iff_false] at hn variable {p} theorem le_nth_count' {n : β„•} (hpn : βˆƒ k, p k ∧ n ≀ k) : n ≀ nth p (count p n) := (le_csInf hpn fun _ => And.right).trans (nth_count_eq_sInf p n).ge theorem le_nth_count (hp : (setOf p).Infinite) (n : β„•) : n ≀ nth p (count p n) := let ⟨m, hp, hn⟩ := hp.exists_gt n le_nth_count' ⟨m, hp, hn.le⟩ /-- If a predicate `p : β„• β†’ Prop` is true for infinitely many numbers, then `Nat.count p` and `Nat.nth p` form a Galois insertion. -/ noncomputable def giCountNth (hp : (setOf p).Infinite) : GaloisInsertion (count p) (nth p) := GaloisInsertion.monotoneIntro (nth_monotone hp) (count_monotone p) (le_nth_count hp) (count_nth_of_infinite hp) theorem gc_count_nth (hp : (setOf p).Infinite) : GaloisConnection (count p) (nth p) := (giCountNth hp).gc theorem count_le_iff_le_nth (hp : (setOf p).Infinite) {a b : β„•} : count p a ≀ b ↔ a ≀ nth p b := gc_count_nth hp _ _ theorem lt_nth_iff_count_lt (hp : (setOf p).Infinite) {a b : β„•} : a < count p b ↔ nth p a < b := (gc_count_nth hp).lt_iff_lt end Count theorem nth_of_forall {n : β„•} (hp : βˆ€ n' ≀ n, p n') : nth p n = n := by classical nth_rw 1 [← count_of_forall (hp Β· Β·.le), nth_count (hp n le_rfl)] @[simp] theorem nth_true (n : β„•) : nth (fun _ ↦ True) n = n := nth_of_forall fun _ _ ↦ trivial theorem nth_of_forall_not {n : β„•} (hp : βˆ€ n' β‰₯ n, Β¬p n') : nth p n = 0 := by have : setOf p βŠ† Finset.range n := by intro n' hn' contrapose! hp exact ⟨n', by simpa using hp, Set.mem_setOf.mp hn'⟩ rw [nth_of_card_le ((finite_toSet _).subset this)] Β· refine (Finset.card_le_card ?_).trans_eq (Finset.card_range n) exact Set.Finite.toFinset_subset.mpr this @[simp] theorem nth_false (n : β„•) : nth (fun _ ↦ False) n = 0 := nth_of_forall_not fun _ _ ↦ id end Nat
Data\Nat\Pairing.lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import Mathlib.Algebra.Group.Prod import Mathlib.Data.Set.Lattice /-! # Naturals pairing function This file defines a pairing function for the naturals as follows: ```text 0 1 4 9 16 2 3 5 10 17 6 7 8 11 18 12 13 14 15 19 20 21 22 23 24 ``` It has the advantage of being monotone in both directions and sending `⟦0, n^2 - 1⟧` to `⟦0, n - 1⟧²`. -/ assert_not_exists MonoidWithZero open Prod Decidable Function namespace Nat /-- Pairing function for the natural numbers. -/ @[pp_nodot] def pair (a b : β„•) : β„• := if a < b then b * b + a else a * a + a + b /-- Unpairing function for the natural numbers. -/ @[pp_nodot] def unpair (n : β„•) : β„• Γ— β„• := let s := sqrt n if n - s * s < s then (n - s * s, s) else (s, n - s * s - s) @[simp] theorem pair_unpair (n : β„•) : pair (unpair n).1 (unpair n).2 = n := by dsimp only [unpair]; let s := sqrt n have sm : s * s + (n - s * s) = n := Nat.add_sub_cancel' (sqrt_le _) split_ifs with h Β· simp [pair, h, sm] Β· have hl : n - s * s - s ≀ s := Nat.sub_le_iff_le_add.2 (Nat.sub_le_iff_le_add'.2 <| by rw [← Nat.add_assoc]; apply sqrt_le_add) simp [pair, hl.not_lt, Nat.add_assoc, Nat.add_sub_cancel' (le_of_not_gt h), sm] theorem pair_unpair' {n a b} (H : unpair n = (a, b)) : pair a b = n := by simpa [H] using pair_unpair n @[simp] theorem unpair_pair (a b : β„•) : unpair (pair a b) = (a, b) := by dsimp only [pair]; split_ifs with h Β· show unpair (b * b + a) = (a, b) have be : sqrt (b * b + a) = b := sqrt_add_eq _ (le_trans (le_of_lt h) (Nat.le_add_left _ _)) simp [unpair, be, Nat.add_sub_cancel_left, h] Β· show unpair (a * a + a + b) = (a, b) have ae : sqrt (a * a + (a + b)) = a := by rw [sqrt_add_eq] exact Nat.add_le_add_left (le_of_not_gt h) _ simp [unpair, ae, Nat.not_lt_zero, Nat.add_assoc, Nat.add_sub_cancel_left] /-- An equivalence between `β„• Γ— β„•` and `β„•`. -/ @[simps (config := .asFn)] def pairEquiv : β„• Γ— β„• ≃ β„• := ⟨uncurry pair, unpair, fun ⟨a, b⟩ => unpair_pair a b, pair_unpair⟩ theorem surjective_unpair : Surjective unpair := pairEquiv.symm.surjective @[simp] theorem pair_eq_pair {a b c d : β„•} : pair a b = pair c d ↔ a = c ∧ b = d := pairEquiv.injective.eq_iff.trans (@Prod.ext_iff β„• β„• (a, b) (c, d)) theorem unpair_lt {n : β„•} (n1 : 1 ≀ n) : (unpair n).1 < n := by let s := sqrt n simp only [unpair, Nat.sub_le_iff_le_add] by_cases h : n - s * s < s <;> simp only [h, ↓reduceIte] Β· exact lt_of_lt_of_le h (sqrt_le_self _) Β· simp only [not_lt] at h have s0 : 0 < s := sqrt_pos.2 n1 exact lt_of_le_of_lt h (Nat.sub_lt n1 (Nat.mul_pos s0 s0)) @[simp] theorem unpair_zero : unpair 0 = 0 := by rw [unpair] simp theorem unpair_left_le : βˆ€ n : β„•, (unpair n).1 ≀ n | 0 => by simp | n + 1 => le_of_lt (unpair_lt (Nat.succ_pos _)) theorem left_le_pair (a b : β„•) : a ≀ pair a b := by simpa using unpair_left_le (pair a b) theorem right_le_pair (a b : β„•) : b ≀ pair a b := by by_cases h : a < b Β· simpa [pair, h] using le_trans (le_mul_self _) (Nat.le_add_right _ _) Β· simp [pair, h] theorem unpair_right_le (n : β„•) : (unpair n).2 ≀ n := by simpa using right_le_pair n.unpair.1 n.unpair.2 theorem pair_lt_pair_left {a₁ aβ‚‚} (b) (h : a₁ < aβ‚‚) : pair a₁ b < pair aβ‚‚ b := by by_cases h₁ : a₁ < b <;> simp [pair, h₁, Nat.add_assoc] Β· by_cases hβ‚‚ : aβ‚‚ < b <;> simp [pair, hβ‚‚, h] simp? at hβ‚‚ says simp only [not_lt] at hβ‚‚ apply Nat.add_lt_add_of_le_of_lt Β· exact Nat.mul_self_le_mul_self hβ‚‚ Β· exact Nat.lt_add_right _ h Β· simp at h₁ simp only [not_lt_of_gt (lt_of_le_of_lt h₁ h), ite_false] apply add_lt_add Β· exact Nat.mul_self_lt_mul_self h Β· apply Nat.add_lt_add_right; assumption theorem pair_lt_pair_right (a) {b₁ bβ‚‚} (h : b₁ < bβ‚‚) : pair a b₁ < pair a bβ‚‚ := by by_cases h₁ : a < b₁ Β· simpa [pair, h₁, Nat.add_assoc, lt_trans h₁ h, h] using mul_self_lt_mul_self h Β· simp only [pair, h₁, ↓reduceIte, Nat.add_assoc] by_cases hβ‚‚ : a < bβ‚‚ <;> simp [pair, hβ‚‚, h] simp? at h₁ says simp only [not_lt] at h₁ rw [Nat.add_comm, Nat.add_comm _ a, Nat.add_assoc, Nat.add_lt_add_iff_left] rwa [Nat.add_comm, ← sqrt_lt, sqrt_add_eq] exact le_trans h₁ (Nat.le_add_left _ _) theorem pair_lt_max_add_one_sq (m n : β„•) : pair m n < (max m n + 1) ^ 2 := by simp only [pair, Nat.pow_two, Nat.mul_add, Nat.add_mul, Nat.mul_one, Nat.one_mul, Nat.add_assoc] split_ifs <;> simp [Nat.max_eq_left, Nat.max_eq_right, Nat.le_of_lt, not_lt.1, *] <;> omega theorem max_sq_add_min_le_pair (m n : β„•) : max m n ^ 2 + min m n ≀ pair m n := by rw [pair] cases' lt_or_le m n with h h Β· rw [if_pos h, max_eq_right h.le, min_eq_left h.le, Nat.pow_two] rw [if_neg h.not_lt, max_eq_left h, min_eq_right h, Nat.pow_two, Nat.add_assoc, Nat.add_le_add_iff_left] exact Nat.le_add_left _ _ theorem add_le_pair (m n : β„•) : m + n ≀ pair m n := by simp only [pair, Nat.add_assoc] split_ifs Β· have := le_mul_self n omega Β· exact Nat.le_add_left _ _ theorem unpair_add_le (n : β„•) : (unpair n).1 + (unpair n).2 ≀ n := (add_le_pair _ _).trans_eq (pair_unpair _) end Nat open Nat section CompleteLattice /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem iSup_unpair {Ξ±} [CompleteLattice Ξ±] (f : β„• β†’ β„• β†’ Ξ±) : ⨆ n : β„•, f n.unpair.1 n.unpair.2 = ⨆ (i : β„•) (j : β„•), f i j := by rw [← (iSup_prod : ⨆ i : β„• Γ— β„•, f i.1 i.2 = _), ← Nat.surjective_unpair.iSup_comp] /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem iInf_unpair {Ξ±} [CompleteLattice Ξ±] (f : β„• β†’ β„• β†’ Ξ±) : β¨… n : β„•, f n.unpair.1 n.unpair.2 = β¨… (i : β„•) (j : β„•), f i j := iSup_unpair (show β„• β†’ β„• β†’ Ξ±α΅’α΅ˆ from f) end CompleteLattice namespace Set theorem iUnion_unpair_prod {Ξ± Ξ²} {s : β„• β†’ Set Ξ±} {t : β„• β†’ Set Ξ²} : ⋃ n : β„•, s n.unpair.fst Γ—Λ’ t n.unpair.snd = (⋃ n, s n) Γ—Λ’ ⋃ n, t n := by rw [← Set.iUnion_prod] exact surjective_unpair.iUnion_comp (fun x => s x.fst Γ—Λ’ t x.snd) /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem iUnion_unpair {Ξ±} (f : β„• β†’ β„• β†’ Set Ξ±) : ⋃ n : β„•, f n.unpair.1 n.unpair.2 = ⋃ (i : β„•) (j : β„•), f i j := iSup_unpair f /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem iInter_unpair {Ξ±} (f : β„• β†’ β„• β†’ Set Ξ±) : β‹‚ n : β„•, f n.unpair.1 n.unpair.2 = β‹‚ (i : β„•) (j : β„•), f i j := iInf_unpair f end Set
Data\Nat\PartENat.lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.Algebra.Group.Equiv.Basic import Mathlib.Data.ENat.Lattice import Mathlib.Data.Part import Mathlib.Tactic.NormNum /-! # Natural numbers with infinity The natural numbers and an extra `top` element `⊀`. This implementation uses `Part β„•` as an implementation. Use `β„•βˆž` instead unless you care about computability. ## Main definitions The following instances are defined: * `OrderedAddCommMonoid PartENat` * `CanonicallyOrderedAddCommMonoid PartENat` * `CompleteLinearOrder PartENat` There is no additive analogue of `MonoidWithZero`; if there were then `PartENat` could be an `AddMonoidWithTop`. * `toWithTop` : the map from `PartENat` to `β„•βˆž`, with theorems that it plays well with `+` and `≀`. * `withTopAddEquiv : PartENat ≃+ β„•βˆž` * `withTopOrderIso : PartENat ≃o β„•βˆž` ## Implementation details `PartENat` is defined to be `Part β„•`. `+` and `≀` are defined on `PartENat`, but there is an issue with `*` because it's not clear what `0 * ⊀` should be. `mul` is hence left undefined. Similarly `⊀ - ⊀` is ambiguous so there is no `-` defined on `PartENat`. Before the `open scoped Classical` line, various proofs are made with decidability assumptions. This can cause issues -- see for example the non-simp lemma `toWithTopZero` proved by `rfl`, followed by `@[simp] lemma toWithTopZero'` whose proof uses `convert`. ## Tags PartENat, β„•βˆž -/ open Part hiding some /-- Type of natural numbers with infinity (`⊀`) -/ def PartENat : Type := Part β„• namespace PartENat /-- The computable embedding `β„• β†’ PartENat`. This coincides with the coercion `coe : β„• β†’ PartENat`, see `PartENat.some_eq_natCast`. -/ @[coe] def some : β„• β†’ PartENat := Part.some instance : Zero PartENat := ⟨some 0⟩ instance : Inhabited PartENat := ⟨0⟩ instance : One PartENat := ⟨some 1⟩ instance : Add PartENat := ⟨fun x y => ⟨x.Dom ∧ y.Dom, fun h => get x h.1 + get y h.2⟩⟩ instance (n : β„•) : Decidable (some n).Dom := isTrue trivial @[simp] theorem dom_some (x : β„•) : (some x).Dom := trivial instance addCommMonoid : AddCommMonoid PartENat where add := (Β· + Β·) zero := 0 add_comm x y := Part.ext' and_comm fun _ _ => add_comm _ _ zero_add x := Part.ext' (true_and_iff _) fun _ _ => zero_add _ add_zero x := Part.ext' (and_true_iff _) fun _ _ => add_zero _ add_assoc x y z := Part.ext' and_assoc fun _ _ => add_assoc _ _ _ nsmul := nsmulRec instance : AddCommMonoidWithOne PartENat := { PartENat.addCommMonoid with one := 1 natCast := some natCast_zero := rfl natCast_succ := fun _ => Part.ext' (true_and_iff _).symm fun _ _ => rfl } theorem some_eq_natCast (n : β„•) : some n = n := rfl instance : CharZero PartENat where cast_injective := Part.some_injective /-- Alias of `Nat.cast_inj` specialized to `PartENat` --/ theorem natCast_inj {x y : β„•} : (x : PartENat) = y ↔ x = y := Nat.cast_inj @[simp] theorem dom_natCast (x : β„•) : (x : PartENat).Dom := trivial -- See note [no_index around OfNat.ofNat] @[simp] theorem dom_ofNat (x : β„•) [x.AtLeastTwo] : (no_index (OfNat.ofNat x : PartENat)).Dom := trivial @[simp] theorem dom_zero : (0 : PartENat).Dom := trivial @[simp] theorem dom_one : (1 : PartENat).Dom := trivial instance : CanLift PartENat β„• (↑) Dom := ⟨fun n hn => ⟨n.get hn, Part.some_get _⟩⟩ instance : LE PartENat := ⟨fun x y => βˆƒ h : y.Dom β†’ x.Dom, βˆ€ hy : y.Dom, x.get (h hy) ≀ y.get hy⟩ instance : Top PartENat := ⟨none⟩ instance : Bot PartENat := ⟨0⟩ instance : Sup PartENat := ⟨fun x y => ⟨x.Dom ∧ y.Dom, fun h => x.get h.1 βŠ” y.get h.2⟩⟩ theorem le_def (x y : PartENat) : x ≀ y ↔ βˆƒ h : y.Dom β†’ x.Dom, βˆ€ hy : y.Dom, x.get (h hy) ≀ y.get hy := Iff.rfl @[elab_as_elim] protected theorem casesOn' {P : PartENat β†’ Prop} : βˆ€ a : PartENat, P ⊀ β†’ (βˆ€ n : β„•, P (some n)) β†’ P a := Part.induction_on @[elab_as_elim] protected theorem casesOn {P : PartENat β†’ Prop} : βˆ€ a : PartENat, P ⊀ β†’ (βˆ€ n : β„•, P n) β†’ P a := by exact PartENat.casesOn' -- not a simp lemma as we will provide a `LinearOrderedAddCommMonoidWithTop` instance later theorem top_add (x : PartENat) : ⊀ + x = ⊀ := Part.ext' (false_and_iff _) fun h => h.left.elim -- not a simp lemma as we will provide a `LinearOrderedAddCommMonoidWithTop` instance later theorem add_top (x : PartENat) : x + ⊀ = ⊀ := by rw [add_comm, top_add] @[simp] theorem natCast_get {x : PartENat} (h : x.Dom) : (x.get h : PartENat) = x := by exact Part.ext' (iff_of_true trivial h) fun _ _ => rfl @[simp, norm_cast] theorem get_natCast' (x : β„•) (h : (x : PartENat).Dom) : get (x : PartENat) h = x := by rw [← natCast_inj, natCast_get] theorem get_natCast {x : β„•} : get (x : PartENat) (dom_natCast x) = x := get_natCast' _ _ theorem coe_add_get {x : β„•} {y : PartENat} (h : ((x : PartENat) + y).Dom) : get ((x : PartENat) + y) h = x + get y h.2 := by rfl @[simp] theorem get_add {x y : PartENat} (h : (x + y).Dom) : get (x + y) h = x.get h.1 + y.get h.2 := rfl @[simp] theorem get_zero (h : (0 : PartENat).Dom) : (0 : PartENat).get h = 0 := rfl @[simp] theorem get_one (h : (1 : PartENat).Dom) : (1 : PartENat).get h = 1 := rfl -- See note [no_index around OfNat.ofNat] @[simp] theorem get_ofNat' (x : β„•) [x.AtLeastTwo] (h : (no_index (OfNat.ofNat x : PartENat)).Dom) : Part.get (no_index (OfNat.ofNat x : PartENat)) h = (no_index (OfNat.ofNat x)) := get_natCast' x h nonrec theorem get_eq_iff_eq_some {a : PartENat} {ha : a.Dom} {b : β„•} : a.get ha = b ↔ a = some b := get_eq_iff_eq_some theorem get_eq_iff_eq_coe {a : PartENat} {ha : a.Dom} {b : β„•} : a.get ha = b ↔ a = b := by rw [get_eq_iff_eq_some] rfl theorem dom_of_le_of_dom {x y : PartENat} : x ≀ y β†’ y.Dom β†’ x.Dom := fun ⟨h, _⟩ => h theorem dom_of_le_some {x : PartENat} {y : β„•} (h : x ≀ some y) : x.Dom := dom_of_le_of_dom h trivial theorem dom_of_le_natCast {x : PartENat} {y : β„•} (h : x ≀ y) : x.Dom := by exact dom_of_le_some h instance decidableLe (x y : PartENat) [Decidable x.Dom] [Decidable y.Dom] : Decidable (x ≀ y) := if hx : x.Dom then decidable_of_decidable_of_iff (le_def x y).symm else if hy : y.Dom then isFalse fun h => hx <| dom_of_le_of_dom h hy else isTrue ⟨fun h => (hy h).elim, fun h => (hy h).elim⟩ -- Porting note: Removed. Use `Nat.castAddMonoidHom` instead. instance partialOrder : PartialOrder PartENat where le := (Β· ≀ Β·) le_refl _ := ⟨id, fun _ => le_rfl⟩ le_trans := fun _ _ _ ⟨hxy₁, hxyβ‚‚βŸ© ⟨hyz₁, hyzβ‚‚βŸ© => ⟨hxy₁ ∘ hyz₁, fun _ => le_trans (hxyβ‚‚ _) (hyzβ‚‚ _)⟩ lt_iff_le_not_le _ _ := Iff.rfl le_antisymm := fun _ _ ⟨hxy₁, hxyβ‚‚βŸ© ⟨hyx₁, hyxβ‚‚βŸ© => Part.ext' ⟨hyx₁, hxyβ‚βŸ© fun _ _ => le_antisymm (hxyβ‚‚ _) (hyxβ‚‚ _) theorem lt_def (x y : PartENat) : x < y ↔ βˆƒ hx : x.Dom, βˆ€ hy : y.Dom, x.get hx < y.get hy := by rw [lt_iff_le_not_le, le_def, le_def, not_exists] constructor Β· rintro ⟨⟨hyx, H⟩, h⟩ by_cases hx : x.Dom Β· use hx intro hy specialize H hy specialize h fun _ => hy rw [not_forall] at h cases' h with hx' h rw [not_le] at h exact h Β· specialize h fun hx' => (hx hx').elim rw [not_forall] at h cases' h with hx' h exact (hx hx').elim Β· rintro ⟨hx, H⟩ exact ⟨⟨fun _ => hx, fun hy => (H hy).le⟩, fun hxy h => not_lt_of_le (h _) (H _)⟩ noncomputable instance orderedAddCommMonoid : OrderedAddCommMonoid PartENat := { PartENat.partialOrder, PartENat.addCommMonoid with add_le_add_left := fun a b ⟨h₁, hβ‚‚βŸ© c => PartENat.casesOn c (by simp [top_add]) fun c => ⟨fun h => And.intro (dom_natCast _) (h₁ h.2), fun h => by simpa only [coe_add_get] using add_le_add_left (hβ‚‚ _) c⟩ } instance semilatticeSup : SemilatticeSup PartENat := { PartENat.partialOrder with sup := (Β· βŠ” Β·) le_sup_left := fun _ _ => ⟨And.left, fun _ => le_sup_left⟩ le_sup_right := fun _ _ => ⟨And.right, fun _ => le_sup_right⟩ sup_le := fun _ _ _ ⟨hx₁, hxβ‚‚βŸ© ⟨hy₁, hyβ‚‚βŸ© => ⟨fun hz => ⟨hx₁ hz, hy₁ hz⟩, fun _ => sup_le (hxβ‚‚ _) (hyβ‚‚ _)⟩ } instance orderBot : OrderBot PartENat where bot := βŠ₯ bot_le _ := ⟨fun _ => trivial, fun _ => Nat.zero_le _⟩ instance orderTop : OrderTop PartENat where top := ⊀ le_top _ := ⟨fun h => False.elim h, fun hy => False.elim hy⟩ instance : ZeroLEOneClass PartENat where zero_le_one := bot_le /-- Alias of `Nat.cast_le` specialized to `PartENat` --/ theorem coe_le_coe {x y : β„•} : (x : PartENat) ≀ y ↔ x ≀ y := Nat.cast_le /-- Alias of `Nat.cast_lt` specialized to `PartENat` --/ theorem coe_lt_coe {x y : β„•} : (x : PartENat) < y ↔ x < y := Nat.cast_lt @[simp] theorem get_le_get {x y : PartENat} {hx : x.Dom} {hy : y.Dom} : x.get hx ≀ y.get hy ↔ x ≀ y := by conv => lhs rw [← coe_le_coe, natCast_get, natCast_get] theorem le_coe_iff (x : PartENat) (n : β„•) : x ≀ n ↔ βˆƒ h : x.Dom, x.get h ≀ n := by show (βˆƒ h : True β†’ x.Dom, _) ↔ βˆƒ h : x.Dom, x.get h ≀ n simp only [forall_prop_of_true, dom_natCast, get_natCast'] theorem lt_coe_iff (x : PartENat) (n : β„•) : x < n ↔ βˆƒ h : x.Dom, x.get h < n := by simp only [lt_def, forall_prop_of_true, get_natCast', dom_natCast] theorem coe_le_iff (n : β„•) (x : PartENat) : (n : PartENat) ≀ x ↔ βˆ€ h : x.Dom, n ≀ x.get h := by rw [← some_eq_natCast] simp only [le_def, exists_prop_of_true, dom_some, forall_true_iff] rfl theorem coe_lt_iff (n : β„•) (x : PartENat) : (n : PartENat) < x ↔ βˆ€ h : x.Dom, n < x.get h := by rw [← some_eq_natCast] simp only [lt_def, exists_prop_of_true, dom_some, forall_true_iff] rfl nonrec theorem eq_zero_iff {x : PartENat} : x = 0 ↔ x ≀ 0 := eq_bot_iff theorem ne_zero_iff {x : PartENat} : x β‰  0 ↔ βŠ₯ < x := bot_lt_iff_ne_bot.symm theorem dom_of_lt {x y : PartENat} : x < y β†’ x.Dom := PartENat.casesOn x not_top_lt fun _ _ => dom_natCast _ theorem top_eq_none : (⊀ : PartENat) = Part.none := rfl @[simp] theorem natCast_lt_top (x : β„•) : (x : PartENat) < ⊀ := Ne.lt_top fun h => absurd (congr_arg Dom h) <| by simp only [dom_natCast]; exact true_ne_false @[simp] theorem zero_lt_top : (0 : PartENat) < ⊀ := natCast_lt_top 0 @[simp] theorem one_lt_top : (1 : PartENat) < ⊀ := natCast_lt_top 1 -- See note [no_index around OfNat.ofNat] @[simp] theorem ofNat_lt_top (x : β„•) [x.AtLeastTwo] : (no_index (OfNat.ofNat x : PartENat)) < ⊀ := natCast_lt_top x @[simp] theorem natCast_ne_top (x : β„•) : (x : PartENat) β‰  ⊀ := ne_of_lt (natCast_lt_top x) @[simp] theorem zero_ne_top : (0 : PartENat) β‰  ⊀ := natCast_ne_top 0 @[simp] theorem one_ne_top : (1 : PartENat) β‰  ⊀ := natCast_ne_top 1 -- See note [no_index around OfNat.ofNat] @[simp] theorem ofNat_ne_top (x : β„•) [x.AtLeastTwo] : (no_index (OfNat.ofNat x : PartENat)) β‰  ⊀ := natCast_ne_top x theorem not_isMax_natCast (x : β„•) : Β¬IsMax (x : PartENat) := not_isMax_of_lt (natCast_lt_top x) theorem ne_top_iff {x : PartENat} : x β‰  ⊀ ↔ βˆƒ n : β„•, x = n := by simpa only [← some_eq_natCast] using Part.ne_none_iff theorem ne_top_iff_dom {x : PartENat} : x β‰  ⊀ ↔ x.Dom := by classical exact not_iff_comm.1 Part.eq_none_iff'.symm theorem not_dom_iff_eq_top {x : PartENat} : Β¬x.Dom ↔ x = ⊀ := Iff.not_left ne_top_iff_dom.symm theorem ne_top_of_lt {x y : PartENat} (h : x < y) : x β‰  ⊀ := ne_of_lt <| lt_of_lt_of_le h le_top theorem eq_top_iff_forall_lt (x : PartENat) : x = ⊀ ↔ βˆ€ n : β„•, (n : PartENat) < x := by constructor Β· rintro rfl n exact natCast_lt_top _ Β· contrapose! rw [ne_top_iff] rintro ⟨n, rfl⟩ exact ⟨n, irrefl _⟩ theorem eq_top_iff_forall_le (x : PartENat) : x = ⊀ ↔ βˆ€ n : β„•, (n : PartENat) ≀ x := (eq_top_iff_forall_lt x).trans ⟨fun h n => (h n).le, fun h n => lt_of_lt_of_le (coe_lt_coe.mpr n.lt_succ_self) (h (n + 1))⟩ theorem pos_iff_one_le {x : PartENat} : 0 < x ↔ 1 ≀ x := PartENat.casesOn x (by simp only [iff_true_iff, le_top, natCast_lt_top, ← @Nat.cast_zero PartENat]) fun n => by rw [← Nat.cast_zero, ← Nat.cast_one, PartENat.coe_lt_coe, PartENat.coe_le_coe] rfl instance isTotal : IsTotal PartENat (Β· ≀ Β·) where total x y := PartENat.casesOn (P := fun z => z ≀ y ∨ y ≀ z) x (Or.inr le_top) (PartENat.casesOn y (fun _ => Or.inl le_top) fun x y => (le_total x y).elim (Or.inr ∘ coe_le_coe.2) (Or.inl ∘ coe_le_coe.2)) noncomputable instance linearOrder : LinearOrder PartENat := { PartENat.partialOrder with le_total := IsTotal.total decidableLE := Classical.decRel _ max := (Β· βŠ” Β·) -- Porting note: was `max_def := @sup_eq_maxDefault _ _ (id _) _ }` max_def := fun a b => by change (fun a b => a βŠ” b) a b = _ rw [@sup_eq_maxDefault PartENat _ (id _) _] rfl } instance boundedOrder : BoundedOrder PartENat := { PartENat.orderTop, PartENat.orderBot with } noncomputable instance lattice : Lattice PartENat := { PartENat.semilatticeSup with inf := min inf_le_left := min_le_left inf_le_right := min_le_right le_inf := fun _ _ _ => le_min } noncomputable instance : CanonicallyOrderedAddCommMonoid PartENat := { PartENat.semilatticeSup, PartENat.orderBot, PartENat.orderedAddCommMonoid with le_self_add := fun a b => PartENat.casesOn b (le_top.trans_eq (add_top _).symm) fun b => PartENat.casesOn a (top_add _).ge fun a => (coe_le_coe.2 le_self_add).trans_eq (Nat.cast_add _ _) exists_add_of_le := fun {a b} => PartENat.casesOn b (fun _ => ⟨⊀, (add_top _).symm⟩) fun b => PartENat.casesOn a (fun h => ((natCast_lt_top _).not_le h).elim) fun a h => ⟨(b - a : β„•), by rw [← Nat.cast_add, natCast_inj, add_comm, tsub_add_cancel_of_le (coe_le_coe.1 h)]⟩ } theorem eq_natCast_sub_of_add_eq_natCast {x y : PartENat} {n : β„•} (h : x + y = n) : x = ↑(n - y.get (dom_of_le_natCast ((le_add_left le_rfl).trans_eq h))) := by lift x to β„• using dom_of_le_natCast ((le_add_right le_rfl).trans_eq h) lift y to β„• using dom_of_le_natCast ((le_add_left le_rfl).trans_eq h) rw [← Nat.cast_add, natCast_inj] at h rw [get_natCast, natCast_inj, eq_tsub_of_add_eq h] protected theorem add_lt_add_right {x y z : PartENat} (h : x < y) (hz : z β‰  ⊀) : x + z < y + z := by rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩ rcases ne_top_iff.mp hz with ⟨k, rfl⟩ induction' y using PartENat.casesOn with n Β· rw [top_add] -- Porting note: was apply_mod_cast natCast_lt_top norm_cast; apply natCast_lt_top norm_cast at h -- Porting note: was `apply_mod_cast add_lt_add_right h` norm_cast; apply add_lt_add_right h protected theorem add_lt_add_iff_right {x y z : PartENat} (hz : z β‰  ⊀) : x + z < y + z ↔ x < y := ⟨lt_of_add_lt_add_right, fun h => PartENat.add_lt_add_right h hz⟩ protected theorem add_lt_add_iff_left {x y z : PartENat} (hz : z β‰  ⊀) : z + x < z + y ↔ x < y := by rw [add_comm z, add_comm z, PartENat.add_lt_add_iff_right hz] protected theorem lt_add_iff_pos_right {x y : PartENat} (hx : x β‰  ⊀) : x < x + y ↔ 0 < y := by conv_rhs => rw [← PartENat.add_lt_add_iff_left hx] rw [add_zero] theorem lt_add_one {x : PartENat} (hx : x β‰  ⊀) : x < x + 1 := by rw [PartENat.lt_add_iff_pos_right hx] norm_cast theorem le_of_lt_add_one {x y : PartENat} (h : x < y + 1) : x ≀ y := by induction' y using PartENat.casesOn with n Β· apply le_top rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩ -- Porting note: was `apply_mod_cast Nat.le_of_lt_succ; apply_mod_cast h` norm_cast; apply Nat.le_of_lt_succ; norm_cast at h theorem add_one_le_of_lt {x y : PartENat} (h : x < y) : x + 1 ≀ y := by induction' y using PartENat.casesOn with n Β· apply le_top rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩ -- Porting note: was `apply_mod_cast Nat.succ_le_of_lt; apply_mod_cast h` norm_cast; apply Nat.succ_le_of_lt; norm_cast at h theorem add_one_le_iff_lt {x y : PartENat} (hx : x β‰  ⊀) : x + 1 ≀ y ↔ x < y := by refine ⟨fun h => ?_, add_one_le_of_lt⟩ rcases ne_top_iff.mp hx with ⟨m, rfl⟩ induction' y using PartENat.casesOn with n Β· apply natCast_lt_top -- Porting note: was `apply_mod_cast Nat.lt_of_succ_le; apply_mod_cast h` norm_cast; apply Nat.lt_of_succ_le; norm_cast at h theorem coe_succ_le_iff {n : β„•} {e : PartENat} : ↑n.succ ≀ e ↔ ↑n < e := by rw [Nat.succ_eq_add_one n, Nat.cast_add, Nat.cast_one, add_one_le_iff_lt (natCast_ne_top n)] theorem lt_add_one_iff_lt {x y : PartENat} (hx : x β‰  ⊀) : x < y + 1 ↔ x ≀ y := by refine ⟨le_of_lt_add_one, fun h => ?_⟩ rcases ne_top_iff.mp hx with ⟨m, rfl⟩ induction' y using PartENat.casesOn with n Β· rw [top_add] apply natCast_lt_top -- Porting note: was `apply_mod_cast Nat.lt_succ_of_le; apply_mod_cast h` norm_cast; apply Nat.lt_succ_of_le; norm_cast at h lemma lt_coe_succ_iff_le {x : PartENat} {n : β„•} (hx : x β‰  ⊀) : x < n.succ ↔ x ≀ n := by rw [Nat.succ_eq_add_one n, Nat.cast_add, Nat.cast_one, lt_add_one_iff_lt hx] theorem add_eq_top_iff {a b : PartENat} : a + b = ⊀ ↔ a = ⊀ ∨ b = ⊀ := by refine PartENat.casesOn a ?_ ?_ <;> refine PartENat.casesOn b ?_ ?_ <;> simp [top_add, add_top] simp only [← Nat.cast_add, PartENat.natCast_ne_top, forall_const, not_false_eq_true] protected theorem add_right_cancel_iff {a b c : PartENat} (hc : c β‰  ⊀) : a + c = b + c ↔ a = b := by rcases ne_top_iff.1 hc with ⟨c, rfl⟩ refine PartENat.casesOn a ?_ ?_ <;> refine PartENat.casesOn b ?_ ?_ <;> simp [add_eq_top_iff, natCast_ne_top, @eq_comm _ (⊀ : PartENat), top_add] simp only [← Nat.cast_add, add_left_cancel_iff, PartENat.natCast_inj, add_comm, forall_const] protected theorem add_left_cancel_iff {a b c : PartENat} (ha : a β‰  ⊀) : a + b = a + c ↔ b = c := by rw [add_comm a, add_comm a, PartENat.add_right_cancel_iff ha] section WithTop /-- Computably converts a `PartENat` to a `β„•βˆž`. -/ def toWithTop (x : PartENat) [Decidable x.Dom] : β„•βˆž := x.toOption theorem toWithTop_top : have : Decidable (⊀ : PartENat).Dom := Part.noneDecidable toWithTop ⊀ = ⊀ := rfl @[simp] theorem toWithTop_top' {h : Decidable (⊀ : PartENat).Dom} : toWithTop ⊀ = ⊀ := by convert toWithTop_top theorem toWithTop_zero : have : Decidable (0 : PartENat).Dom := someDecidable 0 toWithTop 0 = 0 := rfl @[simp] theorem toWithTop_zero' {h : Decidable (0 : PartENat).Dom} : toWithTop 0 = 0 := by convert toWithTop_zero theorem toWithTop_one : have : Decidable (1 : PartENat).Dom := someDecidable 1 toWithTop 1 = 1 := rfl @[simp] theorem toWithTop_one' {h : Decidable (1 : PartENat).Dom} : toWithTop 1 = 1 := by convert toWithTop_one theorem toWithTop_some (n : β„•) : toWithTop (some n) = n := rfl theorem toWithTop_natCast (n : β„•) {_ : Decidable (n : PartENat).Dom} : toWithTop n = n := by simp only [← toWithTop_some] congr @[simp] theorem toWithTop_natCast' (n : β„•) {_ : Decidable (n : PartENat).Dom} : toWithTop (n : PartENat) = n := by rw [toWithTop_natCast n] @[simp] theorem toWithTop_ofNat (n : β„•) [n.AtLeastTwo] {_ : Decidable (OfNat.ofNat n : PartENat).Dom} : toWithTop (no_index (OfNat.ofNat n : PartENat)) = OfNat.ofNat n := toWithTop_natCast' n -- Porting note: statement changed. Mathlib 3 statement was -- ``` -- @[simp] lemma to_with_top_le {x y : part_enat} : -- Ξ  [decidable x.dom] [decidable y.dom], by exactI to_with_top x ≀ to_with_top y ↔ x ≀ y := -- ``` -- This used to be really slow to typecheck when the definition of `ENat` -- was still `deriving AddCommMonoidWithOne`. Now that I removed that it is fine. -- (The problem was that the last `simp` got stuck at `CharZero β„•βˆž β‰Ÿ CharZero β„•βˆž` where -- one side used `instENatAddCommMonoidWithOne` and the other used -- `NonAssocSemiring.toAddCommMonoidWithOne`. Now the former doesn't exist anymore.) @[simp] theorem toWithTop_le {x y : PartENat} [hx : Decidable x.Dom] [hy : Decidable y.Dom] : toWithTop x ≀ toWithTop y ↔ x ≀ y := by induction y using PartENat.casesOn generalizing hy Β· simp induction x using PartENat.casesOn generalizing hx Β· simp Β· simp -- Porting note: this takes too long. /- Porting note: As part of the investigation above, I noticed that Lean4 does not find the following two instances which it could find in Lean3 automatically: ``` #synth Decidable (⊀ : PartENat).Dom variable {n : β„•} #synth Decidable (n : PartENat).Dom ``` -/ @[simp] theorem toWithTop_lt {x y : PartENat} [Decidable x.Dom] [Decidable y.Dom] : toWithTop x < toWithTop y ↔ x < y := lt_iff_lt_of_le_iff_le toWithTop_le end WithTop -- Porting note: new, extracted from `withTopEquiv`. /-- Coercion from `β„•βˆž` to `PartENat`. -/ @[coe] def ofENat : β„•βˆž β†’ PartENat := fun x => match x with | Option.none => none | Option.some n => some n -- Porting note (#10754): new instance instance : Coe β„•βˆž PartENat := ⟨ofENat⟩ -- Porting note: new. This could probably be moved to tests or removed. example (n : β„•) : ((n : β„•βˆž) : PartENat) = ↑n := rfl @[simp, norm_cast] lemma ofENat_top : ofENat ⊀ = ⊀ := rfl @[simp, norm_cast] lemma ofENat_coe (n : β„•) : ofENat n = n := rfl @[simp, norm_cast] theorem ofENat_zero : ofENat 0 = 0 := rfl @[simp, norm_cast] theorem ofENat_one : ofENat 1 = 1 := rfl @[simp, norm_cast] theorem ofENat_ofNat (n : Nat) [n.AtLeastTwo] : ofENat (no_index (OfNat.ofNat n)) = OfNat.ofNat n := rfl @[simp, norm_cast] theorem toWithTop_ofENat (n : β„•βˆž) {_ : Decidable (n : PartENat).Dom} : toWithTop (↑n) = n := by cases n with | top => simp | coe n => simp @[simp, norm_cast] theorem ofENat_toWithTop (x : PartENat) {_ : Decidable (x : PartENat).Dom} : toWithTop x = x := by induction x using PartENat.casesOn <;> simp @[simp, norm_cast] theorem ofENat_le {x y : β„•βˆž} : ofENat x ≀ ofENat y ↔ x ≀ y := by classical rw [← toWithTop_le, toWithTop_ofENat, toWithTop_ofENat] @[simp, norm_cast] theorem ofENat_lt {x y : β„•βˆž} : ofENat x < ofENat y ↔ x < y := by classical rw [← toWithTop_lt, toWithTop_ofENat, toWithTop_ofENat] section WithTopEquiv open scoped Classical @[simp] theorem toWithTop_add {x y : PartENat} : toWithTop (x + y) = toWithTop x + toWithTop y := by refine PartENat.casesOn y ?_ ?_ <;> refine PartENat.casesOn x ?_ ?_ -- Porting note: was `simp [← Nat.cast_add, ← ENat.coe_add]` Β· simp only [add_top, toWithTop_top', _root_.add_top] Β· simp only [add_top, toWithTop_top', toWithTop_natCast', _root_.add_top, forall_const] Β· simp only [top_add, toWithTop_top', toWithTop_natCast', _root_.top_add, forall_const] Β· simp_rw [toWithTop_natCast', ← Nat.cast_add, toWithTop_natCast', forall_const] /-- `Equiv` between `PartENat` and `β„•βˆž` (for the order isomorphism see `withTopOrderIso`). -/ @[simps] noncomputable def withTopEquiv : PartENat ≃ β„•βˆž where toFun x := toWithTop x invFun x := ↑x left_inv x := by simp right_inv x := by simp theorem withTopEquiv_top : withTopEquiv ⊀ = ⊀ := by simp theorem withTopEquiv_natCast (n : Nat) : withTopEquiv n = n := by simp theorem withTopEquiv_zero : withTopEquiv 0 = 0 := by simp theorem withTopEquiv_one : withTopEquiv 1 = 1 := by simp theorem withTopEquiv_ofNat (n : Nat) [n.AtLeastTwo] : withTopEquiv (no_index (OfNat.ofNat n)) = OfNat.ofNat n := by simp theorem withTopEquiv_le {x y : PartENat} : withTopEquiv x ≀ withTopEquiv y ↔ x ≀ y := by simp theorem withTopEquiv_lt {x y : PartENat} : withTopEquiv x < withTopEquiv y ↔ x < y := by simp theorem withTopEquiv_symm_top : withTopEquiv.symm ⊀ = ⊀ := by simp theorem withTopEquiv_symm_coe (n : Nat) : withTopEquiv.symm n = n := by simp theorem withTopEquiv_symm_zero : withTopEquiv.symm 0 = 0 := by simp theorem withTopEquiv_symm_one : withTopEquiv.symm 1 = 1 := by simp theorem withTopEquiv_symm_ofNat (n : Nat) [n.AtLeastTwo] : withTopEquiv.symm (no_index (OfNat.ofNat n)) = OfNat.ofNat n := by simp theorem withTopEquiv_symm_le {x y : β„•βˆž} : withTopEquiv.symm x ≀ withTopEquiv.symm y ↔ x ≀ y := by simp theorem withTopEquiv_symm_lt {x y : β„•βˆž} : withTopEquiv.symm x < withTopEquiv.symm y ↔ x < y := by simp /-- `toWithTop` induces an order isomorphism between `PartENat` and `β„•βˆž`. -/ noncomputable def withTopOrderIso : PartENat ≃o β„•βˆž := { withTopEquiv with map_rel_iff' := @fun _ _ => withTopEquiv_le } /-- `toWithTop` induces an additive monoid isomorphism between `PartENat` and `β„•βˆž`. -/ noncomputable def withTopAddEquiv : PartENat ≃+ β„•βˆž := { withTopEquiv with map_add' := fun x y => by simp only [withTopEquiv] exact toWithTop_add } end WithTopEquiv theorem lt_wf : @WellFounded PartENat (Β· < Β·) := by classical change WellFounded fun a b : PartENat => a < b simp_rw [← withTopEquiv_lt] exact InvImage.wf _ wellFounded_lt instance : WellFoundedLT PartENat := ⟨lt_wf⟩ instance isWellOrder : IsWellOrder PartENat (Β· < Β·) := {} instance wellFoundedRelation : WellFoundedRelation PartENat := ⟨(Β· < Β·), lt_wf⟩ section Find variable (P : β„• β†’ Prop) [DecidablePred P] /-- The smallest `PartENat` satisfying a (decidable) predicate `P : β„• β†’ Prop` -/ def find : PartENat := βŸ¨βˆƒ n, P n, Nat.find⟩ @[simp] theorem find_get (h : (find P).Dom) : (find P).get h = Nat.find h := rfl theorem find_dom (h : βˆƒ n, P n) : (find P).Dom := h theorem lt_find (n : β„•) (h : βˆ€ m ≀ n, Β¬P m) : (n : PartENat) < find P := by rw [coe_lt_iff] intro h₁ rw [find_get] have hβ‚‚ := @Nat.find_spec P _ h₁ revert hβ‚‚ contrapose! exact h _ theorem lt_find_iff (n : β„•) : (n : PartENat) < find P ↔ βˆ€ m ≀ n, Β¬P m := by refine ⟨?_, lt_find P n⟩ intro h m hm by_cases H : (find P).Dom Β· apply Nat.find_min H rw [coe_lt_iff] at h specialize h H exact lt_of_le_of_lt hm h Β· exact not_exists.mp H m theorem find_le (n : β„•) (h : P n) : find P ≀ n := by rw [le_coe_iff] exact ⟨⟨_, h⟩, @Nat.find_min' P _ _ _ h⟩ theorem find_eq_top_iff : find P = ⊀ ↔ βˆ€ n, Β¬P n := (eq_top_iff_forall_lt _).trans ⟨fun h n => (lt_find_iff P n).mp (h n) _ le_rfl, fun h n => lt_find P n fun _ _ => h _⟩ end Find noncomputable instance : LinearOrderedAddCommMonoidWithTop PartENat := { PartENat.linearOrder, PartENat.orderedAddCommMonoid, PartENat.orderTop with top_add' := top_add } noncomputable instance : CompleteLinearOrder PartENat := { lattice, withTopOrderIso.symm.toGaloisInsertion.liftCompleteLattice, linearOrder, LinearOrder.toBiheytingAlgebra with } end PartENat
Data\Nat\Periodic.lean
/- Copyright (c) 2021 Bolton Bailey. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bolton Bailey -/ import Mathlib.Algebra.Periodic import Mathlib.Data.Nat.Count import Mathlib.Data.Nat.GCD.Basic import Mathlib.Order.Interval.Finset.Nat /-! # Periodic Functions on β„• This file identifies a few functions on `β„•` which are periodic, and also proves a lemma about periodic predicates which helps determine their cardinality when filtering intervals over them. -/ namespace Nat open Nat Function theorem periodic_gcd (a : β„•) : Periodic (gcd a) a := by simp only [forall_const, gcd_add_self_right, eq_self_iff_true, Periodic] theorem periodic_coprime (a : β„•) : Periodic (Coprime a) a := by simp only [coprime_add_self_right, forall_const, iff_self_iff, eq_iff_iff, Periodic] theorem periodic_mod (a : β„•) : Periodic (fun n => n % a) a := by simp only [forall_const, eq_self_iff_true, add_mod_right, Periodic] theorem _root_.Function.Periodic.map_mod_nat {Ξ± : Type*} {f : β„• β†’ Ξ±} {a : β„•} (hf : Periodic f a) : βˆ€ n, f (n % a) = f n := fun n => by conv_rhs => rw [← Nat.mod_add_div n a, mul_comm, ← Nat.nsmul_eq_mul, hf.nsmul] section Multiset open Multiset /-- An interval of length `a` filtered over a periodic predicate of period `a` has cardinality equal to the number naturals below `a` for which `p a` is true. -/ theorem filter_multiset_Ico_card_eq_of_periodic (n a : β„•) (p : β„• β†’ Prop) [DecidablePred p] (pp : Periodic p a) : card (filter p (Ico n (n + a))) = a.count p := by rw [count_eq_card_filter_range, Finset.card, Finset.filter_val, Finset.range_val, ← multiset_Ico_map_mod n, ← map_count_True_eq_filter_card, ← map_count_True_eq_filter_card, map_map] congr; funext n exact (Function.Periodic.map_mod_nat pp n).symm end Multiset section Finset open Finset /-- An interval of length `a` filtered over a periodic predicate of period `a` has cardinality equal to the number naturals below `a` for which `p a` is true. -/ theorem filter_Ico_card_eq_of_periodic (n a : β„•) (p : β„• β†’ Prop) [DecidablePred p] (pp : Periodic p a) : ((Ico n (n + a)).filter p).card = a.count p := filter_multiset_Ico_card_eq_of_periodic n a p pp end Finset end Nat
Data\Nat\PrimeFin.lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import Mathlib.Data.Countable.Defs import Mathlib.Data.Nat.Factors import Mathlib.Data.Set.Finite import Mathlib.Data.Nat.Prime.Basic /-! # Prime numbers This file contains some results about prime numbers which depend on finiteness of sets. -/ open Finset namespace Nat variable {a b k m n p : β„•} /-- A version of `Nat.exists_infinite_primes` using the `Set.Infinite` predicate. -/ theorem infinite_setOf_prime : { p | Prime p }.Infinite := Set.infinite_of_not_bddAbove not_bddAbove_setOf_prime instance Primes.infinite : Infinite Primes := infinite_setOf_prime.to_subtype instance Primes.countable : Countable Primes := ⟨⟨coeNat.coe, coe_nat_injective⟩⟩ /-- The prime factors of a natural number as a finset. -/ def primeFactors (n : β„•) : Finset β„• := n.primeFactorsList.toFinset @[simp] lemma toFinset_factors (n : β„•) : n.primeFactorsList.toFinset = n.primeFactors := rfl @[simp] lemma mem_primeFactors : p ∈ n.primeFactors ↔ p.Prime ∧ p ∣ n ∧ n β‰  0 := by simp_rw [← toFinset_factors, List.mem_toFinset, mem_primeFactorsList'] lemma mem_primeFactors_of_ne_zero (hn : n β‰  0) : p ∈ n.primeFactors ↔ p.Prime ∧ p ∣ n := by simp [hn] lemma primeFactors_mono (hmn : m ∣ n) (hn : n β‰  0) : primeFactors m βŠ† primeFactors n := by simp only [subset_iff, mem_primeFactors, and_imp] exact fun p hp hpm _ ↦ ⟨hp, hpm.trans hmn, hn⟩ lemma mem_primeFactors_iff_mem_primeFactorsList : p ∈ n.primeFactors ↔ p ∈ n.primeFactorsList := by simp only [primeFactors, List.mem_toFinset] @[deprecated (since := "2024-07-16")] alias mem_primeFactors_iff_mem_factors := mem_primeFactors_iff_mem_primeFactorsList lemma prime_of_mem_primeFactors (hp : p ∈ n.primeFactors) : p.Prime := (mem_primeFactors.1 hp).1 lemma dvd_of_mem_primeFactors (hp : p ∈ n.primeFactors) : p ∣ n := (mem_primeFactors.1 hp).2.1 lemma pos_of_mem_primeFactors (hp : p ∈ n.primeFactors) : 0 < p := (prime_of_mem_primeFactors hp).pos lemma le_of_mem_primeFactors (h : p ∈ n.primeFactors) : p ≀ n := le_of_dvd (mem_primeFactors.1 h).2.2.bot_lt <| dvd_of_mem_primeFactors h @[simp] lemma primeFactors_zero : primeFactors 0 = βˆ… := by ext simp @[simp] lemma primeFactors_one : primeFactors 1 = βˆ… := by ext simpa using Prime.ne_one @[simp] lemma primeFactors_eq_empty : n.primeFactors = βˆ… ↔ n = 0 ∨ n = 1 := by constructor Β· contrapose! rintro hn obtain ⟨p, hp, hpn⟩ := exists_prime_and_dvd hn.2 exact Nonempty.ne_empty <| ⟨_, mem_primeFactors.2 ⟨hp, hpn, hn.1⟩⟩ Β· rintro (rfl | rfl) <;> simp @[simp] lemma nonempty_primeFactors {n : β„•} : n.primeFactors.Nonempty ↔ 1 < n := by rw [← not_iff_not, Finset.not_nonempty_iff_eq_empty, primeFactors_eq_empty, not_lt, Nat.le_one_iff_eq_zero_or_eq_one] @[simp] protected lemma Prime.primeFactors (hp : p.Prime) : p.primeFactors = {p} := by simp [Nat.primeFactors, primeFactorsList_prime hp] lemma primeFactors_mul (ha : a β‰  0) (hb : b β‰  0) : (a * b).primeFactors = a.primeFactors βˆͺ b.primeFactors := by ext; simp only [Finset.mem_union, mem_primeFactors_iff_mem_primeFactorsList, mem_primeFactorsList_mul ha hb] lemma Coprime.primeFactors_mul {a b : β„•} (hab : Coprime a b) : (a * b).primeFactors = a.primeFactors βˆͺ b.primeFactors := (List.toFinset.ext <| mem_primeFactorsList_mul_of_coprime hab).trans <| List.toFinset_union _ _ lemma primeFactors_gcd (ha : a β‰  0) (hb : b β‰  0) : (a.gcd b).primeFactors = a.primeFactors ∩ b.primeFactors := by ext; simp [dvd_gcd_iff, ha, hb, gcd_ne_zero_left ha]; aesop @[simp] lemma disjoint_primeFactors (ha : a β‰  0) (hb : b β‰  0) : Disjoint a.primeFactors b.primeFactors ↔ Coprime a b := by simp [disjoint_iff_inter_eq_empty, coprime_iff_gcd_eq_one, ← primeFactors_gcd, gcd_ne_zero_left, ha, hb] protected lemma Coprime.disjoint_primeFactors (hab : Coprime a b) : Disjoint a.primeFactors b.primeFactors := List.disjoint_toFinset_iff_disjoint.2 <| coprime_primeFactorsList_disjoint hab lemma primeFactors_pow_succ (n k : β„•) : (n ^ (k + 1)).primeFactors = n.primeFactors := by rcases eq_or_ne n 0 with (rfl | hn) Β· simp induction' k with k ih Β· simp Β· rw [pow_succ', primeFactors_mul hn (pow_ne_zero _ hn), ih, Finset.union_idempotent] lemma primeFactors_pow (n : β„•) (hk : k β‰  0) : (n ^ k).primeFactors = n.primeFactors := by cases k Β· simp at hk rw [primeFactors_pow_succ] /-- The only prime divisor of positive prime power `p^k` is `p` itself -/ lemma primeFactors_prime_pow (hk : k β‰  0) (hp : Prime p) : (p ^ k).primeFactors = {p} := by simp [primeFactors_pow p hk, hp] end Nat
Data\Nat\PSub.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Algebra.Group.Basic import Mathlib.Algebra.Group.Nat /-! # Partial predecessor and partial subtraction on the natural numbers The usual definition of natural number subtraction (`Nat.sub`) returns 0 as a "garbage value" for `a - b` when `a < b`. Similarly, `Nat.pred 0` is defined to be `0`. The functions in this file wrap the result in an `Option` type instead: ## Main definitions - `Nat.ppred`: a partial predecessor operation - `Nat.psub`: a partial subtraction operation -/ namespace Nat /-- Partial predecessor operation. Returns `ppred n = some m` if `n = m + 1`, otherwise `none`. -/ def ppred : β„• β†’ Option β„• | 0 => none | n + 1 => some n @[simp] theorem ppred_zero : ppred 0 = none := rfl @[simp] theorem ppred_succ {n : β„•} : ppred (succ n) = some n := rfl /-- Partial subtraction operation. Returns `psub m n = some k` if `m = n + k`, otherwise `none`. -/ def psub (m : β„•) : β„• β†’ Option β„• | 0 => some m | n + 1 => psub m n >>= ppred @[simp] theorem psub_zero {m : β„•} : psub m 0 = some m := rfl @[simp] theorem psub_succ {m n : β„•} : psub m (succ n) = psub m n >>= ppred := rfl theorem pred_eq_ppred (n : β„•) : pred n = (ppred n).getD 0 := by cases n <;> rfl theorem sub_eq_psub (m : β„•) : βˆ€ n, m - n = (psub m n).getD 0 | 0 => rfl | n + 1 => (pred_eq_ppred (m - n)).trans <| by rw [sub_eq_psub m n, psub]; cases psub m n <;> rfl @[simp] theorem ppred_eq_some {m : β„•} : βˆ€ {n}, ppred n = some m ↔ succ m = n | 0 => by constructor <;> intro h <;> contradiction | n + 1 => by constructor <;> intro h <;> injection h <;> subst m <;> rfl -- Porting note: `contradiction` required an `intro` for the goals -- `ppred (n + 1) = none β†’ n + 1 = 0` and `n + 1 = 0 β†’ ppred (n + 1) = none` @[simp] theorem ppred_eq_none : βˆ€ {n : β„•}, ppred n = none ↔ n = 0 | 0 => by simp | n + 1 => by constructor <;> intro <;> contradiction theorem psub_eq_some {m : β„•} : βˆ€ {n k}, psub m n = some k ↔ k + n = m | 0, k => by simp [eq_comm] | n + 1, k => by apply Option.bind_eq_some.trans simp only [psub_eq_some, ppred_eq_some] simp [add_comm, add_left_comm] theorem psub_eq_none {m n : β„•} : psub m n = none ↔ m < n := by cases s : psub m n <;> simp [eq_comm] Β· show m < n refine lt_of_not_ge fun h => ?_ cases' le.dest h with k e injection s.symm.trans (psub_eq_some.2 <| (add_comm _ _).trans e) Β· show n ≀ m rw [← psub_eq_some.1 s] apply Nat.le_add_left theorem ppred_eq_pred {n} (h : 0 < n) : ppred n = some (pred n) := ppred_eq_some.2 <| succ_pred_eq_of_pos h theorem psub_eq_sub {m n} (h : n ≀ m) : psub m n = some (m - n) := psub_eq_some.2 <| Nat.sub_add_cancel h -- Porting note: we only have the simp lemma `Option.bind_some` which uses `Option.bind` not `>>=` theorem psub_add (m n k) : psub m (n + k) = (do psub (← psub m n) k) := by induction k with | zero => simp only [zero_eq, add_zero, psub_zero, Option.bind_eq_bind, Option.bind_some] | succ n ih => simp only [ih, add_succ, psub_succ, bind_assoc] /-- Same as `psub`, but with a more efficient implementation. -/ @[inline] def psub' (m n : β„•) : Option β„• := if n ≀ m then some (m - n) else none theorem psub'_eq_psub (m n) : psub' m n = psub m n := by rw [psub'] split_ifs with h Β· exact (psub_eq_sub h).symm Β· exact (psub_eq_none.2 (not_le.1 h)).symm end Nat
Data\Nat\Set.lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Data.Set.Image /-! ### Recursion on the natural numbers and `Set.range` -/ namespace Nat section Set open Set theorem zero_union_range_succ : {0} βˆͺ range succ = univ := by ext n cases n <;> simp @[simp] protected theorem range_succ : range succ = { i | 0 < i } := by ext (_ | i) <;> simp [succ_pos, succ_ne_zero, Set.mem_setOf] variable {Ξ± : Type*} theorem range_of_succ (f : β„• β†’ Ξ±) : {f 0} βˆͺ range (f ∘ succ) = range f := by rw [← image_singleton, range_comp, ← image_union, zero_union_range_succ, image_univ] theorem range_rec {Ξ± : Type*} (x : Ξ±) (f : β„• β†’ Ξ± β†’ Ξ±) : (Set.range fun n => Nat.rec x f n : Set Ξ±) = {x} βˆͺ Set.range fun n => Nat.rec (f 0 x) (f ∘ succ) n := by convert (range_of_succ (fun n => Nat.rec x f n : β„• β†’ Ξ±)).symm using 4 dsimp rename_i n induction' n with n ihn Β· rfl Β· dsimp at ihn ⊒ rw [ihn] theorem range_casesOn {Ξ± : Type*} (x : Ξ±) (f : β„• β†’ Ξ±) : (Set.range fun n => Nat.casesOn n x f : Set Ξ±) = {x} βˆͺ Set.range f := (range_of_succ _).symm end Set end Nat
Data\Nat\Size.lean
/- Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import Mathlib.Data.Nat.Bits import Mathlib.Order.Lattice /-! Lemmas about `size`. -/ namespace Nat /-! ### `shiftLeft` and `shiftRight` -/ section theorem shiftLeft_eq_mul_pow (m) : βˆ€ n, m <<< n = m * 2 ^ n := shiftLeft_eq _ theorem shiftLeft'_tt_eq_mul_pow (m) : βˆ€ n, shiftLeft' true m n + 1 = (m + 1) * 2 ^ n | 0 => by simp [shiftLeft', pow_zero, Nat.one_mul] | k + 1 => by rw [shiftLeft', bit_val, cond_true, add_assoc, ← Nat.mul_add_one, shiftLeft'_tt_eq_mul_pow m k, mul_left_comm, mul_comm 2, pow_succ] end theorem shiftLeft'_ne_zero_left (b) {m} (h : m β‰  0) (n) : shiftLeft' b m n β‰  0 := by induction n <;> simp [bit_ne_zero, shiftLeft', *] theorem shiftLeft'_tt_ne_zero (m) : βˆ€ {n}, (n β‰  0) β†’ shiftLeft' true m n β‰  0 | 0, h => absurd rfl h | succ _, _ => by dsimp [shiftLeft', bit]; omega /-! ### `size` -/ @[simp] theorem size_zero : size 0 = 0 := by simp [size] @[simp] theorem size_bit {b n} (h : bit b n β‰  0) : size (bit b n) = succ (size n) := by rw [size] conv => lhs rw [binaryRec] simp [h] rw [div2_bit] section @[simp] theorem size_one : size 1 = 1 := show size (bit true 0) = 1 by rw [size_bit, size_zero]; exact Nat.one_ne_zero end @[simp] theorem size_shiftLeft' {b m n} (h : shiftLeft' b m n β‰  0) : size (shiftLeft' b m n) = size m + n := by induction' n with n IH Β· simp [shiftLeft'] simp only [shiftLeft', ne_eq] at h ⊒ rw [size_bit h, Nat.add_succ] by_cases s0 : shiftLeft' b m n = 0 case neg => rw [IH s0] rw [s0] at h ⊒ cases b; Β· exact absurd rfl h have : shiftLeft' true m n + 1 = 1 := congr_arg (Β· + 1) s0 rw [shiftLeft'_tt_eq_mul_pow] at this obtain rfl := succ.inj (eq_one_of_dvd_one ⟨_, this.symm⟩) simp only [zero_add, one_mul] at this obtain rfl : n = 0 := not_ne_iff.1 fun hn ↦ ne_of_gt (Nat.one_lt_pow hn (by decide)) this rw [add_zero] -- TODO: decide whether `Nat.shiftLeft_eq` (which rewrites the LHS into a power) should be a simp -- lemma; it was not in mathlib3. Until then, tell the simpNF linter to ignore the issue. @[simp, nolint simpNF] theorem size_shiftLeft {m} (h : m β‰  0) (n) : size (m <<< n) = size m + n := by simp only [size_shiftLeft' (shiftLeft'_ne_zero_left _ h _), ← shiftLeft'_false] theorem lt_size_self (n : β„•) : n < 2 ^ size n := by rw [← one_shiftLeft] have : βˆ€ {n}, n = 0 β†’ n < 1 <<< (size n) := by simp apply binaryRec _ _ n Β· apply this rfl intro b n IH by_cases h : bit b n = 0 Β· apply this h rw [size_bit h, shiftLeft_succ, shiftLeft_eq, one_mul] cases b <;> dsimp [bit] <;> omega theorem size_le {m n : β„•} : size m ≀ n ↔ m < 2 ^ n := ⟨fun h => lt_of_lt_of_le (lt_size_self _) (pow_le_pow_of_le_right (by decide) h), by rw [← one_shiftLeft]; revert n apply binaryRec _ _ m Β· intro n simp Β· intro b m IH n h by_cases e : bit b m = 0 Β· simp [e] rw [size_bit e] cases' n with n Β· exact e.elim (Nat.eq_zero_of_le_zero (le_of_lt_succ h)) Β· apply succ_le_succ (IH _) apply Nat.lt_of_mul_lt_mul_left (a := 2) simp only [shiftLeft_succ] at * refine lt_of_le_of_lt ?_ h cases b <;> dsimp [bit] <;> omega⟩ theorem lt_size {m n : β„•} : m < size n ↔ 2 ^ m ≀ n := by rw [← not_lt, Decidable.iff_not_comm, not_lt, size_le] theorem size_pos {n : β„•} : 0 < size n ↔ 0 < n := by rw [lt_size]; rfl theorem size_eq_zero {n : β„•} : size n = 0 ↔ n = 0 := by simpa [Nat.pos_iff_ne_zero, not_iff_not] using size_pos theorem size_pow {n : β„•} : size (2 ^ n) = n + 1 := le_antisymm (size_le.2 <| Nat.pow_lt_pow_right (by decide) (lt_succ_self _)) (lt_size.2 <| le_rfl) theorem size_le_size {m n : β„•} (h : m ≀ n) : size m ≀ size n := size_le.2 <| lt_of_le_of_lt h (lt_size_self _) theorem size_eq_bits_len (n : β„•) : n.bits.length = n.size := by induction' n using Nat.binaryRec' with b n h ih; Β· simp rw [size_bit, bits_append_bit _ _ h] Β· simp [ih] Β· simpa [bit_eq_zero_iff] end Nat
Data\Nat\Squarefree.lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import Mathlib.Algebra.Squarefree.Basic import Mathlib.Data.Nat.Factorization.PrimePow /-! # Lemmas about squarefreeness of natural numbers A number is squarefree when it is not divisible by any squares except the squares of units. ## Main Results - `Nat.squarefree_iff_nodup_primeFactorsList`: A positive natural number `x` is squarefree iff the list `factors x` has no duplicate factors. ## Tags squarefree, multiplicity -/ open Finset namespace Nat theorem squarefree_iff_nodup_primeFactorsList {n : β„•} (h0 : n β‰  0) : Squarefree n ↔ n.primeFactorsList.Nodup := by rw [UniqueFactorizationMonoid.squarefree_iff_nodup_normalizedFactors h0, Nat.factors_eq] simp @[deprecated (since := "2024-07-17")] alias squarefree_iff_nodup_factors := squarefree_iff_nodup_primeFactorsList end Nat theorem Squarefree.nodup_primeFactorsList {n : β„•} (hn : Squarefree n) : n.primeFactorsList.Nodup := (Nat.squarefree_iff_nodup_primeFactorsList hn.ne_zero).mp hn @[deprecated (since := "2024-07-17")] alias Squarefree.nodup_factors := Squarefree.nodup_primeFactorsList namespace Nat variable {s : Finset β„•} {m n p : β„•} theorem squarefree_iff_prime_squarefree {n : β„•} : Squarefree n ↔ βˆ€ x, Prime x β†’ Β¬x * x ∣ n := squarefree_iff_irreducible_sq_not_dvd_of_exists_irreducible ⟨_, prime_two⟩ theorem _root_.Squarefree.natFactorization_le_one {n : β„•} (p : β„•) (hn : Squarefree n) : n.factorization p ≀ 1 := by rcases eq_or_ne n 0 with (rfl | hn') Β· simp rw [multiplicity.squarefree_iff_multiplicity_le_one] at hn by_cases hp : p.Prime Β· have := hn p simp only [multiplicity_eq_factorization hp hn', Nat.isUnit_iff, hp.ne_one, or_false_iff] at this exact mod_cast this Β· rw [factorization_eq_zero_of_non_prime _ hp] exact zero_le_one lemma factorization_eq_one_of_squarefree (hn : Squarefree n) (hp : p.Prime) (hpn : p ∣ n) : factorization n p = 1 := (hn.natFactorization_le_one _).antisymm <| (hp.dvd_iff_one_le_factorization hn.ne_zero).1 hpn theorem squarefree_of_factorization_le_one {n : β„•} (hn : n β‰  0) (hn' : βˆ€ p, n.factorization p ≀ 1) : Squarefree n := by rw [squarefree_iff_nodup_primeFactorsList hn, List.nodup_iff_count_le_one] intro a rw [primeFactorsList_count_eq] apply hn' theorem squarefree_iff_factorization_le_one {n : β„•} (hn : n β‰  0) : Squarefree n ↔ βˆ€ p, n.factorization p ≀ 1 := ⟨fun hn => hn.natFactorization_le_one, squarefree_of_factorization_le_one hn⟩ theorem Squarefree.ext_iff {n m : β„•} (hn : Squarefree n) (hm : Squarefree m) : n = m ↔ βˆ€ p, Prime p β†’ (p ∣ n ↔ p ∣ m) := by refine ⟨by rintro rfl; simp, fun h => eq_of_factorization_eq hn.ne_zero hm.ne_zero fun p => ?_⟩ by_cases hp : p.Prime Β· have h₁ := h _ hp rw [← not_iff_not, hp.dvd_iff_one_le_factorization hn.ne_zero, not_le, lt_one_iff, hp.dvd_iff_one_le_factorization hm.ne_zero, not_le, lt_one_iff] at h₁ have hβ‚‚ := hn.natFactorization_le_one p have h₃ := hm.natFactorization_le_one p rw [Nat.le_add_one_iff, Nat.le_zero] at hβ‚‚ h₃ cases' hβ‚‚ with hβ‚‚ hβ‚‚ Β· rwa [hβ‚‚, eq_comm, ← h₁] Β· rw [hβ‚‚, h₃.resolve_left] rw [← h₁, hβ‚‚] simp only [Nat.one_ne_zero, not_false_iff] rw [factorization_eq_zero_of_non_prime _ hp, factorization_eq_zero_of_non_prime _ hp] theorem squarefree_pow_iff {n k : β„•} (hn : n β‰  1) (hk : k β‰  0) : Squarefree (n ^ k) ↔ Squarefree n ∧ k = 1 := by refine ⟨fun h => ?_, by rintro ⟨hn, rfl⟩; simpa⟩ rcases eq_or_ne n 0 with (rfl | -) Β· simp [zero_pow hk] at h refine ⟨h.squarefree_of_dvd (dvd_pow_self _ hk), by_contradiction fun h₁ => ?_⟩ have : 2 ≀ k := k.two_le_iff.mpr ⟨hk, hβ‚βŸ© apply hn (Nat.isUnit_iff.1 (h _ _)) rw [← sq] exact pow_dvd_pow _ this theorem squarefree_and_prime_pow_iff_prime {n : β„•} : Squarefree n ∧ IsPrimePow n ↔ Prime n := by refine ⟨?_, fun hn => ⟨hn.squarefree, hn.isPrimePow⟩⟩ rw [isPrimePow_nat_iff] rintro ⟨h, p, k, hp, hk, rfl⟩ rw [squarefree_pow_iff hp.ne_one hk.ne'] at h rwa [h.2, pow_one] /-- Assuming that `n` has no factors less than `k`, returns the smallest prime `p` such that `p^2 ∣ n`. -/ def minSqFacAux : β„• β†’ β„• β†’ Option β„• | n, k => if h : n < k * k then none else have : Nat.sqrt n - k < Nat.sqrt n + 2 - k := by exact Nat.minFac_lemma n k h if k ∣ n then let n' := n / k have : Nat.sqrt n' - k < Nat.sqrt n + 2 - k := lt_of_le_of_lt (Nat.sub_le_sub_right (Nat.sqrt_le_sqrt <| Nat.div_le_self _ _) k) this if k ∣ n' then some k else minSqFacAux n' (k + 2) else minSqFacAux n (k + 2) termination_by n k => sqrt n + 2 - k /-- Returns the smallest prime factor `p` of `n` such that `p^2 ∣ n`, or `none` if there is no such `p` (that is, `n` is squarefree). See also `Nat.squarefree_iff_minSqFac`. -/ def minSqFac (n : β„•) : Option β„• := if 2 ∣ n then let n' := n / 2 if 2 ∣ n' then some 2 else minSqFacAux n' 3 else minSqFacAux n 3 /-- The correctness property of the return value of `minSqFac`. * If `none`, then `n` is squarefree; * If `some d`, then `d` is a minimal square factor of `n` -/ def MinSqFacProp (n : β„•) : Option β„• β†’ Prop | none => Squarefree n | some d => Prime d ∧ d * d ∣ n ∧ βˆ€ p, Prime p β†’ p * p ∣ n β†’ d ≀ p theorem minSqFacProp_div (n) {k} (pk : Prime k) (dk : k ∣ n) (dkk : Β¬k * k ∣ n) {o} (H : MinSqFacProp (n / k) o) : MinSqFacProp n o := by have : βˆ€ p, Prime p β†’ p * p ∣ n β†’ k * (p * p) ∣ n := fun p pp dp => have := (coprime_primes pk pp).2 fun e => by subst e contradiction (coprime_mul_iff_right.2 ⟨this, this⟩).mul_dvd_of_dvd_of_dvd dk dp cases' o with d Β· rw [MinSqFacProp, squarefree_iff_prime_squarefree] at H ⊒ exact fun p pp dp => H p pp ((dvd_div_iff_mul_dvd dk).2 (this _ pp dp)) Β· obtain ⟨H1, H2, H3⟩ := H simp only [dvd_div_iff_mul_dvd dk] at H2 H3 exact ⟨H1, dvd_trans (dvd_mul_left _ _) H2, fun p pp dp => H3 _ pp (this _ pp dp)⟩ theorem minSqFacAux_has_prop {n : β„•} (k) (n0 : 0 < n) (i) (e : k = 2 * i + 3) (ih : βˆ€ m, Prime m β†’ m ∣ n β†’ k ≀ m) : MinSqFacProp n (minSqFacAux n k) := by rw [minSqFacAux] by_cases h : n < k * k <;> simp only [h, ↓reduceDIte] Β· refine squarefree_iff_prime_squarefree.2 fun p pp d => ?_ have := ih p pp (dvd_trans ⟨_, rfl⟩ d) have := Nat.mul_le_mul this this exact not_le_of_lt h (le_trans this (le_of_dvd n0 d)) have k2 : 2 ≀ k := by omega have k0 : 0 < k := lt_of_lt_of_le (by decide) k2 have IH : βˆ€ n', n' ∣ n β†’ Β¬k ∣ n' β†’ MinSqFacProp n' (n'.minSqFacAux (k + 2)) := by intro n' nd' nk have hn' := le_of_dvd n0 nd' refine have : Nat.sqrt n' - k < Nat.sqrt n + 2 - k := lt_of_le_of_lt (Nat.sub_le_sub_right (Nat.sqrt_le_sqrt hn') _) (Nat.minFac_lemma n k h) @minSqFacAux_has_prop n' (k + 2) (pos_of_dvd_of_pos nd' n0) (i + 1) (by simp [e, left_distrib]) fun m m2 d => ?_ rcases Nat.eq_or_lt_of_le (ih m m2 (dvd_trans d nd')) with me | ml Β· subst me contradiction apply (Nat.eq_or_lt_of_le ml).resolve_left intro me rw [← me, e] at d change 2 * (i + 2) ∣ n' at d have := ih _ prime_two (dvd_trans (dvd_of_mul_right_dvd d) nd') rw [e] at this exact absurd this (by omega) have pk : k ∣ n β†’ Prime k := by refine fun dk => prime_def_minFac.2 ⟨k2, le_antisymm (minFac_le k0) ?_⟩ exact ih _ (minFac_prime (ne_of_gt k2)) (dvd_trans (minFac_dvd _) dk) split_ifs with dk dkk Β· exact ⟨pk dk, (Nat.dvd_div_iff_mul_dvd dk).1 dkk, fun p pp d => ih p pp (dvd_trans ⟨_, rfl⟩ d)⟩ Β· specialize IH (n / k) (div_dvd_of_dvd dk) dkk exact minSqFacProp_div _ (pk dk) dk (mt (Nat.dvd_div_iff_mul_dvd dk).2 dkk) IH Β· exact IH n (dvd_refl _) dk termination_by n.sqrt + 2 - k theorem minSqFac_has_prop (n : β„•) : MinSqFacProp n (minSqFac n) := by dsimp only [minSqFac]; split_ifs with d2 d4 Β· exact ⟨prime_two, (dvd_div_iff_mul_dvd d2).1 d4, fun p pp _ => pp.two_le⟩ Β· rcases Nat.eq_zero_or_pos n with n0 | n0 Β· subst n0 cases d4 (by decide) refine minSqFacProp_div _ prime_two d2 (mt (dvd_div_iff_mul_dvd d2).2 d4) ?_ refine minSqFacAux_has_prop 3 (Nat.div_pos (le_of_dvd n0 d2) (by decide)) 0 rfl ?_ refine fun p pp dp => succ_le_of_lt (lt_of_le_of_ne pp.two_le ?_) rintro rfl contradiction Β· rcases Nat.eq_zero_or_pos n with n0 | n0 Β· subst n0 cases d2 (by decide) refine minSqFacAux_has_prop _ n0 0 rfl ?_ refine fun p pp dp => succ_le_of_lt (lt_of_le_of_ne pp.two_le ?_) rintro rfl contradiction theorem minSqFac_prime {n d : β„•} (h : n.minSqFac = some d) : Prime d := by have := minSqFac_has_prop n rw [h] at this exact this.1 theorem minSqFac_dvd {n d : β„•} (h : n.minSqFac = some d) : d * d ∣ n := by have := minSqFac_has_prop n rw [h] at this exact this.2.1 theorem minSqFac_le_of_dvd {n d : β„•} (h : n.minSqFac = some d) {m} (m2 : 2 ≀ m) (md : m * m ∣ n) : d ≀ m := by have := minSqFac_has_prop n; rw [h] at this have fd := minFac_dvd m exact le_trans (this.2.2 _ (minFac_prime <| ne_of_gt m2) (dvd_trans (mul_dvd_mul fd fd) md)) (minFac_le <| lt_of_lt_of_le (by decide) m2) theorem squarefree_iff_minSqFac {n : β„•} : Squarefree n ↔ n.minSqFac = none := by have := minSqFac_has_prop n constructor <;> intro H Β· cases' e : n.minSqFac with d Β· rfl rw [e] at this cases squarefree_iff_prime_squarefree.1 H _ this.1 this.2.1 Β· rwa [H] at this instance : DecidablePred (Squarefree : β„• β†’ Prop) := fun _ => decidable_of_iff' _ squarefree_iff_minSqFac theorem squarefree_two : Squarefree 2 := by rw [squarefree_iff_nodup_primeFactorsList] <;> simp theorem divisors_filter_squarefree_of_squarefree {n : β„•} (hn : Squarefree n) : n.divisors.filter Squarefree = n.divisors := Finset.ext fun d => ⟨@Finset.filter_subset _ _ _ _ d, fun hd => Finset.mem_filter.mpr ⟨hd, hn.squarefree_of_dvd (Nat.dvd_of_mem_divisors hd) ⟩⟩ open UniqueFactorizationMonoid theorem divisors_filter_squarefree {n : β„•} (h0 : n β‰  0) : (n.divisors.filter Squarefree).val = (UniqueFactorizationMonoid.normalizedFactors n).toFinset.powerset.val.map fun x => x.val.prod := by rw [(Finset.nodup _).ext ((Finset.nodup _).map_on _)] Β· intro a simp only [Multiset.mem_filter, id, Multiset.mem_map, Finset.filter_val, ← Finset.mem_def, mem_divisors] constructor Β· rintro ⟨⟨an, h0⟩, hsq⟩ use (UniqueFactorizationMonoid.normalizedFactors a).toFinset simp only [id, Finset.mem_powerset] rcases an with ⟨b, rfl⟩ rw [mul_ne_zero_iff] at h0 rw [UniqueFactorizationMonoid.squarefree_iff_nodup_normalizedFactors h0.1] at hsq rw [Multiset.toFinset_subset, Multiset.toFinset_val, hsq.dedup, ← associated_iff_eq, normalizedFactors_mul h0.1 h0.2] exact ⟨Multiset.subset_of_le (Multiset.le_add_right _ _), normalizedFactors_prod h0.1⟩ Β· rintro ⟨s, hs, rfl⟩ rw [Finset.mem_powerset, ← Finset.val_le_iff, Multiset.toFinset_val] at hs have hs0 : s.val.prod β‰  0 := by rw [Ne, Multiset.prod_eq_zero_iff] intro con apply not_irreducible_zero (irreducible_of_normalized_factor 0 (Multiset.mem_dedup.1 (Multiset.mem_of_le hs con))) rw [(normalizedFactors_prod h0).symm.dvd_iff_dvd_right] refine ⟨⟨Multiset.prod_dvd_prod_of_le (le_trans hs (Multiset.dedup_le _)), h0⟩, ?_⟩ have h := UniqueFactorizationMonoid.factors_unique irreducible_of_normalized_factor (fun x hx => irreducible_of_normalized_factor x (Multiset.mem_of_le (le_trans hs (Multiset.dedup_le _)) hx)) (normalizedFactors_prod hs0) rw [associated_eq_eq, Multiset.rel_eq] at h rw [UniqueFactorizationMonoid.squarefree_iff_nodup_normalizedFactors hs0, h] apply s.nodup Β· intro x hx y hy h rw [← Finset.val_inj, ← Multiset.rel_eq, ← associated_eq_eq] rw [← Finset.mem_def, Finset.mem_powerset] at hx hy apply UniqueFactorizationMonoid.factors_unique _ _ (associated_iff_eq.2 h) Β· intro z hz apply irreducible_of_normalized_factor z Β· rw [← Multiset.mem_toFinset] apply hx hz Β· intro z hz apply irreducible_of_normalized_factor z Β· rw [← Multiset.mem_toFinset] apply hy hz theorem sum_divisors_filter_squarefree {n : β„•} (h0 : n β‰  0) {Ξ± : Type*} [AddCommMonoid Ξ±] {f : β„• β†’ Ξ±} : βˆ‘ i ∈ n.divisors.filter Squarefree, f i = βˆ‘ i ∈ (UniqueFactorizationMonoid.normalizedFactors n).toFinset.powerset, f i.val.prod := by rw [Finset.sum_eq_multiset_sum, divisors_filter_squarefree h0, Multiset.map_map, Finset.sum_eq_multiset_sum] rfl theorem sq_mul_squarefree_of_pos {n : β„•} (hn : 0 < n) : βˆƒ a b : β„•, 0 < a ∧ 0 < b ∧ b ^ 2 * a = n ∧ Squarefree a := by classical -- Porting note: This line is not needed in Lean 3 set S := (Finset.range (n + 1)).filter (fun s => s ∣ n ∧ βˆƒ x, s = x ^ 2) have hSne : S.Nonempty := by use 1 have h1 : 0 < n ∧ βˆƒ x : β„•, 1 = x ^ 2 := ⟨hn, ⟨1, (one_pow 2).symm⟩⟩ simp [S, h1] let s := Finset.max' S hSne have hs : s ∈ S := Finset.max'_mem S hSne simp only [S, Finset.mem_filter, Finset.mem_range] at hs obtain ⟨-, ⟨a, hsa⟩, ⟨b, hsb⟩⟩ := hs rw [hsa] at hn obtain ⟨hlts, hlta⟩ := CanonicallyOrderedCommSemiring.mul_pos.mp hn rw [hsb] at hsa hn hlts refine ⟨a, b, hlta, (pow_pos_iff two_ne_zero).mp hlts, hsa.symm, ?_⟩ rintro x ⟨y, hy⟩ rw [Nat.isUnit_iff] by_contra hx refine Nat.lt_le_asymm ?_ (Finset.le_max' S ((b * x) ^ 2) ?_) -- Porting note: these two goals were in the opposite order in Lean 3 Β· convert lt_mul_of_one_lt_right hlts (one_lt_pow two_ne_zero (one_lt_iff_ne_zero_and_ne_one.mpr ⟨fun h => by simp_all, hx⟩)) using 1 rw [mul_pow] Β· simp_rw [S, hsa, Finset.mem_filter, Finset.mem_range] refine ⟨Nat.lt_succ_iff.mpr (le_of_dvd hn ?_), ?_, ⟨b * x, rfl⟩⟩ <;> use y <;> rw [hy] <;> ring theorem sq_mul_squarefree_of_pos' {n : β„•} (h : 0 < n) : βˆƒ a b : β„•, (b + 1) ^ 2 * (a + 1) = n ∧ Squarefree (a + 1) := by obtain ⟨a₁, b₁, ha₁, hb₁, hab₁, habβ‚‚βŸ© := sq_mul_squarefree_of_pos h refine ⟨a₁.pred, b₁.pred, ?_, ?_⟩ <;> simpa only [add_one, succ_pred_eq_of_pos, ha₁, hb₁] theorem sq_mul_squarefree (n : β„•) : βˆƒ a b : β„•, b ^ 2 * a = n ∧ Squarefree a := by cases' n with n Β· exact ⟨1, 0, by simp, squarefree_one⟩ Β· obtain ⟨a, b, -, -, h₁, hβ‚‚βŸ© := sq_mul_squarefree_of_pos (succ_pos n) exact ⟨a, b, h₁, hβ‚‚βŸ© /-- `Squarefree` is multiplicative. Note that the β†’ direction does not require `hmn` and generalizes to arbitrary commutative monoids. See `Squarefree.of_mul_left` and `Squarefree.of_mul_right` above for auxiliary lemmas. -/ theorem squarefree_mul {m n : β„•} (hmn : m.Coprime n) : Squarefree (m * n) ↔ Squarefree m ∧ Squarefree n := by simp only [squarefree_iff_prime_squarefree, ← sq, ← forall_and] refine forallβ‚‚_congr fun p hp => ?_ simp only [hmn.isPrimePow_dvd_mul (hp.isPrimePow.pow two_ne_zero), not_or] theorem coprime_of_squarefree_mul {m n : β„•} (h : Squarefree (m * n)) : m.Coprime n := coprime_of_dvd fun p hp hm hn => squarefree_iff_prime_squarefree.mp h p hp (mul_dvd_mul hm hn) theorem squarefree_mul_iff {m n : β„•} : Squarefree (m * n) ↔ m.Coprime n ∧ Squarefree m ∧ Squarefree n := ⟨fun h => ⟨coprime_of_squarefree_mul h, (squarefree_mul <| coprime_of_squarefree_mul h).mp h⟩, fun h => (squarefree_mul h.1).mpr h.2⟩ lemma coprime_div_gcd_of_squarefree (hm : Squarefree m) (hn : n β‰  0) : Coprime (m / gcd m n) n := by have : Coprime (m / gcd m n) (gcd m n) := coprime_of_squarefree_mul <| by simpa [Nat.div_mul_cancel, gcd_dvd_left] simpa [Nat.div_mul_cancel, gcd_dvd_right] using (coprime_div_gcd_div_gcd (m := m) (gcd_ne_zero_right hn).bot_lt).mul_right this lemma prod_primeFactors_of_squarefree (hn : Squarefree n) : ∏ p ∈ n.primeFactors, p = n := by rw [← toFinset_factors, List.prod_toFinset _ hn.nodup_primeFactorsList, List.map_id', Nat.prod_primeFactorsList hn.ne_zero] lemma primeFactors_prod (hs : βˆ€ p ∈ s, p.Prime) : primeFactors (∏ p ∈ s, p) = s := by have hn : ∏ p ∈ s, p β‰  0 := prod_ne_zero_iff.2 fun p hp ↦ (hs _ hp).ne_zero ext p rw [mem_primeFactors_of_ne_zero hn, and_congr_right (fun hp ↦ hp.prime.dvd_finset_prod_iff _)] refine ⟨?_, fun hp ↦ ⟨hs _ hp, _, hp, dvd_rfl⟩⟩ rintro ⟨hp, q, hq, hpq⟩ rwa [← ((hs _ hq).dvd_iff_eq hp.ne_one).1 hpq] lemma primeFactors_div_gcd (hm : Squarefree m) (hn : n β‰  0) : primeFactors (m / m.gcd n) = primeFactors m \ primeFactors n := by ext p have : m / m.gcd n β‰  0 := (Nat.div_ne_zero_iff <| gcd_ne_zero_right hn).2 <| gcd_le_left _ hm.ne_zero.bot_lt simp only [mem_primeFactors, ne_eq, this, not_false_eq_true, and_true, not_and, mem_sdiff, hm.ne_zero, hn, dvd_div_iff_mul_dvd (gcd_dvd_left _ _)] refine ⟨fun hp ↦ ⟨⟨hp.1, dvd_of_mul_left_dvd hp.2⟩, fun _ hpn ↦ hp.1.not_unit <| hm _ <| (mul_dvd_mul_right (dvd_gcd (dvd_of_mul_left_dvd hp.2) hpn) _).trans hp.2⟩, fun hp ↦ ⟨hp.1.1, Coprime.mul_dvd_of_dvd_of_dvd ?_ (gcd_dvd_left _ _) hp.1.2⟩⟩ rw [coprime_comm, hp.1.1.coprime_iff_not_dvd] exact fun hpn ↦ hp.2 hp.1.1 <| hpn.trans <| gcd_dvd_right _ _ lemma prod_primeFactors_invOn_squarefree : Set.InvOn (fun n : β„• ↦ (factorization n).support) (fun s ↦ ∏ p ∈ s, p) {s | βˆ€ p ∈ s, p.Prime} {n | Squarefree n} := ⟨fun _s ↦ primeFactors_prod, fun _n ↦ prod_primeFactors_of_squarefree⟩ theorem prod_primeFactors_sdiff_of_squarefree {n : β„•} (hn : Squarefree n) {t : Finset β„•} (ht : t βŠ† n.primeFactors) : ∏ a ∈ (n.primeFactors \ t), a = n / ∏ a ∈ t, a := by refine symm <| Nat.div_eq_of_eq_mul_left (Finset.prod_pos fun p hp => (prime_of_mem_primeFactorsList (List.mem_toFinset.mp (ht hp))).pos) ?_ rw [Finset.prod_sdiff ht, prod_primeFactors_of_squarefree hn] end Nat -- Porting note: comment out NormNum tactic, to be moved to another file. /- /-! ### Square-free prover -/ open NormNum namespace Tactic namespace NormNum /-- A predicate representing partial progress in a proof of `Squarefree`. -/ def SquarefreeHelper (n k : β„•) : Prop := 0 < k β†’ (βˆ€ m, Nat.Prime m β†’ m ∣ bit1 n β†’ bit1 k ≀ m) β†’ Squarefree (bit1 n) theorem squarefree_bit10 (n : β„•) (h : SquarefreeHelper n 1) : Squarefree (bit0 (bit1 n)) := by refine' @Nat.minSqFacProp_div _ _ Nat.prime_two two_dvd_bit0 _ none _ Β· rw [bit0_eq_two_mul (bit1 n), mul_dvd_mul_iff_left (two_ne_zero' β„•)] exact Nat.not_two_dvd_bit1 _ Β· rw [bit0_eq_two_mul, Nat.mul_div_right _ (by decide : 0 < 2)] refine' h (by decide) fun p pp dp => Nat.succ_le_of_lt (lt_of_le_of_ne pp.two_le _) rintro rfl exact Nat.not_two_dvd_bit1 _ dp theorem squarefree_bit1 (n : β„•) (h : SquarefreeHelper n 1) : Squarefree (bit1 n) := by refine' h (by decide) fun p pp dp => Nat.succ_le_of_lt (lt_of_le_of_ne pp.two_le _) rintro rfl; exact Nat.not_two_dvd_bit1 _ dp theorem squarefree_helper_0 {k} (k0 : 0 < k) {p : β„•} (pp : Nat.Prime p) (h : bit1 k ≀ p) : bit1 (k + 1) ≀ p ∨ bit1 k = p := by rcases lt_or_eq_of_le h with ((hp : _ + 1 ≀ _) | hp) Β· rw [bit1, bit0_eq_two_mul] at hp change 2 * (_ + 1) ≀ _ at hp rw [bit1, bit0_eq_two_mul] refine' Or.inl (lt_of_le_of_ne hp _) rintro rfl exact Nat.not_prime_mul (by decide) (lt_add_of_pos_left _ k0) pp Β· exact Or.inr hp theorem squarefreeHelper_1 (n k k' : β„•) (e : k + 1 = k') (hk : Nat.Prime (bit1 k) β†’ Β¬bit1 k ∣ bit1 n) (H : SquarefreeHelper n k') : SquarefreeHelper n k := fun k0 ih => by subst e refine' H (Nat.succ_pos _) fun p pp dp => _ refine' (squarefree_helper_0 k0 pp (ih p pp dp)).resolve_right fun hp => _ subst hp; cases hk pp dp theorem squarefreeHelper_2 (n k k' c : β„•) (e : k + 1 = k') (hc : bit1 n % bit1 k = c) (c0 : 0 < c) (h : SquarefreeHelper n k') : SquarefreeHelper n k := by refine' squarefree_helper_1 _ _ _ e (fun _ => _) h refine' mt _ (ne_of_gt c0); intro e₁ rwa [← hc, ← Nat.dvd_iff_mod_eq_zero] theorem squarefreeHelper_3 (n n' k k' c : β„•) (e : k + 1 = k') (hn' : bit1 n' * bit1 k = bit1 n) (hc : bit1 n' % bit1 k = c) (c0 : 0 < c) (H : SquarefreeHelper n' k') : SquarefreeHelper n k := fun k0 ih => by subst e have k0' : 0 < bit1 k := bit1_pos (Nat.zero_le _) have dn' : bit1 n' ∣ bit1 n := ⟨_, hn'.symm⟩ have dk : bit1 k ∣ bit1 n := ⟨_, ((mul_comm _ _).trans hn').symm⟩ have : bit1 n / bit1 k = bit1 n' := by rw [← hn', Nat.mul_div_cancel _ k0'] have k2 : 2 ≀ bit1 k := Nat.succ_le_succ (bit0_pos k0) have pk : (bit1 k).Prime := by refine' Nat.prime_def_minFac.2 ⟨k2, le_antisymm (Nat.minFac_le k0') _⟩ exact ih _ (Nat.minFac_prime (ne_of_gt k2)) (dvd_trans (Nat.minFac_dvd _) dk) have dkk' : Β¬bit1 k ∣ bit1 n' := by rw [Nat.dvd_iff_mod_eq_zero, hc] exact ne_of_gt c0 have dkk : Β¬bit1 k * bit1 k ∣ bit1 n := by rwa [← Nat.dvd_div_iff_mul_dvd dk, this] refine' @Nat.minSqFacProp_div _ _ pk dk dkk none _ rw [this] refine' H (Nat.succ_pos _) fun p pp dp => _ refine' (squarefree_helper_0 k0 pp (ih p pp <| dvd_trans dp dn')).resolve_right fun e => _ subst e contradiction theorem squarefreeHelper_4 (n k k' : β„•) (e : bit1 k * bit1 k = k') (hd : bit1 n < k') : SquarefreeHelper n k := by rcases Nat.eq_zero_or_pos n with h | h Β· subst n exact fun _ _ => squarefree_one subst e refine' fun k0 ih => Irreducible.squarefree (Nat.prime_def_le_sqrt.2 ⟨bit1_lt_bit1.2 h, _⟩) intro m m2 hm md obtain ⟨p, pp, hp⟩ := Nat.exists_prime_and_dvd (ne_of_gt m2) have := (ih p pp (dvd_trans hp md)).trans (le_trans (Nat.le_of_dvd (lt_of_lt_of_le (by decide) m2) hp) hm) rw [Nat.le_sqrt] at this exact not_le_of_lt hd this theorem not_squarefree_mul (a aa b n : β„•) (ha : a * a = aa) (hb : aa * b = n) (h₁ : 1 < a) : Β¬Squarefree n := by rw [← hb, ← ha] exact fun H => ne_of_gt h₁ (Nat.isUnit_iff.1 <| H _ ⟨_, rfl⟩) /-- Given `e` a natural numeral and `a : β„•` with `a^2 ∣ n`, return `⊒ Β¬ Squarefree e`. -/ unsafe def prove_non_squarefree (e : expr) (n a : β„•) : tactic expr := do let ea := reflect a let eaa := reflect (a * a) let c ← mk_instance_cache q(Nat) let (c, p₁) ← prove_lt_nat c q(1) ea let b := n / (a * a) let eb := reflect b let (c, eaa, pa) ← prove_mul_nat c ea ea let (c, e', pb) ← prove_mul_nat c eaa eb guard (e' == e) return <| q(@not_squarefree_mul).mk_app [ea, eaa, eb, e, pa, pb, p₁] /-- Given `en`,`en1 := bit1 en`, `n1` the value of `en1`, `ek`, returns `⊒ squarefree_helper en ek`. -/ unsafe def prove_squarefree_aux : βˆ€ (ic : instance_cache) (en en1 : expr) (n1 : β„•) (ek : expr) (k : β„•), tactic expr | ic, en, en1, n1, ek, k => do let k1 := bit1 k let ek1 := q((bit1 : β„• β†’ β„•)).mk_app [ek] if n1 < k1 * k1 then do let (ic, ek', p₁) ← prove_mul_nat ic ek1 ek1 let (ic, pβ‚‚) ← prove_lt_nat ic en1 ek' pure <| q(squarefreeHelper_4).mk_app [en, ek, ek', p₁, pβ‚‚] else do let c := n1 % k1 let k' := k + 1 let ek' := reflect k' let (ic, p₁) ← prove_succ ic ek ek' if c = 0 then do let n1' := n1 / k1 let n' := n1' / 2 let en' := reflect n' let en1' := q((bit1 : β„• β†’ β„•)).mk_app [en'] let (ic, _, pn') ← prove_mul_nat ic en1' ek1 let c := n1' % k1 guard (c β‰  0) let (ic, ec, pc) ← prove_div_mod ic en1' ek1 tt let (ic, pβ‚€) ← prove_pos ic ec let pβ‚‚ ← prove_squarefree_aux ic en' en1' n1' ek' k' pure <| q(squarefreeHelper_3).mk_app [en, en', ek, ek', ec, p₁, pn', pc, pβ‚€, pβ‚‚] else do let (ic, ec, pc) ← prove_div_mod ic en1 ek1 tt let (ic, pβ‚€) ← prove_pos ic ec let pβ‚‚ ← prove_squarefree_aux ic en en1 n1 ek' k' pure <| q(squarefreeHelper_2).mk_app [en, ek, ek', ec, p₁, pc, pβ‚€, pβ‚‚] /-- Given `n > 0` a squarefree natural numeral, returns `⊒ Squarefree n`. -/ unsafe def prove_squarefree (en : expr) (n : β„•) : tactic expr := match match_numeral en with | match_numeral_result.one => pure q(@squarefree_one β„• _) | match_numeral_result.bit0 en1 => match match_numeral en1 with | match_numeral_result.one => pure q(Nat.squarefree_two) | match_numeral_result.bit1 en => do let ic ← mk_instance_cache q(β„•) let p ← prove_squarefree_aux ic en en1 (n / 2) q((1 : β„•)) 1 pure <| q(squarefree_bit10).mk_app [en, p] | _ => failed | match_numeral_result.bit1 en' => do let ic ← mk_instance_cache q(β„•) let p ← prove_squarefree_aux ic en' en n q((1 : β„•)) 1 pure <| q(squarefree_bit1).mk_app [en', p] | _ => failed /-- Evaluates the `Squarefree` predicate on naturals. -/ @[norm_num] unsafe def eval_squarefree : expr β†’ tactic (expr Γ— expr) | q(@Squarefree β„• $(inst) $(e)) => do is_def_eq inst q(Nat.monoid) let n ← e.toNat match n with | 0 => false_intro q(@not_squarefree_zero β„• _ _) | 1 => true_intro q(@squarefree_one β„• _) | _ => match n with | some d => prove_non_squarefree e n d >>= false_intro | none => prove_squarefree e n >>= true_intro | _ => failed end NormNum end Tactic -/
Data\Nat\SuccPred.lean
/- Copyright (c) 2021 YaΓ«l Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: YaΓ«l Dillies -/ import Mathlib.Algebra.Order.Ring.Nat import Mathlib.Data.Fin.Basic import Mathlib.Order.SuccPred.Basic /-! # Successors and predecessors of naturals In this file, we show that `β„•` is both an archimedean `succOrder` and an archimedean `predOrder`. -/ open Function Order namespace Nat variable {m n : β„•} -- so that Lean reads `Nat.succ` through `succ_order.succ` @[instance] abbrev instSuccOrder : SuccOrder β„• := SuccOrder.ofSuccLeIff succ Nat.succ_le -- so that Lean reads `Nat.pred` through `pred_order.pred` @[instance] abbrev instPredOrder : PredOrder β„• where pred := pred pred_le := pred_le min_of_le_pred {a} ha := by cases a Β· exact isMin_bot Β· exact (not_succ_le_self _ ha).elim le_pred_of_lt {a} {b} h := by cases b Β· exact (a.not_lt_zero h).elim Β· exact le_of_succ_le_succ h le_of_pred_lt {a} {b} h := by cases a Β· exact b.zero_le Β· exact h @[simp] theorem succ_eq_succ : Order.succ = succ := rfl @[simp] theorem pred_eq_pred : Order.pred = pred := rfl theorem succ_iterate (a : β„•) : βˆ€ n, succ^[n] a = a + n | 0 => rfl | n + 1 => by rw [Function.iterate_succ', add_succ] exact congr_arg _ (succ_iterate a n) theorem pred_iterate (a : β„•) : βˆ€ n, pred^[n] a = a - n | 0 => rfl | n + 1 => by rw [Function.iterate_succ', sub_succ] exact congr_arg _ (pred_iterate a n) lemma le_succ_iff_eq_or_le : m ≀ n.succ ↔ m = n.succ ∨ m ≀ n := Order.le_succ_iff_eq_or_le instance : IsSuccArchimedean β„• := ⟨fun {a} {b} h => ⟨b - a, by rw [succ_eq_succ, succ_iterate, add_tsub_cancel_of_le h]⟩⟩ instance : IsPredArchimedean β„• := ⟨fun {a} {b} h => ⟨b - a, by rw [pred_eq_pred, pred_iterate, tsub_tsub_cancel_of_le h]⟩⟩ lemma forall_ne_zero_iff (P : β„• β†’ Prop) : (βˆ€ i, i β‰  0 β†’ P i) ↔ (βˆ€ i, P (i + 1)) := SuccOrder.forall_ne_bot_iff P /-! ### Covering relation -/ protected theorem covBy_iff_succ_eq {m n : β„•} : m β‹– n ↔ m + 1 = n := succ_eq_iff_covBy.symm end Nat @[simp, norm_cast] theorem Fin.coe_covBy_iff {n : β„•} {a b : Fin n} : (a : β„•) β‹– b ↔ a β‹– b := and_congr_right' ⟨fun h _c hc => h hc, fun h c ha hb => @h ⟨c, hb.trans b.prop⟩ ha hb⟩ alias ⟨_, CovBy.coe_fin⟩ := Fin.coe_covBy_iff
Data\Nat\Totient.lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.Algebra.CharP.Two import Mathlib.Data.Nat.Factorization.Basic import Mathlib.Data.Nat.Factorization.Induction import Mathlib.Data.Nat.Periodic import Mathlib.Data.ZMod.Basic /-! # Euler's totient function This file defines [Euler's totient function](https://en.wikipedia.org/wiki/Euler's_totient_function) `Nat.totient n` which counts the number of naturals less than `n` that are coprime with `n`. We prove the divisor sum formula, namely that `n` equals `Ο†` summed over the divisors of `n`. See `sum_totient`. We also prove two lemmas to help compute totients, namely `totient_mul` and `totient_prime_pow`. -/ open Finset namespace Nat /-- Euler's totient function. This counts the number of naturals strictly less than `n` which are coprime with `n`. -/ def totient (n : β„•) : β„• := ((range n).filter n.Coprime).card @[inherit_doc] scoped notation "Ο†" => Nat.totient @[simp] theorem totient_zero : Ο† 0 = 0 := rfl @[simp] theorem totient_one : Ο† 1 = 1 := rfl theorem totient_eq_card_coprime (n : β„•) : Ο† n = ((range n).filter n.Coprime).card := rfl /-- A characterisation of `Nat.totient` that avoids `Finset`. -/ theorem totient_eq_card_lt_and_coprime (n : β„•) : Ο† n = Nat.card { m | m < n ∧ n.Coprime m } := by let e : { m | m < n ∧ n.Coprime m } ≃ Finset.filter n.Coprime (Finset.range n) := { toFun := fun m => ⟨m, by simpa only [Finset.mem_filter, Finset.mem_range] using m.property⟩ invFun := fun m => ⟨m, by simpa only [Finset.mem_filter, Finset.mem_range] using m.property⟩ left_inv := fun m => by simp only [Subtype.coe_mk, Subtype.coe_eta] right_inv := fun m => by simp only [Subtype.coe_mk, Subtype.coe_eta] } rw [totient_eq_card_coprime, card_congr e, card_eq_fintype_card, Fintype.card_coe] theorem totient_le (n : β„•) : Ο† n ≀ n := ((range n).card_filter_le _).trans_eq (card_range n) theorem totient_lt (n : β„•) (hn : 1 < n) : Ο† n < n := (card_lt_card (filter_ssubset.2 ⟨0, by simp [hn.ne', pos_of_gt hn]⟩)).trans_eq (card_range n) @[simp] theorem totient_eq_zero : βˆ€ {n : β„•}, Ο† n = 0 ↔ n = 0 | 0 => by decide | n + 1 => suffices βˆƒ x < n + 1, (n + 1).gcd x = 1 by simpa [totient, filter_eq_empty_iff] ⟨1 % (n + 1), mod_lt _ n.succ_pos, by rw [gcd_comm, ← gcd_rec, gcd_one_right]⟩ @[simp] theorem totient_pos {n : β„•} : 0 < Ο† n ↔ 0 < n := by simp [pos_iff_ne_zero] theorem filter_coprime_Ico_eq_totient (a n : β„•) : ((Ico n (n + a)).filter (Coprime a)).card = totient a := by rw [totient, filter_Ico_card_eq_of_periodic, count_eq_card_filter_range] exact periodic_coprime a theorem Ico_filter_coprime_le {a : β„•} (k n : β„•) (a_pos : 0 < a) : ((Ico k (k + n)).filter (Coprime a)).card ≀ totient a * (n / a + 1) := by conv_lhs => rw [← Nat.mod_add_div n a] induction' n / a with i ih Β· rw [← filter_coprime_Ico_eq_totient a k] simp only [add_zero, mul_one, mul_zero, le_of_lt (mod_lt n a_pos), Nat.zero_eq, zero_add] gcongr exact Ico_subset_Ico rfl.le (add_le_add_left (le_of_lt (mod_lt n a_pos)) k) simp only [mul_succ] simp_rw [← add_assoc] at ih ⊒ calc (filter a.Coprime (Ico k (k + n % a + a * i + a))).card = (filter a.Coprime (Ico k (k + n % a + a * i) βˆͺ Ico (k + n % a + a * i) (k + n % a + a * i + a))).card := by congr rw [Ico_union_Ico_eq_Ico] Β· rw [add_assoc] exact le_self_add exact le_self_add _ ≀ (filter a.Coprime (Ico k (k + n % a + a * i))).card + a.totient := by rw [filter_union, ← filter_coprime_Ico_eq_totient a (k + n % a + a * i)] apply card_union_le _ ≀ a.totient * i + a.totient + a.totient := add_le_add_right ih (totient a) open ZMod /-- Note this takes an explicit `Fintype ((ZMod n)Λ£)` argument to avoid trouble with instance diamonds. -/ @[simp] theorem _root_.ZMod.card_units_eq_totient (n : β„•) [NeZero n] [Fintype (ZMod n)Λ£] : Fintype.card (ZMod n)Λ£ = Ο† n := calc Fintype.card (ZMod n)Λ£ = Fintype.card { x : ZMod n // x.val.Coprime n } := Fintype.card_congr ZMod.unitsEquivCoprime _ = Ο† n := by obtain ⟨m, rfl⟩ : βˆƒ m, n = m + 1 := exists_eq_succ_of_ne_zero NeZero.out simp only [totient, Finset.card_eq_sum_ones, Fintype.card_subtype, Finset.sum_filter, ← Fin.sum_univ_eq_sum_range, @Nat.coprime_comm (m + 1)] rfl theorem totient_even {n : β„•} (hn : 2 < n) : Even n.totient := by haveI : Fact (1 < n) := ⟨one_lt_two.trans hn⟩ haveI : NeZero n := NeZero.of_gt hn suffices 2 = orderOf (-1 : (ZMod n)Λ£) by rw [← ZMod.card_units_eq_totient, even_iff_two_dvd, this] exact orderOf_dvd_card rw [← orderOf_units, Units.coe_neg_one, orderOf_neg_one, ringChar.eq (ZMod n) n, if_neg hn.ne'] theorem totient_mul {m n : β„•} (h : m.Coprime n) : Ο† (m * n) = Ο† m * Ο† n := if hmn0 : m * n = 0 then by cases' Nat.mul_eq_zero.1 hmn0 with h h <;> simp only [totient_zero, mul_zero, zero_mul, h] else by haveI : NeZero (m * n) := ⟨hmn0⟩ haveI : NeZero m := ⟨left_ne_zero_of_mul hmn0⟩ haveI : NeZero n := ⟨right_ne_zero_of_mul hmn0⟩ simp only [← ZMod.card_units_eq_totient] rw [Fintype.card_congr (Units.mapEquiv (ZMod.chineseRemainder h).toMulEquiv).toEquiv, Fintype.card_congr (@MulEquiv.prodUnits (ZMod m) (ZMod n) _ _).toEquiv, Fintype.card_prod] /-- For `d ∣ n`, the totient of `n/d` equals the number of values `k < n` such that `gcd n k = d` -/ theorem totient_div_of_dvd {n d : β„•} (hnd : d ∣ n) : Ο† (n / d) = (filter (fun k : β„• => n.gcd k = d) (range n)).card := by rcases d.eq_zero_or_pos with (rfl | hd0); Β· simp [eq_zero_of_zero_dvd hnd] rcases hnd with ⟨x, rfl⟩ rw [Nat.mul_div_cancel_left x hd0] apply Finset.card_bij fun k _ => d * k Β· simp only [mem_filter, mem_range, and_imp, Coprime] refine fun a ha1 ha2 => ⟨(mul_lt_mul_left hd0).2 ha1, ?_⟩ rw [gcd_mul_left, ha2, mul_one] Β· simp [hd0.ne'] Β· simp only [mem_filter, mem_range, exists_prop, and_imp] refine fun b hb1 hb2 => ?_ have : d ∣ b := by rw [← hb2] apply gcd_dvd_right rcases this with ⟨q, rfl⟩ refine ⟨q, ⟨⟨(mul_lt_mul_left hd0).1 hb1, ?_⟩, rfl⟩⟩ rwa [gcd_mul_left, mul_right_eq_self_iff hd0] at hb2 theorem sum_totient (n : β„•) : n.divisors.sum Ο† = n := by rcases n.eq_zero_or_pos with (rfl | hn) Β· simp rw [← sum_div_divisors n Ο†] have : n = βˆ‘ d ∈ n.divisors, (filter (fun k : β„• => n.gcd k = d) (range n)).card := by nth_rw 1 [← card_range n] refine card_eq_sum_card_fiberwise fun x _ => mem_divisors.2 ⟨?_, hn.ne'⟩ apply gcd_dvd_left nth_rw 3 [this] exact sum_congr rfl fun x hx => totient_div_of_dvd (dvd_of_mem_divisors hx) theorem sum_totient' (n : β„•) : (βˆ‘ m ∈ (range n.succ).filter (Β· ∣ n), Ο† m) = n := by convert sum_totient _ using 1 simp only [Nat.divisors, sum_filter, range_eq_Ico] rw [sum_eq_sum_Ico_succ_bot] <;> simp /-- When `p` is prime, then the totient of `p ^ (n + 1)` is `p ^ n * (p - 1)` -/ theorem totient_prime_pow_succ {p : β„•} (hp : p.Prime) (n : β„•) : Ο† (p ^ (n + 1)) = p ^ n * (p - 1) := calc Ο† (p ^ (n + 1)) = ((range (p ^ (n + 1))).filter (Coprime (p ^ (n + 1)))).card := totient_eq_card_coprime _ _ = (range (p ^ (n + 1)) \ (range (p ^ n)).image (Β· * p)).card := (congr_arg card (by rw [sdiff_eq_filter] apply filter_congr simp only [mem_range, mem_filter, coprime_pow_left_iff n.succ_pos, mem_image, not_exists, hp.coprime_iff_not_dvd] intro a ha constructor Β· intro hap b h; rcases h with ⟨_, rfl⟩ exact hap (dvd_mul_left _ _) Β· rintro h ⟨b, rfl⟩ rw [pow_succ'] at ha exact h b ⟨lt_of_mul_lt_mul_left ha (zero_le _), mul_comm _ _⟩)) _ = _ := by have h1 : Function.Injective (Β· * p) := mul_left_injectiveβ‚€ hp.ne_zero have h2 : (range (p ^ n)).image (Β· * p) βŠ† range (p ^ (n + 1)) := fun a => by simp only [mem_image, mem_range, exists_imp] rintro b ⟨h, rfl⟩ rw [Nat.pow_succ] exact (mul_lt_mul_right hp.pos).2 h rw [card_sdiff h2, Finset.card_image_of_injective _ h1, card_range, card_range, ← one_mul (p ^ n), pow_succ', ← tsub_mul, one_mul, mul_comm] /-- When `p` is prime, then the totient of `p ^ n` is `p ^ (n - 1) * (p - 1)` -/ theorem totient_prime_pow {p : β„•} (hp : p.Prime) {n : β„•} (hn : 0 < n) : Ο† (p ^ n) = p ^ (n - 1) * (p - 1) := by rcases exists_eq_succ_of_ne_zero (pos_iff_ne_zero.1 hn) with ⟨m, rfl⟩ exact totient_prime_pow_succ hp _ theorem totient_prime {p : β„•} (hp : p.Prime) : Ο† p = p - 1 := by rw [← pow_one p, totient_prime_pow hp] <;> simp theorem totient_eq_iff_prime {p : β„•} (hp : 0 < p) : p.totient = p - 1 ↔ p.Prime := by refine ⟨fun h => ?_, totient_prime⟩ replace hp : 1 < p := by apply lt_of_le_of_ne Β· rwa [succ_le_iff] Β· rintro rfl rw [totient_one, tsub_self] at h exact one_ne_zero h rw [totient_eq_card_coprime, range_eq_Ico, ← Ico_insert_succ_left hp.le, Finset.filter_insert, if_neg (not_coprime_of_dvd_of_dvd hp (dvd_refl p) (dvd_zero p)), ← Nat.card_Ico 1 p] at h refine p.prime_of_coprime hp fun n hn hnz => Finset.filter_card_eq h n <| Finset.mem_Ico.mpr ⟨?_, hn⟩ rwa [succ_le_iff, pos_iff_ne_zero] theorem card_units_zmod_lt_sub_one {p : β„•} (hp : 1 < p) [Fintype (ZMod p)Λ£] : Fintype.card (ZMod p)Λ£ ≀ p - 1 := by haveI : NeZero p := ⟨(pos_of_gt hp).ne'⟩ rw [ZMod.card_units_eq_totient p] exact Nat.le_sub_one_of_lt (Nat.totient_lt p hp) theorem prime_iff_card_units (p : β„•) [Fintype (ZMod p)Λ£] : p.Prime ↔ Fintype.card (ZMod p)Λ£ = p - 1 := by cases' eq_zero_or_neZero p with hp hp Β· subst hp simp only [ZMod, not_prime_zero, false_iff_iff, zero_tsub] -- the subst created a non-defeq but subsingleton instance diamond; resolve it suffices Fintype.card β„€Λ£ β‰  0 by convert this simp rw [ZMod.card_units_eq_totient, Nat.totient_eq_iff_prime <| NeZero.pos p] @[simp] theorem totient_two : Ο† 2 = 1 := (totient_prime prime_two).trans rfl theorem totient_eq_one_iff : βˆ€ {n : β„•}, n.totient = 1 ↔ n = 1 ∨ n = 2 | 0 => by simp | 1 => by simp | 2 => by simp | n + 3 => by have : 3 ≀ n + 3 := le_add_self simp only [succ_succ_ne_one, false_or_iff] exact ⟨fun h => not_even_one.elim <| h β–Έ totient_even this, by rintro ⟨⟩⟩ theorem dvd_two_of_totient_le_one {a : β„•} (han : 0 < a) (ha : a.totient ≀ 1) : a ∣ 2 := by rcases totient_eq_one_iff.mp <| le_antisymm ha <| totient_pos.2 han with rfl | rfl <;> norm_num /-! ### Euler's product formula for the totient function We prove several different statements of this formula. -/ /-- Euler's product formula for the totient function. -/ theorem totient_eq_prod_factorization {n : β„•} (hn : n β‰  0) : Ο† n = n.factorization.prod fun p k => p ^ (k - 1) * (p - 1) := by rw [multiplicative_factorization Ο† (@totient_mul) totient_one hn] apply Finsupp.prod_congr _ intro p hp have h := zero_lt_iff.mpr (Finsupp.mem_support_iff.mp hp) rw [totient_prime_pow (prime_of_mem_primeFactors hp) h] /-- Euler's product formula for the totient function. -/ theorem totient_mul_prod_primeFactors (n : β„•) : (Ο† n * ∏ p ∈ n.primeFactors, p) = n * ∏ p ∈ n.primeFactors, (p - 1) := by by_cases hn : n = 0; Β· simp [hn] rw [totient_eq_prod_factorization hn] nth_rw 3 [← factorization_prod_pow_eq_self hn] simp only [prod_primeFactors_prod_factorization, ← Finsupp.prod_mul] refine Finsupp.prod_congr (M := β„•) (N := β„•) fun p hp => ?_ rw [Finsupp.mem_support_iff, ← zero_lt_iff] at hp rw [mul_comm, ← mul_assoc, ← pow_succ', Nat.sub_one, Nat.succ_pred_eq_of_pos hp] /-- Euler's product formula for the totient function. -/ theorem totient_eq_div_primeFactors_mul (n : β„•) : Ο† n = (n / ∏ p ∈ n.primeFactors, p) * ∏ p ∈ n.primeFactors, (p - 1) := by rw [← mul_div_left n.totient, totient_mul_prod_primeFactors, mul_comm, Nat.mul_div_assoc _ (prod_primeFactors_dvd n), mul_comm] exact prod_pos (fun p => pos_of_mem_primeFactors) /-- Euler's product formula for the totient function. -/ theorem totient_eq_mul_prod_factors (n : β„•) : (Ο† n : β„š) = n * ∏ p ∈ n.primeFactors, (1 - (p : β„š)⁻¹) := by by_cases hn : n = 0 Β· simp [hn] have hn' : (n : β„š) β‰  0 := by simp [hn] have hpQ : (∏ p ∈ n.primeFactors, (p : β„š)) β‰  0 := by rw [← cast_prod, cast_ne_zero, ← zero_lt_iff, prod_primeFactors_prod_factorization] exact prod_pos fun p hp => pos_of_mem_primeFactors hp simp only [totient_eq_div_primeFactors_mul n, prod_primeFactors_dvd n, cast_mul, cast_prod, cast_div_charZero, mul_comm_div, mul_right_inj' hn', div_eq_iff hpQ, ← prod_mul_distrib] refine prod_congr rfl fun p hp => ?_ have hp := pos_of_mem_primeFactorsList (List.mem_toFinset.mp hp) have hp' : (p : β„š) β‰  0 := cast_ne_zero.mpr hp.ne.symm rw [sub_mul, one_mul, mul_comm, mul_inv_cancel hp', cast_pred hp] theorem totient_gcd_mul_totient_mul (a b : β„•) : Ο† (a.gcd b) * Ο† (a * b) = Ο† a * Ο† b * a.gcd b := by have shuffle : βˆ€ a1 a2 b1 b2 c1 c2 : β„•, b1 ∣ a1 β†’ b2 ∣ a2 β†’ a1 / b1 * c1 * (a2 / b2 * c2) = a1 * a2 / (b1 * b2) * (c1 * c2) := by intro a1 a2 b1 b2 c1 c2 h1 h2 calc a1 / b1 * c1 * (a2 / b2 * c2) = a1 / b1 * (a2 / b2) * (c1 * c2) := by apply mul_mul_mul_comm _ = a1 * a2 / (b1 * b2) * (c1 * c2) := by congr 1 exact div_mul_div_comm h1 h2 simp only [totient_eq_div_primeFactors_mul] rw [shuffle, shuffle] rotate_left repeat' apply prod_primeFactors_dvd simp only [prod_primeFactors_gcd_mul_prod_primeFactors_mul] rw [eq_comm, mul_comm, ← mul_assoc, ← Nat.mul_div_assoc] exact mul_dvd_mul (prod_primeFactors_dvd a) (prod_primeFactors_dvd b) theorem totient_super_multiplicative (a b : β„•) : Ο† a * Ο† b ≀ Ο† (a * b) := by let d := a.gcd b rcases (zero_le a).eq_or_lt with (rfl | ha0) Β· simp have hd0 : 0 < d := Nat.gcd_pos_of_pos_left _ ha0 apply le_of_mul_le_mul_right _ hd0 rw [← totient_gcd_mul_totient_mul a b, mul_comm] apply mul_le_mul_left' (Nat.totient_le d) theorem totient_dvd_of_dvd {a b : β„•} (h : a ∣ b) : Ο† a ∣ Ο† b := by rcases eq_or_ne a 0 with (rfl | ha0) Β· simp [zero_dvd_iff.1 h] rcases eq_or_ne b 0 with (rfl | hb0) Β· simp have hab' := primeFactors_mono h hb0 rw [totient_eq_prod_factorization ha0, totient_eq_prod_factorization hb0] refine Finsupp.prod_dvd_prod_of_subset_of_dvd hab' fun p _ => mul_dvd_mul ?_ dvd_rfl exact pow_dvd_pow p (tsub_le_tsub_right ((factorization_le_iff_dvd ha0 hb0).2 h p) 1) theorem totient_mul_of_prime_of_dvd {p n : β„•} (hp : p.Prime) (h : p ∣ n) : (p * n).totient = p * n.totient := by have h1 := totient_gcd_mul_totient_mul p n rw [gcd_eq_left h, mul_assoc] at h1 simpa [(totient_pos.2 hp.pos).ne', mul_comm] using h1 theorem totient_mul_of_prime_of_not_dvd {p n : β„•} (hp : p.Prime) (h : Β¬p ∣ n) : (p * n).totient = (p - 1) * n.totient := by rw [totient_mul _, totient_prime hp] simpa [h] using coprime_or_dvd_of_prime hp n end Nat
Data\Nat\Upto.lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Algebra.Order.Ring.Nat /-! # `Nat.Upto` `Nat.Upto p`, with `p` a predicate on `β„•`, is a subtype of elements `n : β„•` such that no value (strictly) below `n` satisfies `p`. This type has the property that `>` is well-founded when `βˆƒ i, p i`, which allows us to implement searches on `β„•`, starting at `0` and with an unknown upper-bound. It is similar to the well founded relation constructed to define `Nat.find` with the difference that, in `Nat.Upto p`, `p` does not need to be decidable. In fact, `Nat.find` could be slightly altered to factor decidability out of its well founded relation and would then fulfill the same purpose as this file. -/ namespace Nat /-- The subtype of natural numbers `i` which have the property that no `j` less than `i` satisfies `p`. This is an initial segment of the natural numbers, up to and including the first value satisfying `p`. We will be particularly interested in the case where there exists a value satisfying `p`, because in this case the `>` relation is well-founded. -/ abbrev Upto (p : β„• β†’ Prop) : Type := { i : β„• // βˆ€ j < i, Β¬p j } namespace Upto variable {p : β„• β†’ Prop} /-- Lift the "greater than" relation on natural numbers to `Nat.Upto`. -/ protected def GT (p) (x y : Upto p) : Prop := x.1 > y.1 instance : LT (Upto p) := ⟨fun x y => x.1 < y.1⟩ /-- The "greater than" relation on `Upto p` is well founded if (and only if) there exists a value satisfying `p`. -/ protected theorem wf : (βˆƒ x, p x) β†’ WellFounded (Upto.GT p) | ⟨x, h⟩ => by suffices Upto.GT p = InvImage (Β· < Β·) fun y : Nat.Upto p => x - y.val by rw [this] exact (measure _).wf ext ⟨a, ha⟩ ⟨b, _⟩ dsimp [InvImage, Upto.GT] rw [tsub_lt_tsub_iff_left_of_le (le_of_not_lt fun h' => ha _ h' h)] /-- Zero is always a member of `Nat.Upto p` because it has no predecessors. -/ def zero : Nat.Upto p := ⟨0, fun _ h => False.elim (Nat.not_lt_zero _ h)⟩ /-- The successor of `n` is in `Nat.Upto p` provided that `n` doesn't satisfy `p`. -/ def succ (x : Nat.Upto p) (h : Β¬p x.val) : Nat.Upto p := ⟨x.val.succ, fun j h' => by rcases Nat.lt_succ_iff_lt_or_eq.1 h' with (h' | rfl) <;> [exact x.2 _ h'; exact h]⟩ end Upto end Nat
Data\Nat\WithBot.lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.Algebra.Order.Ring.Nat import Mathlib.Algebra.Order.Monoid.WithTop import Mathlib.Data.Nat.Cast.WithTop /-! # `WithBot β„•` Lemmas about the type of natural numbers with a bottom element adjoined. -/ namespace Nat namespace WithBot instance : WellFoundedRelation (WithBot β„•) where rel := (Β· < Β·) wf := IsWellFounded.wf theorem add_eq_zero_iff {n m : WithBot β„•} : n + m = 0 ↔ n = 0 ∧ m = 0 := by cases n Β· simp [WithBot.bot_add] cases m Β· simp [WithBot.add_bot] simp [← WithBot.coe_add, _root_.add_eq_zero_iff] theorem add_eq_one_iff {n m : WithBot β„•} : n + m = 1 ↔ n = 0 ∧ m = 1 ∨ n = 1 ∧ m = 0 := by cases n Β· simp only [WithBot.bot_add, WithBot.bot_ne_one, WithBot.bot_ne_zero, false_and, or_self] cases m Β· simp [WithBot.add_bot] simp [← WithBot.coe_add, Nat.add_eq_one_iff] theorem add_eq_two_iff {n m : WithBot β„•} : n + m = 2 ↔ n = 0 ∧ m = 2 ∨ n = 1 ∧ m = 1 ∨ n = 2 ∧ m = 0 := by cases n Β· simp [WithBot.bot_add] cases m Β· simp [WithBot.add_bot] simp [← WithBot.coe_add, Nat.add_eq_two_iff] theorem add_eq_three_iff {n m : WithBot β„•} : n + m = 3 ↔ n = 0 ∧ m = 3 ∨ n = 1 ∧ m = 2 ∨ n = 2 ∧ m = 1 ∨ n = 3 ∧ m = 0 := by cases n Β· simp [WithBot.bot_add] cases m Β· simp [WithBot.add_bot] simp [← WithBot.coe_add, Nat.add_eq_three_iff] theorem coe_nonneg {n : β„•} : 0 ≀ (n : WithBot β„•) := by rw [← WithBot.coe_zero, cast_withBot, WithBot.coe_le_coe] exact n.zero_le @[simp] theorem lt_zero_iff {n : WithBot β„•} : n < 0 ↔ n = βŠ₯ := WithBot.lt_coe_bot theorem one_le_iff_zero_lt {x : WithBot β„•} : 1 ≀ x ↔ 0 < x := by refine ⟨zero_lt_one.trans_le, fun h => ?_⟩ cases x Β· exact (not_lt_bot h).elim Β· rwa [← WithBot.coe_zero, WithBot.coe_lt_coe, ← Nat.add_one_le_iff, zero_add, ← WithBot.coe_le_coe, WithBot.coe_one] at h theorem lt_one_iff_le_zero {x : WithBot β„•} : x < 1 ↔ x ≀ 0 := not_iff_not.mp (by simpa using one_le_iff_zero_lt) theorem add_one_le_of_lt {n m : WithBot β„•} (h : n < m) : n + 1 ≀ m := by cases n Β· simp only [WithBot.bot_add, bot_le] cases m Β· exact (not_lt_bot h).elim Β· rwa [WithBot.coe_lt_coe, ← Nat.add_one_le_iff, ← WithBot.coe_le_coe, WithBot.coe_add, WithBot.coe_one] at h end WithBot end Nat
Data\Nat\Cast\Basic.lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Algebra.Divisibility.Basic 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 OrderedCommGroup assert_not_exists Commute.zero_right assert_not_exists Commute.add_right assert_not_exists abs_eq_max_neg assert_not_exists natCast_ne assert_not_exists MulOpposite.natCast -- Porting note: There are many occasions below where we need `simp [map_zero f]` -- where `simp [map_zero]` should suffice. (Similarly for `map_one`.) -- See https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/simp.20regression.20with.20MonoidHomClass 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_succ, 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] @[simp] lemma _root_.nsmul_eq_mul (n : β„•) (a : Ξ±) : n β€’ a = n * a := by induction n with | zero => rw [zero_nsmul, Nat.cast_zero, zero_mul] | succ n ih => rw [succ_nsmul, ih, Nat.cast_succ, add_mul, one_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] 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] theorem ext_nat' [AddMonoid A] [AddMonoidHomClass F β„• A] (f g : F) (h : f 1 = g 1) : f = g := DFunLike.ext f g <| by intro n induction n with | zero => simp_rw [map_zero f, map_zero g] | succ n ihn => simp [h, ihn] @[ext] theorem AddMonoidHom.ext_nat [AddMonoid A] {f g : β„• β†’+ A} : f 1 = g 1 β†’ f = g := ext_nat' f g variable [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 [map_zero f] | 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 | 0 => by simp [map_zero f] | n + 1 => by rw [Nat.cast_add, map_add, Nat.cast_add, map_natCast' f h n, Nat.cast_one, h, Nat.cast_one] 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 @[simp] lemma nsmul_one {A} [AddMonoidWithOne A] : βˆ€ n : β„•, n β€’ (1 : A) = n := by let f : β„• β†’+ A := { toFun := fun n ↦ n β€’ (1 : A) map_zero' := zero_nsmul _ map_add' := add_nsmul _ } exact eq_natCast' f $ by simp [f] 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'' [MonoidWithZeroHomClass F β„• A] (f g : F) (h_pos : βˆ€ {n : β„•}, 0 < n β†’ f n = g n) : f = g := by apply DFunLike.ext rintro (_ | n) Β· simp [map_zero f, map_zero g] Β· 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 -- See note [no_index around OfNat.ofNat] @[simp] theorem map_ofNat [FunLike F R S] [RingHomClass F R S] (f : F) (n : β„•) [Nat.AtLeastTwo n] : (f (no_index (OfNat.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 only [map_one f, map_one g] theorem NeZero.nat_of_neZero {R S} [Semiring R] [Semiring 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' section Monoid variable (Ξ±) [Monoid Ξ±] (Ξ²) [AddMonoid Ξ²] /-- Additive homomorphisms from `β„•` are defined by the image of `1`. -/ def multiplesHom : Ξ² ≃ (β„• β†’+ Ξ²) where toFun x := { toFun := fun n ↦ n β€’ x map_zero' := zero_nsmul x map_add' := fun _ _ ↦ add_nsmul _ _ _ } invFun f := f 1 left_inv := one_nsmul right_inv f := AddMonoidHom.ext_nat <| one_nsmul (f 1) /-- Monoid homomorphisms from `Multiplicative β„•` are defined by the image of `Multiplicative.ofAdd 1`. -/ @[to_additive existing] def powersHom : Ξ± ≃ (Multiplicative β„• β†’* Ξ±) := Additive.ofMul.trans <| (multiplesHom _).trans <| AddMonoidHom.toMultiplicative'' variable {Ξ±} -- TODO: can `to_additive` generate the following lemmas automatically? lemma multiplesHom_apply (x : Ξ²) (n : β„•) : multiplesHom Ξ² x n = n β€’ x := rfl @[to_additive existing (attr := simp)] lemma powersHom_apply (x : Ξ±) (n : Multiplicative β„•) : powersHom Ξ± x n = x ^ Multiplicative.toAdd n := rfl lemma multiplesHom_symm_apply (f : β„• β†’+ Ξ²) : (multiplesHom Ξ²).symm f = f 1 := rfl @[to_additive existing (attr := simp)] lemma powersHom_symm_apply (f : Multiplicative β„• β†’* Ξ±) : (powersHom Ξ±).symm f = f (Multiplicative.ofAdd 1) := rfl lemma MonoidHom.apply_mnat (f : Multiplicative β„• β†’* Ξ±) (n : Multiplicative β„•) : f n = f (Multiplicative.ofAdd 1) ^ (Multiplicative.toAdd n) := by rw [← powersHom_symm_apply, ← powersHom_apply, Equiv.apply_symm_apply] @[ext] lemma MonoidHom.ext_mnat ⦃f g : Multiplicative β„• β†’* α⦄ (h : f (Multiplicative.ofAdd 1) = g (Multiplicative.ofAdd 1)) : f = g := MonoidHom.ext fun n ↦ by rw [f.apply_mnat, g.apply_mnat, h] lemma AddMonoidHom.apply_nat (f : β„• β†’+ Ξ²) (n : β„•) : f n = n β€’ f 1 := by rw [← multiplesHom_symm_apply, ← multiplesHom_apply, Equiv.apply_symm_apply] end Monoid section CommMonoid variable (Ξ±) [CommMonoid Ξ±] (Ξ²) [AddCommMonoid Ξ²] /-- If `Ξ±` is commutative, `multiplesHom` is an additive equivalence. -/ def multiplesAddHom : Ξ² ≃+ (β„• β†’+ Ξ²) := { multiplesHom Ξ² with map_add' := fun a b ↦ AddMonoidHom.ext fun n ↦ by simp [nsmul_add] } /-- If `Ξ±` is commutative, `powersHom` is a multiplicative equivalence. -/ def powersMulHom : Ξ± ≃* (Multiplicative β„• β†’* Ξ±) := { powersHom Ξ± with map_mul' := fun a b ↦ MonoidHom.ext fun n ↦ by simp [mul_pow] } @[simp] lemma multiplesAddHom_apply (x : Ξ²) (n : β„•) : multiplesAddHom Ξ² x n = n β€’ x := rfl @[simp] lemma powersMulHom_apply (x : Ξ±) (n : Multiplicative β„•) : powersMulHom Ξ± x n = x ^ toAdd n := rfl @[simp] lemma multiplesAddHom_symm_apply (f : β„• β†’+ Ξ²) : (multiplesAddHom Ξ²).symm f = f 1 := rfl @[simp] lemma powersMulHom_symm_apply (f : Multiplicative β„• β†’* Ξ±) : (powersMulHom Ξ±).symm f = f (ofAdd 1) := rfl end CommMonoid namespace Pi variable {Ο€ : Ξ± β†’ Type*} [βˆ€ a, NatCast (Ο€ a)] instance instNatCast : NatCast (βˆ€ a, Ο€ a) where natCast n _ := n theorem natCast_apply (n : β„•) (a : Ξ±) : (n : βˆ€ a, Ο€ a) a = n := rfl @[simp] theorem natCast_def (n : β„•) : (n : βˆ€ a, Ο€ a) = fun _ ↦ ↑n := rfl @[deprecated (since := "2024-04-05")] alias nat_apply := natCast_apply @[deprecated (since := "2024-04-05")] alias coe_nat := natCast_def @[simp] theorem ofNat_apply (n : β„•) [n.AtLeastTwo] (a : Ξ±) : (OfNat.ofNat n : βˆ€ a, Ο€ a) a = n := rfl end Pi theorem Sum.elim_natCast_natCast {Ξ± Ξ² Ξ³ : Type*} [NatCast Ξ³] (n : β„•) : Sum.elim (n : Ξ± β†’ Ξ³) (n : Ξ² β†’ Ξ³) = n := Sum.elim_lam_const_lam_const (Ξ³ := Ξ³) n
Data\Nat\Cast\Commute.lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ 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 @[simp] lemma natCast_mul_natCast_mul (h : SemiconjBy a x y) (m n : β„•) : SemiconjBy (m * a) (n * x) (n * y) := (h.natCast_mul_left m).natCast_mul_right n 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 @[simp] lemma natCast_mul_natCast_mul (h : Commute a b) (m n : β„•) : Commute (m * a) (n * b) := SemiconjBy.natCast_mul_natCast_mul h m n variable (a) (m n : β„•) -- Porting note (#10618): `simp` can prove this using `Commute.refl`, `Commute.natCast_mul_right` -- @[simp] lemma self_natCast_mul : Commute a (n * a) := (Commute.refl a).natCast_mul_right n -- Porting note (#10618): `simp` can prove this using `Commute.refl`, `Commute.natCast_mul_left` -- @[simp] lemma natCast_mul_self : Commute (n * a) a := (Commute.refl a).natCast_mul_left n -- Porting note (#10618): `simp` can prove this using `Commute.refl`, `Commute.natCast_mul_left`, -- `Commute.natCast_mul_right` -- @[simp] lemma self_natCast_mul_natCast_mul : Commute (m * a) (n * a) := (Commute.refl a).natCast_mul_natCast_mul m n @[deprecated (since := "2024-05-27")] alias cast_nat_mul_right := natCast_mul_right @[deprecated (since := "2024-05-27")] alias cast_nat_mul_left := natCast_mul_left @[deprecated (since := "2024-05-27")] alias cast_nat_mul_cast_nat_mul := natCast_mul_natCast_mul @[deprecated (since := "2024-05-27")] alias self_cast_nat_mul := self_natCast_mul @[deprecated (since := "2024-05-27")] alias cast_nat_mul_self := natCast_mul_self @[deprecated (since := "2024-05-27")] alias self_cast_nat_mul_cast_nat_mul := self_natCast_mul_natCast_mul end Commute
Data\Nat\Cast\Defs.lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Gabriel Ebner -/ import Mathlib.Algebra.Group.Defs 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 -- the following four declarations are not in mathlib3 and are relevant to the way numeric -- literals are handled in Lean 4. /-- A type class for natural numbers which are greater than or equal to `2`. -/ class Nat.AtLeastTwo (n : β„•) : Prop where prop : n β‰₯ 2 instance instNatAtLeastTwo {n : β„•} : Nat.AtLeastTwo (n + 2) where prop := Nat.succ_le_succ <| Nat.succ_le_succ <| Nat.zero_le _ namespace Nat.AtLeastTwo variable {n : β„•} [n.AtLeastTwo] lemma one_lt : 1 < n := prop lemma ne_one : n β‰  1 := Nat.ne_of_gt one_lt end Nat.AtLeastTwo /-- 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_note "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)`. 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 (no_index (OfNat.ofNat n)) : R) = OfNat.ofNat n := rfl theorem Nat.cast_eq_ofNat {n : β„•} [NatCast R] [Nat.AtLeastTwo n] : (Nat.cast n : R) = OfNat.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_note "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 apply Nat.strongInductionOn n intros 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 [AddMonoidWithOne R] : ((2 : β„•) : R) = (2 : R) := rfl attribute [simp, norm_cast] Int.natAbs_ofNat 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, Nat.cast], natCast_succ := fun n => by dsimp only [NatCast.natCast] 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
Data\Nat\Cast\Field.lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, YaΓ«l Dillies, Patrick Stevens -/ 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 {Ξ± : Type*} @[simp] theorem cast_div [DivisionSemiring Ξ±] {m n : β„•} (n_dvd : n ∣ m) (hn : (n : Ξ±) β‰  0) : ((m / n : β„•) : Ξ±) = m / n := by rcases n_dvd with ⟨k, rfl⟩ 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] theorem cast_div_div_div_cancel_right [DivisionSemiring Ξ±] [CharZero Ξ±] {m n d : β„•} (hn : d ∣ n) (hm : d ∣ m) : (↑(m / d) : Ξ±) / (↑(n / d) : Ξ±) = (m : Ξ±) / n := by rcases eq_or_ne d 0 with (rfl | hd); Β· simp [Nat.zero_dvd.1 hm] replace hd : (d : Ξ±) β‰  0 := by norm_cast rw [cast_div hm, cast_div hn, div_div_div_cancel_right _ hd] <;> exact hd end Nat
Data\Nat\Cast\NeZero.lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Gabriel Ebner -/ import Mathlib.Data.Nat.Cast.Defs import Mathlib.Algebra.NeZero /-! # Lemmas about nonzero elements of an `AddMonoidWithOne` -/ open Nat namespace NeZero theorem one_le {n : β„•} [NeZero n] : 1 ≀ n := by have := NeZero.ne n; omega 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
Data\Nat\Cast\Prod.lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Algebra.Group.Prod /-! # 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 [*] -- See note [no_index around OfNat.ofNat] @[simp] theorem fst_ofNat (n : β„•) [n.AtLeastTwo] : (no_index (OfNat.ofNat n : Ξ± Γ— Ξ²)).1 = (OfNat.ofNat n : Ξ±) := rfl @[simp] theorem snd_natCast (n : β„•) : (n : Ξ± Γ— Ξ²).snd = n := by induction n <;> simp [*] -- See note [no_index around OfNat.ofNat] @[simp] theorem snd_ofNat (n : β„•) [n.AtLeastTwo] : (no_index (OfNat.ofNat n : Ξ± Γ— Ξ²)).2 = (OfNat.ofNat n : Ξ²) := rfl end Prod
Data\Nat\Cast\SetInterval.lean
/- Copyright (c) 2024 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Algebra.Order.Ring.Int import Mathlib.Order.UpperLower.Basic import Mathlib.Algebra.Order.Ring.Nat import Mathlib.Data.Nat.Cast.Order.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.ofNat_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
Data\Nat\Cast\Synonym.lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ 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`). ## Main declarations * `castAddMonoidHom`: `cast` bundled as an `AddMonoidHom`. * `castRingHom`: `cast` bundled as a `RingHom`. -/ -- Porting note: There are many occasions below where we need `simp [map_zero f]` -- where `simp [map_zero]` should suffice. (Similarly for `map_one`.) -- See https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/simp.20regression.20with.20MonoidHomClass 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 -- See note [no_index around OfNat.ofNat] @[simp] theorem toDual_ofNat [NatCast Ξ±] (n : β„•) [n.AtLeastTwo] : (toDual (no_index (OfNat.ofNat n : Ξ±))) = OfNat.ofNat n := rfl @[simp] theorem ofDual_natCast [NatCast Ξ±] (n : β„•) : (ofDual n : Ξ±) = n := rfl -- See note [no_index around OfNat.ofNat] @[simp] theorem ofDual_ofNat [NatCast Ξ±] (n : β„•) [n.AtLeastTwo] : (ofDual (no_index (OfNat.ofNat n : Ξ±α΅’α΅ˆ))) = OfNat.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 (no_index (OfNat.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 (no_index (OfNat.ofNat n : Lex Ξ±))) = OfNat.ofNat n := rfl
Data\Nat\Cast\WithTop.lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ 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
Data\Nat\Cast\Order\Basic.lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Data.Nat.Cast.Basic import Mathlib.Algebra.Order.Monoid.Unbundled.Basic import Mathlib.Data.Nat.Cast.NeZero import Mathlib.Algebra.Order.ZeroLEOne import Mathlib.Order.Hom.Basic /-! # Cast of natural numbers: lemmas about order -/ assert_not_exists OrderedCommMonoid 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 [CovariantClass Ξ± Ξ± (Β· + Β·) (Β· ≀ Β·)] [ZeroLEOneClass Ξ±] @[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 @[deprecated mono_cast (since := "2024-02-10")] theorem cast_le_cast {a b : β„•} (h : a ≀ b) : (a : Ξ±) ≀ b := mono_cast h @[gcongr] theorem _root_.GCongr.natCast_le_natCast {a b : β„•} (h : a ≀ b) : (a : Ξ±) ≀ b := mono_cast h /-- 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`. -/ -- See note [no_index around OfNat.ofNat] @[simp low] theorem ofNat_nonneg' (n : β„•) [n.AtLeastTwo] : 0 ≀ (no_index (OfNat.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 : β„•} theorem strictMono_cast : StrictMono (Nat.cast : β„• β†’ Ξ±) := mono_cast.strictMono_of_injective cast_injective /-- `Nat.cast : β„• β†’ Ξ±` as an `OrderEmbedding` -/ @[simps! (config := .asFn)] 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] @[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] section variable [m.AtLeastTwo] -- See note [no_index around OfNat.ofNat] @[simp] theorem ofNat_le_cast : (no_index (OfNat.ofNat m : Ξ±)) ≀ n ↔ (OfNat.ofNat m : β„•) ≀ n := cast_le -- See note [no_index around OfNat.ofNat] @[simp] theorem ofNat_lt_cast : (no_index (OfNat.ofNat m : Ξ±)) < n ↔ (OfNat.ofNat m : β„•) < n := cast_lt end variable [n.AtLeastTwo] -- See note [no_index around OfNat.ofNat] @[simp] theorem cast_le_ofNat : (m : Ξ±) ≀ (no_index (OfNat.ofNat n)) ↔ m ≀ OfNat.ofNat n := cast_le -- See note [no_index around OfNat.ofNat] @[simp] theorem cast_lt_ofNat : (m : Ξ±) < (no_index (OfNat.ofNat n)) ↔ m < OfNat.ofNat n := cast_lt -- See note [no_index around OfNat.ofNat] @[simp] theorem one_lt_ofNat : 1 < (no_index (OfNat.ofNat n : Ξ±)) := one_lt_cast.mpr AtLeastTwo.one_lt -- See note [no_index around OfNat.ofNat] @[simp] theorem one_le_ofNat : 1 ≀ (no_index (OfNat.ofNat n : Ξ±)) := one_le_cast.mpr NeZero.one_le -- See note [no_index around OfNat.ofNat] @[simp] theorem not_ofNat_le_one : Β¬(no_index (OfNat.ofNat n : Ξ±)) ≀ 1 := (cast_le_one.not.trans not_le).mpr AtLeastTwo.one_lt -- See note [no_index around OfNat.ofNat] @[simp] theorem not_ofNat_lt_one : Β¬(no_index (OfNat.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 lean4#2867 is fixed in a performant way, these can be made `@[simp]`. -- See note [no_index around OfNat.ofNat] -- @[simp] theorem ofNat_le : (no_index (OfNat.ofNat m : Ξ±)) ≀ (no_index (OfNat.ofNat n)) ↔ (OfNat.ofNat m : β„•) ≀ OfNat.ofNat n := cast_le -- See note [no_index around OfNat.ofNat] -- @[simp] theorem ofNat_lt : (no_index (OfNat.ofNat m : Ξ±)) < (no_index (OfNat.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 : β„•} [h : 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
Data\Nat\Cast\Order\Field.lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, YaΓ«l Dillies, Patrick Stevens -/ 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 variable {Ξ± : Type*} [LinearOrderedSemifield Ξ±] lemma cast_inv_le_one : βˆ€ n : β„•, (n⁻¹ : Ξ±) ≀ 1 | 0 => by simp | n + 1 => inv_le_one $ 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 end Nat
Data\Nat\Cast\Order\Ring.lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Algebra.Order.Ring.Nat import Mathlib.Algebra.Order.Group.Unbundled.Abs import Mathlib.Data.Nat.Cast.Order.Basic /-! # Cast of natural numbers: lemmas about bundled ordered semirings -/ 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 [CovariantClass Ξ± Ξ± (Β· + Β·) (Β· ≀ Β·)] [ZeroLEOneClass Ξ±] /-- Specialisation of `Nat.cast_nonneg'`, which seems to be easier for Lean to use. -/ @[simp] theorem cast_nonneg {Ξ±} [OrderedSemiring Ξ±] (n : β„•) : 0 ≀ (n : Ξ±) := cast_nonneg' n /-- Specialisation of `Nat.ofNat_nonneg'`, which seems to be easier for Lean to use. -/ -- See note [no_index around OfNat.ofNat] @[simp] theorem ofNat_nonneg {Ξ±} [OrderedSemiring Ξ±] (n : β„•) [n.AtLeastTwo] : 0 ≀ (no_index (OfNat.ofNat n : Ξ±)) := ofNat_nonneg' n @[simp, norm_cast] theorem cast_min {Ξ±} [LinearOrderedSemiring Ξ±] {a b : β„•} : ((min a b : β„•) : Ξ±) = min (a : Ξ±) b := (@mono_cast Ξ± _).map_min @[simp, norm_cast] theorem cast_max {Ξ±} [LinearOrderedSemiring Ξ±] {a b : β„•} : ((max a b : β„•) : Ξ±) = max (a : Ξ±) b := (@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 {Ξ±} [OrderedSemiring Ξ±] [Nontrivial Ξ±] {n : β„•} : (0 : Ξ±) < n ↔ 0 < n := cast_pos' /-- See also `Nat.ofNat_pos`, specialised for an `OrderedSemiring`. -/ -- See note [no_index around OfNat.ofNat] @[simp low] theorem ofNat_pos' {n : β„•} [n.AtLeastTwo] : 0 < (no_index (OfNat.ofNat n : Ξ±)) := cast_pos'.mpr (NeZero.pos n) /-- Specialisation of `Nat.ofNat_pos'`, which seems to be easier for Lean to use. -/ -- See note [no_index around OfNat.ofNat] @[simp] theorem ofNat_pos {Ξ±} [OrderedSemiring Ξ±] [Nontrivial Ξ±] {n : β„•} [n.AtLeastTwo] : 0 < (no_index (OfNat.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 [CanonicallyOrderedCommSemiring Ξ±] [Sub Ξ±] [OrderedSub Ξ±] [ContravariantClass Ξ± Ξ± (Β· + Β·) (Β· ≀ Β·)] (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] @[simp, norm_cast] theorem abs_cast [LinearOrderedRing Ξ±] (a : β„•) : |(a : Ξ±)| = a := abs_of_nonneg (cast_nonneg a) -- See note [no_index around OfNat.ofNat] @[simp] theorem abs_ofNat [LinearOrderedRing Ξ±] (n : β„•) [n.AtLeastTwo] : |(no_index (OfNat.ofNat n : Ξ±))| = OfNat.ofNat n := abs_cast n 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_assoc, 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 => rw [add_pow_two, one_pow, mul_one, add_assoc, mul_add, add_right_comm] refine (add_le_add_right hk _).trans ?_ rw [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
Data\Nat\Choose\Basic.lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Bhavik Mehta, Stuart Presnell -/ import Mathlib.Data.Nat.Factorial.Basic import Mathlib.Order.Monotone.Basic /-! # Binomial coefficients This file defines binomial coefficients and proves simple lemmas (i.e. those not requiring more imports). ## Main definition and results * `Nat.choose`: binomial coefficients, defined inductively * `Nat.choose_eq_factorial_div_factorial`: a proof that `choose n k = n! / (k! * (n - k)!)` * `Nat.choose_symm`: symmetry of binomial coefficients * `Nat.choose_le_succ_of_lt_half_left`: `choose n k` is increasing for small values of `k` * `Nat.choose_le_middle`: `choose n r` is maximised when `r` is `n/2` * `Nat.descFactorial_eq_factorial_mul_choose`: Relates binomial coefficients to the descending factorial. This is used to prove `Nat.choose_le_pow` and variants. We provide similar statements for the ascending factorial. * `Nat.multichoose`: whereas `choose` counts combinations, `multichoose` counts multicombinations. The fact that this is indeed the correct counting function for multisets is proved in `Sym.card_sym_eq_multichoose` in `Data.Sym.Card`. * `Nat.multichoose_eq` : a proof that `multichoose n k = (n + k - 1).choose k`. This is central to the "stars and bars" technique in informal mathematics, where we switch between counting multisets of size `k` over an alphabet of size `n` to counting strings of `k` elements ("stars") separated by `n-1` dividers ("bars"). See `Data.Sym.Card` for more detail. ## Tags binomial coefficient, combination, multicombination, stars and bars -/ open Nat namespace Nat /-- `choose n k` is the number of `k`-element subsets in an `n`-element set. Also known as binomial coefficients. -/ def choose : β„• β†’ β„• β†’ β„• | _, 0 => 1 | 0, _ + 1 => 0 | n + 1, k + 1 => choose n k + choose n (k + 1) @[simp] theorem choose_zero_right (n : β„•) : choose n 0 = 1 := by cases n <;> rfl @[simp] theorem choose_zero_succ (k : β„•) : choose 0 (succ k) = 0 := rfl theorem choose_succ_succ (n k : β„•) : choose (succ n) (succ k) = choose n k + choose n (succ k) := rfl theorem choose_succ_succ' (n k : β„•) : choose (n + 1) (k + 1) = choose n k + choose n (k + 1) := rfl theorem choose_eq_zero_of_lt : βˆ€ {n k}, n < k β†’ choose n k = 0 | _, 0, hk => absurd hk (Nat.not_lt_zero _) | 0, k + 1, _ => choose_zero_succ _ | n + 1, k + 1, hk => by have hnk : n < k := lt_of_succ_lt_succ hk have hnk1 : n < k + 1 := lt_of_succ_lt hk rw [choose_succ_succ, choose_eq_zero_of_lt hnk, choose_eq_zero_of_lt hnk1] @[simp] theorem choose_self (n : β„•) : choose n n = 1 := by induction n <;> simp [*, choose, choose_eq_zero_of_lt (lt_succ_self _)] @[simp] theorem choose_succ_self (n : β„•) : choose n (succ n) = 0 := choose_eq_zero_of_lt (lt_succ_self _) @[simp] lemma choose_one_right (n : β„•) : choose n 1 = n := by induction n <;> simp [*, choose, Nat.add_comm] -- The `n+1`-st triangle number is `n` more than the `n`-th triangle number theorem triangle_succ (n : β„•) : (n + 1) * (n + 1 - 1) / 2 = n * (n - 1) / 2 + n := by rw [← add_mul_div_left, Nat.mul_comm 2 n, ← Nat.mul_add, Nat.add_sub_cancel, Nat.mul_comm] cases n <;> rfl; apply zero_lt_succ /-- `choose n 2` is the `n`-th triangle number. -/ theorem choose_two_right (n : β„•) : choose n 2 = n * (n - 1) / 2 := by induction' n with n ih Β· simp Β· rw [triangle_succ n, choose, ih] simp [Nat.add_comm] theorem choose_pos : βˆ€ {n k}, k ≀ n β†’ 0 < choose n k | 0, _, hk => by rw [Nat.eq_zero_of_le_zero hk]; decide | n + 1, 0, _ => by simp | n + 1, k + 1, hk => Nat.add_pos_left (choose_pos (le_of_succ_le_succ hk)) _ theorem choose_eq_zero_iff {n k : β„•} : n.choose k = 0 ↔ n < k := ⟨fun h => lt_of_not_ge (mt Nat.choose_pos h.symm.not_lt), Nat.choose_eq_zero_of_lt⟩ theorem succ_mul_choose_eq : βˆ€ n k, succ n * choose n k = choose (succ n) (succ k) * succ k | 0, 0 => by decide | 0, k + 1 => by simp [choose] | n + 1, 0 => by simp [choose, mul_succ, Nat.add_comm] | n + 1, k + 1 => by rw [choose_succ_succ (succ n) (succ k), Nat.add_mul, ← succ_mul_choose_eq n, mul_succ, ← succ_mul_choose_eq n, Nat.add_right_comm, ← Nat.mul_add, ← choose_succ_succ, ← succ_mul] theorem choose_mul_factorial_mul_factorial : βˆ€ {n k}, k ≀ n β†’ choose n k * k ! * (n - k)! = n ! | 0, _, hk => by simp [Nat.eq_zero_of_le_zero hk] | n + 1, 0, _ => by simp | n + 1, succ k, hk => by rcases lt_or_eq_of_le hk with hk₁ | hk₁ Β· have h : choose n k * k.succ ! * (n - k)! = (k + 1) * n ! := by rw [← choose_mul_factorial_mul_factorial (le_of_succ_le_succ hk)] simp [factorial_succ, Nat.mul_comm, Nat.mul_left_comm, Nat.mul_assoc] have h₁ : (n - k)! = (n - k) * (n - k.succ)! := by rw [← succ_sub_succ, succ_sub (le_of_lt_succ hk₁), factorial_succ] have hβ‚‚ : choose n (succ k) * k.succ ! * ((n - k) * (n - k.succ)!) = (n - k) * n ! := by rw [← choose_mul_factorial_mul_factorial (le_of_lt_succ hk₁)] simp [factorial_succ, Nat.mul_comm, Nat.mul_left_comm, Nat.mul_assoc] have h₃ : k * n ! ≀ n * n ! := Nat.mul_le_mul_right _ (le_of_succ_le_succ hk) rw [choose_succ_succ, Nat.add_mul, Nat.add_mul, succ_sub_succ, h, h₁, hβ‚‚, Nat.add_mul, Nat.mul_sub_right_distrib, factorial_succ, ← Nat.add_sub_assoc h₃, Nat.add_assoc, ← Nat.add_mul, Nat.add_sub_cancel_left, Nat.add_comm] Β· rw [hk₁]; simp [hk₁, Nat.mul_comm, choose, Nat.sub_self] theorem choose_mul {n k s : β„•} (hkn : k ≀ n) (hsk : s ≀ k) : n.choose k * k.choose s = n.choose s * (n - s).choose (k - s) := have h : 0 < (n - k)! * (k - s)! * s ! := by apply_rules [factorial_pos, Nat.mul_pos] Nat.mul_right_cancel h <| calc n.choose k * k.choose s * ((n - k)! * (k - s)! * s !) = n.choose k * (k.choose s * s ! * (k - s)!) * (n - k)! := by rw [Nat.mul_assoc, Nat.mul_assoc, Nat.mul_assoc, Nat.mul_assoc _ s !, Nat.mul_assoc, Nat.mul_comm (n - k)!, Nat.mul_comm s !] _ = n ! := by rw [choose_mul_factorial_mul_factorial hsk, choose_mul_factorial_mul_factorial hkn] _ = n.choose s * s ! * ((n - s).choose (k - s) * (k - s)! * (n - s - (k - s))!) := by rw [choose_mul_factorial_mul_factorial (Nat.sub_le_sub_right hkn _), choose_mul_factorial_mul_factorial (hsk.trans hkn)] _ = n.choose s * (n - s).choose (k - s) * ((n - k)! * (k - s)! * s !) := by rw [Nat.sub_sub_sub_cancel_right hsk, Nat.mul_assoc, Nat.mul_left_comm s !, Nat.mul_assoc, Nat.mul_comm (k - s)!, Nat.mul_comm s !, Nat.mul_right_comm, ← Nat.mul_assoc] theorem choose_eq_factorial_div_factorial {n k : β„•} (hk : k ≀ n) : choose n k = n ! / (k ! * (n - k)!) := by rw [← choose_mul_factorial_mul_factorial hk, Nat.mul_assoc] exact (mul_div_left _ (Nat.mul_pos (factorial_pos _) (factorial_pos _))).symm theorem add_choose (i j : β„•) : (i + j).choose j = (i + j)! / (i ! * j !) := by rw [choose_eq_factorial_div_factorial (Nat.le_add_left j i), Nat.add_sub_cancel_right, Nat.mul_comm] theorem add_choose_mul_factorial_mul_factorial (i j : β„•) : (i + j).choose j * i ! * j ! = (i + j)! := by rw [← choose_mul_factorial_mul_factorial (Nat.le_add_left _ _), Nat.add_sub_cancel_right, Nat.mul_right_comm] theorem factorial_mul_factorial_dvd_factorial {n k : β„•} (hk : k ≀ n) : k ! * (n - k)! ∣ n ! := by rw [← choose_mul_factorial_mul_factorial hk, Nat.mul_assoc]; exact Nat.dvd_mul_left _ _ theorem factorial_mul_factorial_dvd_factorial_add (i j : β„•) : i ! * j ! ∣ (i + j)! := by suffices i ! * (i + j - i) ! ∣ (i + j)! by rwa [Nat.add_sub_cancel_left i j] at this exact factorial_mul_factorial_dvd_factorial (Nat.le_add_right _ _) @[simp] theorem choose_symm {n k : β„•} (hk : k ≀ n) : choose n (n - k) = choose n k := by rw [choose_eq_factorial_div_factorial hk, choose_eq_factorial_div_factorial (Nat.sub_le _ _), Nat.sub_sub_self hk, Nat.mul_comm] theorem choose_symm_of_eq_add {n a b : β„•} (h : n = a + b) : Nat.choose n a = Nat.choose n b := by suffices choose n (n - b) = choose n b by rw [h, Nat.add_sub_cancel_right] at this; rwa [h] exact choose_symm (h β–Έ le_add_left _ _) theorem choose_symm_add {a b : β„•} : choose (a + b) a = choose (a + b) b := choose_symm_of_eq_add rfl theorem choose_symm_half (m : β„•) : choose (2 * m + 1) (m + 1) = choose (2 * m + 1) m := by apply choose_symm_of_eq_add rw [Nat.add_comm m 1, Nat.add_assoc 1 m m, Nat.add_comm (2 * m) 1, Nat.two_mul m] theorem choose_succ_right_eq (n k : β„•) : choose n (k + 1) * (k + 1) = choose n k * (n - k) := by have e : (n + 1) * choose n k = choose n (k + 1) * (k + 1) + choose n k * (k + 1) := by rw [← Nat.add_mul, Nat.add_comm (choose _ _), ← choose_succ_succ, succ_mul_choose_eq] rw [← Nat.sub_eq_of_eq_add e, Nat.mul_comm, ← Nat.mul_sub_left_distrib, Nat.add_sub_add_right] @[simp] theorem choose_succ_self_right : βˆ€ n : β„•, (n + 1).choose n = n + 1 | 0 => rfl | n + 1 => by rw [choose_succ_succ, choose_succ_self_right n, choose_self] theorem choose_mul_succ_eq (n k : β„•) : n.choose k * (n + 1) = (n + 1).choose k * (n + 1 - k) := by cases k with | zero => simp | succ k => obtain hk | hk := le_or_lt (k + 1) (n + 1) Β· rw [choose_succ_succ, Nat.add_mul, succ_sub_succ, ← choose_succ_right_eq, ← succ_sub_succ, Nat.mul_sub_left_distrib, Nat.add_sub_cancel' (Nat.mul_le_mul_left _ hk)] Β· rw [choose_eq_zero_of_lt hk, choose_eq_zero_of_lt (n.lt_succ_self.trans hk), Nat.zero_mul, Nat.zero_mul] theorem ascFactorial_eq_factorial_mul_choose (n k : β„•) : (n + 1).ascFactorial k = k ! * (n + k).choose k := by rw [Nat.mul_comm] apply Nat.mul_right_cancel (n + k - k).factorial_pos rw [choose_mul_factorial_mul_factorial <| Nat.le_add_left k n, Nat.add_sub_cancel_right, ← factorial_mul_ascFactorial, Nat.mul_comm] theorem ascFactorial_eq_factorial_mul_choose' (n k : β„•) : n.ascFactorial k = k ! * (n + k - 1).choose k := by cases n Β· cases k Β· rw [ascFactorial_zero, choose_zero_right, factorial_zero, Nat.mul_one] Β· simp only [zero_ascFactorial, zero_eq, Nat.zero_add, succ_sub_succ_eq_sub, Nat.le_zero_eq, Nat.sub_zero, choose_succ_self, Nat.mul_zero] rw [ascFactorial_eq_factorial_mul_choose] simp only [succ_add_sub_one] theorem factorial_dvd_ascFactorial (n k : β„•) : k ! ∣ n.ascFactorial k := ⟨(n + k - 1).choose k, ascFactorial_eq_factorial_mul_choose' _ _⟩ theorem choose_eq_asc_factorial_div_factorial (n k : β„•) : (n + k).choose k = (n + 1).ascFactorial k / k ! := by apply Nat.mul_left_cancel k.factorial_pos rw [← ascFactorial_eq_factorial_mul_choose] exact (Nat.mul_div_cancel' <| factorial_dvd_ascFactorial _ _).symm theorem choose_eq_asc_factorial_div_factorial' (n k : β„•) : (n + k - 1).choose k = n.ascFactorial k / k ! := Nat.eq_div_of_mul_eq_right k.factorial_ne_zero (ascFactorial_eq_factorial_mul_choose' _ _).symm theorem descFactorial_eq_factorial_mul_choose (n k : β„•) : n.descFactorial k = k ! * n.choose k := by obtain h | h := Nat.lt_or_ge n k Β· rw [descFactorial_eq_zero_iff_lt.2 h, choose_eq_zero_of_lt h, Nat.mul_zero] rw [Nat.mul_comm] apply Nat.mul_right_cancel (n - k).factorial_pos rw [choose_mul_factorial_mul_factorial h, ← factorial_mul_descFactorial h, Nat.mul_comm] theorem factorial_dvd_descFactorial (n k : β„•) : k ! ∣ n.descFactorial k := ⟨n.choose k, descFactorial_eq_factorial_mul_choose _ _⟩ theorem choose_eq_descFactorial_div_factorial (n k : β„•) : n.choose k = n.descFactorial k / k ! := Nat.eq_div_of_mul_eq_right k.factorial_ne_zero (descFactorial_eq_factorial_mul_choose _ _).symm /-- A faster implementation of `choose`, to be used during bytecode evaluation and in compiled code. -/ def fast_choose n k := Nat.descFactorial n k / Nat.factorial k @[csimp] lemma choose_eq_fast_choose : Nat.choose = fast_choose := funext (fun _ => funext (Nat.choose_eq_descFactorial_div_factorial _)) /-! ### Inequalities -/ /-- Show that `Nat.choose` is increasing for small values of the right argument. -/ theorem choose_le_succ_of_lt_half_left {r n : β„•} (h : r < n / 2) : choose n r ≀ choose n (r + 1) := by refine Nat.le_of_mul_le_mul_right ?_ (Nat.sub_pos_of_lt (h.trans_le (n.div_le_self 2))) rw [← choose_succ_right_eq] apply Nat.mul_le_mul_left rw [← Nat.lt_iff_add_one_le, Nat.lt_sub_iff_add_lt, ← Nat.mul_two] exact lt_of_lt_of_le (Nat.mul_lt_mul_of_pos_right h Nat.zero_lt_two) (n.div_mul_le_self 2) /-- Show that for small values of the right argument, the middle value is largest. -/ private theorem choose_le_middle_of_le_half_left {n r : β„•} (hr : r ≀ n / 2) : choose n r ≀ choose n (n / 2) := by induction hr using decreasingInduction with | self => rfl | of_succ k hk ih => exact (choose_le_succ_of_lt_half_left hk).trans ih /-- `choose n r` is maximised when `r` is `n/2`. -/ theorem choose_le_middle (r n : β„•) : choose n r ≀ choose n (n / 2) := by cases' le_or_gt r n with b b Β· rcases le_or_lt r (n / 2) with a | h Β· apply choose_le_middle_of_le_half_left a Β· rw [← choose_symm b] apply choose_le_middle_of_le_half_left rw [div_lt_iff_lt_mul' Nat.zero_lt_two] at h rw [le_div_iff_mul_le' Nat.zero_lt_two, Nat.mul_sub_right_distrib, Nat.sub_le_iff_le_add, ← Nat.sub_le_iff_le_add', Nat.mul_two, Nat.add_sub_cancel] exact le_of_lt h Β· rw [choose_eq_zero_of_lt b] apply zero_le /-! #### Inequalities about increasing the first argument -/ theorem choose_le_succ (a c : β„•) : choose a c ≀ choose a.succ c := by cases c <;> simp [Nat.choose_succ_succ] theorem choose_le_add (a b c : β„•) : choose a c ≀ choose (a + b) c := by induction' b with b_n b_ih Β· simp exact le_trans b_ih (choose_le_succ (a + b_n) c) theorem choose_le_choose {a b : β„•} (c : β„•) (h : a ≀ b) : choose a c ≀ choose b c := Nat.add_sub_cancel' h β–Έ choose_le_add a (b - a) c theorem choose_mono (b : β„•) : Monotone fun a => choose a b := fun _ _ => choose_le_choose b /-! #### Multichoose Whereas `choose n k` is the number of subsets of cardinality `k` from a type of cardinality `n`, `multichoose n k` is the number of multisets of cardinality `k` from a type of cardinality `n`. Alternatively, whereas `choose n k` counts the number of combinations, i.e. ways to select `k` items (up to permutation) from `n` items without replacement, `multichoose n k` counts the number of multicombinations, i.e. ways to select `k` items (up to permutation) from `n` items with replacement. Note that `multichoose` is *not* the multinomial coefficient, although it can be computed in terms of multinomial coefficients. For details see https://mathworld.wolfram.com/Multichoose.html TODO: Prove that `choose (-n) k = (-1)^k * multichoose n k`, where `choose` is the generalized binomial coefficient. <https://github.com/leanprover-community/mathlib/pull/15072#issuecomment-1171415738> -/ /-- `multichoose n k` is the number of multisets of cardinality `k` from a type of cardinality `n`. -/ def multichoose : β„• β†’ β„• β†’ β„• | _, 0 => 1 | 0, _ + 1 => 0 | n + 1, k + 1 => multichoose n (k + 1) + multichoose (n + 1) k @[simp] theorem multichoose_zero_right (n : β„•) : multichoose n 0 = 1 := by cases n <;> simp [multichoose] @[simp] theorem multichoose_zero_succ (k : β„•) : multichoose 0 (k + 1) = 0 := by simp [multichoose] theorem multichoose_succ_succ (n k : β„•) : multichoose (n + 1) (k + 1) = multichoose n (k + 1) + multichoose (n + 1) k := by simp [multichoose] @[simp] theorem multichoose_one (k : β„•) : multichoose 1 k = 1 := by induction' k with k IH; Β· simp simp [multichoose_succ_succ 0 k, IH] @[simp] theorem multichoose_two (k : β„•) : multichoose 2 k = k + 1 := by induction' k with k IH; Β· simp rw [multichoose, IH] simp [Nat.add_comm] @[simp] theorem multichoose_one_right (n : β„•) : multichoose n 1 = n := by induction' n with n IH; Β· simp simp [multichoose_succ_succ n 0, IH] theorem multichoose_eq : βˆ€ n k : β„•, multichoose n k = (n + k - 1).choose k | _, 0 => by simp | 0, k + 1 => by simp | n + 1, k + 1 => by have : n + (k + 1) < (n + 1) + (k + 1) := Nat.add_lt_add_right (Nat.lt_succ_self _) _ have : (n + 1) + k < (n + 1) + (k + 1) := Nat.add_lt_add_left (Nat.lt_succ_self _) _ erw [multichoose_succ_succ, Nat.add_comm, Nat.succ_add_sub_one, ← Nat.add_assoc, Nat.choose_succ_succ] simp [multichoose_eq n (k+1), multichoose_eq (n+1) k] termination_by a b => a + b decreasing_by all_goals assumption end Nat
Data\Nat\Choose\Bounds.lean
/- Copyright (c) 2021 YaΓ«l Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: YaΓ«l Dillies, Eric Rodriguez -/ import Mathlib.Algebra.Order.Field.Basic 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`: `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*} [LinearOrderedSemifield Ξ±] namespace Nat theorem choose_le_pow (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 -- 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 end Nat
Data\Nat\Choose\Cast.lean
/- Copyright (c) 2021 YaΓ«l Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: YaΓ«l Dillies -/ import Mathlib.Data.Nat.Choose.Basic import Mathlib.Data.Nat.Factorial.Cast /-! # Cast of binomial coefficients This file allows calculating the binomial coefficient `a.choose b` as an element of a division ring of characteristic `0`. -/ open Nat variable (K : Type*) [DivisionRing K] [CharZero K] namespace Nat theorem cast_choose {a b : β„•} (h : a ≀ b) : (b.choose a : K) = b ! / (a ! * (b - a)!) := by have : βˆ€ {n : β„•}, (n ! : K) β‰  0 := Nat.cast_ne_zero.2 (factorial_ne_zero _) rw [eq_div_iff_mul_eq (mul_ne_zero this this)] rw_mod_cast [← mul_assoc, choose_mul_factorial_mul_factorial h] theorem cast_add_choose {a b : β„•} : ((a + b).choose a : K) = (a + b)! / (a ! * b !) := by rw [cast_choose K (_root_.le_add_right le_rfl), add_tsub_cancel_left] theorem cast_choose_eq_ascPochhammer_div (a b : β„•) : (a.choose b : K) = (ascPochhammer K b).eval ↑(a - (b - 1)) / b ! := by rw [eq_div_iff_mul_eq (cast_ne_zero.2 b.factorial_ne_zero : (b ! : K) β‰  0), ← cast_mul, mul_comm, ← descFactorial_eq_factorial_mul_choose, ← cast_descFactorial] theorem cast_choose_two (a : β„•) : (a.choose 2 : K) = a * (a - 1) / 2 := by rw [← cast_descFactorial_two, descFactorial_eq_factorial_mul_choose, factorial_two, mul_comm, cast_mul, cast_two, eq_div_iff_mul_eq (two_ne_zero : (2 : K) β‰  0)] end Nat
Data\Nat\Choose\Central.lean
/- Copyright (c) 2021 Patrick Stevens. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Stevens, Thomas Browning -/ import Mathlib.Data.Nat.Choose.Basic import Mathlib.Data.Nat.GCD.Basic import Mathlib.Tactic.Ring import Mathlib.Tactic.Linarith /-! # Central binomial coefficients This file proves properties of the central binomial coefficients (that is, `Nat.choose (2 * n) n`). ## Main definition and results * `Nat.centralBinom`: the central binomial coefficient, `(2 * n).choose n`. * `Nat.succ_mul_centralBinom_succ`: the inductive relationship between successive central binomial coefficients. * `Nat.four_pow_lt_mul_centralBinom`: an exponential lower bound on the central binomial coefficient. * `succ_dvd_centralBinom`: The result that `n+1 ∣ n.centralBinom`, ensuring that the explicit definition of the Catalan numbers is integer-valued. -/ namespace Nat /-- The central binomial coefficient, `Nat.choose (2 * n) n`. -/ def centralBinom (n : β„•) := (2 * n).choose n theorem centralBinom_eq_two_mul_choose (n : β„•) : centralBinom n = (2 * n).choose n := rfl theorem centralBinom_pos (n : β„•) : 0 < centralBinom n := choose_pos (Nat.le_mul_of_pos_left _ zero_lt_two) theorem centralBinom_ne_zero (n : β„•) : centralBinom n β‰  0 := (centralBinom_pos n).ne' @[simp] theorem centralBinom_zero : centralBinom 0 = 1 := choose_zero_right _ /-- The central binomial coefficient is the largest binomial coefficient. -/ theorem choose_le_centralBinom (r n : β„•) : choose (2 * n) r ≀ centralBinom n := calc (2 * n).choose r ≀ (2 * n).choose (2 * n / 2) := choose_le_middle r (2 * n) _ = (2 * n).choose n := by rw [Nat.mul_div_cancel_left n zero_lt_two] theorem two_le_centralBinom (n : β„•) (n_pos : 0 < n) : 2 ≀ centralBinom n := calc 2 ≀ 2 * n := Nat.le_mul_of_pos_right _ n_pos _ = (2 * n).choose 1 := (choose_one_right (2 * n)).symm _ ≀ centralBinom n := choose_le_centralBinom 1 n /-- An inductive property of the central binomial coefficient. -/ theorem succ_mul_centralBinom_succ (n : β„•) : (n + 1) * centralBinom (n + 1) = 2 * (2 * n + 1) * centralBinom n := calc (n + 1) * (2 * (n + 1)).choose (n + 1) = (2 * n + 2).choose (n + 1) * (n + 1) := mul_comm _ _ _ = (2 * n + 1).choose n * (2 * n + 2) := by rw [choose_succ_right_eq, choose_mul_succ_eq] _ = 2 * ((2 * n + 1).choose n * (n + 1)) := by ring _ = 2 * ((2 * n + 1).choose n * (2 * n + 1 - n)) := by rw [two_mul n, add_assoc, Nat.add_sub_cancel_left] _ = 2 * ((2 * n).choose n * (2 * n + 1)) := by rw [choose_mul_succ_eq] _ = 2 * (2 * n + 1) * (2 * n).choose n := by rw [mul_assoc, mul_comm (2 * n + 1)] /-- An exponential lower bound on the central binomial coefficient. This bound is of interest because it appears in [Tochiori's refinement of ErdΕ‘s's proof of Bertrand's postulate](tochiori_bertrand). -/ theorem four_pow_lt_mul_centralBinom (n : β„•) (n_big : 4 ≀ n) : 4 ^ n < n * centralBinom n := by induction' n using Nat.strong_induction_on with n IH rcases lt_trichotomy n 4 with (hn | rfl | hn) Β· clear IH; exact False.elim ((not_lt.2 n_big) hn) Β· norm_num [centralBinom, choose] obtain ⟨n, rfl⟩ : βˆƒ m, n = m + 1 := Nat.exists_eq_succ_of_ne_zero (Nat.not_eq_zero_of_lt hn) calc 4 ^ (n + 1) < 4 * (n * centralBinom n) := lt_of_eq_of_lt pow_succ' <| (mul_lt_mul_left <| zero_lt_four' β„•).mpr (IH n n.lt_succ_self (Nat.le_of_lt_succ hn)) _ ≀ 2 * (2 * n + 1) * centralBinom n := by rw [← mul_assoc]; linarith _ = (n + 1) * centralBinom (n + 1) := (succ_mul_centralBinom_succ n).symm /-- An exponential lower bound on the central binomial coefficient. This bound is weaker than `Nat.four_pow_lt_mul_centralBinom`, but it is of historical interest because it appears in ErdΕ‘s's proof of Bertrand's postulate. -/ theorem four_pow_le_two_mul_self_mul_centralBinom : βˆ€ (n : β„•) (_ : 0 < n), 4 ^ n ≀ 2 * n * centralBinom n | 0, pr => (Nat.not_lt_zero _ pr).elim | 1, _ => by norm_num [centralBinom, choose] | 2, _ => by norm_num [centralBinom, choose] | 3, _ => by norm_num [centralBinom, choose] | n + 4, _ => calc 4 ^ (n+4) ≀ (n+4) * centralBinom (n+4) := (four_pow_lt_mul_centralBinom _ le_add_self).le _ ≀ 2 * (n+4) * centralBinom (n+4) := by rw [mul_assoc]; refine Nat.le_mul_of_pos_left _ zero_lt_two theorem two_dvd_centralBinom_succ (n : β„•) : 2 ∣ centralBinom (n + 1) := by use (n + 1 + n).choose n rw [centralBinom_eq_two_mul_choose, two_mul, ← add_assoc, choose_succ_succ' (n + 1 + n) n, choose_symm_add, ← two_mul] theorem two_dvd_centralBinom_of_one_le {n : β„•} (h : 0 < n) : 2 ∣ centralBinom n := by rw [← Nat.succ_pred_eq_of_pos h] exact two_dvd_centralBinom_succ n.pred /-- A crucial lemma to ensure that Catalan numbers can be defined via their explicit formula `catalan n = n.centralBinom / (n + 1)`. -/ theorem succ_dvd_centralBinom (n : β„•) : n + 1 ∣ n.centralBinom := by have h_s : (n + 1).Coprime (2 * n + 1) := by rw [two_mul, add_assoc, coprime_add_self_right, coprime_self_add_left] exact coprime_one_left n apply h_s.dvd_of_dvd_mul_left apply Nat.dvd_of_mul_dvd_mul_left zero_lt_two rw [← mul_assoc, ← succ_mul_centralBinom_succ, mul_comm] exact mul_dvd_mul_left _ (two_dvd_centralBinom_succ n) end Nat
Data\Nat\Choose\Dvd.lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Patrick Stevens -/ import Mathlib.Data.Nat.Choose.Basic import Mathlib.Data.Nat.Prime.Basic /-! # Divisibility properties of binomial coefficients -/ namespace Nat open Nat namespace Prime variable {p a b k : β„•} theorem dvd_choose_add (hp : Prime p) (hap : a < p) (hbp : b < p) (h : p ≀ a + b) : p ∣ choose (a + b) a := by have h₁ : p ∣ (a + b)! := hp.dvd_factorial.2 h rw [← add_choose_mul_factorial_mul_factorial, ← choose_symm_add, hp.dvd_mul, hp.dvd_mul, hp.dvd_factorial, hp.dvd_factorial] at h₁ exact (h₁.resolve_right hbp.not_le).resolve_right hap.not_le lemma dvd_choose (hp : Prime p) (ha : a < p) (hab : b - a < p) (h : p ≀ b) : p ∣ choose b a := have : a + (b - a) = b := Nat.add_sub_of_le (ha.le.trans h) this β–Έ hp.dvd_choose_add ha hab (this.symm β–Έ h) lemma dvd_choose_self (hp : Prime p) (hk : k β‰  0) (hkp : k < p) : p ∣ choose p k := hp.dvd_choose hkp (sub_lt ((zero_le _).trans_lt hkp) <| zero_lt_of_ne_zero hk) le_rfl end Prime end Nat
Data\Nat\Choose\Factorization.lean
/- Copyright (c) 2022 Bolton Bailey. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bolton Bailey, Patrick Stevens, Thomas Browning -/ import Mathlib.Data.Nat.Choose.Central import Mathlib.Data.Nat.Factorization.Basic import Mathlib.Data.Nat.Multiplicity /-! # Factorization of Binomial Coefficients This file contains a few results on the multiplicity of prime factors within certain size bounds in binomial coefficients. These include: * `Nat.factorization_choose_le_log`: a logarithmic upper bound on the multiplicity of a prime in a binomial coefficient. * `Nat.factorization_choose_le_one`: Primes above `sqrt n` appear at most once in the factorization of `n` choose `k`. * `Nat.factorization_centralBinom_of_two_mul_self_lt_three_mul`: Primes from `2 * n / 3` to `n` do not appear in the factorization of the `n`th central binomial coefficient. * `Nat.factorization_choose_eq_zero_of_lt`: Primes greater than `n` do not appear in the factorization of `n` choose `k`. These results appear in the [ErdΕ‘s proof of Bertrand's postulate](aigner1999proofs). -/ namespace Nat variable {p n k : β„•} /-- A logarithmic upper bound on the multiplicity of a prime in a binomial coefficient. -/ theorem factorization_choose_le_log : (choose n k).factorization p ≀ log p n := by by_cases h : (choose n k).factorization p = 0 Β· simp [h] have hp : p.Prime := Not.imp_symm (choose n k).factorization_eq_zero_of_non_prime h have hkn : k ≀ n := by refine le_of_not_lt fun hnk => h ?_ simp [choose_eq_zero_of_lt hnk] rw [factorization_def _ hp, @padicValNat_def _ ⟨hp⟩ _ (choose_pos hkn)] simp only [hp.multiplicity_choose hkn (lt_add_one _), PartENat.get_natCast] exact (Finset.card_filter_le _ _).trans (le_of_eq (Nat.card_Ico _ _)) /-- A `pow` form of `Nat.factorization_choose_le` -/ theorem pow_factorization_choose_le (hn : 0 < n) : p ^ (choose n k).factorization p ≀ n := pow_le_of_le_log hn.ne' factorization_choose_le_log /-- Primes greater than about `sqrt n` appear only to multiplicity 0 or 1 in the binomial coefficient. -/ theorem factorization_choose_le_one (p_large : n < p ^ 2) : (choose n k).factorization p ≀ 1 := by apply factorization_choose_le_log.trans rcases eq_or_ne n 0 with (rfl | hn0); Β· simp exact Nat.lt_succ_iff.1 (log_lt_of_lt_pow hn0 p_large) theorem factorization_choose_of_lt_three_mul (hp' : p β‰  2) (hk : p ≀ k) (hk' : p ≀ n - k) (hn : n < 3 * p) : (choose n k).factorization p = 0 := by cases' em' p.Prime with hp hp Β· exact factorization_eq_zero_of_non_prime (choose n k) hp cases' lt_or_le n k with hnk hkn Β· simp [choose_eq_zero_of_lt hnk] rw [factorization_def _ hp, @padicValNat_def _ ⟨hp⟩ _ (choose_pos hkn)] simp only [hp.multiplicity_choose hkn (lt_add_one _), PartENat.get_natCast, Finset.card_eq_zero, Finset.filter_eq_empty_iff, not_le] intro i hi rcases eq_or_lt_of_le (Finset.mem_Ico.mp hi).1 with (rfl | hi) Β· rw [pow_one, ← add_lt_add_iff_left (2 * p), ← succ_mul, two_mul, add_add_add_comm] exact lt_of_le_of_lt (add_le_add (add_le_add_right (le_mul_of_one_le_right' ((one_le_div_iff hp.pos).mpr hk)) (k % p)) (add_le_add_right (le_mul_of_one_le_right' ((one_le_div_iff hp.pos).mpr hk')) ((n - k) % p))) (by rwa [div_add_mod, div_add_mod, add_tsub_cancel_of_le hkn]) Β· replace hn : n < p ^ i := by have : 3 ≀ p := lt_of_le_of_ne hp.two_le hp'.symm calc n < 3 * p := hn _ ≀ p * p := mul_le_mul_right' this p _ = p ^ 2 := (sq p).symm _ ≀ p ^ i := pow_le_pow_right hp.one_lt.le hi rwa [mod_eq_of_lt (lt_of_le_of_lt hkn hn), mod_eq_of_lt (lt_of_le_of_lt tsub_le_self hn), add_tsub_cancel_of_le hkn] /-- Primes greater than about `2 * n / 3` and less than `n` do not appear in the factorization of `centralBinom n`. -/ theorem factorization_centralBinom_of_two_mul_self_lt_three_mul (n_big : 2 < n) (p_le_n : p ≀ n) (big : 2 * n < 3 * p) : (centralBinom n).factorization p = 0 := by refine factorization_choose_of_lt_three_mul ?_ p_le_n (p_le_n.trans ?_) big Β· omega Β· rw [two_mul, add_tsub_cancel_left] theorem factorization_factorial_eq_zero_of_lt (h : n < p) : (factorial n).factorization p = 0 := by induction' n with n hn; Β· simp rw [factorial_succ, factorization_mul n.succ_ne_zero n.factorial_ne_zero, Finsupp.coe_add, Pi.add_apply, hn (lt_of_succ_lt h), add_zero, factorization_eq_zero_of_lt h] theorem factorization_choose_eq_zero_of_lt (h : n < p) : (choose n k).factorization p = 0 := by by_cases hnk : n < k; Β· simp [choose_eq_zero_of_lt hnk] rw [choose_eq_factorial_div_factorial (le_of_not_lt hnk), factorization_div (factorial_mul_factorial_dvd_factorial (le_of_not_lt hnk)), Finsupp.coe_tsub, Pi.sub_apply, factorization_factorial_eq_zero_of_lt h, zero_tsub] /-- If a prime `p` has positive multiplicity in the `n`th central binomial coefficient, `p` is no more than `2 * n` -/ theorem factorization_centralBinom_eq_zero_of_two_mul_lt (h : 2 * n < p) : (centralBinom n).factorization p = 0 := factorization_choose_eq_zero_of_lt h /-- Contrapositive form of `Nat.factorization_centralBinom_eq_zero_of_two_mul_lt` -/ theorem le_two_mul_of_factorization_centralBinom_pos (h_pos : 0 < (centralBinom n).factorization p) : p ≀ 2 * n := le_of_not_lt (pos_iff_ne_zero.mp h_pos ∘ factorization_centralBinom_eq_zero_of_two_mul_lt) /-- A binomial coefficient is the product of its prime factors, which are at most `n`. -/ theorem prod_pow_factorization_choose (n k : β„•) (hkn : k ≀ n) : (∏ p ∈ Finset.range (n + 1), p ^ (Nat.choose n k).factorization p) = choose n k := by conv => -- Porting note: was `nth_rw_rhs` rhs rw [← factorization_prod_pow_eq_self (choose_pos hkn).ne'] rw [eq_comm] apply Finset.prod_subset Β· intro p hp rw [Finset.mem_range] contrapose! hp rw [Finsupp.mem_support_iff, Classical.not_not, factorization_choose_eq_zero_of_lt hp] Β· intro p _ h2 simp [Classical.not_not.1 (mt Finsupp.mem_support_iff.2 h2)] /-- The `n`th central binomial coefficient is the product of its prime factors, which are at most `2n`. -/ theorem prod_pow_factorization_centralBinom (n : β„•) : (∏ p ∈ Finset.range (2 * n + 1), p ^ (centralBinom n).factorization p) = centralBinom n := by apply prod_pow_factorization_choose omega end Nat
Data\Nat\Choose\Lucas.lean
/- Copyright (c) 2023 Gareth Ma. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gareth Ma -/ import Mathlib.Data.ZMod.Basic import Mathlib.RingTheory.Polynomial.Basic /-! # Lucas's theorem This file contains a proof of [Lucas's theorem](https://en.wikipedia.org/wiki/Lucas's_theorem) about binomial coefficients, which says that for primes `p`, `n` choose `k` is congruent to product of `n_i` choose `k_i` modulo `p`, where `n_i` and `k_i` are the base-`p` digits of `n` and `k`, respectively. ## Main statements * `lucas_theorem`: the binomial coefficient `n choose k` is congruent to the product of `n_i choose k_i` modulo `p`, where `n_i` and `k_i` are the base-`p` digits of `n` and `k`, respectively. -/ open Finset hiding choose open Nat BigOperators Polynomial namespace Choose variable {n k p : β„•} [Fact p.Prime] /-- For primes `p`, `choose n k` is congruent to `choose (n % p) (k % p) * choose (n / p) (k / p)` modulo `p`. Also see `choose_modEq_choose_mod_mul_choose_div_nat` for the version with `MOD`. -/ theorem choose_modEq_choose_mod_mul_choose_div : choose n k ≑ choose (n % p) (k % p) * choose (n / p) (k / p) [ZMOD p] := by have decompose : ((X : (ZMod p)[X]) + 1) ^ n = (X + 1) ^ (n % p) * (X ^ p + 1) ^ (n / p) := by simpa using add_pow_eq_add_pow_mod_mul_pow_add_pow_div _ (X : (ZMod p)[X]) 1 simp only [← ZMod.intCast_eq_intCast_iff, Int.cast_mul, Int.cast_ofNat, ← coeff_X_add_one_pow _ n k, ← eq_intCast (Int.castRingHom (ZMod p)), ← coeff_map, Polynomial.map_pow, Polynomial.map_add, Polynomial.map_one, map_X, decompose] simp only [add_pow, one_pow, mul_one, ← pow_mul, sum_mul_sum] conv_lhs => enter [1, 2, k, 2, k'] rw [← mul_assoc, mul_right_comm _ _ (X ^ (p * k')), ← pow_add, mul_assoc, ← cast_mul] have h_iff : βˆ€ x ∈ range (n % p + 1) Γ—Λ’ range (n / p + 1), k = x.1 + p * x.2 ↔ (k % p, k / p) = x := by intro ⟨x₁, xβ‚‚βŸ© hx rw [Prod.mk.injEq] constructor <;> intro h Β· simp only [mem_product, mem_range] at hx have h' : x₁ < p := lt_of_lt_of_le hx.left $ mod_lt _ Fin.size_pos' rw [h, add_mul_mod_self_left, add_mul_div_left _ _ Fin.size_pos', eq_comm (b := xβ‚‚)] exact ⟨mod_eq_of_lt h', self_eq_add_left.mpr (div_eq_of_lt h')⟩ Β· rw [← h.left, ← h.right, mod_add_div] simp only [finset_sum_coeff, coeff_mul_natCast, coeff_X_pow, ite_mul, zero_mul, ← cast_mul] rw [← sum_product', sum_congr rfl (fun a ha ↦ if_congr (h_iff a ha) rfl rfl), sum_ite_eq] split_ifs with h Β· simp Β· rw [mem_product, mem_range, mem_range, not_and_or, lt_succ, not_le, not_lt] at h cases h <;> simp [choose_eq_zero_of_lt (by tauto)] /-- For primes `p`, `choose n k` is congruent to `choose (n % p) (k % p) * choose (n / p) (k / p)` modulo `p`. Also see `choose_modEq_choose_mod_mul_choose_div` for the version with `ZMOD`. -/ theorem choose_modEq_choose_mod_mul_choose_div_nat : choose n k ≑ choose (n % p) (k % p) * choose (n / p) (k / p) [MOD p] := by rw [← Int.natCast_modEq_iff] exact_mod_cast choose_modEq_choose_mod_mul_choose_div /-- For primes `p`, `choose n k` is congruent to the product of `choose (⌊n / p ^ iβŒ‹ % p) (⌊k / p ^ iβŒ‹ % p)` over i < a, multiplied by `choose (⌊n / p ^ aβŒ‹) (⌊k / p ^ aβŒ‹)`, modulo `p`. -/ theorem choose_modEq_choose_mul_prod_range_choose (a : β„•) : choose n k ≑ choose (n / p ^ a) (k / p ^ a) * ∏ i in range a, choose (n / p ^ i % p) (k / p ^ i % p) [ZMOD p] := match a with | Nat.zero => by simp | Nat.succ a => (choose_modEq_choose_mul_prod_range_choose a).trans <| by rw [prod_range_succ, cast_mul, ← mul_assoc, mul_right_comm] gcongr apply choose_modEq_choose_mod_mul_choose_div.trans simp_rw [pow_succ, Nat.div_div_eq_div_mul, mul_comm] rfl /-- **Lucas's Theorem**: For primes `p`, `choose n k` is congruent to the product of `choose (⌊n / p ^ iβŒ‹ % p) (⌊k / p ^ iβŒ‹ % p)` over `i` modulo `p`. -/ theorem choose_modEq_prod_range_choose {a : β„•} (ha₁ : n < p ^ a) (haβ‚‚ : k < p ^ a) : choose n k ≑ ∏ i in range a, choose (n / p ^ i % p) (k / p ^ i % p) [ZMOD p] := by apply (choose_modEq_choose_mul_prod_range_choose a).trans simp_rw [Nat.div_eq_of_lt ha₁, Nat.div_eq_of_lt haβ‚‚, choose, cast_one, one_mul, cast_prod, Int.ModEq.refl] /-- **Lucas's Theorem**: For primes `p`, `choose n k` is congruent to the product of `choose (⌊n / p ^ iβŒ‹ % p) (⌊k / p ^ iβŒ‹ % p)` over `i` modulo `p`. -/ theorem choose_modEq_prod_range_choose_nat {a : β„•} (ha₁ : n < p ^ a) (haβ‚‚ : k < p ^ a) : choose n k ≑ ∏ i in range a, choose (n / p ^ i % p) (k / p ^ i % p) [MOD p] := by rw [← Int.natCast_modEq_iff] exact_mod_cast choose_modEq_prod_range_choose ha₁ haβ‚‚ alias lucas_theorem := choose_modEq_prod_range_choose alias lucas_theorem_nat := choose_modEq_prod_range_choose_nat end Choose
Data\Nat\Choose\Multinomial.lean
/- Copyright (c) 2022 Pim Otte. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller, Pim Otte -/ import Mathlib.Algebra.BigOperators.Fin import Mathlib.Algebra.Order.Antidiag.Pi import Mathlib.Data.Nat.Choose.Sum import Mathlib.Data.Nat.Factorial.BigOperators import Mathlib.Data.Nat.Factorial.DoubleFactorial import Mathlib.Data.Fin.VecNotation import Mathlib.Data.Finset.Sym import Mathlib.Data.Finsupp.Multiset /-! # Multinomial This file defines the multinomial coefficient and several small lemma's for manipulating it. ## Main declarations - `Nat.multinomial`: the multinomial coefficient ## Main results - `Finset.sum_pow`: The expansion of `(s.sum x) ^ n` using multinomial coefficients -/ open Finset open scoped Nat namespace Nat variable {Ξ± : Type*} (s : Finset Ξ±) (f : Ξ± β†’ β„•) {a b : Ξ±} (n : β„•) /-- The multinomial coefficient. Gives the number of strings consisting of symbols from `s`, where `c ∈ s` appears with multiplicity `f c`. Defined as `(βˆ‘ i ∈ s, f i)! / ∏ i ∈ s, (f i)!`. -/ def multinomial : β„• := (βˆ‘ i ∈ s, f i)! / ∏ i ∈ s, (f i)! theorem multinomial_pos : 0 < multinomial s f := Nat.div_pos (le_of_dvd (factorial_pos _) (prod_factorial_dvd_factorial_sum s f)) (prod_factorial_pos s f) theorem multinomial_spec : (∏ i ∈ s, (f i)!) * multinomial s f = (βˆ‘ i ∈ s, f i)! := Nat.mul_div_cancel' (prod_factorial_dvd_factorial_sum s f) @[simp] lemma multinomial_empty : multinomial βˆ… f = 1 := by simp [multinomial] @[deprecated (since := "2024-06-01")] alias multinomial_nil := multinomial_empty variable {s f} lemma multinomial_cons (ha : a βˆ‰ s) (f : Ξ± β†’ β„•) : multinomial (s.cons a ha) f = (f a + βˆ‘ i ∈ s, f i).choose (f a) * multinomial s f := by rw [multinomial, Nat.div_eq_iff_eq_mul_left _ (prod_factorial_dvd_factorial_sum _ _), prod_cons, multinomial, mul_assoc, mul_left_comm _ (f a)!, Nat.div_mul_cancel (prod_factorial_dvd_factorial_sum _ _), ← mul_assoc, Nat.choose_symm_add, Nat.add_choose_mul_factorial_mul_factorial, Finset.sum_cons] positivity lemma multinomial_insert [DecidableEq Ξ±] (ha : a βˆ‰ s) (f : Ξ± β†’ β„•) : multinomial (insert a s) f = (f a + βˆ‘ i ∈ s, f i).choose (f a) * multinomial s f := by rw [← cons_eq_insert _ _ ha, multinomial_cons] @[simp] lemma multinomial_singleton (a : Ξ±) (f : Ξ± β†’ β„•) : multinomial {a} f = 1 := by rw [← cons_empty, multinomial_cons]; simp @[simp] theorem multinomial_insert_one [DecidableEq Ξ±] (h : a βˆ‰ s) (h₁ : f a = 1) : multinomial (insert a s) f = (s.sum f).succ * multinomial s f := by simp only [multinomial, one_mul, factorial] rw [Finset.sum_insert h, Finset.prod_insert h, h₁, add_comm, ← succ_eq_add_one, factorial_succ] simp only [factorial_one, one_mul, Function.comp_apply, factorial, mul_one, ← one_eq_succ_zero] rw [Nat.mul_div_assoc _ (prod_factorial_dvd_factorial_sum _ _)] theorem multinomial_congr {f g : Ξ± β†’ β„•} (h : βˆ€ a ∈ s, f a = g a) : multinomial s f = multinomial s g := by simp only [multinomial]; congr 1 Β· rw [Finset.sum_congr rfl h] Β· exact Finset.prod_congr rfl fun a ha => by rw [h a ha] /-! ### Connection to binomial coefficients When `Nat.multinomial` is applied to a `Finset` of two elements `{a, b}`, the result a binomial coefficient. We use `binomial` in the names of lemmas that involves `Nat.multinomial {a, b}`. -/ theorem binomial_eq [DecidableEq Ξ±] (h : a β‰  b) : multinomial {a, b} f = (f a + f b)! / ((f a)! * (f b)!) := by simp [multinomial, Finset.sum_pair h, Finset.prod_pair h] theorem binomial_eq_choose [DecidableEq Ξ±] (h : a β‰  b) : multinomial {a, b} f = (f a + f b).choose (f a) := by simp [binomial_eq h, choose_eq_factorial_div_factorial (Nat.le_add_right _ _)] theorem binomial_spec [DecidableEq Ξ±] (hab : a β‰  b) : (f a)! * (f b)! * multinomial {a, b} f = (f a + f b)! := by simpa [Finset.sum_pair hab, Finset.prod_pair hab] using multinomial_spec {a, b} f @[simp] theorem binomial_one [DecidableEq Ξ±] (h : a β‰  b) (h₁ : f a = 1) : multinomial {a, b} f = (f b).succ := by simp [multinomial_insert_one (Finset.not_mem_singleton.mpr h) h₁] theorem binomial_succ_succ [DecidableEq Ξ±] (h : a β‰  b) : multinomial {a, b} (Function.update (Function.update f a (f a).succ) b (f b).succ) = multinomial {a, b} (Function.update f a (f a).succ) + multinomial {a, b} (Function.update f b (f b).succ) := by simp only [binomial_eq_choose, Function.update_apply, h, Ne, ite_true, ite_false, not_false_eq_true] rw [if_neg h.symm] rw [add_succ, choose_succ_succ, succ_add_eq_add_succ] ring theorem succ_mul_binomial [DecidableEq Ξ±] (h : a β‰  b) : (f a + f b).succ * multinomial {a, b} f = (f a).succ * multinomial {a, b} (Function.update f a (f a).succ) := by rw [binomial_eq_choose h, binomial_eq_choose h, mul_comm (f a).succ, Function.update_same, Function.update_noteq (ne_comm.mp h)] rw [succ_mul_choose_eq (f a + f b) (f a), succ_add (f a) (f b)] /-! ### Simple cases -/ theorem multinomial_univ_two (a b : β„•) : multinomial Finset.univ ![a, b] = (a + b)! / (a ! * b !) := by rw [multinomial, Fin.sum_univ_two, Fin.prod_univ_two, Matrix.cons_val_zero, Matrix.cons_val_one, Matrix.head_cons] theorem multinomial_univ_three (a b c : β„•) : multinomial Finset.univ ![a, b, c] = (a + b + c)! / (a ! * b ! * c !) := by rw [multinomial, Fin.sum_univ_three, Fin.prod_univ_three] rfl end Nat /-! ### Alternative definitions -/ namespace Finsupp variable {Ξ± : Type*} /-- Alternative multinomial definition based on a finsupp, using the support for the big operations -/ def multinomial (f : Ξ± β†’β‚€ β„•) : β„• := (f.sum fun _ => id)! / f.prod fun _ n => n ! theorem multinomial_eq (f : Ξ± β†’β‚€ β„•) : f.multinomial = Nat.multinomial f.support f := rfl theorem multinomial_update (a : Ξ±) (f : Ξ± β†’β‚€ β„•) : f.multinomial = (f.sum fun _ => id).choose (f a) * (f.update a 0).multinomial := by simp only [multinomial_eq] classical by_cases h : a ∈ f.support Β· rw [← Finset.insert_erase h, Nat.multinomial_insert (Finset.not_mem_erase a _), Finset.add_sum_erase _ f h, support_update_zero] congr 1 exact Nat.multinomial_congr fun _ h ↦ (Function.update_noteq (mem_erase.1 h).1 0 f).symm rw [not_mem_support_iff] at h rw [h, Nat.choose_zero_right, one_mul, ← h, update_self] end Finsupp namespace Multiset variable {Ξ± : Type*} /-- Alternative definition of multinomial based on `Multiset` delegating to the finsupp definition -/ def multinomial [DecidableEq Ξ±] (m : Multiset Ξ±) : β„• := m.toFinsupp.multinomial theorem multinomial_filter_ne [DecidableEq Ξ±] (a : Ξ±) (m : Multiset Ξ±) : m.multinomial = m.card.choose (m.count a) * (m.filter (a β‰  Β·)).multinomial := by dsimp only [multinomial] convert Finsupp.multinomial_update a _ Β· rw [← Finsupp.card_toMultiset, m.toFinsupp_toMultiset] Β· ext1 a rw [toFinsupp_apply, count_filter, Finsupp.coe_update] split_ifs with h Β· rw [Function.update_noteq h.symm, toFinsupp_apply] Β· rw [not_ne_iff.1 h, Function.update_same] @[simp] theorem multinomial_zero [DecidableEq Ξ±] : multinomial (0 : Multiset Ξ±) = 1 := by simp [multinomial, Finsupp.multinomial] end Multiset namespace Finset open _root_.Nat /-! ### Multinomial theorem -/ variable {Ξ± R : Type*} [DecidableEq Ξ±] section Semiring variable [Semiring R] -- TODO: Can we prove one of the following two from the other one? /-- The **multinomial theorem**. -/ lemma sum_pow_eq_sum_piAntidiag_of_commute (s : Finset Ξ±) (f : Ξ± β†’ R) (hc : (s : Set Ξ±).Pairwise fun i j ↦ Commute (f i) (f j)) (n : β„•) : (βˆ‘ i in s, f i) ^ n = βˆ‘ k in piAntidiag s n, multinomial s k * s.noncommProd (fun i ↦ f i ^ k i) (hc.mono' fun i j h ↦ h.pow_pow ..) := by classical induction' s using Finset.cons_induction with a s has ih generalizing n Β· cases n <;> simp rw [Finset.sum_cons, piAntidiag_cons, sum_disjiUnion] simp only [sum_map, Function.Embedding.coeFn_mk, Pi.add_apply, multinomial_cons, Pi.add_apply, eq_self_iff_true, if_true, Nat.cast_mul, noncommProd_cons, eq_self_iff_true, if_true, sum_add_distrib, sum_ite_eq', has, if_false, add_zero, addLeftEmbedding_eq_addRightEmbedding, addRightEmbedding_apply] suffices βˆ€ p : β„• Γ— β„•, p ∈ antidiagonal n β†’ βˆ‘ g in piAntidiag s p.2, ((g a + p.1 + s.sum g).choose (g a + p.1) : R) * multinomial s (g + fun i ↦ ite (i = a) p.1 0) * (f a ^ (g a + p.1) * s.noncommProd (fun i ↦ f i ^ (g i + ite (i = a) p.1 0)) ((hc.mono (by simp)).mono' fun i j h ↦ h.pow_pow ..)) = βˆ‘ g in piAntidiag s p.2, n.choose p.1 * multinomial s g * (f a ^ p.1 * s.noncommProd (fun i ↦ f i ^ g i) ((hc.mono (by simp)).mono' fun i j h ↦ h.pow_pow ..)) by rw [sum_congr rfl this] simp only [Nat.antidiagonal_eq_map, sum_map, Function.Embedding.coeFn_mk] rw [(Commute.sum_right _ _ _ fun i hi ↦ hc (by simp) (by simp [hi]) (by simpa [eq_comm] using ne_of_mem_of_not_mem hi has)).add_pow] simp only [ih (hc.mono (by simp)), sum_mul, mul_sum] refine sum_congr rfl fun i _ ↦ sum_congr rfl fun g _ ↦ ?_ rw [← Nat.cast_comm, (Nat.commute_cast (f a ^ i) _).left_comm, mul_assoc] refine fun p hp ↦ sum_congr rfl fun f hf ↦ ?_ rw [mem_piAntidiag] at hf rw [not_imp_comm.1 (hf.2 _) has, zero_add, hf.1] congr 2 Β· rw [mem_antidiagonal.1 hp] Β· rw [multinomial_congr] intro t ht rw [Pi.add_apply, if_neg, add_zero] exact ne_of_mem_of_not_mem ht has refine noncommProd_congr rfl (fun t ht ↦ ?_) _ rw [if_neg, add_zero] exact ne_of_mem_of_not_mem ht has /-- The **multinomial theorem**. -/ theorem sum_pow_of_commute (x : Ξ± β†’ R) (s : Finset Ξ±) (hc : (s : Set Ξ±).Pairwise fun i j => Commute (x i) (x j)) : βˆ€ n, s.sum x ^ n = βˆ‘ k : s.sym n, k.1.1.multinomial * (k.1.1.map <| x).noncommProd (Multiset.map_set_pairwise <| hc.mono <| mem_sym_iff.1 k.2) := by induction' s using Finset.induction with a s ha ih Β· rw [sum_empty] rintro (_ | n) -- Porting note: Lean cannot infer this instance by itself Β· haveI : Subsingleton (Sym Ξ± 0) := Unique.instSubsingleton rw [_root_.pow_zero, Fintype.sum_subsingleton] swap -- Porting note: Lean cannot infer this instance by itself Β· have : Zero (Sym Ξ± 0) := Sym.instZeroSym exact ⟨0, by simp [eq_iff_true_of_subsingleton]⟩ convert (@one_mul R _ _).symm convert @Nat.cast_one R _ simp Β· rw [_root_.pow_succ, mul_zero] -- Porting note: Lean cannot infer this instance by itself haveI : IsEmpty (Finset.sym (βˆ… : Finset Ξ±) n.succ) := Finset.instIsEmpty apply (Fintype.sum_empty _).symm intro n; specialize ih (hc.mono <| s.subset_insert a) rw [sum_insert ha, (Commute.sum_right s _ _ _).add_pow, sum_range]; swap Β· exact fun _ hb => hc (mem_insert_self a s) (mem_insert_of_mem hb) (ne_of_mem_of_not_mem hb ha).symm Β· simp_rw [ih, mul_sum, sum_mul, sum_sigma', univ_sigma_univ] refine (Fintype.sum_equiv (symInsertEquiv ha) _ _ fun m => ?_).symm rw [m.1.1.multinomial_filter_ne a] conv in m.1.1.map _ => rw [← m.1.1.filter_add_not (a = Β·), Multiset.map_add] simp_rw [Multiset.noncommProd_add, m.1.1.filter_eq, Multiset.map_replicate, m.1.2] rw [Multiset.noncommProd_eq_pow_card _ _ _ fun _ => Multiset.eq_of_mem_replicate] rw [Multiset.card_replicate, Nat.cast_mul, mul_assoc, Nat.cast_comm] congr 1; simp_rw [← mul_assoc, Nat.cast_comm]; rfl end Semiring section CommSemiring variable [CommSemiring R] {f : Ξ± β†’ R} {s : Finset Ξ±} lemma sum_pow_eq_sum_piAntidiag (s : Finset Ξ±) (f : Ξ± β†’ R) (n : β„•) : (βˆ‘ i in s, f i) ^ n = βˆ‘ k in piAntidiag s n, multinomial s k * ∏ i in s, f i ^ k i := by simp_rw [← noncommProd_eq_prod] rw [← sum_pow_eq_sum_piAntidiag_of_commute _ _ fun _ _ _ _ _ ↦ Commute.all ..] theorem sum_pow (x : Ξ± β†’ R) (n : β„•) : s.sum x ^ n = βˆ‘ k ∈ s.sym n, k.val.multinomial * (k.val.map x).prod := by conv_rhs => rw [← sum_coe_sort] convert sum_pow_of_commute x s (fun _ _ _ _ _ ↦ Commute.all ..) n rw [Multiset.noncommProd_eq_prod] end CommSemiring end Finset namespace Nat variable {ΞΉ : Type*} {s : Finset ΞΉ} {f : ΞΉ β†’ β„•} lemma multinomial_two_mul_le_mul_multinomial : multinomial s (fun i ↦ 2 * f i) ≀ ((βˆ‘ i in s, f i) ^ βˆ‘ i in s, f i) * multinomial s f := by rw [multinomial, multinomial, ← mul_sum, ← Nat.mul_div_assoc _ (prod_factorial_dvd_factorial_sum ..)] refine Nat.div_le_div_of_mul_le_mul (by positivity) ((prod_factorial_dvd_factorial_sum ..).trans (Nat.dvd_mul_left ..)) ?_ calc (2 * βˆ‘ i ∈ s, f i)! * ∏ i ∈ s, (f i)! ≀ ((2 * βˆ‘ i ∈ s, f i) ^ (βˆ‘ i ∈ s, f i) * (βˆ‘ i ∈ s, f i)!) * ∏ i ∈ s, (f i)! := by gcongr; exact Nat.factorial_two_mul_le _ _ = ((βˆ‘ i ∈ s, f i) ^ βˆ‘ i ∈ s, f i) * (βˆ‘ i ∈ s, f i)! * ∏ i ∈ s, 2 ^ f i * (f i)! := by rw [mul_pow, ← prod_pow_eq_pow_sum, prod_mul_distrib]; ring _ ≀ ((βˆ‘ i ∈ s, f i) ^ βˆ‘ i ∈ s, f i) * (βˆ‘ i ∈ s, f i)! * ∏ i ∈ s, (2 * f i)! := by gcongr rw [← doubleFactorial_two_mul] exact doubleFactorial_le_factorial _ end Nat namespace Sym variable {n : β„•} {Ξ± : Type*} [DecidableEq Ξ±] theorem multinomial_coe_fill_of_not_mem {m : Fin (n + 1)} {s : Sym Ξ± (n - m)} {x : Ξ±} (hx : x βˆ‰ s) : (fill x m s : Multiset Ξ±).multinomial = n.choose m * (s : Multiset Ξ±).multinomial := by rw [Multiset.multinomial_filter_ne x] rw [← mem_coe] at hx refine congrArgβ‚‚ _ ?_ ?_ Β· rw [card_coe, count_coe_fill_self_of_not_mem hx] Β· refine congrArg _ ?_ rw [coe_fill, coe_replicate, Multiset.filter_add] rw [Multiset.filter_eq_self.mpr] Β· rw [add_right_eq_self] rw [Multiset.filter_eq_nil] exact fun j hj ↦ by simp [Multiset.mem_replicate.mp hj] Β· exact fun j hj h ↦ hx <| by simpa [h] using hj end Sym
Data\Nat\Choose\Sum.lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Patrick Stevens -/ import Mathlib.Algebra.BigOperators.Intervals import Mathlib.Algebra.BigOperators.NatAntidiagonal import Mathlib.Algebra.BigOperators.Ring import Mathlib.Algebra.Order.BigOperators.Group.Finset import Mathlib.Data.Nat.Choose.Basic import Mathlib.Tactic.Linarith import Mathlib.Tactic.Ring /-! # Sums of binomial coefficients This file includes variants of the binomial theorem and other results on sums of binomial coefficients. Theorems whose proofs depend on such sums may also go in this file for import reasons. -/ open Nat open Finset variable {R : Type*} namespace Commute variable [Semiring R] {x y : R} /-- A version of the **binomial theorem** for commuting elements in noncommutative semirings. -/ theorem add_pow (h : Commute x y) (n : β„•) : (x + y) ^ n = βˆ‘ m ∈ range (n + 1), x ^ m * y ^ (n - m) * choose n m := by let t : β„• β†’ β„• β†’ R := fun n m ↦ x ^ m * y ^ (n - m) * choose n m change (x + y) ^ n = βˆ‘ m ∈ range (n + 1), t n m have h_first : βˆ€ n, t n 0 = y ^ n := fun n ↦ by simp only [t, choose_zero_right, _root_.pow_zero, Nat.cast_one, mul_one, one_mul, tsub_zero] have h_last : βˆ€ n, t n n.succ = 0 := fun n ↦ by simp only [t, choose_succ_self, cast_zero, mul_zero] have h_middle : βˆ€ n i : β„•, i ∈ range n.succ β†’ (t n.succ (Nat.succ i)) = x * t n i + y * t n i.succ := by intro n i h_mem have h_le : i ≀ n := Nat.le_of_lt_succ (mem_range.mp h_mem) dsimp only [t] rw [choose_succ_succ, Nat.cast_add, mul_add] congr 1 Β· rw [pow_succ' x, succ_sub_succ, mul_assoc, mul_assoc, mul_assoc] Β· rw [← mul_assoc y, ← mul_assoc y, (h.symm.pow_right i.succ).eq] by_cases h_eq : i = n Β· rw [h_eq, choose_succ_self, Nat.cast_zero, mul_zero, mul_zero] Β· rw [succ_sub (lt_of_le_of_ne h_le h_eq)] rw [pow_succ' y, mul_assoc, mul_assoc, mul_assoc, mul_assoc] induction' n with n ih Β· rw [_root_.pow_zero, sum_range_succ, range_zero, sum_empty, zero_add] dsimp only [t] rw [_root_.pow_zero, _root_.pow_zero, choose_self, Nat.cast_one, mul_one, mul_one] Β· rw [sum_range_succ', h_first, sum_congr rfl (h_middle n), sum_add_distrib, add_assoc, pow_succ' (x + y), ih, add_mul, mul_sum, mul_sum] congr 1 rw [sum_range_succ', sum_range_succ, h_first, h_last, mul_zero, add_zero, _root_.pow_succ'] /-- A version of `Commute.add_pow` that avoids β„•-subtraction by summing over the antidiagonal and also with the binomial coefficient applied via scalar action of β„•. -/ theorem add_pow' (h : Commute x y) (n : β„•) : (x + y) ^ n = βˆ‘ m ∈ antidiagonal n, choose n m.fst β€’ (x ^ m.fst * y ^ m.snd) := by simp_rw [Finset.Nat.sum_antidiagonal_eq_sum_range_succ fun m p ↦ choose n m β€’ (x ^ m * y ^ p), _root_.nsmul_eq_mul, cast_comm, h.add_pow] end Commute /-- The **binomial theorem** -/ theorem add_pow [CommSemiring R] (x y : R) (n : β„•) : (x + y) ^ n = βˆ‘ m ∈ range (n + 1), x ^ m * y ^ (n - m) * choose n m := (Commute.all x y).add_pow n namespace Nat /-- The sum of entries in a row of Pascal's triangle -/ theorem sum_range_choose (n : β„•) : (βˆ‘ m ∈ range (n + 1), choose n m) = 2 ^ n := by have := (add_pow 1 1 n).symm simpa [one_add_one_eq_two] using this theorem sum_range_choose_halfway (m : Nat) : (βˆ‘ i ∈ range (m + 1), choose (2 * m + 1) i) = 4 ^ m := have : (βˆ‘ i ∈ range (m + 1), choose (2 * m + 1) (2 * m + 1 - i)) = βˆ‘ i ∈ range (m + 1), choose (2 * m + 1) i := sum_congr rfl fun i hi ↦ choose_symm <| by linarith [mem_range.1 hi] mul_right_injectiveβ‚€ two_ne_zero <| calc (2 * βˆ‘ i ∈ range (m + 1), choose (2 * m + 1) i) = (βˆ‘ i ∈ range (m + 1), choose (2 * m + 1) i) + βˆ‘ i ∈ range (m + 1), choose (2 * m + 1) (2 * m + 1 - i) := by rw [two_mul, this] _ = (βˆ‘ i ∈ range (m + 1), choose (2 * m + 1) i) + βˆ‘ i ∈ Ico (m + 1) (2 * m + 2), choose (2 * m + 1) i := by { rw [range_eq_Ico, sum_Ico_reflect] Β· congr have A : m + 1 ≀ 2 * m + 1 := by omega rw [add_comm, add_tsub_assoc_of_le A, ← add_comm] congr rw [tsub_eq_iff_eq_add_of_le A] ring Β· omega } _ = βˆ‘ i ∈ range (2 * m + 2), choose (2 * m + 1) i := sum_range_add_sum_Ico _ (by omega) _ = 2 ^ (2 * m + 1) := sum_range_choose (2 * m + 1) _ = 2 * 4 ^ m := by rw [Nat.pow_succ, pow_mul, mul_comm]; rfl theorem choose_middle_le_pow (n : β„•) : choose (2 * n + 1) n ≀ 4 ^ n := by have t : choose (2 * n + 1) n ≀ βˆ‘ i ∈ range (n + 1), choose (2 * n + 1) i := single_le_sum (fun x _ ↦ by omega) (self_mem_range_succ n) simpa [sum_range_choose_halfway n] using t theorem four_pow_le_two_mul_add_one_mul_central_binom (n : β„•) : 4 ^ n ≀ (2 * n + 1) * choose (2 * n) n := calc 4 ^ n = (1 + 1) ^ (2 * n) := by norm_num [pow_mul] _ = βˆ‘ m ∈ range (2 * n + 1), choose (2 * n) m := by set_option simprocs false in simp [add_pow] _ ≀ βˆ‘ m ∈ range (2 * n + 1), choose (2 * n) (2 * n / 2) := by gcongr; apply choose_le_middle _ = (2 * n + 1) * choose (2 * n) n := by simp /-- **Zhu Shijie's identity** aka hockey-stick identity. -/ theorem sum_Icc_choose (n k : β„•) : βˆ‘ m ∈ Icc k n, m.choose k = (n + 1).choose (k + 1) := by cases' le_or_gt k n with h h Β· induction' n, h using le_induction with n _ ih; Β· simp rw [← Ico_insert_right (by omega), sum_insert (by simp), show Ico k (n + 1) = Icc k n by rfl, ih, choose_succ_succ' (n + 1)] Β· rw [choose_eq_zero_of_lt (by omega), Icc_eq_empty_of_lt h, sum_empty] end Nat theorem Int.alternating_sum_range_choose {n : β„•} : (βˆ‘ m ∈ range (n + 1), ((-1) ^ m * ↑(choose n m) : β„€)) = if n = 0 then 1 else 0 := by cases n with | zero => simp | succ n => have h := add_pow (-1 : β„€) 1 n.succ simp only [one_pow, mul_one, add_left_neg] at h rw [← h, zero_pow n.succ_ne_zero, if_neg (Nat.succ_ne_zero n)] theorem Int.alternating_sum_range_choose_of_ne {n : β„•} (h0 : n β‰  0) : (βˆ‘ m ∈ range (n + 1), ((-1) ^ m * ↑(choose n m) : β„€)) = 0 := by rw [Int.alternating_sum_range_choose, if_neg h0] namespace Finset theorem sum_powerset_apply_card {Ξ± Ξ² : Type*} [AddCommMonoid Ξ±] (f : β„• β†’ Ξ±) {x : Finset Ξ²} : βˆ‘ m ∈ x.powerset, f m.card = βˆ‘ m ∈ range (x.card + 1), x.card.choose m β€’ f m := by trans βˆ‘ m ∈ range (x.card + 1), βˆ‘ j ∈ x.powerset.filter fun z ↦ z.card = m, f j.card Β· refine (sum_fiberwise_of_maps_to ?_ _).symm intro y hy rw [mem_range, Nat.lt_succ_iff] rw [mem_powerset] at hy exact card_le_card hy Β· refine sum_congr rfl fun y _ ↦ ?_ rw [← card_powersetCard, ← sum_const] refine sum_congr powersetCard_eq_filter.symm fun z hz ↦ ?_ rw [(mem_powersetCard.1 hz).2] theorem sum_powerset_neg_one_pow_card {Ξ± : Type*} [DecidableEq Ξ±] {x : Finset Ξ±} : (βˆ‘ m ∈ x.powerset, (-1 : β„€) ^ m.card) = if x = βˆ… then 1 else 0 := by rw [sum_powerset_apply_card] simp only [nsmul_eq_mul', ← card_eq_zero, Int.alternating_sum_range_choose] theorem sum_powerset_neg_one_pow_card_of_nonempty {Ξ± : Type*} {x : Finset Ξ±} (h0 : x.Nonempty) : (βˆ‘ m ∈ x.powerset, (-1 : β„€) ^ m.card) = 0 := by classical rw [sum_powerset_neg_one_pow_card, if_neg] rw [← Ne, ← nonempty_iff_ne_empty] apply h0 variable {M R : Type*} [CommMonoid M] [NonAssocSemiring R] @[to_additive sum_choose_succ_nsmul] theorem prod_pow_choose_succ {M : Type*} [CommMonoid M] (f : β„• β†’ β„• β†’ M) (n : β„•) : (∏ i ∈ range (n + 2), f i (n + 1 - i) ^ (n + 1).choose i) = (∏ i ∈ range (n + 1), f i (n + 1 - i) ^ n.choose i) * ∏ i ∈ range (n + 1), f (i + 1) (n - i) ^ n.choose i := by have A : (∏ i ∈ range (n + 1), f (i + 1) (n - i) ^ (n.choose (i + 1))) * f 0 (n + 1) = ∏ i ∈ range (n + 1), f i (n + 1 - i) ^ (n.choose i) := by rw [prod_range_succ, prod_range_succ'] simp rw [prod_range_succ'] simpa [Nat.choose_succ_succ, pow_add, prod_mul_distrib, A, mul_assoc] using mul_comm _ _ @[to_additive sum_antidiagonal_choose_succ_nsmul] theorem prod_antidiagonal_pow_choose_succ {M : Type*} [CommMonoid M] (f : β„• β†’ β„• β†’ M) (n : β„•) : (∏ ij ∈ antidiagonal (n + 1), f ij.1 ij.2 ^ (n + 1).choose ij.1) = (∏ ij ∈ antidiagonal n, f ij.1 (ij.2 + 1) ^ n.choose ij.1) * ∏ ij ∈ antidiagonal n, f (ij.1 + 1) ij.2 ^ n.choose ij.2 := by simp only [Nat.prod_antidiagonal_eq_prod_range_succ_mk, prod_pow_choose_succ] have : βˆ€ i ∈ range (n + 1), i ≀ n := fun i hi ↦ by simpa [Nat.lt_succ_iff] using hi congr 1 Β· refine prod_congr rfl fun i hi ↦ ?_ rw [tsub_add_eq_add_tsub (this _ hi)] Β· refine prod_congr rfl fun i hi ↦ ?_ rw [Nat.choose_symm (this _ hi)] -- Porting note: moved from `Mathlib.Analysis.Calculus.ContDiff` /-- The sum of `(n+1).choose i * f i (n+1-i)` can be split into two sums at rank `n`, respectively of `n.choose i * f i (n+1-i)` and `n.choose i * f (i+1) (n-i)`. -/ theorem sum_choose_succ_mul (f : β„• β†’ β„• β†’ R) (n : β„•) : (βˆ‘ i ∈ range (n + 2), ((n + 1).choose i : R) * f i (n + 1 - i)) = (βˆ‘ i ∈ range (n + 1), (n.choose i : R) * f i (n + 1 - i)) + βˆ‘ i ∈ range (n + 1), (n.choose i : R) * f (i + 1) (n - i) := by simpa only [nsmul_eq_mul] using sum_choose_succ_nsmul f n /-- The sum along the antidiagonal of `(n+1).choose i * f i j` can be split into two sums along the antidiagonal at rank `n`, respectively of `n.choose i * f i (j+1)` and `n.choose j * f (i+1) j`. -/ theorem sum_antidiagonal_choose_succ_mul (f : β„• β†’ β„• β†’ R) (n : β„•) : (βˆ‘ ij ∈ antidiagonal (n + 1), ((n + 1).choose ij.1 : R) * f ij.1 ij.2) = (βˆ‘ ij ∈ antidiagonal n, (n.choose ij.1 : R) * f ij.1 (ij.2 + 1)) + βˆ‘ ij ∈ antidiagonal n, (n.choose ij.2 : R) * f (ij.1 + 1) ij.2 := by simpa only [nsmul_eq_mul] using sum_antidiagonal_choose_succ_nsmul f n theorem sum_antidiagonal_choose_add (d n : β„•) : (Finset.sum (antidiagonal n) fun ij => (d + ij.2).choose d) = (d + n).choose d + (d + n).choose (succ d) := by induction n with | zero => simp | succ n hn => simpa [Nat.sum_antidiagonal_succ] using hn end Finset
Data\Nat\Choose\Vandermonde.lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.Algebra.Polynomial.Coeff import Mathlib.Data.Nat.Choose.Basic /-! # Vandermonde's identity In this file we prove Vandermonde's identity (`Nat.add_choose_eq`): `(m + n).choose k = βˆ‘ (i, j) ∈ antidiagonal k, m.choose i * n.choose j` We follow the algebraic proof from https://en.wikipedia.org/wiki/Vandermonde%27s_identity#Algebraic_proof . -/ open Polynomial Finset Finset.Nat /-- Vandermonde's identity -/ theorem Nat.add_choose_eq (m n k : β„•) : (m + n).choose k = βˆ‘ ij ∈ antidiagonal k, m.choose ij.1 * n.choose ij.2 := by calc (m + n).choose k = ((X + 1) ^ (m + n)).coeff k := by rw [coeff_X_add_one_pow, Nat.cast_id] _ = ((X + 1) ^ m * (X + 1) ^ n).coeff k := by rw [pow_add] _ = βˆ‘ ij ∈ antidiagonal k, m.choose ij.1 * n.choose ij.2 := by rw [coeff_mul, Finset.sum_congr rfl] simp only [coeff_X_add_one_pow, Nat.cast_id, eq_self_iff_true, imp_true_iff]
Data\Nat\Factorial\Basic.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes, Floris van Doorn, YaΓ«l Dillies -/ import Mathlib.Data.Nat.Defs import Mathlib.Tactic.GCongr.Core import Mathlib.Tactic.Common import Mathlib.Tactic.Monotonicity.Attr /-! # Factorial and variants This file defines the factorial, along with the ascending and descending variants. ## 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!` -/ 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 : 0 < n) : n * (n - 1)! = n ! := Nat.sub_add_cancel (Nat.succ_le_of_lt 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 _) theorem factorial_dvd_factorial {m n} (h : m ≀ n) : m ! ∣ n ! := by induction' h with n _ ih Β· exact Nat.dvd_refl _ Β· 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_lt 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 with k hnk ih generalizing hn Β· exact this hn Β· 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_lt (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 cases' 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] /-- 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 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] /-- 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 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 omega) (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 : 1 ≀ n) : βˆ€ {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 _ _) (Nat.sub_lt hn k.zero_lt_succ) (Nat.pow_pos (Nat.lt_of_succ_le hn)) 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 _ (pow_le_pow_of_le_left (le_add_left _ _) _) _ ≀ _ := Nat.factorial_mul_pow_le_factorial end Nat
Data\Nat\Factorial\BigOperators.lean
/- Copyright (c) 2022 Pim Otte. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller, Pim Otte -/ import Mathlib.Data.Nat.Factorial.Basic import Mathlib.Algebra.Order.BigOperators.Ring.Finset /-! # 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)! := by positivity theorem prod_factorial_dvd_factorial_sum : (∏ i ∈ s, (f i)!) ∣ (βˆ‘ i ∈ s, f i)! := by induction' s using Finset.cons_induction_on with a s has ih Β· simp Β· rw [prod_cons, Finset.sum_cons] exact (mul_dvd_mul_left _ ih).trans (Nat.factorial_mul_factorial_dvd_factorial_add _ _) 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, mul_comm, descFactorial_eq_prod_range n k] end Nat
Data\Nat\Factorial\Cast.lean
/- Copyright (c) 2021 YaΓ«l Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: YaΓ«l Dillies -/ import Mathlib.RingTheory.Polynomial.Pochhammer /-! # 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 Semiring variable [Semiring S] (a b : β„•) -- Porting note: added type ascription around a + 1 theorem cast_ascFactorial : (a.ascFactorial b : S) = (ascPochhammer S b).eval (a : S) := by rw [← ascPochhammer_nat_eq_ascFactorial, ascPochhammer_eval_cast] -- Porting note: added type ascription around a - (b - 1) theorem cast_descFactorial : (a.descFactorial b : S) = (ascPochhammer S b).eval (a - (b - 1) : S) := by rw [← ascPochhammer_eval_cast, ascPochhammer_nat_eq_descFactorial] induction' b with b Β· simp Β· simp_rw [add_succ, Nat.add_one_sub_one] obtain h | h := le_total a b Β· rw [descFactorial_of_lt (lt_succ_of_le h), descFactorial_of_lt (lt_succ_of_le _)] rw [tsub_eq_zero_iff_le.mpr h, zero_add] Β· rw [tsub_add_cancel_of_le h] theorem cast_factorial : (a ! : S) = (ascPochhammer S a).eval 1 := by rw [← one_ascFactorial, cast_ascFactorial, cast_one] end Semiring 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 [cast_descFactorial] cases a Β· simp Β· rw [succ_sub_succ, tsub_zero, cast_succ, add_sub_cancel_right, ascPochhammer_succ_right, ascPochhammer_one, Polynomial.X_mul, Polynomial.eval_mul_X, Polynomial.eval_add, Polynomial.eval_X, cast_one, Polynomial.eval_one] end Ring end Nat
Data\Nat\Factorial\DoubleFactorial.lean
/- Copyright (c) 2023 Jake Levinson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jake Levinson -/ import Mathlib.Algebra.BigOperators.Group.Finset import Mathlib.Data.Nat.Factorial.Basic import Mathlib.Tactic.Ring import Mathlib.Tactic.Positivity.Core /-! # 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
Data\Nat\Factorial\SuperFactorial.lean
/- Copyright (c) 2023 Moritz Firsching. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Firsching -/ import Mathlib.Algebra.BigOperators.Intervals import Mathlib.Algebra.Polynomial.Monic import Mathlib.Data.Nat.Factorial.Basic import Mathlib.LinearAlgebra.Vandermonde import Mathlib.RingTheory.Polynomial.Pochhammer /-! # 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 variable {n : β„•} @[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_succ_right 1 n.succ, prod_Ico_succ_top <| Nat.succ_le_succ <| Nat.zero_le n, Nat.factorial_succ, Ico_succ_right 1 n, prod_Icc_factorial n, superFactorial, factorial, Nat.succ_eq_add_one, 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] variable {R : Type*} [CommRing R] theorem det_vandermonde_id_eq_superFactorial (n : β„•) : (Matrix.vandermonde (fun (i : Fin (n + 1)) ↦ (i : R))).det = Nat.superFactorial n := by induction' n with n hn Β· simp [Matrix.det_vandermonde] Β· rw [Nat.superFactorial, Matrix.det_vandermonde, Fin.prod_univ_succAbove _ 0] push_cast congr Β· simp only [Fin.val_zero, Nat.cast_zero, sub_zero] norm_cast simp [Fin.prod_univ_eq_prod_range (fun i ↦ (↑i + 1)) (n + 1)] Β· rw [Matrix.det_vandermonde] at hn simp [hn] 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] private theorem matrixOf_eval_descPochhammer_eq_mul_matrixOf_choose {n : β„•} (v : Fin n β†’ β„•) : (Matrix.of (fun (i j : Fin n) => (descPochhammer β„€ j).eval (v i : β„€))).det = (∏ i : Fin n, Nat.factorial i) * (Matrix.of (fun (i j : Fin n) => (Nat.choose (v i) (j : β„•) : β„€))).det := by convert Matrix.det_mul_row (fun (i : Fin n) => ((Nat.factorial (i : β„•)) : β„€)) _ Β· rw [Matrix.of_apply, descPochhammer_eval_eq_descFactorial β„€ _ _] congr exact Nat.descFactorial_eq_factorial_mul_choose _ _ Β· rw [Nat.cast_prod] theorem superFactorial_dvd_vandermonde_det {n : β„•} (v : Fin (n + 1) β†’ β„€) : ↑(Nat.superFactorial n) ∣ (Matrix.vandermonde v).det := by let m := inf' univ ⟨0, mem_univ _⟩ v let w' := fun i ↦ (v i - m).toNat have hw' : βˆ€ i, (w' i : β„€) = v i - m := fun i ↦ Int.toNat_sub_of_le (inf'_le _ (mem_univ _)) have h := Matrix.det_eval_matrixOfPolynomials_eq_det_vandermonde (fun i ↦ ↑(w' i)) (fun i => descPochhammer β„€ i) (fun i => descPochhammer_natDegree β„€ i) (fun i => monic_descPochhammer β„€ i) conv_lhs at h => simp only [hw', Matrix.det_vandermonde_sub] use (Matrix.of (fun (i j : Fin (n + 1)) => (Nat.choose (w' i) (j : β„•) : β„€))).det simp [h, matrixOf_eval_descPochhammer_eq_mul_matrixOf_choose w', Fin.prod_univ_eq_prod_range] end SuperFactorial end Nat
Data\Nat\Factorization\Basic.lean
/- Copyright (c) 2021 Stuart Presnell. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stuart Presnell -/ import Mathlib.Data.Nat.PrimeFin import Mathlib.Data.Nat.Factorization.Defs import Mathlib.Data.Nat.GCD.BigOperators import Mathlib.Order.Interval.Finset.Nat /-! # Basic lemmas on prime factorizations -/ open Nat 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.not_mem_support_iff.mp (mt le_of_mem_primeFactors (not_le_of_lt h)) @[simp] theorem factorization_one_right (n : β„•) : n.factorization 1 = 0 := factorization_eq_zero_of_non_prime _ not_prime_one 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_iff.mp 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 [factorization, AddEquiv.map_eq_zero_iff, Multiset.coe_eq_zero] /-! ## Lemmas about factorizations of products and powers -/ /-- 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` -/ @[simp] theorem Prime.factorization_self {p : β„•} (hp : Prime p) : p.factorization p = 1 := by simp [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 -- Porting note: explicitly added `Finsupp.prod_single_index` rw [← Nat.factorization_prod_pow_eq_self hn, h, Finsupp.prod_single_index] 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 @[simp] theorem ord_proj_of_not_prime (n p : β„•) (hp : Β¬p.Prime) : ord_proj[p] n = 1 := by simp [factorization_eq_zero_of_non_prime n hp] @[simp] theorem ord_compl_of_not_prime (n p : β„•) (hp : Β¬p.Prime) : ord_compl[p] n = n := by simp [factorization_eq_zero_of_non_prime n hp] theorem ord_compl_dvd (n p : β„•) : ord_compl[p] n ∣ n := div_dvd_of_dvd (ord_proj_dvd n p) theorem ord_proj_pos (n p : β„•) : 0 < ord_proj[p] n := by if pp : p.Prime then simp [pow_pos pp.pos] else simp [pp] theorem ord_proj_le {n : β„•} (p : β„•) (hn : n β‰  0) : ord_proj[p] n ≀ n := le_of_dvd hn.bot_lt (Nat.ord_proj_dvd n p) theorem ord_compl_pos {n : β„•} (p : β„•) (hn : n β‰  0) : 0 < ord_compl[p] n := by if pp : p.Prime then exact Nat.div_pos (ord_proj_le p hn) (ord_proj_pos n p) else simpa [Nat.factorization_eq_zero_of_non_prime n pp] using hn.bot_lt theorem ord_compl_le (n p : β„•) : ord_compl[p] n ≀ n := Nat.div_le_self _ _ theorem ord_proj_mul_ord_compl_eq_self (n p : β„•) : ord_proj[p] n * ord_compl[p] n = n := Nat.mul_div_cancel' (ord_proj_dvd n p) theorem ord_proj_mul {a b : β„•} (p : β„•) (ha : a β‰  0) (hb : b β‰  0) : ord_proj[p] (a * b) = ord_proj[p] a * ord_proj[p] b := by simp [factorization_mul ha hb, pow_add] theorem ord_compl_mul (a b p : β„•) : ord_compl[p] (a * b) = ord_compl[p] a * ord_compl[p] b := by if ha : a = 0 then simp [ha] else if hb : b = 0 then simp [hb] else simp only [ord_proj_mul p ha hb] rw [div_mul_div_comm (ord_proj_dvd a p) (ord_proj_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 (pow_lt_pow_iff_right pp.one_lt).1 <| (ord_proj_le p hn).trans_lt <| lt_pow_self pp.one_lt _ Β· simpa only [factorization_eq_zero_of_non_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 (pow_le_pow_iff_right pp.one_lt).1 ((ord_proj_le p hn).trans hb) else simp [factorization_eq_zero_of_non_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_non_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 (pow_pos pp.pos k).ne' hn, pp.factorization_pow, single_le_iff] theorem Prime.pow_dvd_iff_dvd_ord_proj {p k n : β„•} (pp : Prime p) (hn : n β‰  0) : p ^ k ∣ n ↔ p ^ k ∣ ord_proj[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 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_ord_proj_of_dvd {n p : β„•} (hn : n β‰  0) (pp : p.Prime) (h : p ∣ n) : p ∣ ord_proj[p] n := dvd_pow_self p (Prime.factorization_pos_of_dvd pp hn h).ne' theorem not_dvd_ord_compl {n p : β„•} (hp : Prime p) (hn : n β‰  0) : Β¬p ∣ ord_compl[p] n := by rw [Nat.Prime.dvd_iff_one_le_factorization hp (ord_compl_pos p hn).ne'] rw [Nat.factorization_div (Nat.ord_proj_dvd n p)] simp [hp.factorization] theorem coprime_ord_compl {n p : β„•} (hp : Prime p) (hn : n β‰  0) : Coprime p (ord_compl[p] n) := (or_iff_left (not_dvd_ord_compl hp hn)).mp <| coprime_or_dvd_of_prime hp _ theorem factorization_ord_compl (n p : β„•) : (ord_compl[p] n).factorization = n.factorization.erase p := by if hn : n = 0 then simp [hn] else if pp : p.Prime then ?_ else -- Porting note: needed to solve side goal explicitly rw [Finsupp.erase_of_not_mem_support] <;> simp [pp] ext q rcases eq_or_ne q p with (rfl | hqp) Β· simp only [Finsupp.erase_same, factorization_eq_zero_iff, not_dvd_ord_compl pp hn] simp Β· rw [Finsupp.erase_ne hqp, factorization_div (ord_proj_dvd n p)] simp [pp.factorization, hqp.symm] -- `ord_compl[p] n` is the largest divisor of `n` not divisible by `p`. theorem dvd_ord_compl_of_dvd_not_dvd {p d n : β„•} (hdn : d ∣ n) (hpd : Β¬p ∣ d) : d ∣ ord_compl[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 (ord_compl_pos p hn0).ne', factorization_ord_compl] 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β‚‚βŸ© := multiplicity.exists_eq_pow_mul_and_not_dvd (multiplicity.finite_nat_iff.mpr ⟨hp, Nat.pos_of_ne_zero hn⟩) ⟨_, 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, odd_iff_not_even.mpr (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 := fun H => Nat.lt_asymm hd_lt_n ((Nat.div_eq_zero_iff hd.bot_lt).mp H) intro h rw [dvd_iff_le_div_mul n d] by_contra h2 cases' exists_factorization_lt_of_lt (mul_ne_zero h1 hd) (not_le.mp h2) with p hp rwa [factorization_mul h1 hd, add_apply, ← lt_tsub_iff_right, h, tsub_apply, lt_self_iff_false] at hp theorem ord_proj_dvd_ord_proj_of_dvd {a b : β„•} (hb0 : b β‰  0) (hab : a ∣ b) (p : β„•) : ord_proj[p] a ∣ ord_proj[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 ord_proj_dvd_ord_proj_iff_dvd {a b : β„•} (ha0 : a β‰  0) (hb0 : b β‰  0) : (βˆ€ p : β„•, ord_proj[p] a ∣ ord_proj[p] b) ↔ a ∣ b := by refine ⟨fun h => ?_, fun hab p => ord_proj_dvd_ord_proj_of_dvd hb0 hab p⟩ rw [← factorization_le_iff_dvd ha0 hb0] intro q rcases le_or_lt q 1 with (hq_le | hq1) Β· interval_cases q <;> simp exact (pow_dvd_pow_iff_le_right hq1).1 (h q) theorem ord_compl_dvd_ord_compl_of_dvd {a b : β„•} (hab : a ∣ b) (p : β„•) : ord_compl[p] a ∣ ord_compl[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 (ord_proj_le p ha0) (ord_proj_pos a p)).ne' have hb := (Nat.div_pos (ord_proj_le p hb0) (ord_proj_pos b p)).ne' rw [← factorization_le_iff_dvd ha hb, factorization_ord_compl a p, factorization_ord_compl 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 ord_compl_dvd_ord_compl_iff_dvd (a b : β„•) : (βˆ€ p : β„•, ord_compl[p] a ∣ ord_compl[p] b) ↔ a ∣ b := by refine ⟨fun h => ?_, fun hab p => ord_compl_dvd_ord_compl_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_iff, not_forall] exact ⟨2, n, prime_two, dvd_zero _, mt (le_of_dvd hn.bot_lt) (lt_two_pow n).not_le⟩ 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 (ord_proj_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 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, pow_eq_zero_iff', ne_eq] 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] @[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 [Nat.lt_succ_iff, 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) = (Ico 1 n).filter fun i : β„• => 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 = ((Ico 1 n).filter fun i => p ^ i ∣ n).card := 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) : ((Ico 1 n).filter fun i => p ^ i ∣ n) = (Icc 1 b).filter fun i => 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) <| (pow_le_pow_iff_right pp.one_lt).1 <| (le_of_dvd hn.bot_lt h1).trans hb /-! ### 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_non_prime, pp] theorem prod_pow_prime_padicValNat (n : Nat) (hn : n β‰  0) (m : Nat) (pr : n < m) : (∏ p ∈ Finset.filter Nat.Prime (Finset.range m), p ^ padicValNat p n) = n := by -- Porting note: was `nth_rw_rhs` conv => rhs rw [← 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 cases' Finset.mem_sdiff.mp hp with hp1 hp2 rw [← factorization_def n (Finset.mem_filter.mp hp1).2] simp [Finsupp.not_mem_support_iff.mp hp2] Β· intro p hp simp [factorization_def n (prime_of_mem_primeFactors hp)] /-! ### Lemmas about factorizations of particular functions -/ -- TODO: Port lemmas from `Data/Nat/Multiplicity` to here, re-written in terms of `factorization` /-- 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 : β„•) : card ((Finset.range n).filter fun e => p ∣ e + 1) = n / p := by induction' n with n hn Β· simp simp [Nat.succ_div, add_ite, add_zero, Finset.range_succ, filter_insert, apply_ite card, card_insert_of_not_mem, hn] /-- Exactly `n / p` naturals in `(0, n]` are multiples of `p`. -/ theorem Ioc_filter_dvd_card_eq_div (n p : β„•) : ((Ioc 0 n).filter fun x => p ∣ x).card = n / p := by induction' n with n IH Β· simp -- TODO: Golf away `h1` after YaΓ«l PRs a lemma asserting this have h1 : Ioc 0 n.succ = insert n.succ (Ioc 0 n) := by rcases n.eq_zero_or_pos with (rfl | hn) Β· simp simp_rw [← Ico_succ_succ, Ico_insert_right (succ_le_succ hn.le), Ico_succ_right] simp [Nat.succ_div, add_ite, add_zero, h1, filter_insert, apply_ite card, card_insert_eq_ite, IH, Finset.mem_filter, mem_Ioc, not_le.2 (lt_add_one n)] /-- 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 : β„•) : ((Finset.range N.succ).filter (fun k ↦ k β‰  0 ∧ n ∣ k)).card = N / n := by induction N with | zero => simp [Finset.filter_false_of_mem] | succ N ih => rw [Finset.range_succ, 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
Data\Nat\Factorization\Defs.lean
/- Copyright (c) 2021 Stuart Presnell. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stuart Presnell -/ import Mathlib.Data.Finsupp.Multiset import Mathlib.NumberTheory.Padics.PadicVal /-! # 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 `RingTheory/UniqueFactorizationDomain`. * Extend the inductions to any `NormalizationMonoid` with unique factorization. -/ -- Workaround for lean4#2038 attribute [-instance] instBEqNat 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.le_count_iff_replicate_sublist.mp le_rfl |>.subperm Β· rw [← Nat.lt_add_one_iff, lt_iff_not_ge, ge_iff_le, 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 @[deprecated (since := "2024-07-16")] alias factors_count_eq := primeFactorsList_count_eq @[deprecated (since := "2024-07-16")] alias factorization_eq_factors_multiset := factorization_eq_primeFactorsList_multiset 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, 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.bot_lt] /-! ### 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, factorization, 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 [← not_mem_support_iff, support_factorization, mem_primeFactors, not_and_or, not_ne_iff] @[simp] theorem factorization_eq_zero_of_non_prime (n : β„•) {p : β„•} (hp : Β¬p.Prime) : n.factorization p = 0 := by simp [factorization_eq_zero_iff, hp] @[simp] theorem factorization_zero_right (n : β„•) : n.factorization 0 = 0 := factorization_eq_zero_of_non_prime _ not_prime_zero 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.card = 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 k ih; Β· simp 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_pos hp.pos _).ne' hn] at h simpa [hp.factorization] using h p /-! ### 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_not_mem_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 `ord_proj[p] n` for the largest power of the prime `p` that divides `n` and `ord_compl[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, `ord_proj[2] n` is the even part of `n` and `ord_compl[2] n` is the odd part. -/ -- Porting note: Lean 4 thinks we need `HPow` without this set_option quotPrecheck false in notation "ord_proj[" p "] " n:arg => p ^ Nat.factorization n p notation "ord_compl[" p "] " n:arg => n / ord_proj[p] n theorem ord_proj_dvd (n p : β„•) : ord_proj[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] /-! ### 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
Data\Nat\Factorization\Induction.lean
/- Copyright (c) 2021 Stuart Presnell. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stuart Presnell -/ 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 {P : β„• β†’ Sort*} (h0 : P 0) (h1 : P 1) (h : βˆ€ a p n : β„•, p.Prime β†’ Β¬p ∣ a β†’ 0 < n β†’ P a β†’ P (p ^ n * a)) : βˆ€ a : β„•, P a := fun a => Nat.strongRecOn a fun n => match n with | 0 => fun _ => h0 | 1 => fun _ => h1 | 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 := ord_proj_dvd _ _ haveI htp : 0 < t := hp.factorization_pos_of_dvd (k + 1).succ_ne_zero (k + 2).minFac_dvd convert h ((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 [lt_mul_iff_one_lt_left Nat.succ_pos', one_lt_pow_iff 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 {P : β„• β†’ Sort*} (hp : βˆ€ p n : β„•, Prime p β†’ 0 < n β†’ P (p ^ n)) (h0 : P 0) (h1 : P 1) (h : βˆ€ a b, 1 < a β†’ 1 < b β†’ Coprime a b β†’ P a β†’ P b β†’ P (a * b)) : βˆ€ a, P a := recOnPrimePow h0 h1 <| by intro a p n hp' hpa hn hPa by_cases ha1 : a = 1 Β· rw [ha1, mul_one] exact hp p n hp' hn refine h (p ^ n) a (hp'.one_lt.trans_le (le_self_pow hn.ne' _)) ?_ ?_ (hp _ _ 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 {P : β„• β†’ Sort*} (h0 : P 0) (hp : βˆ€ p n : β„•, Prime p β†’ P (p ^ n)) (h : βˆ€ a b, 1 < a β†’ 1 < b β†’ Coprime a b β†’ P a β†’ P b β†’ P (a * b)) : βˆ€ a, P a := recOnPosPrimePosCoprime (fun p n h _ => hp p n h) h0 (hp 2 0 prime_two) h /-- 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 {P : β„• β†’ Sort*} (h0 : P 0) (h1 : P 1) (hp : βˆ€ p, Prime p β†’ P p) (h : βˆ€ a b, P a β†’ P b β†’ P (a * b)) : βˆ€ a, P a := let rec /-- The predicate holds on prime powers -/ hp'' (p n : β„•) (hp' : Prime p) : P (p ^ n) := match n with | 0 => h1 | n + 1 => h _ _ (hp'' p n hp') (hp p hp') recOnPrimeCoprime h0 hp'' fun a b _ _ _ => h a b lemma _root_.induction_on_primes {P : β„• β†’ Prop} (hβ‚€ : P 0) (h₁ : P 1) (h : βˆ€ p a : β„•, p.Prime β†’ P a β†’ P (p * a)) : βˆ€ n, P n := by refine recOnPrimePow hβ‚€ h₁ ?_ rintro a p n hp - - ha induction' n with n ih Β· simpa using ha Β· rw [pow_succ', mul_assoc] exact h _ _ hp ih lemma prime_composite_induction {P : β„• β†’ Prop} (zero : P 0) (one : P 1) (prime : βˆ€ p : β„•, p.Prime β†’ P p) (composite : βˆ€ a, 2 ≀ a β†’ P a β†’ βˆ€ b, 2 ≀ b β†’ P b β†’ P (a * b)) (n : β„•) : P 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 - - -- Porting note: replaced `simp` with `rw` rw [Prime.factorization_pow hp, Finsupp.prod_single_index _] rwa [pow_zero] Β· 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
Data\Nat\Factorization\PrimePow.lean
/- Copyright (c) 2022 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import Mathlib.Algebra.IsPrimePow import Mathlib.Data.Nat.Factorization.Basic /-! # Prime powers and factorizations This file deals with factorizations of prime powers. -/ variable {R : Type*} [CommMonoidWithZero R] (n p : R) (k : β„•) 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_ord_compl_eq_one {n : β„•} (h : IsPrimePow n) : βˆƒ p : β„•, p.Prime ∧ ord_compl[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_non_prime n pp, h1] refine ⟨p, pp, ?_⟩ refine Nat.eq_of_factorization_eq (Nat.ord_compl_pos p hn0).ne' (by simp) fun q => ?_ rw [Nat.factorization_ord_compl n p, h1] simp theorem exists_ord_compl_eq_one_iff_isPrimePow {n : β„•} (hn : n β‰  1) : IsPrimePow n ↔ βˆƒ p : β„•, p.Prime ∧ ord_compl[p] n = 1 := by refine ⟨fun h => IsPrimePow.exists_ord_compl_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.ord_proj_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.ord_proj_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 only [and_congr_right_iff] intro p hp exact ⟨hp.dvd_of_dvd_pow, fun t => t.trans (dvd_pow_self _ 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 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] 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.not_mem_support_iff, ← Finsupp.not_mem_support_iff, ← not_and_or, ← Finset.mem_inter] intro t -- Porting note: used to be `exact` below, but the definition of `∈` has changed. simpa using hab.disjoint_primeFactors.le_bot t cases' this with h h <;> simp [h, imp_or] theorem Nat.mul_divisors_filter_prime_pow {a b : β„•} (hab : a.Coprime b) : (a * b).divisors.filter IsPrimePow = (a.divisors βˆͺ b.divisors).filter IsPrimePow := 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_iff, Ne, and_congr_left_iff, not_false_iff, Nat.mem_divisors, or_self_iff] apply hab.isPrimePow_dvd_mul
Data\Nat\Factorization\Root.lean
/- Copyright (c) 2023 YaΓ«l Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: YaΓ«l Dillies -/ import Mathlib.Algebra.Order.Floor.Div 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 theoretical 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 (config := { contextual := true }) [floorRoot, not_imp_not, 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 theoretical 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 (config := { contextual := true }) [ceilRoot_def, not_imp_not, 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 eg `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
Data\Nat\Fib\Basic.lean
/- Copyright (c) 2019 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann, Kyle Miller, Mario Carneiro -/ import Mathlib.Algebra.BigOperators.Group.Finset import Mathlib.Data.Finset.NatAntidiagonal import Mathlib.Data.Nat.GCD.Basic import Mathlib.Data.Nat.Bits import Mathlib.Init.Data.Nat.Lemmas import Mathlib.Logic.Function.Iterate import Mathlib.Tactic.Ring import Mathlib.Tactic.Zify /-! # Fibonacci Numbers This file defines the fibonacci series, proves results about it and introduces methods to compute it quickly. -/ /-! # The Fibonacci Sequence ## Summary Definition of the Fibonacci sequence `Fβ‚€ = 0, F₁ = 1, Fβ‚™β‚Šβ‚‚ = Fβ‚™ + Fβ‚™β‚Šβ‚`. ## 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`). There are `bit0`/`bit1` variants of these can be used to simplify `fib` expressions: `simp only [Nat.fib_bit0, Nat.fib_bit1, Nat.fib_bit0_succ, Nat.fib_bit1_succ, Nat.fib_one, Nat.fib_two]`. ## Implementation Notes For efficiency purposes, the sequence is defined using `Stream.iterate`. ## Tags fib, fibonacci -/ 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 [hm] | 1 => by simp [hm] | 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 n five_le_n IH Β· -- 5 ≀ fib 5 rfl Β· -- 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 n ih Β· simp Β· 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 with n ih generalizing m Β· simp Β· specialize ih (m + 1) rw [add_assoc m 1 n, add_comm 1 n] at ih simp only [fib_add_two, succ_eq_add_one, 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] -- Porting note: A bunch of issues similar to [this zulip thread](https://github.com/leanprover-community/mathlib4/pull/1576) with `zify` 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 apply Nat.binaryRec _ (fun b n' ih => _) 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_iff] <;> 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.mp] 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 n ih Β· simp Β· 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
Data\Nat\Fib\Zeckendorf.lean
/- Copyright (c) 2023 YaΓ«l Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: YaΓ«l Dillies -/ 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]).Chain' (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 | n, [], _, hn => fib_pos.2 <| hn _ rfl | n, a :: l, hl, hn => by simp only [IsZeckendorfRep, cons_append, chain'_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, ← chain'_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 {l : List β„•} {a 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') <| add_le_add_right hab _ @[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 <| add_le_add_right h _) 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_le⟩ @[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) => let 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, chain'_iff_pairwise, pairwise_cons, mem_append, mem_singleton, or_imp, forall_and, forall_eq, zero_add] at hl rw [← chain'_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
Data\Nat\GCD\Basic.lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ import Mathlib.Order.Lattice import Mathlib.Algebra.GroupWithZero.Divisibility import Mathlib.Algebra.Ring.Nat import Mathlib.Init.Data.Nat.Lemmas /-! # Definitions and properties of `Nat.gcd`, `Nat.lcm`, and `Nat.coprime` 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. -/ namespace Nat /-! ### `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 gcd_add_mul_right_right (m n k : β„•) : gcd m (n + k * m) = gcd m n := by simp [gcd_rec m (n + k * m), gcd_rec m n] @[simp] theorem gcd_add_mul_left_right (m n k : β„•) : gcd m (n + m * k) = gcd m n := by simp [gcd_rec m (n + m * k), gcd_rec m n] @[simp] theorem gcd_mul_right_add_right (m n k : β„•) : gcd m (k * m + n) = gcd m n := by simp [add_comm _ n] @[simp] theorem gcd_mul_left_add_right (m n k : β„•) : gcd m (m * k + n) = gcd m n := by simp [add_comm _ n] @[simp] theorem gcd_add_mul_right_left (m n k : β„•) : gcd (m + k * n) n = gcd m n := by rw [gcd_comm, gcd_add_mul_right_right, gcd_comm] @[simp] theorem gcd_add_mul_left_left (m n k : β„•) : gcd (m + n * k) n = gcd m n := by rw [gcd_comm, gcd_add_mul_left_right, gcd_comm] @[simp] theorem gcd_mul_right_add_left (m n k : β„•) : gcd (k * n + m) n = gcd m n := by rw [gcd_comm, gcd_mul_right_add_right, gcd_comm] @[simp] theorem gcd_mul_left_add_left (m n k : β„•) : gcd (n * k + m) n = gcd m n := by rw [gcd_comm, gcd_mul_left_add_right, gcd_comm] /-! Lemmas where one argument consists of an addition of the other -/ @[simp] theorem gcd_add_self_right (m n : β„•) : gcd m (n + m) = gcd m n := Eq.trans (by rw [one_mul]) (gcd_add_mul_right_right m n 1) @[simp] theorem gcd_add_self_left (m n : β„•) : gcd (m + n) n = gcd m n := by rw [gcd_comm, gcd_add_self_right, gcd_comm] @[simp] theorem gcd_self_add_left (m n : β„•) : gcd (m + n) m = gcd n m := by rw [add_comm, gcd_add_self_left] @[simp] theorem gcd_self_add_right (m n : β„•) : gcd m (m + n) = gcd m n := by rw [add_comm, gcd_add_self_right] /-! Lemmas where one argument consists of a subtraction of the other -/ @[simp] theorem gcd_sub_self_left {m n : β„•} (h : m ≀ n) : gcd (n - m) m = gcd n m := by calc gcd (n - m) m = gcd (n - m + m) m := by rw [← gcd_add_self_left (n - m) m] _ = gcd n m := by rw [Nat.sub_add_cancel h] @[simp] theorem gcd_sub_self_right {m n : β„•} (h : m ≀ n) : gcd m (n - m) = gcd m n := by rw [gcd_comm, gcd_sub_self_left h, gcd_comm] @[simp] theorem gcd_self_sub_left {m n : β„•} (h : m ≀ n) : gcd (n - m) n = gcd m n := by have := Nat.sub_add_cancel h rw [gcd_comm m n, ← this, gcd_add_self_left (n - m) m] have : gcd (n - m) n = gcd (n - m) m := by nth_rw 2 [← Nat.add_sub_cancel' h] rw [gcd_add_self_right, gcd_comm] convert this @[simp] theorem gcd_self_sub_right {m n : β„•} (h : m ≀ n) : gcd n (n - m) = gcd n m := by rw [gcd_comm, gcd_self_sub_left h, gcd_comm] /-! ### `lcm` -/ theorem lcm_dvd_mul (m n : β„•) : lcm m n ∣ m * n := lcm_dvd (dvd_mul_right _ _) (dvd_mul_left _ _) theorem lcm_dvd_iff {m n k : β„•} : lcm m n ∣ k ↔ m ∣ k ∧ n ∣ k := ⟨fun h => ⟨(dvd_lcm_left _ _).trans h, (dvd_lcm_right _ _).trans h⟩, and_imp.2 lcm_dvd⟩ theorem lcm_pos {m n : β„•} : 0 < m β†’ 0 < n β†’ 0 < m.lcm n := by simp_rw [Nat.pos_iff_ne_zero] exact lcm_ne_zero theorem lcm_mul_left {m n k : β„•} : (m * n).lcm (m * k) = m * n.lcm k := by apply dvd_antisymm Β· exact lcm_dvd (mul_dvd_mul_left m (dvd_lcm_left n k)) (mul_dvd_mul_left m (dvd_lcm_right n k)) Β· have h : m ∣ lcm (m * n) (m * k) := (dvd_mul_right m n).trans (dvd_lcm_left (m * n) (m * k)) rw [← dvd_div_iff_mul_dvd h, lcm_dvd_iff, dvd_div_iff_mul_dvd h, dvd_div_iff_mul_dvd h, ← lcm_dvd_iff] theorem lcm_mul_right {m n k : β„•} : (m * n).lcm (k * n) = m.lcm k * n := by rw [mul_comm, mul_comm k n, lcm_mul_left, mul_comm] /-! ### `Coprime` See also `Nat.coprime_of_dvd` and `Nat.coprime_of_dvd'` to prove `Nat.Coprime m n`. -/ instance (m n : β„•) : Decidable (Coprime m n) := inferInstanceAs (Decidable (gcd m n = 1)) 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] @[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 hn.ne' 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.eq_zero_of_mul_eq_zero 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⟩ /-- Represent a divisor of `m * n` as a product of a divisor of `m` and a divisor of `n`. See `exists_dvd_and_dvd_of_dvd_mul` for the more general but less constructive version for other `GCDMonoid`s. -/ def prodDvdAndDvdOfDvdProd {m n k : β„•} (H : k ∣ m * n) : { d : { m' // m' ∣ m } Γ— { n' // n' ∣ n } // k = d.1 * d.2 } := by cases h0 : gcd k m with | zero => obtain rfl : k = 0 := eq_zero_of_gcd_eq_zero_left h0 obtain rfl : m = 0 := eq_zero_of_gcd_eq_zero_right h0 exact ⟨⟨⟨0, dvd_refl 0⟩, ⟨n, dvd_refl n⟩⟩, (zero_mul n).symm⟩ | succ tmp => have hpos : 0 < gcd k m := h0.symm β–Έ Nat.zero_lt_succ _; clear h0 tmp have hd : gcd k m * (k / gcd k m) = k := Nat.mul_div_cancel' (gcd_dvd_left k m) refine ⟨⟨⟨gcd k m, gcd_dvd_right k m⟩, ⟨k / gcd k m, ?_⟩⟩, hd.symm⟩ apply Nat.dvd_of_mul_dvd_mul_left hpos rw [hd, ← gcd_mul_right] exact dvd_gcd (dvd_mul_right _ _) H theorem dvd_mul {x m n : β„•} : x ∣ m * n ↔ βˆƒ y z, y ∣ m ∧ z ∣ n ∧ y * z = x := by constructor Β· intro h obtain ⟨⟨⟨y, hy⟩, ⟨z, hz⟩⟩, rfl⟩ := prod_dvd_and_dvd_of_dvd_prod h exact ⟨y, z, hy, hz, rfl⟩ Β· rintro ⟨y, z, hy, hz, rfl⟩ exact mul_dvd_mul hy hz theorem pow_dvd_pow_iff {a b n : β„•} (n0 : n β‰  0) : a ^ n ∣ b ^ n ↔ a ∣ b := by refine ⟨fun h => ?_, fun h => pow_dvd_pow_of_dvd h _⟩ rcases Nat.eq_zero_or_pos (gcd a b) with g0 | g0 Β· simp [eq_zero_of_gcd_eq_zero_right g0] rcases exists_coprime' g0 with ⟨g, a', b', g0', co, rfl, rfl⟩ rw [mul_pow, mul_pow] at h replace h := Nat.dvd_of_mul_dvd_mul_right (Nat.pos_pow_of_pos _ g0') h have := pow_dvd_pow a' <| Nat.pos_of_ne_zero n0 rw [pow_one, (co.pow n n).eq_one_of_dvd h] at this simp [eq_one_of_dvd_one this] 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, add_mul, add_mul, mul_comm _ n, ← mul_assoc, mul_comm y] variable {x n m : β„•} theorem dvd_gcd_mul_iff_dvd_mul : x ∣ gcd x n * m ↔ x ∣ n * m := by refine ⟨(Β·.trans <| mul_dvd_mul_right (x.gcd_dvd_right n) m), fun ⟨y, hy⟩ ↦ ?_⟩ rw [← gcd_mul_right, hy, gcd_mul_left] exact dvd_mul_right x (gcd m y) theorem dvd_mul_gcd_iff_dvd_mul : x ∣ n * gcd x m ↔ x ∣ n * m := by rw [mul_comm, dvd_gcd_mul_iff_dvd_mul, mul_comm] theorem dvd_gcd_mul_gcd_iff_dvd_mul : x ∣ gcd x n * gcd x m ↔ x ∣ n * m := by rw [dvd_gcd_mul_iff_dvd_mul, dvd_mul_gcd_iff_dvd_mul] 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 _ end Nat
Data\Nat\GCD\BigOperators.lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ import Mathlib.Algebra.BigOperators.Group.Finset /-! # 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
Data\Nat\Order\Lemmas.lean
/- Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import Mathlib.Data.Nat.Defs import Mathlib.Data.Nat.Find import Mathlib.Data.Set.Basic /-! # Further lemmas about the natural numbers The distinction between this file and `Mathlib.Algebra.Order.Ring.Nat` is not particularly clear. They were separated for now to minimize the porting requirements for tactics during the transition to mathlib4. Please feel free to reorganize these two files. -/ universe u v variable {a b m n k : β„•} namespace Nat /-! ### Sets -/ instance Subtype.orderBot (s : Set β„•) [DecidablePred (Β· ∈ s)] [h : Nonempty s] : OrderBot s where bot := ⟨Nat.find (nonempty_subtype.1 h), Nat.find_spec (nonempty_subtype.1 h)⟩ bot_le x := Nat.find_min' _ x.2 instance Subtype.semilatticeSup (s : Set β„•) : SemilatticeSup s := { Subtype.instLinearOrder s, LinearOrder.toLattice with } theorem Subtype.coe_bot {s : Set β„•} [DecidablePred (Β· ∈ s)] [h : Nonempty s] : ((βŠ₯ : s) : β„•) = Nat.find (nonempty_subtype.1 h) := rfl theorem set_eq_univ {S : Set β„•} : S = Set.univ ↔ 0 ∈ S ∧ βˆ€ k : β„•, k ∈ S β†’ k + 1 ∈ S := ⟨by rintro rfl; simp, fun ⟨h0, hs⟩ => Set.eq_univ_of_forall (set_induction h0 hs)⟩ lemma exists_not_and_succ_of_not_zero_of_exists {p : β„• β†’ Prop} (H' : Β¬ p 0) (H : βˆƒ n, p n) : βˆƒ n, Β¬ p n ∧ p (n + 1) := by classical let k := Nat.find H have hk : p k := Nat.find_spec H suffices 0 < k from ⟨k - 1, Nat.find_min H <| Nat.pred_lt this.ne', by rwa [Nat.sub_add_cancel this]⟩ by_contra! contra rw [le_zero_eq] at contra exact H' (contra β–Έ hk) end Nat
Data\Nat\Prime\Basic.lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import Mathlib.Algebra.Ring.Int import Mathlib.Order.Bounds.Basic import Mathlib.Data.Nat.Factorial.Basic import Mathlib.Data.Nat.Prime.Defs import Mathlib.Algebra.Order.Monoid.Unbundled.Pow /-! ## 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 variable {n : β„•} 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 -- Porting note (#11043): was `decide!` match p with | 0 => decide | 1 => decide | 2 => decide | 3 => decide | 4 => decide | n + 5 => exact (h.not_le <| le_add_left ..).elim 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 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) /-- 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⟩ 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 : β„•} [Fact p.Prime] : p % 2 = 1 ↔ p β‰  2 := by refine ⟨fun h hf => ?_, (Nat.Prime.eq_two_or_odd <| @Fact.out p.Prime _).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 cases' h with p hp apply Nat.not_coprime_of_dvd_of_dvd (Prime.one_lt hp.1) hp.2.1 hp.2.2 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, odd_iff_not_even, even_iff_two_dvd] @[simp] lemma coprime_two_right : n.Coprime 2 ↔ Odd n := coprime_comm.trans coprime_two_left alias ⟨Coprime.odd_of_left, _root_.Odd.coprime_two_left⟩ := coprime_two_left alias ⟨Coprime.odd_of_right, _root_.Odd.coprime_two_right⟩ := coprime_two_right -- Porting note: attributes `protected`, `nolint dup_namespace` removed 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, and_true_iff, pow_one] 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] 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_right_eq_self_iff (Nat.mul_pos hp.pos hp.pos : 0 < a * a)] at h exact h theorem Prime.dvd_factorial : βˆ€ {n p : β„•} (_ : Prime p), p ∣ n ! ↔ p ≀ n | 0, p, hp => iff_of_false hp.not_dvd_one (not_le_of_lt 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 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} (n_pos : 0 < n) (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 n_pos h) theorem eq_or_coprime_of_le_prime {n p} (n_pos : 0 < n) (hle : n ≀ p) (pp : Prime p) : p = n ∨ Coprime p n := hle.eq_or_lt.imp Eq.symm fun h => coprime_of_lt_prime n_pos h pp 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 let ha : a β‰  1 := Nat.succ_succ_ne_one n simp only [true_iff_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 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, not_prime_one] at hp, fun a b => by simpa only [Int.natCast_dvd_natCast, (Int.ofNat_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)⟩ theorem exists_pow_lt_factorial (c : β„•) : βˆƒ n0 > 1, βˆ€ n β‰₯ n0, c ^ n < (n - 1)! := by refine ⟨2 * (c ^ 2 + 1), ?_, ?_⟩ Β· omega intro n hn obtain ⟨d, rfl⟩ := Nat.exists_eq_add_of_le hn obtain (rfl | c0) := c.eq_zero_or_pos Β· simp [Nat.factorial_pos] refine (Nat.le_mul_of_pos_right _ (Nat.pow_pos (n := d) c0)).trans_lt ?_ convert_to (c ^ 2) ^ (c ^ 2 + d + 1) < (c ^ 2 + (c ^ 2 + d + 1))! Β· rw [← pow_mul, ← pow_add] congr 1 omega Β· congr omega refine lt_of_lt_of_le ?_ Nat.factorial_mul_pow_le_factorial rw [← one_mul (_ ^ _ : β„•)] exact Nat.mul_lt_mul_of_le_of_lt (Nat.one_le_of_lt (Nat.factorial_pos _)) (Nat.pow_lt_pow_left (Nat.lt_succ_self _) (Nat.succ_ne_zero _)) (Nat.factorial_pos _) theorem exists_mul_pow_lt_factorial (a : β„•) (c : β„•) : βˆƒ n0, βˆ€ n β‰₯ n0, a * c ^ n < (n - 1)! := by obtain ⟨n0, hn, h⟩ := Nat.exists_pow_lt_factorial (a * c) refine ⟨n0, fun n hn => lt_of_le_of_lt ?_ (h n hn)⟩ rw [mul_pow] refine Nat.mul_le_mul_right _ (Nat.le_self_pow ?_ _) omega theorem exists_prime_mul_pow_lt_factorial (n a c : β„•) : βˆƒ p > n, p.Prime ∧ a * c ^ p < (p - 1)! := have ⟨n0, h⟩ := Nat.exists_mul_pow_lt_factorial a c have ⟨p, hp, prime_p⟩ := (max (n + 1) n0).exists_infinite_primes ⟨p, (le_max_left _ _).trans hp, prime_p, h _ <| le_of_max_le_right hp⟩ end Nat namespace Int theorem prime_two : Prime (2 : β„€) := Nat.prime_iff_prime_int.mp Nat.prime_two theorem prime_three : Prime (3 : β„€) := Nat.prime_iff_prime_int.mp Nat.prime_three end Int
Data\Nat\Prime\Defs.lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import Mathlib.Algebra.Associated.Basic import Mathlib.Algebra.Ring.Parity import Mathlib.Data.Nat.GCD.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 -/ open Bool Subtype open Nat 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`. -/ @[pp_nodot] def Prime (p : β„•) := Irreducible p theorem irreducible_iff_nat_prime (a : β„•) : Irreducible a ↔ Nat.Prime a := Iff.rfl @[aesop safe destruct] theorem not_prime_zero : Β¬Prime 0 | h => h.ne_zero rfl @[aesop safe destruct] theorem not_prime_one : Β¬Prime 1 | h => h.ne_one rfl 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] theorem prime_def_lt'' {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', fun a b hab => ?_⟩ simp only [Nat.isUnit_iff] apply Or.imp_right _ (h.2 a _) Β· rintro rfl rw [← mul_right_inj' (zero_lt_of_lt h1).ne', ← hab, mul_one] Β· rw [hab] exact dvd_mul_right _ _ theorem prime_def_lt {p : β„•} : Prime p ↔ 2 ≀ p ∧ βˆ€ m < p, m ∣ p β†’ m = 1 := prime_def_lt''.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) Β· rw [eq_zero_of_zero_dvd d] at p2 revert p2 decide Β· rfl Β· exact (h (le_add_left _ _) 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 => have : βˆ€ {m k : β„•}, m ≀ k β†’ 1 < m β†’ p β‰  m * k := fun {m k} mk m1 e => a m m1 (le_sqrt.2 (e.symm β–Έ Nat.mul_le_mul_left m mk)) ⟨k, e⟩ fun m m2 l ⟨k, e⟩ => by rcases le_total m k with mk | km Β· exact this mk m2 e Β· rw [mul_comm] at e refine this km (Nat.lt_of_mul_lt_mul_right (a := m) ?_) e rwa [one_mul, ← e]⟩ 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 section /-- This instance is slower than the instance `decidablePrime` defined below, but has the advantage that it works in the kernel for small values. 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. -/ @[local instance] def decidablePrime1 (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 end 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 theorem prime_mul_iff {a b : β„•} : Nat.Prime (a * b) ↔ a.Prime ∧ b = 1 ∨ b.Prime ∧ a = 1 := by simp only [iff_self_iff, 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, _root_.not_or, *] theorem not_prime_mul' {a b n : β„•} (h : a * b = n) (h₁ : a β‰  1) (hβ‚‚ : b β‰  1) : Β¬Prime n := h β–Έ not_prime_mul h₁ hβ‚‚ 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 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`. By default this well-founded recursion would be irreducible. This prevents use `decide` to resolve `Nat.prime n` for small values of `n`, so we mark this as `@[semireducible]`. In future, we may want to remove this annotation and instead use `norm_num` instead of `decide` in these situations. -/ @[semireducible] 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, minFacAux] 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 [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 [h, ↓reduceIte] by_cases dk : k ∣ n <;> simp only [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, 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, GE.ge] have n2 : 2 ≀ n := by revert n0 n1 rcases n with (_ | _ | _) <;> simp [succ_le_succ] simp only [minFac_eq, Nat.isUnit_iff] 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))⟩ 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_lt 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 instance is faster in the virtual machine than `decidablePrime1`, but slower in the kernel. 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_minFac 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, or_false_iff, 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 rfl @[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' => ?_ have := le_antisymm (Nat.succ_le_of_lt lb) (Nat.lt_succ_iff.mp h') rw [eq_comm, Nat.minFac_eq_one_iff] at this subst this exact not_lt_of_le (le_of_dvd lb h) h' 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 m 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 _⟩ theorem prime_iff {p : β„•} : p.Prime ↔ _root_.Prime p := ⟨fun h => ⟨h.ne_zero, h.not_unit, fun _ _ => h.dvd_mul.mp⟩, Prime.irreducible⟩ alias ⟨Prime.prime, _root_.Prime.nat_prime⟩ := prime_iff theorem irreducible_iff_prime {p : β„•} : Irreducible p ↔ _root_.Prime p := prime_iff /-- 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⟩ -- Porting note: change in signature to match change in coercion theorem coe_nat_injective : Function.Injective (fun (a : Nat.Primes) ↦ (a : β„•)) := 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 : β„•)⟩ end Nat namespace Nat instance fact_prime_two : Fact (Prime 2) := ⟨prime_two⟩ instance fact_prime_three : Fact (Prime 3) := ⟨prime_three⟩ end Nat
Data\NNRat\BigOperators.lean
/- Copyright (c) 2022 YaΓ«l Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: YaΓ«l Dillies, Bhavik Mehta -/ import Mathlib.Algebra.Order.BigOperators.Ring.Finset import Mathlib.Data.NNRat.Defs /-! # Casting lemmas for non-negative rational numbers involving sums and products -/ variable {ΞΉ Ξ± : Type*} namespace NNRat @[norm_cast] theorem coe_list_sum (l : List β„šβ‰₯0) : (l.sum : β„š) = (l.map (↑)).sum := map_list_sum coeHom _ @[norm_cast] theorem coe_list_prod (l : List β„šβ‰₯0) : (l.prod : β„š) = (l.map (↑)).prod := map_list_prod coeHom _ @[norm_cast] theorem coe_multiset_sum (s : Multiset β„šβ‰₯0) : (s.sum : β„š) = (s.map (↑)).sum := map_multiset_sum coeHom _ @[norm_cast] theorem coe_multiset_prod (s : Multiset β„šβ‰₯0) : (s.prod : β„š) = (s.map (↑)).prod := map_multiset_prod coeHom _ @[norm_cast] theorem coe_sum {s : Finset Ξ±} {f : Ξ± β†’ β„šβ‰₯0} : ↑(βˆ‘ a ∈ s, f a) = βˆ‘ a ∈ s, (f a : β„š) := map_sum coeHom _ _ theorem toNNRat_sum_of_nonneg {s : Finset Ξ±} {f : Ξ± β†’ β„š} (hf : βˆ€ a, a ∈ s β†’ 0 ≀ f a) : (βˆ‘ a ∈ s, f a).toNNRat = βˆ‘ a ∈ s, (f a).toNNRat := by rw [← coe_inj, coe_sum, Rat.coe_toNNRat _ (Finset.sum_nonneg hf)] exact Finset.sum_congr rfl fun x hxs ↦ by rw [Rat.coe_toNNRat _ (hf x hxs)] @[norm_cast] theorem coe_prod {s : Finset Ξ±} {f : Ξ± β†’ β„šβ‰₯0} : ↑(∏ a ∈ s, f a) = ∏ a ∈ s, (f a : β„š) := map_prod coeHom _ _ theorem toNNRat_prod_of_nonneg {s : Finset Ξ±} {f : Ξ± β†’ β„š} (hf : βˆ€ a ∈ s, 0 ≀ f a) : (∏ a ∈ s, f a).toNNRat = ∏ a ∈ s, (f a).toNNRat := by rw [← coe_inj, coe_prod, Rat.coe_toNNRat _ (Finset.prod_nonneg hf)] exact Finset.prod_congr rfl fun x hxs ↦ by rw [Rat.coe_toNNRat _ (hf x hxs)] end NNRat
Data\NNRat\Defs.lean
/- Copyright (c) 2022 YaΓ«l Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: YaΓ«l Dillies, Bhavik Mehta -/ import Mathlib.Algebra.Order.Nonneg.Ring import Mathlib.Algebra.Order.Ring.Rat import Mathlib.Data.Nat.Cast.Order.Ring /-! # Nonnegative rationals This file defines the nonnegative rationals as a subtype of `Rat` and provides its basic algebraic order structure. Note that `NNRat` is not declared as a `Field` here. See `Data.NNRat.Lemmas` for that instance. We also define an instance `CanLift β„š β„šβ‰₯0`. This instance can be used by the `lift` tactic to replace `x : β„š` and `hx : 0 ≀ x` in the proof context with `x : β„šβ‰₯0` while replacing all occurrences of `x` with `↑x`. This tactic also works for a function `f : Ξ± β†’ β„š` with a hypothesis `hf : βˆ€ x, 0 ≀ f x`. ## Notation `β„šβ‰₯0` is notation for `NNRat` in locale `NNRat`. ## Huge warning Whenever you state a lemma about the coercion `β„šβ‰₯0 β†’ β„š`, check that Lean inserts `NNRat.cast`, not `Subtype.val`. Else your lemma will never apply. -/ open Function deriving instance CanonicallyOrderedCommSemiring for NNRat deriving instance CanonicallyLinearOrderedAddCommMonoid for NNRat deriving instance Sub for NNRat deriving instance Inhabited for NNRat -- TODO: `deriving instance OrderedSub for NNRat` doesn't work yet, so we add the instance manually instance NNRat.instOrderedSub : OrderedSub β„šβ‰₯0 := Nonneg.orderedSub namespace NNRat variable {Ξ± : Type*} {p q : β„šβ‰₯0} @[simp] lemma val_eq_cast (q : β„šβ‰₯0) : q.1 = q := rfl instance canLift : CanLift β„š β„šβ‰₯0 (↑) fun q ↦ 0 ≀ q where prf q hq := ⟨⟨q, hq⟩, rfl⟩ @[ext] theorem ext : (p : β„š) = (q : β„š) β†’ p = q := Subtype.ext protected theorem coe_injective : Injective ((↑) : β„šβ‰₯0 β†’ β„š) := Subtype.coe_injective @[simp, norm_cast] theorem coe_inj : (p : β„š) = q ↔ p = q := Subtype.coe_inj theorem ne_iff {x y : β„šβ‰₯0} : (x : β„š) β‰  (y : β„š) ↔ x β‰  y := NNRat.coe_inj.not -- TODO: We have to write `NNRat.cast` explicitly, else the statement picks up `Subtype.val` instead @[simp, norm_cast] lemma coe_mk (q : β„š) (hq) : NNRat.cast ⟨q, hq⟩ = q := rfl lemma Β«forallΒ» {p : β„šβ‰₯0 β†’ Prop} : (βˆ€ q, p q) ↔ βˆ€ q hq, p ⟨q, hq⟩ := Subtype.forall lemma Β«existsΒ» {p : β„šβ‰₯0 β†’ Prop} : (βˆƒ q, p q) ↔ βˆƒ q hq, p ⟨q, hq⟩ := Subtype.exists /-- Reinterpret a rational number `q` as a non-negative rational number. Returns `0` if `q ≀ 0`. -/ def _root_.Rat.toNNRat (q : β„š) : β„šβ‰₯0 := ⟨max q 0, le_max_right _ _⟩ theorem _root_.Rat.coe_toNNRat (q : β„š) (hq : 0 ≀ q) : (q.toNNRat : β„š) = q := max_eq_left hq theorem _root_.Rat.le_coe_toNNRat (q : β„š) : q ≀ q.toNNRat := le_max_left _ _ open Rat (toNNRat) @[simp] theorem coe_nonneg (q : β„šβ‰₯0) : (0 : β„š) ≀ q := q.2 @[simp, norm_cast] lemma coe_zero : ((0 : β„šβ‰₯0) : β„š) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : β„šβ‰₯0) : β„š) = 1 := rfl @[simp, norm_cast] theorem coe_add (p q : β„šβ‰₯0) : ((p + q : β„šβ‰₯0) : β„š) = p + q := rfl @[simp, norm_cast] theorem coe_mul (p q : β„šβ‰₯0) : ((p * q : β„šβ‰₯0) : β„š) = p * q := rfl @[simp, norm_cast] lemma coe_pow (q : β„šβ‰₯0) (n : β„•) : (↑(q ^ n) : β„š) = (q : β„š) ^ n := rfl @[simp] lemma num_pow (q : β„šβ‰₯0) (n : β„•) : (q ^ n).num = q.num ^ n := by simp [num, Int.natAbs_pow] @[simp] lemma den_pow (q : β„šβ‰₯0) (n : β„•) : (q ^ n).den = q.den ^ n := rfl -- Porting note: `bit0` `bit1` are deprecated, so remove these theorems. @[simp, norm_cast] theorem coe_sub (h : q ≀ p) : ((p - q : β„šβ‰₯0) : β„š) = p - q := max_eq_left <| le_sub_comm.2 <| by rwa [sub_zero] @[simp] theorem coe_eq_zero : (q : β„š) = 0 ↔ q = 0 := by norm_cast theorem coe_ne_zero : (q : β„š) β‰  0 ↔ q β‰  0 := coe_eq_zero.not @[norm_cast] -- Porting note (#10618): simp can prove this theorem coe_le_coe : (p : β„š) ≀ q ↔ p ≀ q := Iff.rfl @[norm_cast] -- Porting note (#10618): simp can prove this theorem coe_lt_coe : (p : β„š) < q ↔ p < q := Iff.rfl -- `cast_pos`, defined in a later file, makes this lemma redundant @[simp, norm_cast, nolint simpNF] theorem coe_pos : (0 : β„š) < q ↔ 0 < q := Iff.rfl theorem coe_mono : Monotone ((↑) : β„šβ‰₯0 β†’ β„š) := fun _ _ ↦ coe_le_coe.2 theorem toNNRat_mono : Monotone toNNRat := fun _ _ h ↦ max_le_max h le_rfl @[simp] theorem toNNRat_coe (q : β„šβ‰₯0) : toNNRat q = q := ext <| max_eq_left q.2 @[simp] theorem toNNRat_coe_nat (n : β„•) : toNNRat n = n := ext <| by simp only [Nat.cast_nonneg, Rat.coe_toNNRat]; rfl /-- `toNNRat` and `(↑) : β„šβ‰₯0 β†’ β„š` form a Galois insertion. -/ protected def gi : GaloisInsertion toNNRat (↑) := GaloisInsertion.monotoneIntro coe_mono toNNRat_mono Rat.le_coe_toNNRat toNNRat_coe /-- Coercion `β„šβ‰₯0 β†’ β„š` as a `RingHom`. -/ def coeHom : β„šβ‰₯0 β†’+* β„š where toFun := (↑) map_one' := coe_one map_mul' := coe_mul map_zero' := coe_zero map_add' := coe_add @[simp, norm_cast] lemma coe_natCast (n : β„•) : (↑(↑n : β„šβ‰₯0) : β„š) = n := rfl -- See note [no_index around OfNat.ofNat] @[simp] theorem mk_natCast (n : β„•) : @Eq β„šβ‰₯0 (⟨(n : β„š), n.cast_nonneg⟩ : β„šβ‰₯0) n := rfl @[deprecated (since := "2024-04-05")] alias mk_coe_nat := mk_natCast @[simp] theorem coe_coeHom : ⇑coeHom = ((↑) : β„šβ‰₯0 β†’ β„š) := rfl @[norm_cast] theorem nsmul_coe (q : β„šβ‰₯0) (n : β„•) : ↑(n β€’ q) = n β€’ (q : β„š) := coeHom.toAddMonoidHom.map_nsmul _ _ theorem bddAbove_coe {s : Set β„šβ‰₯0} : BddAbove ((↑) '' s : Set β„š) ↔ BddAbove s := ⟨fun ⟨b, hb⟩ ↦ ⟨toNNRat b, fun ⟨y, _⟩ hys ↦ show y ≀ max b 0 from (hb <| Set.mem_image_of_mem _ hys).trans <| le_max_left _ _⟩, fun ⟨b, hb⟩ ↦ ⟨b, fun _ ⟨_, hx, Eq⟩ ↦ Eq β–Έ hb hx⟩⟩ theorem bddBelow_coe (s : Set β„šβ‰₯0) : BddBelow (((↑) : β„šβ‰₯0 β†’ β„š) '' s) := ⟨0, fun _ ⟨q, _, h⟩ ↦ h β–Έ q.2⟩ -- `cast_max`, defined in a later file, makes this lemma redundant @[simp, norm_cast, nolint simpNF] theorem coe_max (x y : β„šβ‰₯0) : ((max x y : β„šβ‰₯0) : β„š) = max (x : β„š) (y : β„š) := coe_mono.map_max -- `cast_max`, defined in a later file, makes this lemma redundant @[simp, norm_cast, nolint simpNF] theorem coe_min (x y : β„šβ‰₯0) : ((min x y : β„šβ‰₯0) : β„š) = min (x : β„š) (y : β„š) := coe_mono.map_min theorem sub_def (p q : β„šβ‰₯0) : p - q = toNNRat (p - q) := rfl @[simp] theorem abs_coe (q : β„šβ‰₯0) : |(q : β„š)| = q := abs_of_nonneg q.2 end NNRat open NNRat namespace Rat variable {p q : β„š} @[simp] theorem toNNRat_zero : toNNRat 0 = 0 := rfl @[simp] theorem toNNRat_one : toNNRat 1 = 1 := rfl @[simp] theorem toNNRat_pos : 0 < toNNRat q ↔ 0 < q := by simp [toNNRat, ← coe_lt_coe] @[simp] theorem toNNRat_eq_zero : toNNRat q = 0 ↔ q ≀ 0 := by simpa [-toNNRat_pos] using (@toNNRat_pos q).not alias ⟨_, toNNRat_of_nonpos⟩ := toNNRat_eq_zero @[simp] theorem toNNRat_le_toNNRat_iff (hp : 0 ≀ p) : toNNRat q ≀ toNNRat p ↔ q ≀ p := by simp [← coe_le_coe, toNNRat, hp] @[simp] theorem toNNRat_lt_toNNRat_iff' : toNNRat q < toNNRat p ↔ q < p ∧ 0 < p := by simp [← coe_lt_coe, toNNRat, lt_irrefl] theorem toNNRat_lt_toNNRat_iff (h : 0 < p) : toNNRat q < toNNRat p ↔ q < p := toNNRat_lt_toNNRat_iff'.trans (and_iff_left h) theorem toNNRat_lt_toNNRat_iff_of_nonneg (hq : 0 ≀ q) : toNNRat q < toNNRat p ↔ q < p := toNNRat_lt_toNNRat_iff'.trans ⟨And.left, fun h ↦ ⟨h, hq.trans_lt h⟩⟩ @[simp] theorem toNNRat_add (hq : 0 ≀ q) (hp : 0 ≀ p) : toNNRat (q + p) = toNNRat q + toNNRat p := NNRat.ext <| by simp [toNNRat, hq, hp, add_nonneg] theorem toNNRat_add_le : toNNRat (q + p) ≀ toNNRat q + toNNRat p := coe_le_coe.1 <| max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) <| coe_nonneg _ theorem toNNRat_le_iff_le_coe {p : β„šβ‰₯0} : toNNRat q ≀ p ↔ q ≀ ↑p := NNRat.gi.gc q p theorem le_toNNRat_iff_coe_le {q : β„šβ‰₯0} (hp : 0 ≀ p) : q ≀ toNNRat p ↔ ↑q ≀ p := by rw [← coe_le_coe, Rat.coe_toNNRat p hp] theorem le_toNNRat_iff_coe_le' {q : β„šβ‰₯0} (hq : 0 < q) : q ≀ toNNRat p ↔ ↑q ≀ p := (le_or_lt 0 p).elim le_toNNRat_iff_coe_le fun hp ↦ by simp only [(hp.trans_le q.coe_nonneg).not_le, toNNRat_eq_zero.2 hp.le, hq.not_le] theorem toNNRat_lt_iff_lt_coe {p : β„šβ‰₯0} (hq : 0 ≀ q) : toNNRat q < p ↔ q < ↑p := by rw [← coe_lt_coe, Rat.coe_toNNRat q hq] theorem lt_toNNRat_iff_coe_lt {q : β„šβ‰₯0} : q < toNNRat p ↔ ↑q < p := NNRat.gi.gc.lt_iff_lt -- Porting note: `bit0` `bit1` are deprecated, so remove these theorems. theorem toNNRat_mul (hp : 0 ≀ p) : toNNRat (p * q) = toNNRat p * toNNRat q := by rcases le_total 0 q with hq | hq Β· ext; simp [toNNRat, hp, hq, max_eq_left, mul_nonneg] Β· have hpq := mul_nonpos_of_nonneg_of_nonpos hp hq rw [toNNRat_eq_zero.2 hq, toNNRat_eq_zero.2 hpq, mul_zero] end Rat /-- The absolute value on `β„š` as a map to `β„šβ‰₯0`. -/ @[pp_nodot] def Rat.nnabs (x : β„š) : β„šβ‰₯0 := ⟨abs x, abs_nonneg x⟩ @[norm_cast, simp] theorem Rat.coe_nnabs (x : β„š) : (Rat.nnabs x : β„š) = abs x := rfl /-! ### Numerator and denominator -/ namespace NNRat variable {p q : β„šβ‰₯0} @[norm_cast] lemma num_coe (q : β„šβ‰₯0) : (q : β„š).num = q.num := by simp [num, abs_of_nonneg, Rat.num_nonneg, q.2] theorem natAbs_num_coe : (q : β„š).num.natAbs = q.num := rfl @[norm_cast] lemma den_coe : (q : β„š).den = q.den := rfl @[simp] lemma num_ne_zero : q.num β‰  0 ↔ q β‰  0 := by simp [num] @[simp] lemma num_pos : 0 < q.num ↔ 0 < q := by simp [pos_iff_ne_zero] @[simp] lemma den_pos (q : β„šβ‰₯0) : 0 < q.den := Rat.den_pos _ @[simp] lemma den_ne_zero (q : β„šβ‰₯0) : q.den β‰  0 := Rat.den_ne_zero _ lemma coprime_num_den (q : β„šβ‰₯0) : q.num.Coprime q.den := by simpa [num, den] using Rat.reduced _ -- TODO: Rename `Rat.coe_nat_num`, `Rat.intCast_den`, `Rat.ofNat_num`, `Rat.ofNat_den` @[simp, norm_cast] lemma num_natCast (n : β„•) : num n = n := rfl @[simp, norm_cast] lemma den_natCast (n : β„•) : den n = 1 := rfl -- See note [no_index around OfNat.ofNat] @[simp] lemma num_ofNat (n : β„•) [n.AtLeastTwo] : num (no_index (OfNat.ofNat n)) = OfNat.ofNat n := rfl @[simp] lemma den_ofNat (n : β„•) [n.AtLeastTwo] : den (no_index (OfNat.ofNat n)) = 1 := rfl theorem ext_num_den (hn : p.num = q.num) (hd : p.den = q.den) : p = q := by refine ext <| Rat.ext ?_ hd simpa [num_coe] theorem ext_num_den_iff : p = q ↔ p.num = q.num ∧ p.den = q.den := ⟨by rintro rfl; exact ⟨rfl, rfl⟩, fun h ↦ ext_num_den h.1 h.2⟩ /-- Form the quotient `n / d` where `n d : β„•`. See also `Rat.divInt` and `mkRat`. -/ def divNat (n d : β„•) : β„šβ‰₯0 := ⟨.divInt n d, Rat.divInt_nonneg n.cast_nonneg d.cast_nonneg⟩ variable {n₁ nβ‚‚ d₁ dβ‚‚ d : β„•} @[simp, norm_cast] lemma coe_divNat (n d : β„•) : (divNat n d : β„š) = .divInt n d := rfl lemma mk_divInt (n d : β„•) : ⟨.divInt n d, Rat.divInt_nonneg n.cast_nonneg d.cast_nonneg⟩ = divNat n d := rfl lemma divNat_inj (h₁ : d₁ β‰  0) (hβ‚‚ : dβ‚‚ β‰  0) : divNat n₁ d₁ = divNat nβ‚‚ dβ‚‚ ↔ n₁ * dβ‚‚ = nβ‚‚ * d₁ := by rw [← coe_inj]; simp [Rat.mkRat_eq_iff, h₁, hβ‚‚]; norm_cast @[simp] lemma divNat_zero (n : β„•) : divNat n 0 = 0 := by simp [divNat]; rfl @[simp] lemma num_divNat_den (q : β„šβ‰₯0) : divNat q.num q.den = q := ext $ by rw [← (q : β„š).mkRat_num_den']; simp [num_coe, den_coe] lemma natCast_eq_divNat (n : β„•) : (n : β„šβ‰₯0) = divNat n 1 := (num_divNat_den _).symm lemma divNat_mul_divNat (n₁ nβ‚‚ : β„•) {d₁ dβ‚‚} (hd₁ : d₁ β‰  0) (hdβ‚‚ : dβ‚‚ β‰  0) : divNat n₁ d₁ * divNat nβ‚‚ dβ‚‚ = divNat (n₁ * nβ‚‚) (d₁ * dβ‚‚) := by ext; push_cast; exact Rat.divInt_mul_divInt _ _ (mod_cast hd₁) (mod_cast hdβ‚‚) lemma divNat_mul_left {a : β„•} (ha : a β‰  0) (n d : β„•) : divNat (a * n) (a * d) = divNat n d := by ext; push_cast; exact Rat.divInt_mul_left (mod_cast ha) lemma divNat_mul_right {a : β„•} (ha : a β‰  0) (n d : β„•) : divNat (n * a) (d * a) = divNat n d := by ext; push_cast; exact Rat.divInt_mul_right (mod_cast ha) @[simp] lemma mul_den_eq_num (q : β„šβ‰₯0) : q * q.den = q.num := by ext push_cast rw [← Int.cast_natCast, ← den_coe, ← Int.cast_natCast q.num, ← num_coe] exact Rat.mul_den_eq_num _ @[simp] lemma den_mul_eq_num (q : β„šβ‰₯0) : q.den * q = q.num := by rw [mul_comm, mul_den_eq_num] /-- Define a (dependent) function or prove `βˆ€ r : β„š, p r` by dealing with nonnegative rational numbers of the form `n / d` with `d β‰  0` and `n`, `d` coprime. -/ @[elab_as_elim] def numDenCasesOn.{u} {C : β„šβ‰₯0 β†’ Sort u} (q) (H : βˆ€ n d, d β‰  0 β†’ n.Coprime d β†’ C (divNat n d)) : C q := by rw [← q.num_divNat_den]; exact H _ _ q.den_ne_zero q.coprime_num_den lemma add_def (q r : β„šβ‰₯0) : q + r = divNat (q.num * r.den + r.num * q.den) (q.den * r.den) := by ext; simp [Rat.add_def', Rat.mkRat_eq_divInt, num_coe, den_coe] lemma mul_def (q r : β„šβ‰₯0) : q * r = divNat (q.num * r.num) (q.den * r.den) := by ext; simp [Rat.mul_eq_mkRat, Rat.mkRat_eq_divInt, num_coe, den_coe] theorem lt_def {p q : β„šβ‰₯0} : p < q ↔ p.num * q.den < q.num * p.den := by rw [← NNRat.coe_lt_coe, Rat.lt_def]; norm_cast theorem le_def {p q : β„šβ‰₯0} : p ≀ q ↔ p.num * q.den ≀ q.num * p.den := by rw [← NNRat.coe_le_coe, Rat.le_def]; norm_cast end NNRat
Data\NNRat\Lemmas.lean
/- Copyright (c) 2022 YaΓ«l Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: YaΓ«l Dillies, Bhavik Mehta -/ import Mathlib.Algebra.Field.Rat import Mathlib.Algebra.Group.Indicator import Mathlib.Algebra.Order.Field.Rat /-! # Field and action structures on the nonnegative rationals This file provides additional results about `NNRat` that cannot live in earlier files due to import cycles. -/ open Function open scoped NNRat namespace NNRat variable {Ξ± : Type*} {p q : β„šβ‰₯0} /-- A `MulAction` over `β„š` restricts to a `MulAction` over `β„šβ‰₯0`. -/ instance [MulAction β„š Ξ±] : MulAction β„šβ‰₯0 Ξ± := MulAction.compHom Ξ± coeHom.toMonoidHom /-- A `DistribMulAction` over `β„š` restricts to a `DistribMulAction` over `β„šβ‰₯0`. -/ instance [AddCommMonoid Ξ±] [DistribMulAction β„š Ξ±] : DistribMulAction β„šβ‰₯0 Ξ± := DistribMulAction.compHom Ξ± coeHom.toMonoidHom @[simp, norm_cast] lemma coe_indicator (s : Set Ξ±) (f : Ξ± β†’ β„šβ‰₯0) (a : Ξ±) : ((s.indicator f a : β„šβ‰₯0) : β„š) = s.indicator (fun x ↦ ↑(f x)) a := (coeHom : β„šβ‰₯0 β†’+ β„š).map_indicator _ _ _ end NNRat open NNRat namespace Rat variable {p q : β„š} lemma toNNRat_inv (q : β„š) : toNNRat q⁻¹ = (toNNRat q)⁻¹ := by obtain hq | hq := le_total q 0 Β· rw [toNNRat_eq_zero.mpr hq, inv_zero, toNNRat_eq_zero.mpr (inv_nonpos (Ξ± := β„š) |>.mpr hq)] Β· nth_rw 1 [← Rat.coe_toNNRat q hq] rw [← coe_inv, toNNRat_coe] lemma toNNRat_div (hp : 0 ≀ p) : toNNRat (p / q) = toNNRat p / toNNRat q := by rw [div_eq_mul_inv, div_eq_mul_inv, ← toNNRat_inv, ← toNNRat_mul hp] lemma toNNRat_div' (hq : 0 ≀ q) : toNNRat (p / q) = toNNRat p / toNNRat q := by rw [div_eq_inv_mul, div_eq_inv_mul, toNNRat_mul (inv_nonneg (Ξ± := β„š) |>.2 hq), toNNRat_inv] end Rat /-! ### Numerator and denominator -/ namespace NNRat variable {p q : β„šβ‰₯0} @[simp] lemma num_div_den (q : β„šβ‰₯0) : (q.num : β„šβ‰₯0) / q.den = q := by ext : 1 rw [coe_div, coe_natCast, coe_natCast, num, ← Int.cast_natCast, Int.natAbs_of_nonneg (Rat.num_nonneg.2 q.cast_nonneg)] exact Rat.num_div_den q /-- A recursor for nonnegative rationals in terms of numerators and denominators. -/ protected def rec {Ξ± : β„šβ‰₯0 β†’ Sort*} (h : βˆ€ m n : β„•, Ξ± (m / n)) (q : β„šβ‰₯0) : Ξ± q := by rw [← num_div_den q]; apply h end NNRat
Data\NNReal\Basic.lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.Algebra.Algebra.Defs import Mathlib.Algebra.Order.BigOperators.Ring.Finset import Mathlib.Algebra.Order.Field.Canonical.Basic import Mathlib.Algebra.Order.Nonneg.Field import Mathlib.Algebra.Order.Nonneg.Floor import Mathlib.Data.Real.Pointwise import Mathlib.Order.ConditionallyCompleteLattice.Group import Mathlib.Tactic.Bound.Attribute import Mathlib.Tactic.GCongr.Core import Mathlib.Algebra.Ring.Regular /-! # Nonnegative real numbers In this file we define `NNReal` (notation: `ℝβ‰₯0`) to be the type of non-negative real numbers, a.k.a. the interval `[0, ∞)`. We also define the following operations and structures on `ℝβ‰₯0`: * the order on `ℝβ‰₯0` is the restriction of the order on `ℝ`; these relations define a conditionally complete linear order with a bottom element, `ConditionallyCompleteLinearOrderBot`; * `a + b` and `a * b` are the restrictions of addition and multiplication of real numbers to `ℝβ‰₯0`; these operations together with `0 = ⟨0, _⟩` and `1 = ⟨1, _⟩` turn `ℝβ‰₯0` into a conditionally complete linear ordered archimedean commutative semifield; we have no typeclass for this in `mathlib` yet, so we define the following instances instead: - `LinearOrderedSemiring ℝβ‰₯0`; - `OrderedCommSemiring ℝβ‰₯0`; - `CanonicallyOrderedCommSemiring ℝβ‰₯0`; - `LinearOrderedCommGroupWithZero ℝβ‰₯0`; - `CanonicallyLinearOrderedAddCommMonoid ℝβ‰₯0`; - `Archimedean ℝβ‰₯0`; - `ConditionallyCompleteLinearOrderBot ℝβ‰₯0`. These instances are derived from corresponding instances about the type `{x : Ξ± // 0 ≀ x}` in an appropriate ordered field/ring/group/monoid `Ξ±`, see `Mathlib.Algebra.Order.Nonneg.OrderedRing`. * `Real.toNNReal x` is defined as `⟨max x 0, _⟩`, i.e. `↑(Real.toNNReal x) = x` when `0 ≀ x` and `↑(Real.toNNReal x) = 0` otherwise. We also define an instance `CanLift ℝ ℝβ‰₯0`. This instance can be used by the `lift` tactic to replace `x : ℝ` and `hx : 0 ≀ x` in the proof context with `x : ℝβ‰₯0` while replacing all occurrences of `x` with `↑x`. This tactic also works for a function `f : Ξ± β†’ ℝ` with a hypothesis `hf : βˆ€ x, 0 ≀ f x`. ## Notations This file defines `ℝβ‰₯0` as a localized notation for `NNReal`. -/ assert_not_exists Star open Function -- to ensure these instances are computable /-- Nonnegative real numbers. -/ def NNReal := { r : ℝ // 0 ≀ r } deriving Zero, One, Semiring, StrictOrderedSemiring, CommMonoidWithZero, CommSemiring, SemilatticeInf, SemilatticeSup, DistribLattice, OrderedCommSemiring, CanonicallyOrderedCommSemiring, Inhabited namespace NNReal scoped notation "ℝβ‰₯0" => NNReal noncomputable instance : FloorSemiring ℝβ‰₯0 := Nonneg.floorSemiring instance instDenselyOrdered : DenselyOrdered ℝβ‰₯0 := Nonneg.instDenselyOrdered instance : OrderBot ℝβ‰₯0 := inferInstance instance : Archimedean ℝβ‰₯0 := Nonneg.archimedean noncomputable instance : Sub ℝβ‰₯0 := Nonneg.sub noncomputable instance : OrderedSub ℝβ‰₯0 := Nonneg.orderedSub noncomputable instance : CanonicallyLinearOrderedSemifield ℝβ‰₯0 := Nonneg.canonicallyLinearOrderedSemifield /-- Coercion `ℝβ‰₯0 β†’ ℝ`. -/ @[coe] def toReal : ℝβ‰₯0 β†’ ℝ := Subtype.val instance : Coe ℝβ‰₯0 ℝ := ⟨toReal⟩ -- Simp lemma to put back `n.val` into the normal form given by the coercion. @[simp] theorem val_eq_coe (n : ℝβ‰₯0) : n.val = n := rfl instance canLift : CanLift ℝ ℝβ‰₯0 toReal fun r => 0 ≀ r := Subtype.canLift _ @[ext] protected theorem eq {n m : ℝβ‰₯0} : (n : ℝ) = (m : ℝ) β†’ n = m := Subtype.eq theorem ne_iff {x y : ℝβ‰₯0} : (x : ℝ) β‰  (y : ℝ) ↔ x β‰  y := NNReal.eq_iff.symm.not protected theorem Β«forallΒ» {p : ℝβ‰₯0 β†’ Prop} : (βˆ€ x : ℝβ‰₯0, p x) ↔ βˆ€ (x : ℝ) (hx : 0 ≀ x), p ⟨x, hx⟩ := Subtype.forall protected theorem Β«existsΒ» {p : ℝβ‰₯0 β†’ Prop} : (βˆƒ x : ℝβ‰₯0, p x) ↔ βˆƒ (x : ℝ) (hx : 0 ≀ x), p ⟨x, hx⟩ := Subtype.exists /-- Reinterpret a real number `r` as a non-negative real number. Returns `0` if `r < 0`. -/ noncomputable def _root_.Real.toNNReal (r : ℝ) : ℝβ‰₯0 := ⟨max r 0, le_max_right _ _⟩ theorem _root_.Real.coe_toNNReal (r : ℝ) (hr : 0 ≀ r) : (Real.toNNReal r : ℝ) = r := max_eq_left hr theorem _root_.Real.toNNReal_of_nonneg {r : ℝ} (hr : 0 ≀ r) : r.toNNReal = ⟨r, hr⟩ := by simp_rw [Real.toNNReal, max_eq_left hr] theorem _root_.Real.le_coe_toNNReal (r : ℝ) : r ≀ Real.toNNReal r := le_max_left r 0 @[bound] theorem coe_nonneg (r : ℝβ‰₯0) : (0 : ℝ) ≀ r := r.2 @[simp, norm_cast] theorem coe_mk (a : ℝ) (ha) : toReal ⟨a, ha⟩ = a := rfl example : Zero ℝβ‰₯0 := by infer_instance example : One ℝβ‰₯0 := by infer_instance example : Add ℝβ‰₯0 := by infer_instance noncomputable example : Sub ℝβ‰₯0 := by infer_instance example : Mul ℝβ‰₯0 := by infer_instance noncomputable example : Inv ℝβ‰₯0 := by infer_instance noncomputable example : Div ℝβ‰₯0 := by infer_instance example : LE ℝβ‰₯0 := by infer_instance example : Bot ℝβ‰₯0 := by infer_instance example : Inhabited ℝβ‰₯0 := by infer_instance example : Nontrivial ℝβ‰₯0 := by infer_instance protected theorem coe_injective : Injective ((↑) : ℝβ‰₯0 β†’ ℝ) := Subtype.coe_injective @[simp, norm_cast] lemma coe_inj {r₁ rβ‚‚ : ℝβ‰₯0} : (r₁ : ℝ) = rβ‚‚ ↔ r₁ = rβ‚‚ := NNReal.coe_injective.eq_iff @[deprecated (since := "2024-02-03")] protected alias coe_eq := coe_inj @[simp, norm_cast] lemma coe_zero : ((0 : ℝβ‰₯0) : ℝ) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : ℝβ‰₯0) : ℝ) = 1 := rfl @[simp, norm_cast] protected theorem coe_add (r₁ rβ‚‚ : ℝβ‰₯0) : ((r₁ + rβ‚‚ : ℝβ‰₯0) : ℝ) = r₁ + rβ‚‚ := rfl @[simp, norm_cast] protected theorem coe_mul (r₁ rβ‚‚ : ℝβ‰₯0) : ((r₁ * rβ‚‚ : ℝβ‰₯0) : ℝ) = r₁ * rβ‚‚ := rfl @[simp, norm_cast] protected theorem coe_inv (r : ℝβ‰₯0) : ((r⁻¹ : ℝβ‰₯0) : ℝ) = (r : ℝ)⁻¹ := rfl @[simp, norm_cast] protected theorem coe_div (r₁ rβ‚‚ : ℝβ‰₯0) : ((r₁ / rβ‚‚ : ℝβ‰₯0) : ℝ) = (r₁ : ℝ) / rβ‚‚ := rfl protected theorem coe_two : ((2 : ℝβ‰₯0) : ℝ) = 2 := rfl @[simp, norm_cast] protected theorem coe_sub {r₁ rβ‚‚ : ℝβ‰₯0} (h : rβ‚‚ ≀ r₁) : ((r₁ - rβ‚‚ : ℝβ‰₯0) : ℝ) = ↑r₁ - ↑rβ‚‚ := max_eq_left <| le_sub_comm.2 <| by simp [show (rβ‚‚ : ℝ) ≀ r₁ from h] variable {r r₁ rβ‚‚ : ℝβ‰₯0} {x y : ℝ} @[simp, norm_cast] lemma coe_eq_zero : (r : ℝ) = 0 ↔ r = 0 := by rw [← coe_zero, coe_inj] @[simp, norm_cast] lemma coe_eq_one : (r : ℝ) = 1 ↔ r = 1 := by rw [← coe_one, coe_inj] @[norm_cast] lemma coe_ne_zero : (r : ℝ) β‰  0 ↔ r β‰  0 := coe_eq_zero.not @[norm_cast] lemma coe_ne_one : (r : ℝ) β‰  1 ↔ r β‰  1 := coe_eq_one.not example : CommSemiring ℝβ‰₯0 := by infer_instance /-- Coercion `ℝβ‰₯0 β†’ ℝ` as a `RingHom`. Porting note (#11215): TODO: what if we define `Coe ℝβ‰₯0 ℝ` using this function? -/ def toRealHom : ℝβ‰₯0 β†’+* ℝ where toFun := (↑) map_one' := NNReal.coe_one map_mul' := NNReal.coe_mul map_zero' := NNReal.coe_zero map_add' := NNReal.coe_add @[simp] theorem coe_toRealHom : ⇑toRealHom = toReal := rfl section Actions /-- A `MulAction` over `ℝ` restricts to a `MulAction` over `ℝβ‰₯0`. -/ instance {M : Type*} [MulAction ℝ M] : MulAction ℝβ‰₯0 M := MulAction.compHom M toRealHom.toMonoidHom theorem smul_def {M : Type*} [MulAction ℝ M] (c : ℝβ‰₯0) (x : M) : c β€’ x = (c : ℝ) β€’ x := rfl instance {M N : Type*} [MulAction ℝ M] [MulAction ℝ N] [SMul M N] [IsScalarTower ℝ M N] : IsScalarTower ℝβ‰₯0 M N where smul_assoc r := (smul_assoc (r : ℝ) : _) instance smulCommClass_left {M N : Type*} [MulAction ℝ N] [SMul M N] [SMulCommClass ℝ M N] : SMulCommClass ℝβ‰₯0 M N where smul_comm r := (smul_comm (r : ℝ) : _) instance smulCommClass_right {M N : Type*} [MulAction ℝ N] [SMul M N] [SMulCommClass M ℝ N] : SMulCommClass M ℝβ‰₯0 N where smul_comm m r := (smul_comm m (r : ℝ) : _) /-- A `DistribMulAction` over `ℝ` restricts to a `DistribMulAction` over `ℝβ‰₯0`. -/ instance {M : Type*} [AddMonoid M] [DistribMulAction ℝ M] : DistribMulAction ℝβ‰₯0 M := DistribMulAction.compHom M toRealHom.toMonoidHom /-- A `Module` over `ℝ` restricts to a `Module` over `ℝβ‰₯0`. -/ instance {M : Type*} [AddCommMonoid M] [Module ℝ M] : Module ℝβ‰₯0 M := Module.compHom M toRealHom -- Porting note (#11215): TODO: after this line, `↑` uses `Algebra.cast` instead of `toReal` /-- An `Algebra` over `ℝ` restricts to an `Algebra` over `ℝβ‰₯0`. -/ instance {A : Type*} [Semiring A] [Algebra ℝ A] : Algebra ℝβ‰₯0 A where smul := (Β· β€’ Β·) commutes' r x := by simp [Algebra.commutes] smul_def' r x := by simp [← Algebra.smul_def (r : ℝ) x, smul_def] toRingHom := (algebraMap ℝ A).comp (toRealHom : ℝβ‰₯0 β†’+* ℝ) -- verify that the above produces instances we might care about example : Algebra ℝβ‰₯0 ℝ := by infer_instance example : DistribMulAction ℝβ‰₯0Λ£ ℝ := by infer_instance end Actions example : MonoidWithZero ℝβ‰₯0 := by infer_instance example : CommMonoidWithZero ℝβ‰₯0 := by infer_instance noncomputable example : CommGroupWithZero ℝβ‰₯0 := by infer_instance @[simp, norm_cast] theorem coe_indicator {Ξ±} (s : Set Ξ±) (f : Ξ± β†’ ℝβ‰₯0) (a : Ξ±) : ((s.indicator f a : ℝβ‰₯0) : ℝ) = s.indicator (fun x => ↑(f x)) a := (toRealHom : ℝβ‰₯0 β†’+ ℝ).map_indicator _ _ _ @[simp, norm_cast] theorem coe_pow (r : ℝβ‰₯0) (n : β„•) : ((r ^ n : ℝβ‰₯0) : ℝ) = (r : ℝ) ^ n := rfl @[simp, norm_cast] theorem coe_zpow (r : ℝβ‰₯0) (n : β„€) : ((r ^ n : ℝβ‰₯0) : ℝ) = (r : ℝ) ^ n := rfl @[norm_cast] theorem coe_list_sum (l : List ℝβ‰₯0) : ((l.sum : ℝβ‰₯0) : ℝ) = (l.map (↑)).sum := map_list_sum toRealHom l @[norm_cast] theorem coe_list_prod (l : List ℝβ‰₯0) : ((l.prod : ℝβ‰₯0) : ℝ) = (l.map (↑)).prod := map_list_prod toRealHom l @[norm_cast] theorem coe_multiset_sum (s : Multiset ℝβ‰₯0) : ((s.sum : ℝβ‰₯0) : ℝ) = (s.map (↑)).sum := map_multiset_sum toRealHom s @[norm_cast] theorem coe_multiset_prod (s : Multiset ℝβ‰₯0) : ((s.prod : ℝβ‰₯0) : ℝ) = (s.map (↑)).prod := map_multiset_prod toRealHom s @[norm_cast] theorem coe_sum {Ξ±} {s : Finset Ξ±} {f : Ξ± β†’ ℝβ‰₯0} : ↑(βˆ‘ a ∈ s, f a) = βˆ‘ a ∈ s, (f a : ℝ) := map_sum toRealHom _ _ theorem _root_.Real.toNNReal_sum_of_nonneg {Ξ±} {s : Finset Ξ±} {f : Ξ± β†’ ℝ} (hf : βˆ€ a, a ∈ s β†’ 0 ≀ f a) : Real.toNNReal (βˆ‘ a ∈ s, f a) = βˆ‘ a ∈ s, Real.toNNReal (f a) := by rw [← coe_inj, NNReal.coe_sum, Real.coe_toNNReal _ (Finset.sum_nonneg hf)] exact Finset.sum_congr rfl fun x hxs => by rw [Real.coe_toNNReal _ (hf x hxs)] @[norm_cast] theorem coe_prod {Ξ±} {s : Finset Ξ±} {f : Ξ± β†’ ℝβ‰₯0} : ↑(∏ a ∈ s, f a) = ∏ a ∈ s, (f a : ℝ) := map_prod toRealHom _ _ theorem _root_.Real.toNNReal_prod_of_nonneg {Ξ±} {s : Finset Ξ±} {f : Ξ± β†’ ℝ} (hf : βˆ€ a, a ∈ s β†’ 0 ≀ f a) : Real.toNNReal (∏ a ∈ s, f a) = ∏ a ∈ s, Real.toNNReal (f a) := by rw [← coe_inj, NNReal.coe_prod, Real.coe_toNNReal _ (Finset.prod_nonneg hf)] exact Finset.prod_congr rfl fun x hxs => by rw [Real.coe_toNNReal _ (hf x hxs)] -- Porting note (#11215): TODO: `simp`? `norm_cast`? theorem coe_nsmul (r : ℝβ‰₯0) (n : β„•) : ↑(n β€’ r) = n β€’ (r : ℝ) := rfl @[simp, norm_cast] protected theorem coe_natCast (n : β„•) : (↑(↑n : ℝβ‰₯0) : ℝ) = n := map_natCast toRealHom n @[deprecated (since := "2024-04-17")] alias coe_nat_cast := NNReal.coe_natCast -- See note [no_index around OfNat.ofNat] @[simp, norm_cast] protected theorem coe_ofNat (n : β„•) [n.AtLeastTwo] : (no_index (OfNat.ofNat n : ℝβ‰₯0) : ℝ) = OfNat.ofNat n := rfl @[simp, norm_cast] protected theorem coe_ofScientific (m : β„•) (s : Bool) (e : β„•) : ↑(OfScientific.ofScientific m s e : ℝβ‰₯0) = (OfScientific.ofScientific m s e : ℝ) := rfl @[simp, norm_cast] lemma algebraMap_eq_coe : (algebraMap ℝβ‰₯0 ℝ : ℝβ‰₯0 β†’ ℝ) = (↑) := rfl noncomputable example : LinearOrder ℝβ‰₯0 := by infer_instance @[simp, norm_cast] lemma coe_le_coe : (r₁ : ℝ) ≀ rβ‚‚ ↔ r₁ ≀ rβ‚‚ := Iff.rfl @[simp, norm_cast] lemma coe_lt_coe : (r₁ : ℝ) < rβ‚‚ ↔ r₁ < rβ‚‚ := Iff.rfl @[bound] private alias ⟨_, Bound.coe_lt_coe_of_lt⟩ := coe_lt_coe @[simp, norm_cast] lemma coe_pos : (0 : ℝ) < r ↔ 0 < r := Iff.rfl @[bound] private alias ⟨_, Bound.coe_pos_of_pos⟩ := coe_pos @[simp, norm_cast] lemma one_le_coe : 1 ≀ (r : ℝ) ↔ 1 ≀ r := by rw [← coe_le_coe, coe_one] @[simp, norm_cast] lemma one_lt_coe : 1 < (r : ℝ) ↔ 1 < r := by rw [← coe_lt_coe, coe_one] @[simp, norm_cast] lemma coe_le_one : (r : ℝ) ≀ 1 ↔ r ≀ 1 := by rw [← coe_le_coe, coe_one] @[simp, norm_cast] lemma coe_lt_one : (r : ℝ) < 1 ↔ r < 1 := by rw [← coe_lt_coe, coe_one] @[mono] lemma coe_mono : Monotone ((↑) : ℝβ‰₯0 β†’ ℝ) := fun _ _ => NNReal.coe_le_coe.2 /-- Alias for the use of `gcongr` -/ @[gcongr] alias ⟨_, GCongr.toReal_le_toReal⟩ := coe_le_coe protected theorem _root_.Real.toNNReal_mono : Monotone Real.toNNReal := fun _ _ h => max_le_max h (le_refl 0) @[simp] theorem _root_.Real.toNNReal_coe {r : ℝβ‰₯0} : Real.toNNReal r = r := NNReal.eq <| max_eq_left r.2 @[simp] theorem mk_natCast (n : β„•) : @Eq ℝβ‰₯0 (⟨(n : ℝ), n.cast_nonneg⟩ : ℝβ‰₯0) n := NNReal.eq (NNReal.coe_natCast n).symm @[deprecated (since := "2024-04-05")] alias mk_coe_nat := mk_natCast -- Porting note: place this in the `Real` namespace @[simp] theorem toNNReal_coe_nat (n : β„•) : Real.toNNReal n = n := NNReal.eq <| by simp [Real.coe_toNNReal] -- See note [no_index around OfNat.ofNat] @[simp] theorem _root_.Real.toNNReal_ofNat (n : β„•) [n.AtLeastTwo] : Real.toNNReal (no_index (OfNat.ofNat n)) = OfNat.ofNat n := toNNReal_coe_nat n /-- `Real.toNNReal` and `NNReal.toReal : ℝβ‰₯0 β†’ ℝ` form a Galois insertion. -/ noncomputable def gi : GaloisInsertion Real.toNNReal (↑) := GaloisInsertion.monotoneIntro NNReal.coe_mono Real.toNNReal_mono Real.le_coe_toNNReal fun _ => Real.toNNReal_coe -- note that anything involving the (decidability of the) linear order, -- will be noncomputable, everything else should not be. example : OrderBot ℝβ‰₯0 := by infer_instance example : PartialOrder ℝβ‰₯0 := by infer_instance noncomputable example : CanonicallyLinearOrderedAddCommMonoid ℝβ‰₯0 := by infer_instance noncomputable example : LinearOrderedAddCommMonoid ℝβ‰₯0 := by infer_instance example : DistribLattice ℝβ‰₯0 := by infer_instance example : SemilatticeInf ℝβ‰₯0 := by infer_instance example : SemilatticeSup ℝβ‰₯0 := by infer_instance noncomputable example : LinearOrderedSemiring ℝβ‰₯0 := by infer_instance example : OrderedCommSemiring ℝβ‰₯0 := by infer_instance noncomputable example : LinearOrderedCommMonoid ℝβ‰₯0 := by infer_instance noncomputable example : LinearOrderedCommMonoidWithZero ℝβ‰₯0 := by infer_instance noncomputable example : LinearOrderedCommGroupWithZero ℝβ‰₯0 := by infer_instance example : CanonicallyOrderedCommSemiring ℝβ‰₯0 := by infer_instance example : DenselyOrdered ℝβ‰₯0 := by infer_instance example : NoMaxOrder ℝβ‰₯0 := by infer_instance instance instPosSMulStrictMono {Ξ±} [Preorder Ξ±] [MulAction ℝ Ξ±] [PosSMulStrictMono ℝ Ξ±] : PosSMulStrictMono ℝβ‰₯0 Ξ± where elim _r hr _a₁ _aβ‚‚ ha := (smul_lt_smul_of_pos_left ha (coe_pos.2 hr):) instance instSMulPosStrictMono {Ξ±} [Zero Ξ±] [Preorder Ξ±] [MulAction ℝ Ξ±] [SMulPosStrictMono ℝ Ξ±] : SMulPosStrictMono ℝβ‰₯0 Ξ± where elim _a ha _r₁ _rβ‚‚ hr := (smul_lt_smul_of_pos_right (coe_lt_coe.2 hr) ha :) /-- If `a` is a nonnegative real number, then the closed interval `[0, a]` in `ℝ` is order isomorphic to the interval `Set.Iic a`. -/ -- Porting note (#11215): TODO: restore once `simps` supports `ℝβ‰₯0` @[simps!? apply_coe_coe] def orderIsoIccZeroCoe (a : ℝβ‰₯0) : Set.Icc (0 : ℝ) a ≃o Set.Iic a where toEquiv := Equiv.Set.sep (Set.Ici 0) fun x : ℝ => x ≀ a map_rel_iff' := Iff.rfl @[simp] theorem orderIsoIccZeroCoe_apply_coe_coe (a : ℝβ‰₯0) (b : Set.Icc (0 : ℝ) a) : (orderIsoIccZeroCoe a b : ℝ) = b := rfl @[simp] theorem orderIsoIccZeroCoe_symm_apply_coe (a : ℝβ‰₯0) (b : Set.Iic a) : ((orderIsoIccZeroCoe a).symm b : ℝ) = b := rfl -- note we need the `@` to make the `Membership.mem` have a sensible type theorem coe_image {s : Set ℝβ‰₯0} : (↑) '' s = { x : ℝ | βˆƒ h : 0 ≀ x, @Membership.mem ℝβ‰₯0 _ _ ⟨x, h⟩ s } := Subtype.coe_image theorem bddAbove_coe {s : Set ℝβ‰₯0} : BddAbove (((↑) : ℝβ‰₯0 β†’ ℝ) '' s) ↔ BddAbove s := Iff.intro (fun ⟨b, hb⟩ => ⟨Real.toNNReal b, fun ⟨y, _⟩ hys => show y ≀ max b 0 from le_max_of_le_left <| hb <| Set.mem_image_of_mem _ hys⟩) fun ⟨b, hb⟩ => ⟨b, fun _ ⟨_, hx, eq⟩ => eq β–Έ hb hx⟩ theorem bddBelow_coe (s : Set ℝβ‰₯0) : BddBelow (((↑) : ℝβ‰₯0 β†’ ℝ) '' s) := ⟨0, fun _ ⟨q, _, eq⟩ => eq β–Έ q.2⟩ noncomputable instance : ConditionallyCompleteLinearOrderBot ℝβ‰₯0 := Nonneg.conditionallyCompleteLinearOrderBot 0 @[norm_cast] theorem coe_sSup (s : Set ℝβ‰₯0) : (↑(sSup s) : ℝ) = sSup (((↑) : ℝβ‰₯0 β†’ ℝ) '' s) := by rcases Set.eq_empty_or_nonempty s with rfl|hs Β· simp by_cases H : BddAbove s Β· have A : sSup (Subtype.val '' s) ∈ Set.Ici 0 := by apply Real.sSup_nonneg rintro - ⟨y, -, rfl⟩ exact y.2 exact (@subset_sSup_of_within ℝ (Set.Ici (0 : ℝ)) _ _ (_) s hs H A).symm Β· simp only [csSup_of_not_bddAbove H, csSup_empty, bot_eq_zero', NNReal.coe_zero] apply (Real.sSup_of_not_bddAbove ?_).symm contrapose! H exact bddAbove_coe.1 H @[simp, norm_cast] -- Porting note: add `simp` theorem coe_iSup {ΞΉ : Sort*} (s : ΞΉ β†’ ℝβ‰₯0) : (↑(⨆ i, s i) : ℝ) = ⨆ i, ↑(s i) := by rw [iSup, iSup, coe_sSup, ← Set.range_comp]; rfl @[norm_cast] theorem coe_sInf (s : Set ℝβ‰₯0) : (↑(sInf s) : ℝ) = sInf (((↑) : ℝβ‰₯0 β†’ ℝ) '' s) := by rcases Set.eq_empty_or_nonempty s with rfl|hs Β· simp only [Set.image_empty, Real.sInf_empty, coe_eq_zero] exact @subset_sInf_emptyset ℝ (Set.Ici (0 : ℝ)) _ _ (_) have A : sInf (Subtype.val '' s) ∈ Set.Ici 0 := by apply Real.sInf_nonneg rintro - ⟨y, -, rfl⟩ exact y.2 exact (@subset_sInf_of_within ℝ (Set.Ici (0 : ℝ)) _ _ (_) s hs (OrderBot.bddBelow s) A).symm @[simp] theorem sInf_empty : sInf (βˆ… : Set ℝβ‰₯0) = 0 := by rw [← coe_eq_zero, coe_sInf, Set.image_empty, Real.sInf_empty] @[norm_cast] theorem coe_iInf {ΞΉ : Sort*} (s : ΞΉ β†’ ℝβ‰₯0) : (↑(β¨… i, s i) : ℝ) = β¨… i, ↑(s i) := by rw [iInf, iInf, coe_sInf, ← Set.range_comp]; rfl theorem le_iInf_add_iInf {ΞΉ ΞΉ' : Sort*} [Nonempty ΞΉ] [Nonempty ΞΉ'] {f : ΞΉ β†’ ℝβ‰₯0} {g : ΞΉ' β†’ ℝβ‰₯0} {a : ℝβ‰₯0} (h : βˆ€ i j, a ≀ f i + g j) : a ≀ (β¨… i, f i) + β¨… j, g j := by rw [← NNReal.coe_le_coe, NNReal.coe_add, coe_iInf, coe_iInf] exact le_ciInf_add_ciInf h example : Archimedean ℝβ‰₯0 := by infer_instance -- Porting note (#11215): TODO: remove? instance covariant_add : CovariantClass ℝβ‰₯0 ℝβ‰₯0 (Β· + Β·) (Β· ≀ Β·) := inferInstance instance contravariant_add : ContravariantClass ℝβ‰₯0 ℝβ‰₯0 (Β· + Β·) (Β· < Β·) := inferInstance instance covariant_mul : CovariantClass ℝβ‰₯0 ℝβ‰₯0 (Β· * Β·) (Β· ≀ Β·) := inferInstance -- Porting note (#11215): TODO: delete? nonrec theorem le_of_forall_pos_le_add {a b : ℝβ‰₯0} (h : βˆ€ Ξ΅, 0 < Ξ΅ β†’ a ≀ b + Ξ΅) : a ≀ b := le_of_forall_pos_le_add h theorem lt_iff_exists_rat_btwn (a b : ℝβ‰₯0) : a < b ↔ βˆƒ q : β„š, 0 ≀ q ∧ a < Real.toNNReal q ∧ Real.toNNReal q < b := Iff.intro (fun h : (↑a : ℝ) < (↑b : ℝ) => let ⟨q, haq, hqb⟩ := exists_rat_btwn h have : 0 ≀ (q : ℝ) := le_trans a.2 <| le_of_lt haq ⟨q, Rat.cast_nonneg.1 this, by simp [Real.coe_toNNReal _ this, NNReal.coe_lt_coe.symm, haq, hqb]⟩) fun ⟨q, _, haq, hqb⟩ => lt_trans haq hqb theorem bot_eq_zero : (βŠ₯ : ℝβ‰₯0) = 0 := rfl theorem mul_sup (a b c : ℝβ‰₯0) : a * (b βŠ” c) = a * b βŠ” a * c := mul_max_of_nonneg _ _ <| zero_le a theorem sup_mul (a b c : ℝβ‰₯0) : (a βŠ” b) * c = a * c βŠ” b * c := max_mul_of_nonneg _ _ <| zero_le c theorem mul_finset_sup {Ξ±} (r : ℝβ‰₯0) (s : Finset Ξ±) (f : Ξ± β†’ ℝβ‰₯0) : r * s.sup f = s.sup fun a => r * f a := Finset.comp_sup_eq_sup_comp _ (NNReal.mul_sup r) (mul_zero r) theorem finset_sup_mul {Ξ±} (s : Finset Ξ±) (f : Ξ± β†’ ℝβ‰₯0) (r : ℝβ‰₯0) : s.sup f * r = s.sup fun a => f a * r := Finset.comp_sup_eq_sup_comp (Β· * r) (fun x y => NNReal.sup_mul x y r) (zero_mul r) theorem finset_sup_div {Ξ±} {f : Ξ± β†’ ℝβ‰₯0} {s : Finset Ξ±} (r : ℝβ‰₯0) : s.sup f / r = s.sup fun a => f a / r := by simp only [div_eq_inv_mul, mul_finset_sup] @[simp, norm_cast] theorem coe_max (x y : ℝβ‰₯0) : ((max x y : ℝβ‰₯0) : ℝ) = max (x : ℝ) (y : ℝ) := NNReal.coe_mono.map_max @[simp, norm_cast] theorem coe_min (x y : ℝβ‰₯0) : ((min x y : ℝβ‰₯0) : ℝ) = min (x : ℝ) (y : ℝ) := NNReal.coe_mono.map_min @[simp] theorem zero_le_coe {q : ℝβ‰₯0} : 0 ≀ (q : ℝ) := q.2 instance instOrderedSMul {M : Type*} [OrderedAddCommMonoid M] [Module ℝ M] [OrderedSMul ℝ M] : OrderedSMul ℝβ‰₯0 M where smul_lt_smul_of_pos hab hc := (smul_lt_smul_of_pos_left hab (NNReal.coe_pos.2 hc) : _) lt_of_smul_lt_smul_of_pos {a b c} hab _ := lt_of_smul_lt_smul_of_nonneg_left (by exact hab) (NNReal.coe_nonneg c) end NNReal open NNReal namespace Real section ToNNReal @[simp] theorem coe_toNNReal' (r : ℝ) : (Real.toNNReal r : ℝ) = max r 0 := rfl @[simp] theorem toNNReal_zero : Real.toNNReal 0 = 0 := NNReal.eq <| coe_toNNReal _ le_rfl @[simp] theorem toNNReal_one : Real.toNNReal 1 = 1 := NNReal.eq <| coe_toNNReal _ zero_le_one @[simp] theorem toNNReal_pos {r : ℝ} : 0 < Real.toNNReal r ↔ 0 < r := by simp [← NNReal.coe_lt_coe, lt_irrefl] @[simp] theorem toNNReal_eq_zero {r : ℝ} : Real.toNNReal r = 0 ↔ r ≀ 0 := by simpa [-toNNReal_pos] using not_iff_not.2 (@toNNReal_pos r) theorem toNNReal_of_nonpos {r : ℝ} : r ≀ 0 β†’ Real.toNNReal r = 0 := toNNReal_eq_zero.2 lemma toNNReal_eq_iff_eq_coe {r : ℝ} {p : ℝβ‰₯0} (hp : p β‰  0) : r.toNNReal = p ↔ r = p := ⟨fun h ↦ h β–Έ (coe_toNNReal _ <| not_lt.1 fun hlt ↦ hp <| h β–Έ toNNReal_of_nonpos hlt.le).symm, fun h ↦ h.symm β–Έ toNNReal_coe⟩ @[simp] lemma toNNReal_eq_one {r : ℝ} : r.toNNReal = 1 ↔ r = 1 := toNNReal_eq_iff_eq_coe one_ne_zero @[simp] lemma toNNReal_eq_natCast {r : ℝ} {n : β„•} (hn : n β‰  0) : r.toNNReal = n ↔ r = n := mod_cast toNNReal_eq_iff_eq_coe <| Nat.cast_ne_zero.2 hn @[deprecated (since := "2024-04-17")] alias toNNReal_eq_nat_cast := toNNReal_eq_natCast @[simp] lemma toNNReal_eq_ofNat {r : ℝ} {n : β„•} [n.AtLeastTwo] : r.toNNReal = no_index (OfNat.ofNat n) ↔ r = OfNat.ofNat n := toNNReal_eq_natCast (NeZero.ne n) @[simp] theorem toNNReal_le_toNNReal_iff {r p : ℝ} (hp : 0 ≀ p) : toNNReal r ≀ toNNReal p ↔ r ≀ p := by simp [← NNReal.coe_le_coe, hp] @[simp] lemma toNNReal_le_one {r : ℝ} : r.toNNReal ≀ 1 ↔ r ≀ 1 := by simpa using toNNReal_le_toNNReal_iff zero_le_one @[simp] lemma one_lt_toNNReal {r : ℝ} : 1 < r.toNNReal ↔ 1 < r := by simpa only [not_le] using toNNReal_le_one.not @[simp] lemma toNNReal_le_natCast {r : ℝ} {n : β„•} : r.toNNReal ≀ n ↔ r ≀ n := by simpa using toNNReal_le_toNNReal_iff n.cast_nonneg @[deprecated (since := "2024-04-17")] alias toNNReal_le_nat_cast := toNNReal_le_natCast @[simp] lemma natCast_lt_toNNReal {r : ℝ} {n : β„•} : n < r.toNNReal ↔ n < r := by simpa only [not_le] using toNNReal_le_natCast.not @[deprecated (since := "2024-04-17")] alias nat_cast_lt_toNNReal := natCast_lt_toNNReal @[simp] lemma toNNReal_le_ofNat {r : ℝ} {n : β„•} [n.AtLeastTwo] : r.toNNReal ≀ no_index (OfNat.ofNat n) ↔ r ≀ n := toNNReal_le_natCast @[simp] lemma ofNat_lt_toNNReal {r : ℝ} {n : β„•} [n.AtLeastTwo] : no_index (OfNat.ofNat n) < r.toNNReal ↔ n < r := natCast_lt_toNNReal @[simp] theorem toNNReal_eq_toNNReal_iff {r p : ℝ} (hr : 0 ≀ r) (hp : 0 ≀ p) : toNNReal r = toNNReal p ↔ r = p := by simp [← coe_inj, coe_toNNReal, hr, hp] @[simp] theorem toNNReal_lt_toNNReal_iff' {r p : ℝ} : Real.toNNReal r < Real.toNNReal p ↔ r < p ∧ 0 < p := NNReal.coe_lt_coe.symm.trans max_lt_max_left_iff theorem toNNReal_lt_toNNReal_iff {r p : ℝ} (h : 0 < p) : Real.toNNReal r < Real.toNNReal p ↔ r < p := toNNReal_lt_toNNReal_iff'.trans (and_iff_left h) theorem lt_of_toNNReal_lt {r p : ℝ} (h : r.toNNReal < p.toNNReal) : r < p := (Real.toNNReal_lt_toNNReal_iff <| Real.toNNReal_pos.1 (ne_bot_of_gt h).bot_lt).1 h theorem toNNReal_lt_toNNReal_iff_of_nonneg {r p : ℝ} (hr : 0 ≀ r) : Real.toNNReal r < Real.toNNReal p ↔ r < p := toNNReal_lt_toNNReal_iff'.trans ⟨And.left, fun h => ⟨h, lt_of_le_of_lt hr h⟩⟩ lemma toNNReal_le_toNNReal_iff' {r p : ℝ} : r.toNNReal ≀ p.toNNReal ↔ r ≀ p ∨ r ≀ 0 := by simp_rw [← not_lt, toNNReal_lt_toNNReal_iff', not_and_or] lemma toNNReal_le_toNNReal_iff_of_pos {r p : ℝ} (hr : 0 < r) : r.toNNReal ≀ p.toNNReal ↔ r ≀ p := by simp [toNNReal_le_toNNReal_iff', hr.not_le] @[simp] lemma one_le_toNNReal {r : ℝ} : 1 ≀ r.toNNReal ↔ 1 ≀ r := by simpa using toNNReal_le_toNNReal_iff_of_pos one_pos @[simp] lemma toNNReal_lt_one {r : ℝ} : r.toNNReal < 1 ↔ r < 1 := by simp only [← not_le, one_le_toNNReal] @[simp] lemma natCastle_toNNReal' {n : β„•} {r : ℝ} : ↑n ≀ r.toNNReal ↔ n ≀ r ∨ n = 0 := by simpa [n.cast_nonneg.le_iff_eq] using toNNReal_le_toNNReal_iff' (r := n) @[deprecated (since := "2024-04-17")] alias nat_cast_le_toNNReal' := natCastle_toNNReal' @[simp] lemma toNNReal_lt_natCast' {n : β„•} {r : ℝ} : r.toNNReal < n ↔ r < n ∧ n β‰  0 := by simpa [pos_iff_ne_zero] using toNNReal_lt_toNNReal_iff' (r := r) (p := n) @[deprecated (since := "2024-04-17")] alias toNNReal_lt_nat_cast' := toNNReal_lt_natCast' lemma natCast_le_toNNReal {n : β„•} {r : ℝ} (hn : n β‰  0) : ↑n ≀ r.toNNReal ↔ n ≀ r := by simp [hn] @[deprecated (since := "2024-04-17")] alias nat_cast_le_toNNReal := natCast_le_toNNReal lemma toNNReal_lt_natCast {r : ℝ} {n : β„•} (hn : n β‰  0) : r.toNNReal < n ↔ r < n := by simp [hn] @[deprecated (since := "2024-04-17")] alias toNNReal_lt_nat_cast := toNNReal_lt_natCast @[simp] lemma toNNReal_lt_ofNat {r : ℝ} {n : β„•} [n.AtLeastTwo] : r.toNNReal < no_index (OfNat.ofNat n) ↔ r < OfNat.ofNat n := toNNReal_lt_natCast (NeZero.ne n) @[simp] lemma ofNat_le_toNNReal {n : β„•} {r : ℝ} [n.AtLeastTwo] : no_index (OfNat.ofNat n) ≀ r.toNNReal ↔ OfNat.ofNat n ≀ r := natCast_le_toNNReal (NeZero.ne n) @[simp] theorem toNNReal_add {r p : ℝ} (hr : 0 ≀ r) (hp : 0 ≀ p) : Real.toNNReal (r + p) = Real.toNNReal r + Real.toNNReal p := NNReal.eq <| by simp [hr, hp, add_nonneg] theorem toNNReal_add_toNNReal {r p : ℝ} (hr : 0 ≀ r) (hp : 0 ≀ p) : Real.toNNReal r + Real.toNNReal p = Real.toNNReal (r + p) := (Real.toNNReal_add hr hp).symm theorem toNNReal_le_toNNReal {r p : ℝ} (h : r ≀ p) : Real.toNNReal r ≀ Real.toNNReal p := Real.toNNReal_mono h theorem toNNReal_add_le {r p : ℝ} : Real.toNNReal (r + p) ≀ Real.toNNReal r + Real.toNNReal p := NNReal.coe_le_coe.1 <| max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) NNReal.zero_le_coe theorem toNNReal_le_iff_le_coe {r : ℝ} {p : ℝβ‰₯0} : toNNReal r ≀ p ↔ r ≀ ↑p := NNReal.gi.gc r p theorem le_toNNReal_iff_coe_le {r : ℝβ‰₯0} {p : ℝ} (hp : 0 ≀ p) : r ≀ Real.toNNReal p ↔ ↑r ≀ p := by rw [← NNReal.coe_le_coe, Real.coe_toNNReal p hp] theorem le_toNNReal_iff_coe_le' {r : ℝβ‰₯0} {p : ℝ} (hr : 0 < r) : r ≀ Real.toNNReal p ↔ ↑r ≀ p := (le_or_lt 0 p).elim le_toNNReal_iff_coe_le fun hp => by simp only [(hp.trans_le r.coe_nonneg).not_le, toNNReal_eq_zero.2 hp.le, hr.not_le] theorem toNNReal_lt_iff_lt_coe {r : ℝ} {p : ℝβ‰₯0} (ha : 0 ≀ r) : Real.toNNReal r < p ↔ r < ↑p := by rw [← NNReal.coe_lt_coe, Real.coe_toNNReal r ha] theorem lt_toNNReal_iff_coe_lt {r : ℝβ‰₯0} {p : ℝ} : r < Real.toNNReal p ↔ ↑r < p := lt_iff_lt_of_le_iff_le toNNReal_le_iff_le_coe theorem toNNReal_pow {x : ℝ} (hx : 0 ≀ x) (n : β„•) : (x ^ n).toNNReal = x.toNNReal ^ n := by rw [← coe_inj, NNReal.coe_pow, Real.coe_toNNReal _ (pow_nonneg hx _), Real.coe_toNNReal x hx] theorem toNNReal_mul {p q : ℝ} (hp : 0 ≀ p) : Real.toNNReal (p * q) = Real.toNNReal p * Real.toNNReal q := NNReal.eq <| by simp [mul_max_of_nonneg, hp] end ToNNReal end Real open Real namespace NNReal section Mul theorem mul_eq_mul_left {a b c : ℝβ‰₯0} (h : a β‰  0) : a * b = a * c ↔ b = c := by rw [mul_eq_mul_left_iff, or_iff_left h] end Mul section Pow theorem pow_antitone_exp {a : ℝβ‰₯0} (m n : β„•) (mn : m ≀ n) (a1 : a ≀ 1) : a ^ n ≀ a ^ m := pow_le_pow_of_le_one (zero_le a) a1 mn nonrec theorem exists_pow_lt_of_lt_one {a b : ℝβ‰₯0} (ha : 0 < a) (hb : b < 1) : βˆƒ n : β„•, b ^ n < a := by simpa only [← coe_pow, NNReal.coe_lt_coe] using exists_pow_lt_of_lt_one (NNReal.coe_pos.2 ha) (NNReal.coe_lt_coe.2 hb) nonrec theorem exists_mem_Ico_zpow {x : ℝβ‰₯0} {y : ℝβ‰₯0} (hx : x β‰  0) (hy : 1 < y) : βˆƒ n : β„€, x ∈ Set.Ico (y ^ n) (y ^ (n + 1)) := exists_mem_Ico_zpow (Ξ± := ℝ) hx.bot_lt hy nonrec theorem exists_mem_Ioc_zpow {x : ℝβ‰₯0} {y : ℝβ‰₯0} (hx : x β‰  0) (hy : 1 < y) : βˆƒ n : β„€, x ∈ Set.Ioc (y ^ n) (y ^ (n + 1)) := exists_mem_Ioc_zpow (Ξ± := ℝ) hx.bot_lt hy end Pow section Sub /-! ### Lemmas about subtraction In this section we provide a few lemmas about subtraction that do not fit well into any other typeclass. For lemmas about subtraction and addition see lemmas about `OrderedSub` in the file `Mathlib.Algebra.Order.Sub.Basic`. See also `mul_tsub` and `tsub_mul`. -/ theorem sub_def {r p : ℝβ‰₯0} : r - p = Real.toNNReal (r - p) := rfl theorem coe_sub_def {r p : ℝβ‰₯0} : ↑(r - p) = max (r - p : ℝ) 0 := rfl example : OrderedSub ℝβ‰₯0 := by infer_instance theorem sub_div (a b c : ℝβ‰₯0) : (a - b) / c = a / c - b / c := tsub_div _ _ _ end Sub section Inv @[simp] theorem inv_le {r p : ℝβ‰₯0} (h : r β‰  0) : r⁻¹ ≀ p ↔ 1 ≀ r * p := by rw [← mul_le_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h] theorem inv_le_of_le_mul {r p : ℝβ‰₯0} (h : 1 ≀ r * p) : r⁻¹ ≀ p := by by_cases r = 0 <;> simp [*, inv_le] @[simp] theorem le_inv_iff_mul_le {r p : ℝβ‰₯0} (h : p β‰  0) : r ≀ p⁻¹ ↔ r * p ≀ 1 := by rw [← mul_le_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] @[simp] theorem lt_inv_iff_mul_lt {r p : ℝβ‰₯0} (h : p β‰  0) : r < p⁻¹ ↔ r * p < 1 := by rw [← mul_lt_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] theorem mul_le_iff_le_inv {a b r : ℝβ‰₯0} (hr : r β‰  0) : r * a ≀ b ↔ a ≀ r⁻¹ * b := by have : 0 < r := lt_of_le_of_ne (zero_le r) hr.symm rw [← mul_le_mul_left (inv_pos.mpr this), ← mul_assoc, inv_mul_cancel hr, one_mul] theorem le_div_iff_mul_le {a b r : ℝβ‰₯0} (hr : r β‰  0) : a ≀ b / r ↔ a * r ≀ b := le_div_iffβ‚€ hr theorem div_le_iff {a b r : ℝβ‰₯0} (hr : r β‰  0) : a / r ≀ b ↔ a ≀ b * r := div_le_iffβ‚€ hr nonrec theorem div_le_iff' {a b r : ℝβ‰₯0} (hr : r β‰  0) : a / r ≀ b ↔ a ≀ r * b := @div_le_iff' ℝ _ a r b <| pos_iff_ne_zero.2 hr theorem div_le_of_le_mul {a b c : ℝβ‰₯0} (h : a ≀ b * c) : a / c ≀ b := if h0 : c = 0 then by simp [h0] else (div_le_iff h0).2 h theorem div_le_of_le_mul' {a b c : ℝβ‰₯0} (h : a ≀ b * c) : a / b ≀ c := div_le_of_le_mul <| mul_comm b c β–Έ h nonrec theorem le_div_iff {a b r : ℝβ‰₯0} (hr : r β‰  0) : a ≀ b / r ↔ a * r ≀ b := @le_div_iff ℝ _ a b r <| pos_iff_ne_zero.2 hr nonrec theorem le_div_iff' {a b r : ℝβ‰₯0} (hr : r β‰  0) : a ≀ b / r ↔ r * a ≀ b := @le_div_iff' ℝ _ a b r <| pos_iff_ne_zero.2 hr theorem div_lt_iff {a b r : ℝβ‰₯0} (hr : r β‰  0) : a / r < b ↔ a < b * r := lt_iff_lt_of_le_iff_le (le_div_iff hr) theorem div_lt_iff' {a b r : ℝβ‰₯0} (hr : r β‰  0) : a / r < b ↔ a < r * b := lt_iff_lt_of_le_iff_le (le_div_iff' hr) theorem lt_div_iff {a b r : ℝβ‰₯0} (hr : r β‰  0) : a < b / r ↔ a * r < b := lt_iff_lt_of_le_iff_le (div_le_iff hr) theorem lt_div_iff' {a b r : ℝβ‰₯0} (hr : r β‰  0) : a < b / r ↔ r * a < b := lt_iff_lt_of_le_iff_le (div_le_iff' hr) theorem mul_lt_of_lt_div {a b r : ℝβ‰₯0} (h : a < b / r) : a * r < b := (lt_div_iff fun hr => False.elim <| by simp [hr] at h).1 h theorem div_le_div_left_of_le {a b c : ℝβ‰₯0} (c0 : c β‰  0) (cb : c ≀ b) : a / b ≀ a / c := div_le_div_of_nonneg_left (zero_le _) c0.bot_lt cb nonrec theorem div_le_div_left {a b c : ℝβ‰₯0} (a0 : 0 < a) (b0 : 0 < b) (c0 : 0 < c) : a / b ≀ a / c ↔ c ≀ b := div_le_div_left a0 b0 c0 theorem le_of_forall_lt_one_mul_le {x y : ℝβ‰₯0} (h : βˆ€ a < 1, a * x ≀ y) : x ≀ y := le_of_forall_ge_of_dense fun a ha => by have hx : x β‰  0 := pos_iff_ne_zero.1 (lt_of_le_of_lt (zero_le _) ha) have hx' : x⁻¹ β‰  0 := by rwa [Ne, inv_eq_zero] have : a * x⁻¹ < 1 := by rwa [← lt_inv_iff_mul_lt hx', inv_inv] have : a * x⁻¹ * x ≀ y := h _ this rwa [mul_assoc, inv_mul_cancel hx, mul_one] at this nonrec theorem half_le_self (a : ℝβ‰₯0) : a / 2 ≀ a := half_le_self bot_le nonrec theorem half_lt_self {a : ℝβ‰₯0} (h : a β‰  0) : a / 2 < a := half_lt_self h.bot_lt theorem div_lt_one_of_lt {a b : ℝβ‰₯0} (h : a < b) : a / b < 1 := by rwa [div_lt_iff, one_mul] exact ne_of_gt (lt_of_le_of_lt (zero_le _) h) theorem _root_.Real.toNNReal_inv {x : ℝ} : Real.toNNReal x⁻¹ = (Real.toNNReal x)⁻¹ := by rcases le_total 0 x with hx | hx Β· nth_rw 1 [← Real.coe_toNNReal x hx] rw [← NNReal.coe_inv, Real.toNNReal_coe] Β· rw [toNNReal_eq_zero.mpr hx, inv_zero, toNNReal_eq_zero.mpr (inv_nonpos.mpr hx)] theorem _root_.Real.toNNReal_div {x y : ℝ} (hx : 0 ≀ x) : Real.toNNReal (x / y) = Real.toNNReal x / Real.toNNReal y := by rw [div_eq_mul_inv, div_eq_mul_inv, ← Real.toNNReal_inv, ← Real.toNNReal_mul hx] theorem _root_.Real.toNNReal_div' {x y : ℝ} (hy : 0 ≀ y) : Real.toNNReal (x / y) = Real.toNNReal x / Real.toNNReal y := by rw [div_eq_inv_mul, div_eq_inv_mul, Real.toNNReal_mul (inv_nonneg.2 hy), Real.toNNReal_inv] theorem inv_lt_one_iff {x : ℝβ‰₯0} (hx : x β‰  0) : x⁻¹ < 1 ↔ 1 < x := by rw [← one_div, div_lt_iff hx, one_mul] theorem zpow_pos {x : ℝβ‰₯0} (hx : x β‰  0) (n : β„€) : 0 < x ^ n := zpow_pos_of_pos hx.bot_lt _ theorem inv_lt_inv {x y : ℝβ‰₯0} (hx : x β‰  0) (h : x < y) : y⁻¹ < x⁻¹ := inv_lt_inv_of_lt hx.bot_lt h end Inv @[simp] theorem abs_eq (x : ℝβ‰₯0) : |(x : ℝ)| = x := abs_of_nonneg x.property section Csupr open Set variable {ΞΉ : Sort*} {f : ΞΉ β†’ ℝβ‰₯0} theorem le_toNNReal_of_coe_le {x : ℝβ‰₯0} {y : ℝ} (h : ↑x ≀ y) : x ≀ y.toNNReal := (le_toNNReal_iff_coe_le <| x.2.trans h).2 h nonrec theorem sSup_of_not_bddAbove {s : Set ℝβ‰₯0} (hs : Β¬BddAbove s) : SupSet.sSup s = 0 := by rw [← bddAbove_coe] at hs rw [← coe_inj, coe_sSup, NNReal.coe_zero] exact sSup_of_not_bddAbove hs theorem iSup_of_not_bddAbove (hf : Β¬BddAbove (range f)) : ⨆ i, f i = 0 := sSup_of_not_bddAbove hf theorem iSup_empty [IsEmpty ΞΉ] (f : ΞΉ β†’ ℝβ‰₯0) : ⨆ i, f i = 0 := ciSup_of_empty f theorem iInf_empty [IsEmpty ΞΉ] (f : ΞΉ β†’ ℝβ‰₯0) : β¨… i, f i = 0 := by rw [_root_.iInf_of_isEmpty, sInf_empty] @[simp] theorem iInf_const_zero {Ξ± : Sort*} : β¨… _ : Ξ±, (0 : ℝβ‰₯0) = 0 := by rw [← coe_inj, coe_iInf] exact Real.ciInf_const_zero theorem iInf_mul (f : ΞΉ β†’ ℝβ‰₯0) (a : ℝβ‰₯0) : iInf f * a = β¨… i, f i * a := by rw [← coe_inj, NNReal.coe_mul, coe_iInf, coe_iInf] exact Real.iInf_mul_of_nonneg (NNReal.coe_nonneg _) _ theorem mul_iInf (f : ΞΉ β†’ ℝβ‰₯0) (a : ℝβ‰₯0) : a * iInf f = β¨… i, a * f i := by simpa only [mul_comm] using iInf_mul f a theorem mul_iSup (f : ΞΉ β†’ ℝβ‰₯0) (a : ℝβ‰₯0) : (a * ⨆ i, f i) = ⨆ i, a * f i := by rw [← coe_inj, NNReal.coe_mul, NNReal.coe_iSup, NNReal.coe_iSup] exact Real.mul_iSup_of_nonneg (NNReal.coe_nonneg _) _ theorem iSup_mul (f : ΞΉ β†’ ℝβ‰₯0) (a : ℝβ‰₯0) : (⨆ i, f i) * a = ⨆ i, f i * a := by rw [mul_comm, mul_iSup] simp_rw [mul_comm] theorem iSup_div (f : ΞΉ β†’ ℝβ‰₯0) (a : ℝβ‰₯0) : (⨆ i, f i) / a = ⨆ i, f i / a := by simp only [div_eq_mul_inv, iSup_mul] -- Porting note: generalized to allow empty `ΞΉ` theorem mul_iSup_le {a : ℝβ‰₯0} {g : ℝβ‰₯0} {h : ΞΉ β†’ ℝβ‰₯0} (H : βˆ€ j, g * h j ≀ a) : g * iSup h ≀ a := by rw [mul_iSup] exact ciSup_le' H -- Porting note: generalized to allow empty `ΞΉ` theorem iSup_mul_le {a : ℝβ‰₯0} {g : ΞΉ β†’ ℝβ‰₯0} {h : ℝβ‰₯0} (H : βˆ€ i, g i * h ≀ a) : iSup g * h ≀ a := by rw [iSup_mul] exact ciSup_le' H -- Porting note: generalized to allow empty `ΞΉ` theorem iSup_mul_iSup_le {a : ℝβ‰₯0} {g h : ΞΉ β†’ ℝβ‰₯0} (H : βˆ€ i j, g i * h j ≀ a) : iSup g * iSup h ≀ a := iSup_mul_le fun _ => mul_iSup_le <| H _ variable [Nonempty ΞΉ] theorem le_mul_iInf {a : ℝβ‰₯0} {g : ℝβ‰₯0} {h : ΞΉ β†’ ℝβ‰₯0} (H : βˆ€ j, a ≀ g * h j) : a ≀ g * iInf h := by rw [mul_iInf] exact le_ciInf H theorem le_iInf_mul {a : ℝβ‰₯0} {g : ΞΉ β†’ ℝβ‰₯0} {h : ℝβ‰₯0} (H : βˆ€ i, a ≀ g i * h) : a ≀ iInf g * h := by rw [iInf_mul] exact le_ciInf H theorem le_iInf_mul_iInf {a : ℝβ‰₯0} {g h : ΞΉ β†’ ℝβ‰₯0} (H : βˆ€ i j, a ≀ g i * h j) : a ≀ iInf g * iInf h := le_iInf_mul fun i => le_mul_iInf <| H i end Csupr end NNReal namespace Set namespace OrdConnected variable {s : Set ℝ} {t : Set ℝβ‰₯0} theorem preimage_coe_nnreal_real (h : s.OrdConnected) : ((↑) ⁻¹' s : Set ℝβ‰₯0).OrdConnected := h.preimage_mono NNReal.coe_mono theorem image_coe_nnreal_real (h : t.OrdConnected) : ((↑) '' t : Set ℝ).OrdConnected := ⟨forall_mem_image.2 fun x hx => forall_mem_image.2 fun _y hy z hz => ⟨⟨z, x.2.trans hz.1⟩, h.out hx hy hz, rfl⟩⟩ -- Porting note (#11215): TODO: does it generalize to a `GaloisInsertion`? theorem image_real_toNNReal (h : s.OrdConnected) : (Real.toNNReal '' s).OrdConnected := by refine ⟨forall_mem_image.2 fun x hx => forall_mem_image.2 fun y hy z hz => ?_⟩ rcases le_total y 0 with hyβ‚€ | hyβ‚€ Β· rw [mem_Icc, Real.toNNReal_of_nonpos hyβ‚€, nonpos_iff_eq_zero] at hz exact ⟨y, hy, (toNNReal_of_nonpos hyβ‚€).trans hz.2.symm⟩ Β· lift y to ℝβ‰₯0 using hyβ‚€ rw [toNNReal_coe] at hz exact ⟨z, h.out hx hy ⟨toNNReal_le_iff_le_coe.1 hz.1, hz.2⟩, toNNReal_coe⟩ theorem preimage_real_toNNReal (h : t.OrdConnected) : (Real.toNNReal ⁻¹' t).OrdConnected := h.preimage_mono Real.toNNReal_mono end OrdConnected end Set namespace Real /-- The absolute value on `ℝ` as a map to `ℝβ‰₯0`. -/ -- Porting note (kmill): `pp_nodot` has no affect here -- unless RFC lean4#1910 leads to dot notation for CoeFun @[pp_nodot] def nnabs : ℝ β†’*β‚€ ℝβ‰₯0 where toFun x := ⟨|x|, abs_nonneg x⟩ map_zero' := by ext; simp map_one' := by ext; simp map_mul' x y := by ext; simp [abs_mul] @[norm_cast, simp] theorem coe_nnabs (x : ℝ) : (nnabs x : ℝ) = |x| := rfl @[simp] theorem nnabs_of_nonneg {x : ℝ} (h : 0 ≀ x) : nnabs x = toNNReal x := by ext rw [coe_toNNReal x h, coe_nnabs, abs_of_nonneg h] theorem nnabs_coe (x : ℝβ‰₯0) : nnabs x = x := by simp theorem coe_toNNReal_le (x : ℝ) : (toNNReal x : ℝ) ≀ |x| := max_le (le_abs_self _) (abs_nonneg _) @[simp] lemma toNNReal_abs (x : ℝ) : |x|.toNNReal = nnabs x := NNReal.coe_injective <| by simp theorem cast_natAbs_eq_nnabs_cast (n : β„€) : (n.natAbs : ℝβ‰₯0) = nnabs n := by ext rw [NNReal.coe_natCast, Int.cast_natAbs, Real.coe_nnabs, Int.cast_abs] end Real section StrictMono open NNReal variable {Ξ“β‚€ : Type*} [LinearOrderedCommGroupWithZero Ξ“β‚€] /-- If `Ξ“β‚€Λ£` is nontrivial and `f : Ξ“β‚€ β†’*β‚€ ℝβ‰₯0` is strictly monotone, then for any positive `r : ℝβ‰₯0`, there exists `d : Ξ“β‚€Λ£` with `f d < r`. -/ theorem NNReal.exists_lt_of_strictMono [h : Nontrivial Ξ“β‚€Λ£] {f : Ξ“β‚€ β†’*β‚€ ℝβ‰₯0} (hf : StrictMono f) {r : ℝβ‰₯0} (hr : 0 < r) : βˆƒ d : Ξ“β‚€Λ£, f d < r := by obtain ⟨g, hg1⟩ := (nontrivial_iff_exists_ne (1 : Ξ“β‚€Λ£)).mp h set u : Ξ“β‚€Λ£ := if g < 1 then g else g⁻¹ with hu have hfu : f u < 1 := by rw [hu] split_ifs with hu1 Β· rw [← _root_.map_one f]; exact hf hu1 Β· have hfg0 : f g β‰  0 := fun h0 ↦ (Units.ne_zero g) ((map_eq_zero f).mp h0) have hg1' : 1 < g := lt_of_le_of_ne (not_lt.mp hu1) hg1.symm rw [Units.val_inv_eq_inv_val, map_invβ‚€, inv_lt_one_iff hfg0, ← _root_.map_one f] exact hf hg1' obtain ⟨n, hn⟩ := exists_pow_lt_of_lt_one hr hfu use u ^ n rwa [Units.val_pow_eq_pow_val, _root_.map_pow] /-- If `Ξ“β‚€Λ£` is nontrivial and `f : Ξ“β‚€ β†’*β‚€ ℝβ‰₯0` is strictly monotone, then for any positive real `r`, there exists `d : Ξ“β‚€Λ£` with `f d < r`. -/ theorem Real.exists_lt_of_strictMono [h : Nontrivial Ξ“β‚€Λ£] {f : Ξ“β‚€ β†’*β‚€ ℝβ‰₯0} (hf : StrictMono f) {r : ℝ} (hr : 0 < r) : βˆƒ d : Ξ“β‚€Λ£, (f d : ℝ) < r := by set s : NNReal := ⟨r, le_of_lt hr⟩ have hs : 0 < s := hr exact NNReal.exists_lt_of_strictMono hf hs end StrictMono namespace Mathlib.Meta.Positivity open Lean Meta Qq Function private alias ⟨_, nnreal_coe_pos⟩ := coe_pos /-- Extension for the `positivity` tactic: cast from `ℝβ‰₯0` to `ℝ`. -/ @[positivity NNReal.toReal _] def evalNNRealtoReal : PositivityExt where eval {u Ξ±} _zΞ± _pΞ± e := do match u, Ξ±, e with | 0, ~q(ℝ), ~q(NNReal.toReal $a) => let ra ← core q(inferInstance) q(inferInstance) a assertInstancesCommute match ra with | .positive pa => pure (.positive q(nnreal_coe_pos $pa)) | _ => pure (.nonnegative q(NNReal.coe_nonneg $a)) | _, _, _ => throwError "not NNReal.toReal" end Mathlib.Meta.Positivity
Data\NNReal\Star.lean
/- Copyright (c) 2023 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import Mathlib.Data.Real.Star import Mathlib.Data.NNReal.Basic /-! # The non-negative real numbers are a `*`-ring, with the trivial `*`-structure -/ open scoped NNReal instance : StarRing ℝβ‰₯0 := starRingOfComm instance : TrivialStar ℝβ‰₯0 where star_trivial _ := rfl instance : StarModule ℝβ‰₯0 ℝ where star_smul := by simp only [star_trivial, eq_self_iff_true, forall_const] instance {E : Type*} [AddCommMonoid E] [Star E] [Module ℝ E] [StarModule ℝ E] : StarModule ℝβ‰₯0 E where star_smul _ := star_smul (_ : ℝ)
Data\Num\Basic.lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import Lean.Linter.Deprecated import Mathlib.Data.Int.Notation import Mathlib.Algebra.Group.ZeroOne import Mathlib.Data.Nat.Bits /-! # 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 {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 : @DecidableRel PosNum (Β· < Β·) | a, b => by dsimp [LT.lt]; infer_instance instance decidableLE : @DecidableRel PosNum (Β· ≀ Β·) | a, b => by dsimp [LE.le]; infer_instance end PosNum section variable {Ξ± : Type*} [One Ξ±] [Add Ξ±] section deprecated set_option linter.deprecated false /-- `castPosNum` casts a `PosNum` into any type which has `1` and `+`. -/ @[deprecated (since := "2022-11-18"), 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 `+`. -/ @[deprecated (since := "2022-11-18"), coe] def castNum [Zero Ξ±] : Num β†’ Ξ± | 0 => 0 | Num.pos p => castPosNum p -- see Note [coercion into rings] @[deprecated (since := "2023-03-31")] instance (priority := 900) posNumCoe : CoeHTCT PosNum Ξ± := ⟨castPosNum⟩ -- see Note [coercion into rings] @[deprecated (since := "2023-03-31")] instance (priority := 900) numNatCoe [Zero Ξ±] : CoeHTCT Num Ξ± := ⟨castNum⟩ end deprecated 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 : @DecidableRel Num (Β· < Β·) | a, b => by dsimp [LT.lt]; infer_instance instance decidableLE : @DecidableRel 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 : @DecidableRel ZNum (Β· < Β·) | a, b => by dsimp [LT.lt]; infer_instance instance decidableLE : @DecidableRel 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 set_option linter.deprecated false variable {Ξ± : Type*} [Zero Ξ±] [One Ξ±] [Add Ξ±] [Neg Ξ±] /-- `castZNum` casts a `ZNum` into any type which has `0`, `1`, `+` and `neg` -/ @[deprecated (since := "2022-11-18"), coe] def castZNum : ZNum β†’ Ξ± | 0 => 0 | ZNum.pos p => p | ZNum.neg p => -p -- see Note [coercion into rings] @[deprecated (since := "2023-03-31")] instance (priority := 900) znumCoe : CoeHTCT ZNum Ξ± := ⟨castZNum⟩ instance : Repr ZNum := ⟨fun n _ => repr (n : β„€)⟩ end
Data\Num\Bitwise.lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ 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 Mathlib 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 -- Porting note: `PosNum.shiftl` is defined as tail-recursive in Lean4. -- This theorem ensures the definition is same to one in Lean3. 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 : Xor 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 -- Porting note: Removed `deriving has_reflect`. /-- 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 -- Porting note: Removed `deriving has_reflect`. 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 -- Porting note: Defined `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, 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
Data\Num\Lemmas.lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Algebra.Order.Ring.Cast import Mathlib.Data.Int.Cast.Lemmas import Mathlib.Data.Nat.Bitwise import Mathlib.Data.Nat.PSub import Mathlib.Data.Nat.Size import Mathlib.Data.Num.Bitwise /-! # Properties of the binary representation of integers -/ -- Porting note: Required for the notation `-[n+1]`. open Int Function 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] -- @[simp] -- Porting note (#10618): simp can prove this 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 p => 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 a, bit0 b => rfl | bit0 a, bit1 b => congr_arg bit0 (add_succ a b) | bit1 a, bit0 b => 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 m IH m IH <;> intro n <;> cases' n with 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 only at h; simp [h] | Ordering.eq, h => by simp only at h; simp [h, lt_irrefl] | 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 p, pos q => 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 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] Β· erw [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 b => to_nat_pos _ | pos a, 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 only at h; simp [h] | Ordering.eq, h => by simp only at h; simp [h, lt_irrefl] | 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' set_option linter.deprecated false in lemma toNat_injective : Injective (castNum : Num β†’ β„•) := 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 add := (Β· + Β·) zero := 0 zero_add := zero_add add_zero := add_zero add_assoc := by transfer nsmul := nsmulRec instance addMonoidWithOne : AddMonoidWithOne Num := { Num.addMonoid with natCast := Num.ofNat' one := 1 natCast_zero := ofNat'_zero natCast_succ := fun _ => ofNat'_succ } instance commSemiring : CommSemiring Num where __ := Num.addMonoid __ := Num.addMonoidWithOne mul := (Β· * Β·) 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 orderedCancelAddCommMonoid : OrderedCancelAddCommMonoid Num where le := (Β· ≀ Β·) lt := (Β· < Β·) lt_iff_le_not_le a b := by simp only [← lt_to_nat, ← le_to_nat, lt_iff_le_not_le] 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 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 linearOrderedSemiring : LinearOrderedSemiring Num := { Num.commSemiring, Num.orderedCancelAddCommMonoid with le_total := by intro a b transfer_rw apply le_total zero_le_one := by decide mul_lt_mul_of_pos_left := by intro a b c transfer_rw apply mul_lt_mul_of_pos_left mul_lt_mul_of_pos_right := by intro a b c transfer_rw apply mul_lt_mul_of_pos_right decidableLT := Num.decidableLT decidableLE := Num.decidableLE -- This is relying on an automatically generated instance name, -- generated in a `deriving` handler. -- See https://github.com/leanprover/lean4/issues/2343 decidableEq := instDecidableEqNum exists_pair_ne := ⟨0, 1, by decide⟩ } @[norm_cast] -- @[simp] -- Porting note (#10618): simp can prove this theorem add_of_nat (m n) : ((m + n : β„•) : Num) = m + n := add_ofNat' _ _ @[norm_cast] -- @[simp] -- Porting note (#10618): simp can prove this 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] @[deprecated (since := "2024-04-17")] alias of_nat_cast := of_natCast @[norm_cast] -- @[simp] -- Porting note (#10618): simp can prove this theorem of_nat_inj {m n : β„•} : (m : Num) = n ↔ m = n := ⟨fun h => Function.LeftInverse.injective to_of_nat h, congr_arg _⟩ -- Porting note: 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 -- Porting note: 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 n => 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] erw [@Nat.size_bit false n] have := to_nat_pos n dsimp [Nat.bit]; omega | bit1 n => by rw [size, succ_to_nat, size_to_nat n, cast_bit1, ← two_mul] erw [@Nat.size_bit true n] dsimp [Nat.bit]; omega 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 := (Β· + Β·) add_assoc := by transfer add_comm := by transfer instance commMonoid : CommMonoid PosNum where mul := (Β· * Β·) one := (1 : PosNum) 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 add := (Β· + Β·) mul := (Β· * Β·) left_distrib := by transfer; simp [mul_add] right_distrib := by transfer; simp [mul_add, mul_comm] instance linearOrder : LinearOrder PosNum where lt := (Β· < Β·) lt_iff_le_not_le := by intro a b transfer_rw apply lt_iff_le_not_le le := (Β· ≀ Β·) 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 decidableLT := by infer_instance decidableLE := by infer_instance decidableEq := 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 [LinearOrderedSemiring Ξ±] (n : PosNum) : (1 : Ξ±) ≀ n := by rw [← cast_to_nat, ← Nat.cast_one, Nat.cast_le (Ξ± := Ξ±)]; apply to_nat_pos @[simp] theorem cast_pos [LinearOrderedSemiring Ξ±] (n : PosNum) : 0 < (n : Ξ±) := lt_of_lt_of_le zero_lt_one (one_le_cast n) @[simp, norm_cast] theorem cast_mul [Semiring Ξ±] (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 [LinearOrderedSemiring Ξ±] {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 [LinearOrderedSemiring Ξ±] {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 [Semiring Ξ±] (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 [Semiring Ξ±] (n : Num) : (n.bit0 : Ξ±) = 2 * (n : Ξ±) := by rw [← bit0_of_bit0, two_mul, cast_add] @[simp, norm_cast] theorem cast_bit1 [Semiring Ξ±] (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 [Semiring Ξ±] : βˆ€ 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 rw [ofNat'] at IH ⊒ rw [Nat.binaryRec_eq, IH] -- Porting note: `Nat.cast_bit0` & `Nat.cast_bit1` are not `simp` theorems anymore. Β· cases b <;> simp only [cond_false, cond_true, Nat.bit, two_mul, Nat.cast_add, Nat.cast_one] Β· rw [bit0_of_bit0] Β· rw [bit1_of_bit1] Β· rfl 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 [AddGroup Ξ±] [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_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 [LinearOrderedSemiring Ξ±] {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 [LinearOrderedSemiring Ξ±] {m n : Num} : (m : Ξ±) ≀ n ↔ m ≀ n := by rw [← not_lt]; exact not_congr cast_lt @[simp, norm_cast] theorem cast_inj [LinearOrderedSemiring Ξ±] {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 intros m n cases' m with m <;> cases' n with 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 : βˆ€ (b) (n : PosNum), (cond b (↑n) 0 : β„•) = ↑(cond b (pos n) 0 : Num) := by intros b _; cases b <;> rfl induction' m with m IH m IH generalizing n <;> cases' n with 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 [show βˆ€ b n, (pos (PosNum.bit b n) : β„•) = Nat.bit b ↑n by intros b _; cases b <;> simp_all] 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 -- Porting note: A name of an implicit local hypothesis is not available so -- `cases_type*` is used. apply castNum_eq_bitwise fun x y => pos (PosNum.lor x y) <;> intros <;> (try cases_type* Bool) <;> 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 n IH Β· rfl simp [PosNum.shiftl_succ_eq_bit0_shiftl, Nat.shiftLeft_succ, IH, pow_succ, ← mul_assoc, mul_comm, -shiftl_eq_shiftLeft, -PosNum.shiftl_eq_shiftLeft, shiftl, mul_two] @[simp, norm_cast] theorem castNum_shiftRight (m : Num) (n : Nat) : ↑(m >>> n) = (m : β„•) >>> (n : β„•) := by cases' m with m <;> dsimp only [← shiftr_eq_shiftRight, shiftr] Β· symm apply Nat.zero_shiftRight induction' n with n IH generalizing m Β· cases m <;> rfl have hdiv2 : βˆ€ m, Nat.div2 (m + m) = m := by intro; rw [Nat.div2_val]; omega cases' m with 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 -- Porting note: `unfold` β†’ `dsimp only` 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 with n IH generalizing m <;> cases' m with m m <;> dsimp only [PosNum.testBit, Nat.zero_eq] Β· 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 Β· rw [PosNum.cast_bit1, ← two_mul, ← congr_fun Nat.bit_true, Nat.testBit_bit_succ, IH] Β· rw [PosNum.cast_bit0, ← two_mul, ← congr_fun Nat.bit_false, Nat.testBit_bit_succ, IH] end Num 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 [AddGroup Ξ±] [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] cases' 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 -- Porting note: `rw [Num.succ']` yields a `match` pattern. Β· 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, add_left_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 [PosNum.cast_pos] | 1, b => by rw [one_sub', Num.cast_toZNumNeg, ← neg_sub, neg_inj, ← Num.cast_to_nat, pred'_to_nat, ← Nat.sub_one] simp [PosNum.cast_pos] | 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] -- Porting note: `erw [ZNum.ofInt', ZNum.ofInt']` yields `match` so -- `change` & `dsimp` are required. 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 m, 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 @[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 [AddGroupWithOne Ξ±] (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 a, pos b => 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 [Ring Ξ±] (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] -- Porting note: `erw [ofInt']` yields `match` so `dsimp` is required. theorem of_to_int' : βˆ€ n : ZNum, ZNum.ofInt' n = n | 0 => by dsimp [ofInt', cast_zero]; erw [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 <;> dsimp <;> [simp; exact congr_arg pos; simp [GT.gt]] | neg a, neg b => by have := PosNum.cmp_to_nat b a; revert this; dsimp [cmp] cases PosNum.cmp b a <;> dsimp <;> [simp; simp (config := { contextual := true }); simp [GT.gt]] | pos a, 0 => PosNum.cast_pos _ | pos a, neg b => lt_trans (neg_lt_zero.2 <| PosNum.cast_pos _) (PosNum.cast_pos _) | 0, neg b => neg_lt_zero.2 <| PosNum.cast_pos _ | neg a, 0 => neg_lt_zero.2 <| PosNum.cast_pos _ | neg a, pos b => lt_trans (neg_lt_zero.2 <| PosNum.cast_pos _) (PosNum.cast_pos _) | 0, pos b => 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, lt_irrefl] | 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 [LinearOrderedRing Ξ±] {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 [LinearOrderedRing Ξ±] {m n : ZNum} : (m : Ξ±) ≀ n ↔ m ≀ n := by rw [← not_lt]; exact not_congr cast_lt @[simp, norm_cast] theorem cast_inj [LinearOrderedRing Ξ±] {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 := (Β· < Β·) lt_iff_le_not_le := by intro a b transfer_rw apply lt_iff_le_not_le le := (Β· ≀ Β·) 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 decidableEq := instDecidableEqZNum decidableLE := ZNum.decidableLE decidableLT := ZNum.decidableLT instance addMonoid : AddMonoid ZNum where add := (Β· + Β·) add_assoc := by transfer zero := 0 zero_add := zero_add add_zero := add_zero nsmul := nsmulRec instance addCommGroup : AddCommGroup ZNum := { ZNum.addMonoid with add_comm := by transfer neg := Neg.neg zsmul := zsmulRec add_left_neg := by transfer } instance addMonoidWithOne : AddMonoidWithOne ZNum := { ZNum.addMonoid with one := 1 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] } -- Porting note: These theorems should be declared out of the instance, otherwise 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 linearOrderedCommRing : LinearOrderedCommRing ZNum := { ZNum.linearOrder, ZNum.addCommGroup, ZNum.addMonoidWithOne with mul := (Β· * Β·) mul_assoc := 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 exists_pair_ne := ⟨0, 1, by decide⟩ add_le_add_left := add_le_add_left mul_pos := fun a b => show 0 < a β†’ 0 < b β†’ 0 < a * b by transfer_rw apply mul_pos zero_le_one := by decide } @[simp, norm_cast] theorem cast_sub [Ring Ξ±] (m n) : ((m - n : ZNum) : Ξ±) = m - n := by simp [sub_eq_neg_add] @[norm_cast] -- @[simp] -- Porting note (#10618): simp can prove this theorem neg_of_int : βˆ€ n, ((-n : β„€) : ZNum) = -n | (n + 1 : β„•) => rfl | 0 => by rw [Int.cast_neg] | -[n+1] => (zneg_zneg _).symm @[simp] theorem ofInt'_eq : βˆ€ n : β„€, ZNum.ofInt' n = n | (n : β„•) => rfl | -[n+1] => by show 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 -- Porting note: 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] @[deprecated (since := "2024-04-17")] alias of_int_cast := of_intCast @[simp, norm_cast] theorem of_natCast [AddGroupWithOne Ξ±] (n : β„•) : ((n : ZNum) : Ξ±) = n := by rw [← Int.cast_natCast, of_intCast, Int.cast_natCast] @[deprecated (since := "2024-04-17")] alias of_nat_cast := of_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 cases' 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 => ?_⟩ cases' Nat.le.dest h with rβ‚‚ e' 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 n IH n IH Β· exact divMod_to_nat_aux (by simp) (Nat.mul_le_mul_left 2 (PosNum.cast_pos d : (0 : β„•) < d)) Β· unfold divMod -- Porting note: `cases'` didn't rewrite at `this`, so `revert` & `intro` are required. revert IH; cases' divMod d n with q r; intro IH simp only [divMod] 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 Β· unfold divMod -- Porting note: `cases'` didn't rewrite at `this`, so `revert` & `intro` are required. revert IH; cases' divMod d n with q r; intro IH simp only [divMod] 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 d => (Nat.zero_div _).symm | pos n, 0 => (Nat.div_zero _).symm | pos n, pos d => 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 d => (Nat.zero_mod _).symm | pos n, 0 => (Nat.mod_zero _).symm | pos n, pos d => 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, b, _ab, _h => (Nat.gcd_zero_left _).symm | 0, pos a, 0, ab, _h => (not_lt_of_ge ab).elim rfl | 0, pos a, pos b, _ab, h => (not_lt_of_le h).elim <| PosNum.natSize_pos _ | Nat.succ n, 0, b, _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] refine add_le_add_left (Nat.mul_le_mul_left _ (le_trans (le_of_lt (Nat.mod_lt _ (PosNum.cast_pos _))) ?_)) _ suffices 1 ≀ _ by simpa using Nat.mul_le_mul_left (pos a) this rw [Nat.le_div_iff_mul_le a.cast_pos, one_mul] exact le_to_nat.2 ab @[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_le 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 d => (Int.zero_ediv _).symm | 0, neg d => (Int.zero_ediv _).symm | pos n, 0 => (Int.ediv_zero _).symm | neg n, 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, d => (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 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⟩
Data\Num\Prime.lean
/- Copyright (c) 2020 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Data.Num.Lemmas import Mathlib.Data.Nat.Prime.Defs 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 set_option linter.deprecated false in 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 with fuel ih generalizing k <;> rw [minFacAux, Nat.minFacAux] Β· rw [Nat.zero_add, Nat.sqrt_lt] at h simp only [h, ite_true] 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 cases' n with n Β· rfl Β· 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 set_option simprocs false in 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
Data\Option\Basic.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ 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. -- 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 @[simp] theorem none_bind' (f : Ξ± β†’ Option Ξ²) : none.bind f = none := rfl @[simp] theorem some_bind' (a : Ξ±) (f : Ξ± β†’ Option Ξ²) : (some a).bind f = f a := rfl theorem bind_eq_some' {x : Option Ξ±} {f : Ξ± β†’ Option Ξ²} {b : Ξ²} : x.bind f = some b ↔ βˆƒ a, x = some a ∧ f a = some b := by cases x <;> simp theorem bind_congr {f g : Ξ± β†’ Option Ξ²} {x : Option Ξ±} (h : βˆ€ a ∈ x, f a = g a) : x.bind f = x.bind g := by cases x <;> simp only [some_bind, none_bind, mem_def, h] @[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 attribute [simp] map_id @[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 Ξ±) -- Porting note: Can't simp tag this anymore because `pbind` simplifies -- @[simp] theorem pbind_eq_bind (f : Ξ± β†’ Option Ξ²) (x : Option Ξ±) : (x.pbind fun a _ ↦ f a) = x.bind f := by cases x <;> simp only [pbind, none_bind', some_bind'] theorem map_bind {Ξ± Ξ² Ξ³} (f : Ξ² β†’ Ξ³) (x : Option Ξ±) (g : Ξ± β†’ Option Ξ²) : Option.map f (x >>= g) = x >>= fun a ↦ Option.map f (g a) := by simp only [← map_eq_map, ← bind_pure_comp, LawfulMonad.bind_assoc] theorem map_bind' (f : Ξ² β†’ Ξ³) (x : Option Ξ±) (g : Ξ± β†’ Option Ξ²) : Option.map f (x.bind g) = x.bind fun a ↦ Option.map f (g a) := by cases x <;> simp theorem map_pbind (f : Ξ² β†’ Ξ³) (x : Option Ξ±) (g : βˆ€ a, a ∈ x β†’ Option Ξ²) : Option.map f (x.pbind g) = x.pbind fun a H ↦ Option.map f (g a H) := by cases x <;> simp only [pbind, map_none'] theorem pbind_map (f : Ξ± β†’ Ξ²) (x : Option Ξ±) (g : βˆ€ b : Ξ², b ∈ x.map f β†’ Option Ξ³) : pbind (Option.map f x) g = x.pbind fun a h ↦ g (f a) (mem_map_of_mem _ h) := by cases x <;> rfl @[simp] theorem pmap_none (f : βˆ€ a : Ξ±, p a β†’ Ξ²) {H} : pmap f (@none Ξ±) H = none := rfl @[simp] theorem pmap_some (f : βˆ€ a : Ξ±, p a β†’ Ξ²) {x : Ξ±} (h : p x) : pmap f (some x) = fun _ ↦ some (f x h) := rfl 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_map (g : Ξ³ β†’ Ξ±) (x : Option Ξ³) (H) : pmap f (x.map g) H = pmap (fun a h ↦ f (g a) h) x fun a h ↦ H _ (mem_map_of_mem _ h) := by cases x <;> simp only [map_none', map_some', pmap] theorem map_pmap (g : Ξ² β†’ Ξ³) (f : βˆ€ a, p a β†’ Ξ²) (x H) : Option.map g (pmap f x H) = pmap (fun a h ↦ g (f a h)) x H := by cases x <;> simp only [map_none', map_some', pmap] -- Porting note: Can't simp tag this anymore because `pmap` simplifies -- @[simp] theorem pmap_eq_map (p : Ξ± β†’ Prop) (f : Ξ± β†’ Ξ²) (x H) : @pmap _ _ p (fun a _ ↦ f a) x H = Option.map f x := by cases x <;> simp only [map_none', map_some', pmap] 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 b h ↦ H _ (H' a _ h) := by cases x <;> simp only [pmap, bind_eq_bind, none_bind, some_bind] 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 cases x <;> simp only [pmap, bind_eq_bind, none_bind, some_bind, pbind] 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 cases x Β· simp Β· simp only [pbind, iff_false] intro h cases h' _ rfl h theorem pbind_eq_some {f : βˆ€ a : Ξ±, a ∈ x β†’ Option Ξ²} {y : Ξ²} : x.pbind f = some y ↔ βˆƒ (z : Ξ±) (H : z ∈ x), f z H = some y := by rcases x with (_|x) Β· simp only [pbind, false_iff, not_exists] intro z h simp at h Β· simp only [pbind] refine ⟨fun h ↦ ⟨x, rfl, h⟩, ?_⟩ rintro ⟨z, H, hz⟩ simp only [mem_def, Option.some_inj] at H simpa [H] using hz -- Porting note: Can't simp tag this anymore because `pmap` simplifies -- @[simp] theorem pmap_eq_none_iff {h} : pmap f x h = none ↔ x = none := by cases x <;> simp -- Porting note: Can't simp tag this anymore because `pmap` simplifies -- @[simp] theorem pmap_eq_some_iff {hf} {y : Ξ²} : pmap f x hf = some y ↔ βˆƒ (a : Ξ±) (H : x = some a), f a (hf a H) = y := by rcases x with (_|x) Β· simp only [not_mem_none, exists_false, pmap, not_false_iff, exists_prop_of_false] Β· constructor Β· intro h simp only [pmap, Option.some_inj] at h exact ⟨x, rfl, h⟩ Β· rintro ⟨a, H, rfl⟩ simp only [mem_def, Option.some_inj] at H simp only [H, pmap] -- Porting note: Can't simp tag this anymore because `join` and `pmap` simplify -- @[simp] 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 rcases x with (_ | _ | x) <;> simp end pmap @[simp] theorem seq_some {Ξ± Ξ²} {a : Ξ±} {f : Ξ± β†’ Ξ²} : some f <*> some a = some (f a) := rfl @[simp] theorem some_orElse' (a : Ξ±) (x : Option Ξ±) : (some a).orElse (fun _ ↦ x) = some a := rfl @[simp] theorem none_orElse' (x : Option Ξ±) : none.orElse (fun _ ↦ x) = x := by cases x <;> rfl @[simp] theorem orElse_none' (x : Option Ξ±) : x.orElse (fun _ ↦ none) = x := by cases x <;> rfl theorem exists_ne_none {p : Option Ξ± β†’ Prop} : (βˆƒ x β‰  none, p x) ↔ (βˆƒ x : Ξ±, p x) := by simp only [← exists_prop, bex_ne_none] @[simp] theorem get_map (f : Ξ± β†’ Ξ²) {o : Option Ξ±} (h : isSome (o.map f)) : (o.map f).get h = f (o.get (by rwa [← isSome_map'])) := by cases o <;> [simp at h; 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] theorem guard_eq_some' {p : Prop} [Decidable p] (u) : _root_.guard p = some u ↔ p := by cases u by_cases h : p <;> simp [_root_.guard, h] theorem liftOrGet_choice {f : Ξ± β†’ Ξ± β†’ Ξ±} (h : βˆ€ a b, f a b = a ∨ f a b = b) : βˆ€ o₁ oβ‚‚, liftOrGet f o₁ oβ‚‚ = o₁ ∨ liftOrGet f o₁ oβ‚‚ = oβ‚‚ | none, none => Or.inl rfl | some a, none => Or.inl rfl | none, some b => Or.inr rfl | some a, some b => by simpa [liftOrGet] using h a b /-- 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 -- Porting note: Left-hand side does not simplify. -- @[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 -- porting note: workaround for leanprover/lean4#2049 compile_inductive% Option theorem orElse_eq_some (o o' : Option Ξ±) (x : Ξ±) : (o <|> o') = some x ↔ o = some x ∨ o = none ∧ o' = some x := by cases o Β· simp only [true_and, false_or, eq_self_iff_true, none_orElse] Β· simp only [some_orElse, or_false, false_and] theorem orElse_eq_some' (o o' : Option Ξ±) (x : Ξ±) : o.orElse (fun _ ↦ o') = some x ↔ o = some x ∨ o = none ∧ o' = some x := Option.orElse_eq_some o o' x @[simp] theorem orElse_eq_none (o o' : Option Ξ±) : (o <|> o') = none ↔ o = none ∧ o' = none := by cases o Β· simp only [true_and, none_orElse, eq_self_iff_true] Β· simp only [some_orElse, false_and] @[simp] theorem orElse_eq_none' (o o' : Option Ξ±) : o.orElse (fun _ ↦ o') = none ↔ o = none ∧ o' = none := Option.orElse_eq_none o o' section open scoped Classical theorem choice_eq_none (Ξ± : Type*) [IsEmpty Ξ±] : choice Ξ± = none := dif_neg (not_nonempty_iff_imp_false.mpr isEmptyElim) end -- Porting note: Can't simp tag this anymore because `elim` simplifies -- @[simp] theorem elim_none_some (f : Option Ξ± β†’ Ξ²) : (fun x ↦ Option.elim x (f none) (f ∘ some)) = f := funext fun o ↦ by cases o <;> 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] @[simp] lemma bnot_isSome (a : Option Ξ±) : (! a.isSome) = a.isNone := by funext cases a <;> simp @[simp] lemma bnot_comp_isSome : (! Β·) ∘ @Option.isSome Ξ± = Option.isNone := by funext simp @[simp] lemma bnot_isNone (a : Option Ξ±) : (! a.isNone) = a.isSome := by funext cases a <;> simp @[simp] lemma bnot_comp_isNone : (! Β·) ∘ @Option.isNone Ξ± = Option.isSome := by funext x simp @[simp] lemma isNone_eq_false_iff (a : Option Ξ±) : Option.isNone a = false ↔ Option.isSome a := by cases a <;> simp lemma eq_none_or_eq_some (a : Option Ξ±) : a = none ∨ βˆƒ x, a = some x := Option.exists.mp exists_eq' lemma forall_some_ne_iff_eq_none {o : Option Ξ±} : (βˆ€ (x : Ξ±), some x β‰  o) ↔ o = none := by apply not_iff_not.1 simpa only [not_forall, not_not] using Option.ne_none_iff_exists.symm end Option
Data\Option\Defs.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Tactic.Lemma import Mathlib.Tactic.TypeStar /-! # Extra definitions on `Option` This file defines more operations involving `Option Ξ±`. Lemmas about them are located in other files under `Mathlib.Data.Option`. 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 Ξ²) | none => pure none | some x => some <$> f x variable {Ξ± : Type*} {Ξ² : Type*} -- Porting note: Would need to add the attribute directly in `Init.Prelude`. -- attribute [inline] Option.isSome Option.isNone /-- 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 -- Porting note: this lemma was introduced because it is necessary -- in `CategoryTheory.Category.PartialFun` lemma elim'_eq_elim {Ξ± Ξ² : Type*} (b : Ξ²) (f : Ξ± β†’ Ξ²) (a : Option Ξ±) : Option.elim' b f a = Option.elim a b f := by cases a <;> rfl theorem mem_some_iff {Ξ± : Type*} {a b : Ξ±} : a ∈ some b ↔ b = a := by simp /-- `o = none` is decidable even if the wrapped type does not have decidable equality. This is not an instance because it is not definitionally equal to `Option.decidableEq`. Try to use `o.isNone` or `o.isSome` instead. -/ @[inline] def decidableEqNone {o : Option Ξ±} : Decidable (o = none) := decidable_of_decidable_of_iff isNone_iff_eq_none instance decidableForallMem {p : Ξ± β†’ Prop} [DecidablePred p] : βˆ€ o : Option Ξ±, Decidable (βˆ€ a ∈ o, p a) | none => isTrue (by simp [false_imp_iff]) | some a => if h : p a then isTrue fun o e ↦ some_inj.1 e β–Έ h else isFalse <| mt (fun H ↦ H _ rfl) h instance decidableExistsMem {p : Ξ± β†’ Prop} [DecidablePred p] : βˆ€ o : Option Ξ±, Decidable (βˆƒ a ∈ o, p a) | none => isFalse fun ⟨a, ⟨h, _⟩⟩ ↦ by cases h | some a => if h : p a then isTrue <| ⟨_, rfl, h⟩ else isFalse fun ⟨_, ⟨rfl, hn⟩⟩ ↦ h hn /-- 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 @[simp] theorem mem_toList {a : Ξ±} {o : Option Ξ±} : a ∈ toList o ↔ a ∈ o := by cases o <;> simp [toList, eq_comm] instance liftOrGet_isCommutative (f : Ξ± β†’ Ξ± β†’ Ξ±) [Std.Commutative f] : Std.Commutative (liftOrGet f) := ⟨fun a b ↦ by cases a <;> cases b <;> simp [liftOrGet, Std.Commutative.comm]⟩ instance liftOrGet_isAssociative (f : Ξ± β†’ Ξ± β†’ Ξ±) [Std.Associative f] : Std.Associative (liftOrGet f) := ⟨fun a b c ↦ by cases a <;> cases b <;> cases c <;> simp [liftOrGet, Std.Associative.assoc]⟩ instance liftOrGet_isIdempotent (f : Ξ± β†’ Ξ± β†’ Ξ±) [Std.IdempotentOp f] : Std.IdempotentOp (liftOrGet f) := ⟨fun a ↦ by cases a <;> simp [liftOrGet, Std.IdempotentOp.idempotent]⟩ instance liftOrGet_isId (f : Ξ± β†’ Ξ± β†’ Ξ±) : Std.LawfulIdentity (liftOrGet f) none where left_id a := by cases a <;> simp [liftOrGet] right_id a := by cases a <;> simp [liftOrGet] /-- Convert `undef` to `none` to make an `LOption` into an `Option`. -/ def _root_.Lean.LOption.toOption {Ξ±} : Lean.LOption Ξ± β†’ Option Ξ± | .some a => some a | _ => none
Data\Option\NAry.lean
/- Copyright (c) 2022 YaΓ«l Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: YaΓ«l Dillies -/ 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`, to `Mathlib.Data.Finset.NAry` and to `Mathlib.Order.Filter.NAry`. Please keep them in sync. (porting note - only some of these may exist right now!) 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 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 -- Porting note (#10618): In Lean3, was `@[simp]` but now `simp` can prove it 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] theorem mapβ‚‚_none_left (f : Ξ± β†’ Ξ² β†’ Ξ³) (b : Option Ξ²) : mapβ‚‚ f none b = none := rfl @[simp] 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 -- Porting note: This proof was `rfl` in Lean3, but now is not. @[simp] theorem mapβ‚‚_coe_right (f : Ξ± β†’ Ξ² β†’ Ξ³) (a : Option Ξ±) (b : Ξ²) : mapβ‚‚ f a b = a.map fun a => f a b := by cases a <;> rfl -- Porting note: Removed the `@[simp]` tag as membership of an `Option` is no-longer simp-normal. theorem mem_mapβ‚‚_iff {c : Ξ³} : c ∈ mapβ‚‚ f a b ↔ βˆƒ a' b', a' ∈ a ∧ b' ∈ b ∧ f a' b' = c := by simp [mapβ‚‚, bind_eq_some] @[simp] theorem mapβ‚‚_eq_none_iff : mapβ‚‚ f a b = none ↔ a = none ∨ b = none := by cases a <;> cases b <;> simp theorem mapβ‚‚_swap (f : Ξ± β†’ Ξ² β†’ Ξ³) (a : Option Ξ±) (b : Option Ξ²) : mapβ‚‚ f a b = mapβ‚‚ (fun a b => f b a) b a := by cases a <;> cases b <;> rfl theorem map_mapβ‚‚ (f : Ξ± β†’ Ξ² β†’ Ξ³) (g : Ξ³ β†’ Ξ΄) : (mapβ‚‚ f a b).map g = mapβ‚‚ (fun a b => g (f a b)) a b := by cases a <;> cases b <;> rfl theorem mapβ‚‚_map_left (f : Ξ³ β†’ Ξ² β†’ Ξ΄) (g : Ξ± β†’ Ξ³) : mapβ‚‚ f (a.map g) b = mapβ‚‚ (fun a b => f (g a) b) a b := by cases a <;> rfl theorem mapβ‚‚_map_right (f : Ξ± β†’ Ξ³ β†’ Ξ΄) (g : Ξ² β†’ Ξ³) : mapβ‚‚ f a (b.map g) = mapβ‚‚ (fun a b => f a (g b)) a b := by cases b <;> rfl @[simp] theorem mapβ‚‚_curry (f : Ξ± Γ— Ξ² β†’ Ξ³) (a : Option Ξ±) (b : Option Ξ²) : mapβ‚‚ (curry f) a b = Option.map f (mapβ‚‚ Prod.mk a b) := (map_mapβ‚‚ _ _).symm @[simp] theorem map_uncurry (f : Ξ± β†’ Ξ² β†’ Ξ³) (x : Option (Ξ± Γ— Ξ²)) : x.map (uncurry f) = mapβ‚‚ f (x.map Prod.fst) (x.map Prod.snd) := by cases x <;> rfl /-! ### 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 cases a <;> cases b <;> cases c <;> simp [h_assoc] theorem mapβ‚‚_comm {g : Ξ² β†’ Ξ± β†’ Ξ³} (h_comm : βˆ€ a b, f a b = g b a) : mapβ‚‚ f a b = mapβ‚‚ g b a := by cases a <;> cases b <;> simp [h_comm] 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 cases a <;> cases b <;> cases c <;> simp [h_left_comm] 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 cases a <;> cases b <;> cases c <;> simp [h_right_comm] 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 cases a <;> cases b <;> simp [h_distrib] /-! 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 cases a <;> cases b <;> simp [h_distrib] /-- 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 cases a <;> cases b <;> simp [h_distrib] /-- 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 cases a <;> cases b <;> simp [h_left_comm] /-- 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 cases a <;> cases b <;> simp [h_right_comm] 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 cases a <;> cases b <;> simp [h_antidistrib] /-- 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 cases a <;> cases b <;> simp [h_antidistrib] /-- 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 cases a <;> cases b <;> simp [h_antidistrib] /-- 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 cases a <;> cases b <;> simp [h_left_anticomm] /-- 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 cases a <;> cases b <;> simp [h_right_anticomm] /-- 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 cases o; exacts [rfl, congr_arg some (h _)] /-- 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 simp [h, mapβ‚‚] end Option
Data\Ordering\Basic.lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ /-! # Helper definitions and instances for `Ordering` -/ universe u deriving instance Repr for Ordering namespace Ordering /-- Combine two `Ordering`s lexicographically. -/ @[inline] def orElse : Ordering β†’ Ordering β†’ Ordering | lt, _ => lt | eq, o => o | gt, _ => gt /-- The relation corresponding to each `Ordering` constructor (e.g. `.lt.toProp a b` is `a < b`). -/ def toRel {Ξ± : Type u} [LT Ξ±] : Ordering β†’ Ξ± β†’ Ξ± β†’ Prop | .lt => (Β· < Β·) | .eq => Eq | .gt => (Β· > Β·) end Ordering /-- Lift a decidable relation to an `Ordering`, assuming that incomparable terms are `Ordering.eq`. -/ def cmpUsing {Ξ± : Type u} (lt : Ξ± β†’ Ξ± β†’ Prop) [DecidableRel lt] (a b : Ξ±) : Ordering := if lt a b then Ordering.lt else if lt b a then Ordering.gt else Ordering.eq /-- Construct an `Ordering` from a type with a decidable `LT` instance, assuming that incomparable terms are `Ordering.eq`. -/ def cmp {Ξ± : Type u} [LT Ξ±] [DecidableRel ((Β· < Β·) : Ξ± β†’ Ξ± β†’ Prop)] (a b : Ξ±) : Ordering := cmpUsing (Β· < Β·) a b
Data\Ordering\Lemmas.lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.Init.Algebra.Classes import Mathlib.Data.Ordering.Basic /-! # Some `Ordering` lemmas -/ universe u namespace Ordering @[simp] theorem ite_eq_lt_distrib (c : Prop) [Decidable c] (a b : Ordering) : ((if c then a else b) = Ordering.lt) = if c then a = Ordering.lt else b = Ordering.lt := by by_cases c <;> simp [*] @[simp] theorem ite_eq_eq_distrib (c : Prop) [Decidable c] (a b : Ordering) : ((if c then a else b) = Ordering.eq) = if c then a = Ordering.eq else b = Ordering.eq := by by_cases c <;> simp [*] @[simp] theorem ite_eq_gt_distrib (c : Prop) [Decidable c] (a b : Ordering) : ((if c then a else b) = Ordering.gt) = if c then a = Ordering.gt else b = Ordering.gt := by by_cases c <;> simp [*] end Ordering section variable {Ξ± : Type u} {lt : Ξ± β†’ Ξ± β†’ Prop} [DecidableRel lt] attribute [local simp] cmpUsing @[simp] theorem cmpUsing_eq_lt (a b : Ξ±) : (cmpUsing lt a b = Ordering.lt) = lt a b := by simp only [cmpUsing, Ordering.ite_eq_lt_distrib, ite_self, if_false_right, and_true] @[simp] theorem cmpUsing_eq_gt [IsStrictOrder Ξ± lt] (a b : Ξ±) : cmpUsing lt a b = Ordering.gt ↔ lt b a := by simp only [cmpUsing, Ordering.ite_eq_gt_distrib, if_false_right, and_true, if_false_left, and_iff_right_iff_imp] exact fun hba hab ↦ (irrefl a) (_root_.trans hab hba) @[simp] theorem cmpUsing_eq_eq (a b : Ξ±) : cmpUsing lt a b = Ordering.eq ↔ Β¬lt a b ∧ Β¬lt b a := by simp end
Data\Ordmap\Ordnode.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Order.Compare import Mathlib.Data.List.Defs import Mathlib.Data.Nat.PSub import Mathlib.Data.Option.Basic /-! # Ordered sets This file defines a data structure for ordered sets, supporting a variety of useful operations including insertion and deletion, logarithmic time lookup, set operations, folds, and conversion from lists. The `Ordnode Ξ±` operations all assume that `Ξ±` has the structure of a total preorder, meaning a `≀` operation that is * Transitive: `x ≀ y β†’ y ≀ z β†’ x ≀ z` * Reflexive: `x ≀ x` * Total: `x ≀ y ∨ y ≀ x` For example, in order to use this data structure as a map type, one can store pairs `(k, v)` where `(k, v) ≀ (k', v')` is defined to mean `k ≀ k'` (assuming that the key values are linearly ordered). Two values `x,y` are equivalent if `x ≀ y` and `y ≀ x`. An `Ordnode Ξ±` maintains the invariant that it never stores two equivalent nodes; the insertion operation comes with two variants depending on whether you want to keep the old value or the new value in case you insert a value that is equivalent to one in the set. The operations in this file are not verified, in the sense that they provide "raw operations" that work for programming purposes but the invariants are not explicitly in the structure. See `Ordset` for a verified version of this data structure. ## Main definitions * `Ordnode Ξ±`: A set of values of type `Ξ±` ## Implementation notes Based on weight balanced trees: * Stephen Adams, "Efficient sets: a balancing act", Journal of Functional Programming 3(4):553-562, October 1993, <http://www.swiss.ai.mit.edu/~adams/BB/>. * J. Nievergelt and E.M. Reingold, "Binary search trees of bounded balance", SIAM journal of computing 2(1), March 1973. Ported from Haskell's `Data.Set`. ## Tags ordered map, ordered set, data structure -/ universe u /-- An `Ordnode Ξ±` is a finite set of values, represented as a tree. The operations on this type maintain that the tree is balanced and correctly stores subtree sizes at each level. -/ inductive Ordnode (Ξ± : Type u) : Type u | nil : Ordnode Ξ± | node (size : β„•) (l : Ordnode Ξ±) (x : Ξ±) (r : Ordnode Ξ±) : Ordnode Ξ± -- Porting note: `Nat.Partrec.Code.recOn` is noncomputable in Lean4, so we make it computable. compile_inductive% Ordnode namespace Ordnode variable {Ξ± : Type*} instance : EmptyCollection (Ordnode Ξ±) := ⟨nil⟩ instance : Inhabited (Ordnode Ξ±) := ⟨nil⟩ /-- **Internal use only** The maximal relative difference between the sizes of two trees, it corresponds with the `w` in Adams' paper. According to the Haskell comment, only `(delta, ratio)` settings of `(3, 2)` and `(4, 2)` will work, and the proofs in `Ordset.lean` assume `delta := 3` and `ratio := 2`. -/ @[inline] def delta := 3 /-- **Internal use only** The ratio between an outer and inner sibling of the heavier subtree in an unbalanced setting. It determines whether a double or single rotation should be performed to restore balance. It is corresponds with the inverse of `Ξ±` in Adam's article. -/ @[inline] def ratio := 2 /-- O(1). Construct a singleton set containing value `a`. singleton 3 = {3} -/ @[inline] protected def singleton (a : Ξ±) : Ordnode Ξ± := node 1 nil a nil local prefix:arg "ΞΉ" => Ordnode.singleton instance : Singleton Ξ± (Ordnode Ξ±) := ⟨Ordnode.singleton⟩ /-- O(1). Get the size of the set. size {2, 1, 1, 4} = 3 -/ @[inline] def size : Ordnode Ξ± β†’ β„• | nil => 0 | node sz _ _ _ => sz -- Porting note(#11647): during the port we marked these lemmas with `@[eqns]` -- to emulate the old Lean 3 behaviour. @[simp] theorem size_nil : size (nil : Ordnode Ξ±) = 0 := rfl @[simp] theorem size_node (sz : β„•) (l : Ordnode Ξ±) (x : Ξ±) (r : Ordnode Ξ±) : size (node sz l x r) = sz := rfl /-- O(1). Is the set empty? empty βˆ… = tt empty {1, 2, 3} = ff -/ @[inline] def empty : Ordnode Ξ± β†’ Bool | nil => true | node _ _ _ _ => false /-- **Internal use only**, because it violates the BST property on the original order. O(n). The dual of a tree is a tree with its left and right sides reversed throughout. The dual of a valid BST is valid under the dual order. This is convenient for exploiting symmetries in the algorithms. -/ @[simp] def dual : Ordnode Ξ± β†’ Ordnode Ξ± | nil => nil | node s l x r => node s (dual r) x (dual l) /-- **Internal use only** O(1). Construct a node with the correct size information, without rebalancing. -/ @[inline, reducible] def node' (l : Ordnode Ξ±) (x : Ξ±) (r : Ordnode Ξ±) : Ordnode Ξ± := node (size l + size r + 1) l x r /-- Basic pretty printing for `Ordnode Ξ±` that shows the structure of the tree. repr {3, 1, 2, 4} = ((βˆ… 1 βˆ…) 2 ((βˆ… 3 βˆ…) 4 βˆ…)) -/ def repr {Ξ±} [Repr Ξ±] (o : Ordnode Ξ±) (n : β„•) : Std.Format := match o with | nil => (Std.Format.text "βˆ…") | node _ l x r => let fmt := Std.Format.joinSep [repr l n, Repr.reprPrec x n, repr r n] " " Std.Format.paren fmt instance {Ξ±} [Repr Ξ±] : Repr (Ordnode Ξ±) := ⟨repr⟩ -- Note: The function has been written with tactics to avoid extra junk /-- **Internal use only** O(1). Rebalance a tree which was previously balanced but has had its left side grow by 1, or its right side shrink by 1. -/ def balanceL (l : Ordnode Ξ±) (x : Ξ±) (r : Ordnode Ξ±) : Ordnode Ξ± := by -- Porting note: removed `clean` cases' id r with rs Β· cases' id l with ls ll lx lr Β· exact ΞΉ x Β· cases' id ll with lls Β· cases' lr with _ _ lrx Β· exact node 2 l x nil Β· exact node 3 (ΞΉ lx) lrx ΞΉ x Β· cases' id lr with lrs lrl lrx lrr Β· exact node 3 ll lx ΞΉ x Β· exact if lrs < ratio * lls then node (ls + 1) ll lx (node (lrs + 1) lr x nil) else node (ls + 1) (node (lls + size lrl + 1) ll lx lrl) lrx (node (size lrr + 1) lrr x nil) Β· cases' id l with ls ll lx lr Β· exact node (rs + 1) nil x r Β· refine if ls > delta * rs then ?_ else node (ls + rs + 1) l x r cases' id ll with lls Β· exact nil --should not happen cases' id lr with lrs lrl lrx lrr Β· exact nil --should not happen exact if lrs < ratio * lls then node (ls + rs + 1) ll lx (node (rs + lrs + 1) lr x r) else node (ls + rs + 1) (node (lls + size lrl + 1) ll lx lrl) lrx (node (size lrr + rs + 1) lrr x r) /-- **Internal use only** O(1). Rebalance a tree which was previously balanced but has had its right side grow by 1, or its left side shrink by 1. -/ def balanceR (l : Ordnode Ξ±) (x : Ξ±) (r : Ordnode Ξ±) : Ordnode Ξ± := by -- Porting note: removed `clean` cases' id l with ls Β· cases' id r with rs rl rx rr Β· exact ΞΉ x Β· cases' id rr with rrs Β· cases' rl with _ _ rlx Β· exact node 2 nil x r Β· exact node 3 (ΞΉ x) rlx ΞΉ rx Β· cases' id rl with rls rll rlx rlr Β· exact node 3 (ΞΉ x) rx rr Β· exact if rls < ratio * rrs then node (rs + 1) (node (rls + 1) nil x rl) rx rr else node (rs + 1) (node (size rll + 1) nil x rll) rlx (node (size rlr + rrs + 1) rlr rx rr) Β· cases' id r with rs rl rx rr Β· exact node (ls + 1) l x nil Β· refine if rs > delta * ls then ?_ else node (ls + rs + 1) l x r cases' id rr with rrs Β· exact nil --should not happen cases' id rl with rls rll rlx rlr Β· exact nil --should not happen exact if rls < ratio * rrs then node (ls + rs + 1) (node (ls + rls + 1) l x rl) rx rr else node (ls + rs + 1) (node (ls + size rll + 1) l x rll) rlx (node (size rlr + rrs + 1) rlr rx rr) /-- **Internal use only** O(1). Rebalance a tree which was previously balanced but has had one side change by at most 1. -/ def balance (l : Ordnode Ξ±) (x : Ξ±) (r : Ordnode Ξ±) : Ordnode Ξ± := by -- Porting note: removed `clean` cases' id l with ls ll lx lr Β· cases' id r with rs rl rx rr Β· exact ΞΉ x Β· cases' id rl with rls rll rlx rlr Β· cases id rr Β· exact node 2 nil x r Β· exact node 3 (ΞΉ x) rx rr Β· cases' id rr with rrs Β· exact node 3 (ΞΉ x) rlx ΞΉ rx Β· exact if rls < ratio * rrs then node (rs + 1) (node (rls + 1) nil x rl) rx rr else node (rs + 1) (node (size rll + 1) nil x rll) rlx (node (size rlr + rrs + 1) rlr rx rr) Β· cases' id r with rs rl rx rr Β· cases' id ll with lls Β· cases' lr with _ _ lrx Β· exact node 2 l x nil Β· exact node 3 (ΞΉ lx) lrx ΞΉ x Β· cases' id lr with lrs lrl lrx lrr Β· exact node 3 ll lx ΞΉ x Β· exact if lrs < ratio * lls then node (ls + 1) ll lx (node (lrs + 1) lr x nil) else node (ls + 1) (node (lls + size lrl + 1) ll lx lrl) lrx (node (size lrr + 1) lrr x nil) Β· refine if delta * ls < rs then ?_ else if delta * rs < ls then ?_ else node (ls + rs + 1) l x r Β· cases' id rl with rls rll rlx rlr Β· exact nil --should not happen cases' id rr with rrs Β· exact nil --should not happen exact if rls < ratio * rrs then node (ls + rs + 1) (node (ls + rls + 1) l x rl) rx rr else node (ls + rs + 1) (node (ls + size rll + 1) l x rll) rlx (node (size rlr + rrs + 1) rlr rx rr) Β· cases' id ll with lls Β· exact nil --should not happen cases' id lr with lrs lrl lrx lrr Β· exact nil --should not happen exact if lrs < ratio * lls then node (ls + rs + 1) ll lx (node (lrs + rs + 1) lr x r) else node (ls + rs + 1) (node (lls + size lrl + 1) ll lx lrl) lrx (node (size lrr + rs + 1) lrr x r) /-- O(n). Does every element of the map satisfy property `P`? All (fun x ↦ x < 5) {1, 2, 3} = True All (fun x ↦ x < 5) {1, 2, 3, 5} = False -/ def All (P : Ξ± β†’ Prop) : Ordnode Ξ± β†’ Prop | nil => True | node _ l x r => All P l ∧ P x ∧ All P r instance All.decidable {P : Ξ± β†’ Prop} : (t : Ordnode Ξ±) β†’ [DecidablePred P] β†’ Decidable (All P t) | nil => decidableTrue | node _ l _ r => have : Decidable (All P l) := All.decidable l have : Decidable (All P r) := All.decidable r And.decidable /-- O(n). Does any element of the map satisfy property `P`? Any (fun x ↦ x < 2) {1, 2, 3} = True Any (fun x ↦ x < 2) {2, 3, 5} = False -/ def Any (P : Ξ± β†’ Prop) : Ordnode Ξ± β†’ Prop | nil => False | node _ l x r => Any P l ∨ P x ∨ Any P r instance Any.decidable {P : Ξ± β†’ Prop} : (t : Ordnode Ξ± ) β†’ [DecidablePred P] β†’ Decidable (Any P t) | nil => decidableFalse | node _ l _ r => have : Decidable (Any P l) := Any.decidable l have : Decidable (Any P r) := Any.decidable r Or.decidable /-- O(n). Exact membership in the set. This is useful primarily for stating correctness properties; use `∈` for a version that actually uses the BST property of the tree. Emem 2 {1, 2, 3} = true Emem 4 {1, 2, 3} = false -/ def Emem (x : Ξ±) : Ordnode Ξ± β†’ Prop := Any (Eq x) instance Emem.decidable (x : Ξ±) [DecidableEq Ξ±] : βˆ€ t, Decidable (Emem x t) := by dsimp [Emem]; infer_instance /-- O(n). Approximate membership in the set, that is, whether some element in the set is equivalent to this one in the preorder. This is useful primarily for stating correctness properties; use `∈` for a version that actually uses the BST property of the tree. Amem 2 {1, 2, 3} = true Amem 4 {1, 2, 3} = false To see the difference with `Emem`, we need a preorder that is not a partial order. For example, suppose we compare pairs of numbers using only their first coordinate. Then: -- Porting note: Verify below example emem (0, 1) {(0, 0), (1, 2)} = false amem (0, 1) {(0, 0), (1, 2)} = true (0, 1) ∈ {(0, 0), (1, 2)} = true The `∈` relation is equivalent to `Amem` as long as the `Ordnode` is well formed, and should always be used instead of `Amem`. -/ def Amem [LE Ξ±] (x : Ξ±) : Ordnode Ξ± β†’ Prop := Any fun y => x ≀ y ∧ y ≀ x instance Amem.decidable [LE Ξ±] [@DecidableRel Ξ± (Β· ≀ Β·)] (x : Ξ±) : βˆ€ t, Decidable (Amem x t) := by dsimp [Amem]; infer_instance /-- O(log n). Return the minimum element of the tree, or the provided default value. findMin' 37 {1, 2, 3} = 1 findMin' 37 βˆ… = 37 -/ def findMin' : Ordnode Ξ± β†’ Ξ± β†’ Ξ± | nil, x => x | node _ l x _, _ => findMin' l x /-- O(log n). Return the minimum element of the tree, if it exists. findMin {1, 2, 3} = some 1 findMin βˆ… = none -/ def findMin : Ordnode Ξ± β†’ Option Ξ± | nil => none | node _ l x _ => some (findMin' l x) /-- O(log n). Return the maximum element of the tree, or the provided default value. findMax' 37 {1, 2, 3} = 3 findMax' 37 βˆ… = 37 -/ def findMax' : Ξ± β†’ Ordnode Ξ± β†’ Ξ± | x, nil => x | _, node _ _ x r => findMax' x r /-- O(log n). Return the maximum element of the tree, if it exists. findMax {1, 2, 3} = some 3 findMax βˆ… = none -/ def findMax : Ordnode Ξ± β†’ Option Ξ± | nil => none | node _ _ x r => some (findMax' x r) /-- O(log n). Remove the minimum element from the tree, or do nothing if it is already empty. eraseMin {1, 2, 3} = {2, 3} eraseMin βˆ… = βˆ… -/ def eraseMin : Ordnode Ξ± β†’ Ordnode Ξ± | nil => nil | node _ nil _ r => r | node _ (node sz l' y r') x r => balanceR (eraseMin (node sz l' y r')) x r /-- O(log n). Remove the maximum element from the tree, or do nothing if it is already empty. eraseMax {1, 2, 3} = {1, 2} eraseMax βˆ… = βˆ… -/ def eraseMax : Ordnode Ξ± β†’ Ordnode Ξ± | nil => nil | node _ l _ nil => l | node _ l x (node sz l' y r') => balanceL l x (eraseMax (node sz l' y r')) /-- **Internal use only**, because it requires a balancing constraint on the inputs. O(log n). Extract and remove the minimum element from a nonempty tree. -/ def splitMin' : Ordnode Ξ± β†’ Ξ± β†’ Ordnode Ξ± β†’ Ξ± Γ— Ordnode Ξ± | nil, x, r => (x, r) | node _ ll lx lr, x, r => let (xm, l') := splitMin' ll lx lr (xm, balanceR l' x r) /-- O(log n). Extract and remove the minimum element from the tree, if it exists. split_min {1, 2, 3} = some (1, {2, 3}) split_min βˆ… = none -/ def splitMin : Ordnode Ξ± β†’ Option (Ξ± Γ— Ordnode Ξ±) | nil => none | node _ l x r => splitMin' l x r /-- **Internal use only**, because it requires a balancing constraint on the inputs. O(log n). Extract and remove the maximum element from a nonempty tree. -/ def splitMax' : Ordnode Ξ± β†’ Ξ± β†’ Ordnode Ξ± β†’ Ordnode Ξ± Γ— Ξ± | l, x, nil => (l, x) | l, x, node _ rl rx rr => let (r', xm) := splitMax' rl rx rr (balanceL l x r', xm) /-- O(log n). Extract and remove the maximum element from the tree, if it exists. split_max {1, 2, 3} = some ({1, 2}, 3) split_max βˆ… = none -/ def splitMax : Ordnode Ξ± β†’ Option (Ordnode Ξ± Γ— Ξ±) | nil => none | node _ x l r => splitMax' x l r /-- **Internal use only** O(log(m + n)). Concatenate two trees that are balanced and ordered with respect to each other. -/ def glue : Ordnode Ξ± β†’ Ordnode Ξ± β†’ Ordnode Ξ± | nil, r => r | l@(node _ _ _ _), nil => l | l@(node sl ll lx lr), r@(node sr rl rx rr) => if sl > sr then let (l', m) := splitMax' ll lx lr balanceR l' m r else let (m, r') := splitMin' rl rx rr balanceL l m r' /-- O(log(m + n)). Concatenate two trees that are ordered with respect to each other. merge {1, 2} {3, 4} = {1, 2, 3, 4} merge {3, 4} {1, 2} = precondition violation -/ def merge (l : Ordnode Ξ±) : Ordnode Ξ± β†’ Ordnode Ξ± := (Ordnode.recOn (motive := fun _ => Ordnode Ξ± β†’ Ordnode Ξ±) l fun r => r) fun ls ll lx lr _ IHlr r => (Ordnode.recOn (motive := fun _ => Ordnode Ξ±) r (node ls ll lx lr)) fun rs rl rx rr IHrl _ => if delta * ls < rs then balanceL IHrl rx rr else if delta * rs < ls then balanceR ll lx (IHlr <| node rs rl rx rr) else glue (node ls ll lx lr) (node rs rl rx rr) /-- O(log n). Insert an element above all the others, without any comparisons. (Assumes that the element is in fact above all the others). insertMax {1, 2} 4 = {1, 2, 4} insertMax {1, 2} 0 = precondition violation -/ def insertMax : Ordnode Ξ± β†’ Ξ± β†’ Ordnode Ξ± | nil, x => ΞΉ x | node _ l y r, x => balanceR l y (insertMax r x) /-- O(log n). Insert an element below all the others, without any comparisons. (Assumes that the element is in fact below all the others). insertMin {1, 2} 0 = {0, 1, 2} insertMin {1, 2} 4 = precondition violation -/ def insertMin (x : Ξ±) : Ordnode Ξ± β†’ Ordnode Ξ± | nil => ΞΉ x | node _ l y r => balanceR (insertMin x l) y r /-- O(log(m+n)). Build a tree from an element between two trees, without any assumption on the relative sizes. link {1, 2} 4 {5, 6} = {1, 2, 4, 5, 6} link {1, 3} 2 {5} = precondition violation -/ def link (l : Ordnode Ξ±) (x : Ξ±) : Ordnode Ξ± β†’ Ordnode Ξ± := -- Porting note: Previous code was: -- (Ordnode.recOn l (insertMin x)) fun ls ll lx lr IHll IHlr r => -- (Ordnode.recOn r (insertMax l x)) fun rs rl rx rr IHrl IHrr => -- if delta * ls < rs then balanceL IHrl rx rr -- else if delta * rs < ls then balanceR ll lx (IHlr r) else node' l x r -- -- failed to elaborate eliminator, expected type is not available. match l with | nil => insertMin x | node ls ll lx lr => fun r ↦ match r with | nil => insertMax l x | node rs rl rx rr => if delta * ls < rs then balanceL (link ll x rl) rx rr else if delta * rs < ls then balanceR ll lx (link lr x rr) else node' l x r /-- O(n). Filter the elements of a tree satisfying a predicate. filter (fun x ↦ x < 3) {1, 2, 4} = {1, 2} filter (fun x ↦ x > 5) {1, 2, 4} = βˆ… -/ def filter (p : Ξ± β†’ Prop) [DecidablePred p] : Ordnode Ξ± β†’ Ordnode Ξ± | nil => nil | node _ l x r => if p x then link (filter p l) x (filter p r) else merge (filter p l) (filter p r) /-- O(n). Split the elements of a tree into those satisfying, and not satisfying, a predicate. partition (fun x ↦ x < 3) {1, 2, 4} = ({1, 2}, {3}) -/ def partition (p : Ξ± β†’ Prop) [DecidablePred p] : Ordnode Ξ± β†’ Ordnode Ξ± Γ— Ordnode Ξ± | nil => (nil, nil) | node _ l x r => let (l₁, lβ‚‚) := partition p l let (r₁, rβ‚‚) := partition p r if p x then (link l₁ x r₁, merge lβ‚‚ rβ‚‚) else (merge l₁ r₁, link lβ‚‚ x rβ‚‚) /-- O(n). Map a function across a tree, without changing the structure. Only valid when the function is strictly monotone, i.e. `x < y β†’ f x < f y`. partition (fun x ↦ x + 2) {1, 2, 4} = {2, 3, 6} partition (fun x : β„• ↦ x - 2) {1, 2, 4} = precondition violation -/ def map {Ξ²} (f : Ξ± β†’ Ξ²) : Ordnode Ξ± β†’ Ordnode Ξ² | nil => nil | node s l x r => node s (map f l) (f x) (map f r) /-- O(n). Fold a function across the structure of a tree. fold z f {1, 2, 4} = f (f z 1 z) 2 (f z 4 z) The exact structure of function applications depends on the tree and so is unspecified. -/ def fold {Ξ²} (z : Ξ²) (f : Ξ² β†’ Ξ± β†’ Ξ² β†’ Ξ²) : Ordnode Ξ± β†’ Ξ² | nil => z | node _ l x r => f (fold z f l) x (fold z f r) /-- O(n). Fold a function from left to right (in increasing order) across the tree. foldl f z {1, 2, 4} = f (f (f z 1) 2) 4 -/ def foldl {Ξ²} (f : Ξ² β†’ Ξ± β†’ Ξ²) : Ξ² β†’ Ordnode Ξ± β†’ Ξ² | z, nil => z | z, node _ l x r => foldl f (f (foldl f z l) x) r /-- O(n). Fold a function from right to left (in decreasing order) across the tree. foldr f {1, 2, 4} z = f 1 (f 2 (f 4 z)) -/ def foldr {Ξ²} (f : Ξ± β†’ Ξ² β†’ Ξ²) : Ordnode Ξ± β†’ Ξ² β†’ Ξ² | nil, z => z | node _ l x r, z => foldr f l (f x (foldr f r z)) /-- O(n). Build a list of elements in ascending order from the tree. toList {1, 2, 4} = [1, 2, 4] toList {2, 1, 1, 4} = [1, 2, 4] -/ def toList (t : Ordnode Ξ±) : List Ξ± := foldr List.cons t [] /-- O(n). Build a list of elements in descending order from the tree. toRevList {1, 2, 4} = [4, 2, 1] toRevList {2, 1, 1, 4} = [4, 2, 1] -/ def toRevList (t : Ordnode Ξ±) : List Ξ± := foldl (flip List.cons) [] t instance [ToString Ξ±] : ToString (Ordnode Ξ±) := ⟨fun t => "{" ++ String.intercalate ", " (t.toList.map toString) ++ "}"⟩ -- Porting note removed unsafe instance [Std.ToFormat Ξ±] : Std.ToFormat (Ordnode Ξ±) where format := fun t => Std.Format.joinSep (t.toList.map Std.ToFormat.format) (Std.Format.text ", ") /-- O(n). True if the trees have the same elements, ignoring structural differences. Equiv {1, 2, 4} {2, 1, 1, 4} = true Equiv {1, 2, 4} {1, 2, 3} = false -/ def Equiv (t₁ tβ‚‚ : Ordnode Ξ±) : Prop := t₁.size = tβ‚‚.size ∧ t₁.toList = tβ‚‚.toList instance [DecidableEq Ξ±] : DecidableRel (@Equiv Ξ±) := fun _ _ => And.decidable /-- O(2^n). Constructs the powerset of a given set, that is, the set of all subsets. powerset {1, 2, 3} = {βˆ…, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}} -/ def powerset (t : Ordnode Ξ±) : Ordnode (Ordnode Ξ±) := insertMin nil <| foldr (fun x ts => glue (insertMin (ΞΉ x) (map (insertMin x) ts)) ts) t nil /-- O(m * n). The cartesian product of two sets: `(a, b) ∈ s.prod t` iff `a ∈ s` and `b ∈ t`. prod {1, 2} {2, 3} = {(1, 2), (1, 3), (2, 2), (2, 3)} -/ protected def prod {Ξ²} (t₁ : Ordnode Ξ±) (tβ‚‚ : Ordnode Ξ²) : Ordnode (Ξ± Γ— Ξ²) := fold nil (fun s₁ a sβ‚‚ => merge s₁ <| merge (map (Prod.mk a) tβ‚‚) sβ‚‚) t₁ /-- O(m + n). Build a set on the disjoint union by combining sets on the factors. `Or.inl a ∈ s.copair t` iff `a ∈ s`, and `Or.inr b ∈ s.copair t` iff `b ∈ t`. copair {1, 2} {2, 3} = {inl 1, inl 2, inr 2, inr 3} -/ protected def copair {Ξ²} (t₁ : Ordnode Ξ±) (tβ‚‚ : Ordnode Ξ²) : Ordnode (Ξ± βŠ• Ξ²) := merge (map Sum.inl t₁) (map Sum.inr tβ‚‚) /-- O(n). Map a partial function across a set. The result depends on a proof that the function is defined on all members of the set. pmap (fin.mk : βˆ€ n, n < 4 β†’ fin 4) {1, 2} H = {(1 : fin 4), (2 : fin 4)} -/ def pmap {P : Ξ± β†’ Prop} {Ξ²} (f : βˆ€ a, P a β†’ Ξ²) : βˆ€ t : Ordnode Ξ±, All P t β†’ Ordnode Ξ² | nil, _ => nil | node s l x r, ⟨hl, hx, hr⟩ => node s (pmap f l hl) (f x hx) (pmap f r hr) /-- O(n). "Attach" the information that every element of `t` satisfies property P to these elements inside the set, producing a set in the subtype. attach' (fun x ↦ x < 4) {1, 2} H = ({1, 2} : Ordnode {x // x<4}) -/ def attach' {P : Ξ± β†’ Prop} : βˆ€ t, All P t β†’ Ordnode { a // P a } := pmap Subtype.mk /-- O(log n). Get the `i`th element of the set, by its index from left to right. nth {a, b, c, d} 2 = some c nth {a, b, c, d} 5 = none -/ def nth : Ordnode Ξ± β†’ β„• β†’ Option Ξ± | nil, _ => none | node _ l x r, i => match Nat.psub' i (size l) with | none => nth l i | some 0 => some x | some (j + 1) => nth r j /-- O(log n). Remove the `i`th element of the set, by its index from left to right. remove_nth {a, b, c, d} 2 = {a, b, d} remove_nth {a, b, c, d} 5 = {a, b, c, d} -/ def removeNth : Ordnode Ξ± β†’ β„• β†’ Ordnode Ξ± | nil, _ => nil | node _ l x r, i => match Nat.psub' i (size l) with | none => balanceR (removeNth l i) x r | some 0 => glue l r | some (j + 1) => balanceL l x (removeNth r j) /-- Auxiliary definition for `take`. (Can also be used in lieu of `take` if you know the index is within the range of the data structure.) takeAux {a, b, c, d} 2 = {a, b} takeAux {a, b, c, d} 5 = {a, b, c, d} -/ def takeAux : Ordnode Ξ± β†’ β„• β†’ Ordnode Ξ± | nil, _ => nil | node _ l x r, i => if i = 0 then nil else match Nat.psub' i (size l) with | none => takeAux l i | some 0 => l | some (j + 1) => link l x (takeAux r j) /-- O(log n). Get the first `i` elements of the set, counted from the left. take 2 {a, b, c, d} = {a, b} take 5 {a, b, c, d} = {a, b, c, d} -/ def take (i : β„•) (t : Ordnode Ξ±) : Ordnode Ξ± := if size t ≀ i then t else takeAux t i /-- Auxiliary definition for `drop`. (Can also be used in lieu of `drop` if you know the index is within the range of the data structure.) drop_aux {a, b, c, d} 2 = {c, d} drop_aux {a, b, c, d} 5 = βˆ… -/ def dropAux : Ordnode Ξ± β†’ β„• β†’ Ordnode Ξ± | nil, _ => nil | t@(node _ l x r), i => if i = 0 then t else match Nat.psub' i (size l) with | none => link (dropAux l i) x r | some 0 => insertMin x r | some (j + 1) => dropAux r j /-- O(log n). Remove the first `i` elements of the set, counted from the left. drop 2 {a, b, c, d} = {c, d} drop 5 {a, b, c, d} = βˆ… -/ def drop (i : β„•) (t : Ordnode Ξ±) : Ordnode Ξ± := if size t ≀ i then nil else dropAux t i /-- Auxiliary definition for `splitAt`. (Can also be used in lieu of `splitAt` if you know the index is within the range of the data structure.) splitAtAux {a, b, c, d} 2 = ({a, b}, {c, d}) splitAtAux {a, b, c, d} 5 = ({a, b, c, d}, βˆ…) -/ def splitAtAux : Ordnode Ξ± β†’ β„• β†’ Ordnode Ξ± Γ— Ordnode Ξ± | nil, _ => (nil, nil) | t@(node _ l x r), i => if i = 0 then (nil, t) else match Nat.psub' i (size l) with | none => let (l₁, lβ‚‚) := splitAtAux l i (l₁, link lβ‚‚ x r) | some 0 => (glue l r, insertMin x r) | some (j + 1) => let (r₁, rβ‚‚) := splitAtAux r j (link l x r₁, rβ‚‚) /-- O(log n). Split a set at the `i`th element, getting the first `i` and everything else. splitAt 2 {a, b, c, d} = ({a, b}, {c, d}) splitAt 5 {a, b, c, d} = ({a, b, c, d}, βˆ…) -/ def splitAt (i : β„•) (t : Ordnode Ξ±) : Ordnode Ξ± Γ— Ordnode Ξ± := if size t ≀ i then (t, nil) else splitAtAux t i /-- O(log n). Get an initial segment of the set that satisfies the predicate `p`. `p` is required to be antitone, that is, `x < y β†’ p y β†’ p x`. takeWhile (fun x ↦ x < 4) {1, 2, 3, 4, 5} = {1, 2, 3} takeWhile (fun x ↦ x > 4) {1, 2, 3, 4, 5} = precondition violation -/ def takeWhile (p : Ξ± β†’ Prop) [DecidablePred p] : Ordnode Ξ± β†’ Ordnode Ξ± | nil => nil | node _ l x r => if p x then link l x (takeWhile p r) else takeWhile p l /-- O(log n). Remove an initial segment of the set that satisfies the predicate `p`. `p` is required to be antitone, that is, `x < y β†’ p y β†’ p x`. dropWhile (fun x ↦ x < 4) {1, 2, 3, 4, 5} = {4, 5} dropWhile (fun x ↦ x > 4) {1, 2, 3, 4, 5} = precondition violation -/ def dropWhile (p : Ξ± β†’ Prop) [DecidablePred p] : Ordnode Ξ± β†’ Ordnode Ξ± | nil => nil | node _ l x r => if p x then dropWhile p r else link (dropWhile p l) x r /-- O(log n). Split the set into those satisfying and not satisfying the predicate `p`. `p` is required to be antitone, that is, `x < y β†’ p y β†’ p x`. span (fun x ↦ x < 4) {1, 2, 3, 4, 5} = ({1, 2, 3}, {4, 5}) span (fun x ↦ x > 4) {1, 2, 3, 4, 5} = precondition violation -/ def span (p : Ξ± β†’ Prop) [DecidablePred p] : Ordnode Ξ± β†’ Ordnode Ξ± Γ— Ordnode Ξ± | nil => (nil, nil) | node _ l x r => if p x then let (r₁, rβ‚‚) := span p r (link l x r₁, rβ‚‚) else let (l₁, lβ‚‚) := span p l (l₁, link lβ‚‚ x r) /-- Auxiliary definition for `ofAscList`. **Note:** This function is defined by well founded recursion, so it will probably not compute in the kernel, meaning that you probably can't prove things like `ofAscList [1, 2, 3] = {1, 2, 3}` by `rfl`. This implementation is optimized for VM evaluation. -/ def ofAscListAux₁ : βˆ€ l : List Ξ±, β„• β†’ Ordnode Ξ± Γ— { l' : List Ξ± // l'.length ≀ l.length } | [] => fun _ => (nil, ⟨[], le_rfl⟩) | x :: xs => fun s => if s = 1 then (ΞΉ x, ⟨xs, Nat.le_succ _⟩) else match ofAscListAux₁ xs (s <<< 1) with | (t, ⟨[], _⟩) => (t, ⟨[], Nat.zero_le _⟩) | (l, ⟨y :: ys, h⟩) => have := Nat.le_succ_of_le h let (r, ⟨zs, h'⟩) := ofAscListAux₁ ys (s <<< 1) (link l y r, ⟨zs, le_trans h' (le_of_lt this)⟩) termination_by l => l.length /-- Auxiliary definition for `ofAscList`. -/ def ofAscListAuxβ‚‚ : List Ξ± β†’ Ordnode Ξ± β†’ β„• β†’ Ordnode Ξ± | [] => fun t _ => t | x :: xs => fun l s => match ofAscListAux₁ xs s with | (r, ⟨ys, h⟩) => have := Nat.lt_succ_of_le h ofAscListAuxβ‚‚ ys (link l x r) (s <<< 1) termination_by l => l.length /-- O(n). Build a set from a list which is already sorted. Performs no comparisons. ofAscList [1, 2, 3] = {1, 2, 3} ofAscList [3, 2, 1] = precondition violation -/ def ofAscList : List Ξ± β†’ Ordnode Ξ± | [] => nil | x :: xs => ofAscListAuxβ‚‚ xs (ΞΉ x) 1 section variable [LE Ξ±] [@DecidableRel Ξ± (Β· ≀ Β·)] /-- O(log n). Does the set (approximately) contain the element `x`? That is, is there an element that is equivalent to `x` in the order? 1 ∈ {1, 2, 3} = true 4 ∈ {1, 2, 3} = false Using a preorder on `β„• Γ— β„•` that only compares the first coordinate: (1, 1) ∈ {(0, 1), (1, 2)} = true (3, 1) ∈ {(0, 1), (1, 2)} = false -/ def mem (x : Ξ±) : Ordnode Ξ± β†’ Bool | nil => false | node _ l y r => match cmpLE x y with | Ordering.lt => mem x l | Ordering.eq => true | Ordering.gt => mem x r /-- O(log n). Retrieve an element in the set that is equivalent to `x` in the order, if it exists. find 1 {1, 2, 3} = some 1 find 4 {1, 2, 3} = none Using a preorder on `β„• Γ— β„•` that only compares the first coordinate: find (1, 1) {(0, 1), (1, 2)} = some (1, 2) find (3, 1) {(0, 1), (1, 2)} = none -/ def find (x : Ξ±) : Ordnode Ξ± β†’ Option Ξ± | nil => none | node _ l y r => match cmpLE x y with | Ordering.lt => find x l | Ordering.eq => some y | Ordering.gt => find x r instance : Membership Ξ± (Ordnode Ξ±) := ⟨fun x t => t.mem x⟩ instance mem.decidable (x : Ξ±) (t : Ordnode Ξ±) : Decidable (x ∈ t) := Bool.decEq _ _ /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, the function `f` is used to generate the element to insert (being passed the current value in the set). insertWith f 0 {1, 2, 3} = {0, 1, 2, 3} insertWith f 1 {1, 2, 3} = {f 1, 2, 3} Using a preorder on `β„• Γ— β„•` that only compares the first coordinate: insertWith f (1, 1) {(0, 1), (1, 2)} = {(0, 1), f (1, 2)} insertWith f (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2), (3, 1)} -/ def insertWith (f : Ξ± β†’ Ξ±) (x : Ξ±) : Ordnode Ξ± β†’ Ordnode Ξ± | nil => ΞΉ x | node sz l y r => match cmpLE x y with | Ordering.lt => balanceL (insertWith f x l) y r | Ordering.eq => node sz l (f y) r | Ordering.gt => balanceR l y (insertWith f x r) /-- O(log n). Modify an element in the set with the given function, doing nothing if the key is not found. Note that the element returned by `f` must be equivalent to `x`. adjustWith f 0 {1, 2, 3} = {1, 2, 3} adjustWith f 1 {1, 2, 3} = {f 1, 2, 3} Using a preorder on `β„• Γ— β„•` that only compares the first coordinate: adjustWith f (1, 1) {(0, 1), (1, 2)} = {(0, 1), f (1, 2)} adjustWith f (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2)} -/ def adjustWith (f : Ξ± β†’ Ξ±) (x : Ξ±) : Ordnode Ξ± β†’ Ordnode Ξ± | nil => nil | _t@(node sz l y r) => match cmpLE x y with | Ordering.lt => node sz (adjustWith f x l) y r | Ordering.eq => node sz l (f y) r | Ordering.gt => node sz l y (adjustWith f x r) /-- O(log n). Modify an element in the set with the given function, doing nothing if the key is not found. Note that the element returned by `f` must be equivalent to `x`. updateWith f 0 {1, 2, 3} = {1, 2, 3} updateWith f 1 {1, 2, 3} = {2, 3} if f 1 = none = {a, 2, 3} if f 1 = some a -/ def updateWith (f : Ξ± β†’ Option Ξ±) (x : Ξ±) : Ordnode Ξ± β†’ Ordnode Ξ± | nil => nil | _t@(node sz l y r) => match cmpLE x y with | Ordering.lt => balanceR (updateWith f x l) y r | Ordering.eq => match f y with | none => glue l r | some a => node sz l a r | Ordering.gt => balanceL l y (updateWith f x r) /-- O(log n). Modify an element in the set with the given function, doing nothing if the key is not found. Note that the element returned by `f` must be equivalent to `x`. alter f 0 {1, 2, 3} = {1, 2, 3} if f none = none = {a, 1, 2, 3} if f none = some a alter f 1 {1, 2, 3} = {2, 3} if f 1 = none = {a, 2, 3} if f 1 = some a -/ def alter (f : Option Ξ± β†’ Option Ξ±) (x : Ξ±) : Ordnode Ξ± β†’ Ordnode Ξ± | nil => Option.recOn (f none) nil Ordnode.singleton | _t@(node sz l y r) => match cmpLE x y with | Ordering.lt => balance (alter f x l) y r | Ordering.eq => match f (some y) with | none => glue l r | some a => node sz l a r | Ordering.gt => balance l y (alter f x r) /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, this replaces it. insert 1 {1, 2, 3} = {1, 2, 3} insert 4 {1, 2, 3} = {1, 2, 3, 4} Using a preorder on `β„• Γ— β„•` that only compares the first coordinate: insert (1, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 1)} insert (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2), (3, 1)} -/ protected def insert (x : Ξ±) : Ordnode Ξ± β†’ Ordnode Ξ± | nil => ΞΉ x | node sz l y r => match cmpLE x y with | Ordering.lt => balanceL (Ordnode.insert x l) y r | Ordering.eq => node sz l x r | Ordering.gt => balanceR l y (Ordnode.insert x r) instance : Insert Ξ± (Ordnode Ξ±) := ⟨Ordnode.insert⟩ /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, the set is returned as is. insert' 1 {1, 2, 3} = {1, 2, 3} insert' 4 {1, 2, 3} = {1, 2, 3, 4} Using a preorder on `β„• Γ— β„•` that only compares the first coordinate: insert' (1, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2)} insert' (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2), (3, 1)} -/ def insert' (x : Ξ±) : Ordnode Ξ± β†’ Ordnode Ξ± | nil => ΞΉ x | t@(node _ l y r) => match cmpLE x y with | Ordering.lt => balanceL (insert' x l) y r | Ordering.eq => t | Ordering.gt => balanceR l y (insert' x r) /-- O(log n). Split the tree into those smaller than `x` and those greater than it. If an element equivalent to `x` is in the set, it is discarded. split 2 {1, 2, 4} = ({1}, {4}) split 3 {1, 2, 4} = ({1, 2}, {4}) split 4 {1, 2, 4} = ({1, 2}, βˆ…) Using a preorder on `β„• Γ— β„•` that only compares the first coordinate: split (1, 1) {(0, 1), (1, 2)} = ({(0, 1)}, βˆ…) split (3, 1) {(0, 1), (1, 2)} = ({(0, 1), (1, 2)}, βˆ…) -/ def split (x : Ξ±) : Ordnode Ξ± β†’ Ordnode Ξ± Γ— Ordnode Ξ± | nil => (nil, nil) | node _ l y r => match cmpLE x y with | Ordering.lt => let (lt, gt) := split x l (lt, link gt y r) | Ordering.eq => (l, r) | Ordering.gt => let (lt, gt) := split x r (link l y lt, gt) /-- O(log n). Split the tree into those smaller than `x` and those greater than it, plus an element equivalent to `x`, if it exists. split3 2 {1, 2, 4} = ({1}, some 2, {4}) split3 3 {1, 2, 4} = ({1, 2}, none, {4}) split3 4 {1, 2, 4} = ({1, 2}, some 4, βˆ…) Using a preorder on `β„• Γ— β„•` that only compares the first coordinate: split3 (1, 1) {(0, 1), (1, 2)} = ({(0, 1)}, some (1, 2), βˆ…) split3 (3, 1) {(0, 1), (1, 2)} = ({(0, 1), (1, 2)}, none, βˆ…) -/ def split3 (x : Ξ±) : Ordnode Ξ± β†’ Ordnode Ξ± Γ— Option Ξ± Γ— Ordnode Ξ± | nil => (nil, none, nil) | node _ l y r => match cmpLE x y with | Ordering.lt => let (lt, f, gt) := split3 x l (lt, f, link gt y r) | Ordering.eq => (l, some y, r) | Ordering.gt => let (lt, f, gt) := split3 x r (link l y lt, f, gt) /-- O(log n). Remove an element from the set equivalent to `x`. Does nothing if there is no such element. erase 1 {1, 2, 3} = {2, 3} erase 4 {1, 2, 3} = {1, 2, 3} Using a preorder on `β„• Γ— β„•` that only compares the first coordinate: erase (1, 1) {(0, 1), (1, 2)} = {(0, 1)} erase (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2)} -/ def erase (x : Ξ±) : Ordnode Ξ± β†’ Ordnode Ξ± | nil => nil | _t@(node _ l y r) => match cmpLE x y with | Ordering.lt => balanceR (erase x l) y r | Ordering.eq => glue l r | Ordering.gt => balanceL l y (erase x r) /-- Auxiliary definition for `findLt`. -/ def findLtAux (x : Ξ±) : Ordnode Ξ± β†’ Ξ± β†’ Ξ± | nil, best => best | node _ l y r, best => if x ≀ y then findLtAux x l best else findLtAux x r y /-- O(log n). Get the largest element in the tree that is `< x`. findLt 2 {1, 2, 4} = some 1 findLt 3 {1, 2, 4} = some 2 findLt 0 {1, 2, 4} = none -/ def findLt (x : Ξ±) : Ordnode Ξ± β†’ Option Ξ± | nil => none | node _ l y r => if x ≀ y then findLt x l else some (findLtAux x r y) /-- Auxiliary definition for `findGt`. -/ def findGtAux (x : Ξ±) : Ordnode Ξ± β†’ Ξ± β†’ Ξ± | nil, best => best | node _ l y r, best => if y ≀ x then findGtAux x r best else findGtAux x l y /-- O(log n). Get the smallest element in the tree that is `> x`. findGt 2 {1, 2, 4} = some 4 findGt 3 {1, 2, 4} = some 4 findGt 4 {1, 2, 4} = none -/ def findGt (x : Ξ±) : Ordnode Ξ± β†’ Option Ξ± | nil => none | node _ l y r => if y ≀ x then findGt x r else some (findGtAux x l y) /-- Auxiliary definition for `findLe`. -/ def findLeAux (x : Ξ±) : Ordnode Ξ± β†’ Ξ± β†’ Ξ± | nil, best => best | node _ l y r, best => match cmpLE x y with | Ordering.lt => findLeAux x l best | Ordering.eq => y | Ordering.gt => findLeAux x r y /-- O(log n). Get the largest element in the tree that is `≀ x`. findLe 2 {1, 2, 4} = some 2 findLe 3 {1, 2, 4} = some 2 findLe 0 {1, 2, 4} = none -/ def findLe (x : Ξ±) : Ordnode Ξ± β†’ Option Ξ± | nil => none | node _ l y r => match cmpLE x y with | Ordering.lt => findLe x l | Ordering.eq => some y | Ordering.gt => some (findLeAux x r y) /-- Auxiliary definition for `findGe`. -/ def findGeAux (x : Ξ±) : Ordnode Ξ± β†’ Ξ± β†’ Ξ± | nil, best => best | node _ l y r, best => match cmpLE x y with | Ordering.lt => findGeAux x l y | Ordering.eq => y | Ordering.gt => findGeAux x r best -- Porting note: find_le β†’ findGe /-- O(log n). Get the smallest element in the tree that is `β‰₯ x`. findGe 2 {1, 2, 4} = some 2 findGe 3 {1, 2, 4} = some 4 findGe 5 {1, 2, 4} = none -/ def findGe (x : Ξ±) : Ordnode Ξ± β†’ Option Ξ± | nil => none | node _ l y r => match cmpLE x y with | Ordering.lt => some (findGeAux x l y) | Ordering.eq => some y | Ordering.gt => findGe x r /-- Auxiliary definition for `findIndex`. -/ def findIndexAux (x : Ξ±) : Ordnode Ξ± β†’ β„• β†’ Option β„• | nil, _ => none | node _ l y r, i => match cmpLE x y with | Ordering.lt => findIndexAux x l i | Ordering.eq => some (i + size l) | Ordering.gt => findIndexAux x r (i + size l + 1) /-- O(log n). Get the index, counting from the left, of an element equivalent to `x` if it exists. findIndex 2 {1, 2, 4} = some 1 findIndex 4 {1, 2, 4} = some 2 findIndex 5 {1, 2, 4} = none -/ def findIndex (x : Ξ±) (t : Ordnode Ξ±) : Option β„• := findIndexAux x t 0 /-- Auxiliary definition for `isSubset`. -/ def isSubsetAux : Ordnode Ξ± β†’ Ordnode Ξ± β†’ Bool | nil, _ => true | _, nil => false | node _ l x r, t => let (lt, found, gt) := split3 x t found.isSome && isSubsetAux l lt && isSubsetAux r gt /-- O(m + n). Is every element of `t₁` equivalent to some element of `tβ‚‚`? is_subset {1, 4} {1, 2, 4} = tt is_subset {1, 3} {1, 2, 4} = ff -/ def isSubset (t₁ tβ‚‚ : Ordnode Ξ±) : Bool := decide (size t₁ ≀ size tβ‚‚) && isSubsetAux t₁ tβ‚‚ /-- O(m + n). Is every element of `t₁` not equivalent to any element of `tβ‚‚`? disjoint {1, 3} {2, 4} = tt disjoint {1, 2} {2, 4} = ff -/ def disjoint : Ordnode Ξ± β†’ Ordnode Ξ± β†’ Bool | nil, _ => true | _, nil => true | node _ l x r, t => let (lt, found, gt) := split3 x t found.isNone && disjoint l lt && disjoint r gt /-- O(m * log(|m βˆͺ n| + 1)), m ≀ n. The union of two sets, preferring members of `t₁` over those of `tβ‚‚` when equivalent elements are encountered. union {1, 2} {2, 3} = {1, 2, 3} union {1, 3} {2} = {1, 2, 3} Using a preorder on `β„• Γ— β„•` that only compares the first coordinate: union {(1, 1)} {(0, 1), (1, 2)} = {(0, 1), (1, 1)} -/ def union : Ordnode Ξ± β†’ Ordnode Ξ± β†’ Ordnode Ξ± | t₁, nil => t₁ | nil, tβ‚‚ => tβ‚‚ | t₁@(node s₁ l₁ x₁ r₁), tβ‚‚@(node sβ‚‚ _ xβ‚‚ _) => if sβ‚‚ = 1 then insert' xβ‚‚ t₁ else if s₁ = 1 then insert x₁ tβ‚‚ else let (lβ‚‚', rβ‚‚') := split x₁ tβ‚‚ link (union l₁ lβ‚‚') x₁ (union r₁ rβ‚‚') /-- O(m * log(|m βˆͺ n| + 1)), m ≀ n. Difference of two sets. diff {1, 2} {2, 3} = {1} diff {1, 2, 3} {2} = {1, 3} -/ def diff : Ordnode Ξ± β†’ Ordnode Ξ± β†’ Ordnode Ξ± | t₁, nil => t₁ | t₁, tβ‚‚@(node _ lβ‚‚ x rβ‚‚) => cond t₁.empty tβ‚‚ <| let (l₁, r₁) := split x t₁ let l₁₂ := diff l₁ lβ‚‚ let r₁₂ := diff r₁ rβ‚‚ if size l₁₂ + size r₁₂ = size t₁ then t₁ else merge l₁₂ r₁₂ /-- O(m * log(|m βˆͺ n| + 1)), m ≀ n. Intersection of two sets, preferring members of `t₁` over those of `tβ‚‚` when equivalent elements are encountered. inter {1, 2} {2, 3} = {2} inter {1, 3} {2} = βˆ… -/ def inter : Ordnode Ξ± β†’ Ordnode Ξ± β†’ Ordnode Ξ± | nil, _ => nil | t₁@(node _ l₁ x r₁), tβ‚‚ => cond tβ‚‚.empty t₁ <| let (lβ‚‚, y, rβ‚‚) := split3 x tβ‚‚ let l₁₂ := inter l₁ lβ‚‚ let r₁₂ := inter r₁ rβ‚‚ cond y.isSome (link l₁₂ x r₁₂) (merge l₁₂ r₁₂) /-- O(n * log n). Build a set from a list, preferring elements that appear earlier in the list in the case of equivalent elements. ofList [1, 2, 3] = {1, 2, 3} ofList [2, 1, 1, 3] = {1, 2, 3} Using a preorder on `β„• Γ— β„•` that only compares the first coordinate: ofList [(1, 1), (0, 1), (1, 2)] = {(0, 1), (1, 1)} -/ def ofList (l : List Ξ±) : Ordnode Ξ± := l.foldr insert nil /-- O(n * log n). Adaptively chooses between the linear and log-linear algorithm depending on whether the input list is already sorted. ofList' [1, 2, 3] = {1, 2, 3} ofList' [2, 1, 1, 3] = {1, 2, 3} -/ def ofList' : List Ξ± β†’ Ordnode Ξ± | [] => nil | x :: xs => if List.Chain (fun a b => Β¬b ≀ a) x xs then ofAscList (x :: xs) else ofList (x :: xs) /-- O(n * log n). Map a function on a set. Unlike `map` this has no requirements on `f`, and the resulting set may be smaller than the input if `f` is noninjective. Equivalent elements are selected with a preference for smaller source elements. image (fun x ↦ x + 2) {1, 2, 4} = {3, 4, 6} image (fun x : β„• ↦ x - 2) {1, 2, 4} = {0, 2} -/ def image {Ξ± Ξ²} [LE Ξ²] [@DecidableRel Ξ² (Β· ≀ Β·)] (f : Ξ± β†’ Ξ²) (t : Ordnode Ξ±) : Ordnode Ξ² := ofList (t.toList.map f) end end Ordnode
Data\Ordmap\Ordset.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Algebra.Order.Ring.Defs import Mathlib.Algebra.Group.Int import Mathlib.Data.Nat.Dist import Mathlib.Data.Ordmap.Ordnode import Mathlib.Tactic.Abel import Mathlib.Tactic.Linarith /-! # Verification of the `Ordnode Ξ±` datatype This file proves the correctness of the operations in `Data.Ordmap.Ordnode`. The public facing version is the type `Ordset Ξ±`, which is a wrapper around `Ordnode Ξ±` which includes the correctness invariant of the type, and it exposes parallel operations like `insert` as functions on `Ordset` that do the same thing but bundle the correctness proofs. The advantage is that it is possible to, for example, prove that the result of `find` on `insert` will actually find the element, while `Ordnode` cannot guarantee this if the input tree did not satisfy the type invariants. ## Main definitions * `Ordset Ξ±`: A well formed set of values of type `Ξ±` ## Implementation notes The majority of this file is actually in the `Ordnode` namespace, because we first have to prove the correctness of all the operations (and defining what correctness means here is actually somewhat subtle). So all the actual `Ordset` operations are at the very end, once we have all the theorems. An `Ordnode Ξ±` is an inductive type which describes a tree which stores the `size` at internal nodes. The correctness invariant of an `Ordnode Ξ±` is: * `Ordnode.Sized t`: All internal `size` fields must match the actual measured size of the tree. (This is not hard to satisfy.) * `Ordnode.Balanced t`: Unless the tree has the form `()` or `((a) b)` or `(a (b))` (that is, nil or a single singleton subtree), the two subtrees must satisfy `size l ≀ Ξ΄ * size r` and `size r ≀ Ξ΄ * size l`, where `Ξ΄ := 3` is a global parameter of the data structure (and this property must hold recursively at subtrees). This is why we say this is a "size balanced tree" data structure. * `Ordnode.Bounded lo hi t`: The members of the tree must be in strictly increasing order, meaning that if `a` is in the left subtree and `b` is the root, then `a ≀ b` and `Β¬ (b ≀ a)`. We enforce this using `Ordnode.Bounded` which includes also a global upper and lower bound. Because the `Ordnode` file was ported from Haskell, the correctness invariants of some of the functions have not been spelled out, and some theorems like `Ordnode.Valid'.balanceL_aux` show very intricate assumptions on the sizes, which may need to be revised if it turns out some operations violate these assumptions, because there is a decent amount of slop in the actual data structure invariants, so the theorem will go through with multiple choices of assumption. **Note:** This file is incomplete, in the sense that the intent is to have verified versions and lemmas about all the definitions in `Ordnode.lean`, but at the moment only a few operations are verified (the hard part should be out of the way, but still). Contributors are encouraged to pick this up and finish the job, if it appeals to you. ## Tags ordered map, ordered set, data structure, verified programming -/ variable {Ξ± : Type*} namespace Ordnode /-! ### delta and ratio -/ theorem not_le_delta {s} (H : 1 ≀ s) : Β¬s ≀ delta * 0 := not_le_of_gt H theorem delta_lt_false {a b : β„•} (h₁ : delta * a < b) (hβ‚‚ : delta * b < a) : False := not_le_of_lt (lt_trans ((mul_lt_mul_left (by decide)).2 h₁) hβ‚‚) <| by simpa [mul_assoc] using Nat.mul_le_mul_right a (by decide : 1 ≀ delta * delta) /-! ### `singleton` -/ /-! ### `size` and `empty` -/ /-- O(n). Computes the actual number of elements in the set, ignoring the cached `size` field. -/ def realSize : Ordnode Ξ± β†’ β„• | nil => 0 | node _ l _ r => realSize l + realSize r + 1 /-! ### `Sized` -/ /-- The `Sized` property asserts that all the `size` fields in nodes match the actual size of the respective subtrees. -/ def Sized : Ordnode Ξ± β†’ Prop | nil => True | node s l _ r => s = size l + size r + 1 ∧ Sized l ∧ Sized r theorem Sized.node' {l x r} (hl : @Sized Ξ± l) (hr : Sized r) : Sized (node' l x r) := ⟨rfl, hl, hr⟩ theorem Sized.eq_node' {s l x r} (h : @Sized Ξ± (node s l x r)) : node s l x r = .node' l x r := by rw [h.1] theorem Sized.size_eq {s l x r} (H : Sized (@node Ξ± s l x r)) : size (@node Ξ± s l x r) = size l + size r + 1 := H.1 @[elab_as_elim] theorem Sized.induction {t} (hl : @Sized Ξ± t) {C : Ordnode Ξ± β†’ Prop} (H0 : C nil) (H1 : βˆ€ l x r, C l β†’ C r β†’ C (.node' l x r)) : C t := by induction t with | nil => exact H0 | node _ _ _ _ t_ih_l t_ih_r => rw [hl.eq_node'] exact H1 _ _ _ (t_ih_l hl.2.1) (t_ih_r hl.2.2) theorem size_eq_realSize : βˆ€ {t : Ordnode Ξ±}, Sized t β†’ size t = realSize t | nil, _ => rfl | node s l x r, ⟨h₁, hβ‚‚, hβ‚ƒβŸ© => by rw [size, h₁, size_eq_realSize hβ‚‚, size_eq_realSize h₃]; rfl @[simp] theorem Sized.size_eq_zero {t : Ordnode Ξ±} (ht : Sized t) : size t = 0 ↔ t = nil := by cases t <;> [simp;simp [ht.1]] theorem Sized.pos {s l x r} (h : Sized (@node Ξ± s l x r)) : 0 < s := by rw [h.1]; apply Nat.le_add_left /-! `dual` -/ theorem dual_dual : βˆ€ t : Ordnode Ξ±, dual (dual t) = t | nil => rfl | node s l x r => by rw [dual, dual, dual_dual l, dual_dual r] @[simp] theorem size_dual (t : Ordnode Ξ±) : size (dual t) = size t := by cases t <;> rfl /-! `Balanced` -/ /-- The `BalancedSz l r` asserts that a hypothetical tree with children of sizes `l` and `r` is balanced: either `l ≀ Ξ΄ * r` and `r ≀ Ξ΄ * r`, or the tree is trivial with a singleton on one side and nothing on the other. -/ def BalancedSz (l r : β„•) : Prop := l + r ≀ 1 ∨ l ≀ delta * r ∧ r ≀ delta * l instance BalancedSz.dec : DecidableRel BalancedSz := fun _ _ => Or.decidable /-- The `Balanced t` asserts that the tree `t` satisfies the balance invariants (at every level). -/ def Balanced : Ordnode Ξ± β†’ Prop | nil => True | node _ l _ r => BalancedSz (size l) (size r) ∧ Balanced l ∧ Balanced r instance Balanced.dec : DecidablePred (@Balanced Ξ±) | nil => by unfold Balanced infer_instance | node _ l _ r => by unfold Balanced haveI := Balanced.dec l haveI := Balanced.dec r infer_instance @[symm] theorem BalancedSz.symm {l r : β„•} : BalancedSz l r β†’ BalancedSz r l := Or.imp (by rw [add_comm]; exact id) And.symm theorem balancedSz_zero {l : β„•} : BalancedSz l 0 ↔ l ≀ 1 := by simp (config := { contextual := true }) [BalancedSz] theorem balancedSz_up {l r₁ rβ‚‚ : β„•} (h₁ : r₁ ≀ rβ‚‚) (hβ‚‚ : l + rβ‚‚ ≀ 1 ∨ rβ‚‚ ≀ delta * l) (H : BalancedSz l r₁) : BalancedSz l rβ‚‚ := by refine or_iff_not_imp_left.2 fun h => ?_ refine ⟨?_, hβ‚‚.resolve_left h⟩ cases H with | inl H => cases rβ‚‚ Β· cases h (le_trans (Nat.add_le_add_left (Nat.zero_le _) _) H) Β· exact le_trans (le_trans (Nat.le_add_right _ _) H) (Nat.le_add_left 1 _) | inr H => exact le_trans H.1 (Nat.mul_le_mul_left _ h₁) theorem balancedSz_down {l r₁ rβ‚‚ : β„•} (h₁ : r₁ ≀ rβ‚‚) (hβ‚‚ : l + rβ‚‚ ≀ 1 ∨ l ≀ delta * r₁) (H : BalancedSz l rβ‚‚) : BalancedSz l r₁ := have : l + rβ‚‚ ≀ 1 β†’ BalancedSz l r₁ := fun H => Or.inl (le_trans (Nat.add_le_add_left h₁ _) H) Or.casesOn H this fun H => Or.casesOn hβ‚‚ this fun hβ‚‚ => Or.inr ⟨hβ‚‚, le_trans h₁ H.2⟩ theorem Balanced.dual : βˆ€ {t : Ordnode Ξ±}, Balanced t β†’ Balanced (dual t) | nil, _ => ⟨⟩ | node _ l _ r, ⟨b, bl, br⟩ => ⟨by rw [size_dual, size_dual]; exact b.symm, br.dual, bl.dual⟩ /-! ### `rotate` and `balance` -/ /-- Build a tree from three nodes, left associated (ignores the invariants). -/ def node3L (l : Ordnode Ξ±) (x : Ξ±) (m : Ordnode Ξ±) (y : Ξ±) (r : Ordnode Ξ±) : Ordnode Ξ± := node' (node' l x m) y r /-- Build a tree from three nodes, right associated (ignores the invariants). -/ def node3R (l : Ordnode Ξ±) (x : Ξ±) (m : Ordnode Ξ±) (y : Ξ±) (r : Ordnode Ξ±) : Ordnode Ξ± := node' l x (node' m y r) /-- Build a tree from three nodes, with `a () b -> (a ()) b` and `a (b c) d -> ((a b) (c d))`. -/ def node4L : Ordnode Ξ± β†’ Ξ± β†’ Ordnode Ξ± β†’ Ξ± β†’ Ordnode Ξ± β†’ Ordnode Ξ± | l, x, node _ ml y mr, z, r => node' (node' l x ml) y (node' mr z r) | l, x, nil, z, r => node3L l x nil z r -- should not happen /-- Build a tree from three nodes, with `a () b -> a (() b)` and `a (b c) d -> ((a b) (c d))`. -/ def node4R : Ordnode Ξ± β†’ Ξ± β†’ Ordnode Ξ± β†’ Ξ± β†’ Ordnode Ξ± β†’ Ordnode Ξ± | l, x, node _ ml y mr, z, r => node' (node' l x ml) y (node' mr z r) | l, x, nil, z, r => node3R l x nil z r -- should not happen /-- Concatenate two nodes, performing a left rotation `x (y z) -> ((x y) z)` if balance is upset. -/ def rotateL : Ordnode Ξ± β†’ Ξ± β†’ Ordnode Ξ± β†’ Ordnode Ξ± | l, x, node _ m y r => if size m < ratio * size r then node3L l x m y r else node4L l x m y r | l, x, nil => node' l x nil -- Porting note (#11467): during the port we marked these lemmas with `@[eqns]` -- to emulate the old Lean 3 behaviour. theorem rotateL_node (l : Ordnode Ξ±) (x : Ξ±) (sz : β„•) (m : Ordnode Ξ±) (y : Ξ±) (r : Ordnode Ξ±) : rotateL l x (node sz m y r) = if size m < ratio * size r then node3L l x m y r else node4L l x m y r := rfl theorem rotateL_nil (l : Ordnode Ξ±) (x : Ξ±) : rotateL l x nil = node' l x nil := rfl -- should not happen /-- Concatenate two nodes, performing a right rotation `(x y) z -> (x (y z))` if balance is upset. -/ def rotateR : Ordnode Ξ± β†’ Ξ± β†’ Ordnode Ξ± β†’ Ordnode Ξ± | node _ l x m, y, r => if size m < ratio * size l then node3R l x m y r else node4R l x m y r | nil, y, r => node' nil y r -- Porting note (#11467): during the port we marked these lemmas with `@[eqns]` -- to emulate the old Lean 3 behaviour. theorem rotateR_node (sz : β„•) (l : Ordnode Ξ±) (x : Ξ±) (m : Ordnode Ξ±) (y : Ξ±) (r : Ordnode Ξ±) : rotateR (node sz l x m) y r = if size m < ratio * size l then node3R l x m y r else node4R l x m y r := rfl theorem rotateR_nil (y : Ξ±) (r : Ordnode Ξ±) : rotateR nil y r = node' nil y r := rfl -- should not happen /-- A left balance operation. This will rebalance a concatenation, assuming the original nodes are not too far from balanced. -/ def balanceL' (l : Ordnode Ξ±) (x : Ξ±) (r : Ordnode Ξ±) : Ordnode Ξ± := if size l + size r ≀ 1 then node' l x r else if size l > delta * size r then rotateR l x r else node' l x r /-- A right balance operation. This will rebalance a concatenation, assuming the original nodes are not too far from balanced. -/ def balanceR' (l : Ordnode Ξ±) (x : Ξ±) (r : Ordnode Ξ±) : Ordnode Ξ± := if size l + size r ≀ 1 then node' l x r else if size r > delta * size l then rotateL l x r else node' l x r /-- The full balance operation. This is the same as `balance`, but with less manual inlining. It is somewhat easier to work with this version in proofs. -/ def balance' (l : Ordnode Ξ±) (x : Ξ±) (r : Ordnode Ξ±) : Ordnode Ξ± := if size l + size r ≀ 1 then node' l x r else if size r > delta * size l then rotateL l x r else if size l > delta * size r then rotateR l x r else node' l x r theorem dual_node' (l : Ordnode Ξ±) (x : Ξ±) (r : Ordnode Ξ±) : dual (node' l x r) = node' (dual r) x (dual l) := by simp [node', add_comm] theorem dual_node3L (l : Ordnode Ξ±) (x : Ξ±) (m : Ordnode Ξ±) (y : Ξ±) (r : Ordnode Ξ±) : dual (node3L l x m y r) = node3R (dual r) y (dual m) x (dual l) := by simp [node3L, node3R, dual_node', add_comm] theorem dual_node3R (l : Ordnode Ξ±) (x : Ξ±) (m : Ordnode Ξ±) (y : Ξ±) (r : Ordnode Ξ±) : dual (node3R l x m y r) = node3L (dual r) y (dual m) x (dual l) := by simp [node3L, node3R, dual_node', add_comm] theorem dual_node4L (l : Ordnode Ξ±) (x : Ξ±) (m : Ordnode Ξ±) (y : Ξ±) (r : Ordnode Ξ±) : dual (node4L l x m y r) = node4R (dual r) y (dual m) x (dual l) := by cases m <;> simp [node4L, node4R, node3R, dual_node3L, dual_node', add_comm] theorem dual_node4R (l : Ordnode Ξ±) (x : Ξ±) (m : Ordnode Ξ±) (y : Ξ±) (r : Ordnode Ξ±) : dual (node4R l x m y r) = node4L (dual r) y (dual m) x (dual l) := by cases m <;> simp [node4L, node4R, node3L, dual_node3R, dual_node', add_comm] theorem dual_rotateL (l : Ordnode Ξ±) (x : Ξ±) (r : Ordnode Ξ±) : dual (rotateL l x r) = rotateR (dual r) x (dual l) := by cases r <;> simp [rotateL, rotateR, dual_node']; split_ifs <;> simp [dual_node3L, dual_node4L, node3R, add_comm] theorem dual_rotateR (l : Ordnode Ξ±) (x : Ξ±) (r : Ordnode Ξ±) : dual (rotateR l x r) = rotateL (dual r) x (dual l) := by rw [← dual_dual (rotateL _ _ _), dual_rotateL, dual_dual, dual_dual] theorem dual_balance' (l : Ordnode Ξ±) (x : Ξ±) (r : Ordnode Ξ±) : dual (balance' l x r) = balance' (dual r) x (dual l) := by simp [balance', add_comm]; split_ifs with h h_1 h_2 <;> simp [dual_node', dual_rotateL, dual_rotateR, add_comm] cases delta_lt_false h_1 h_2 theorem dual_balanceL (l : Ordnode Ξ±) (x : Ξ±) (r : Ordnode Ξ±) : dual (balanceL l x r) = balanceR (dual r) x (dual l) := by unfold balanceL balanceR cases' r with rs rl rx rr Β· cases' l with ls ll lx lr; Β· rfl cases' ll with lls lll llx llr <;> cases' lr with lrs lrl lrx lrr <;> dsimp only [dual, id] <;> try rfl split_ifs with h <;> repeat simp [h, add_comm] Β· cases' l with ls ll lx lr; Β· rfl dsimp only [dual, id] split_ifs; swap; Β· simp [add_comm] cases' ll with lls lll llx llr <;> cases' lr with lrs lrl lrx lrr <;> try rfl dsimp only [dual, id] split_ifs with h <;> simp [h, add_comm] theorem dual_balanceR (l : Ordnode Ξ±) (x : Ξ±) (r : Ordnode Ξ±) : dual (balanceR l x r) = balanceL (dual r) x (dual l) := by rw [← dual_dual (balanceL _ _ _), dual_balanceL, dual_dual, dual_dual] theorem Sized.node3L {l x m y r} (hl : @Sized Ξ± l) (hm : Sized m) (hr : Sized r) : Sized (node3L l x m y r) := (hl.node' hm).node' hr theorem Sized.node3R {l x m y r} (hl : @Sized Ξ± l) (hm : Sized m) (hr : Sized r) : Sized (node3R l x m y r) := hl.node' (hm.node' hr) theorem Sized.node4L {l x m y r} (hl : @Sized Ξ± l) (hm : Sized m) (hr : Sized r) : Sized (node4L l x m y r) := by cases m <;> [exact (hl.node' hm).node' hr; exact (hl.node' hm.2.1).node' (hm.2.2.node' hr)] theorem node3L_size {l x m y r} : size (@node3L Ξ± l x m y r) = size l + size m + size r + 2 := by dsimp [node3L, node', size]; rw [add_right_comm _ 1] theorem node3R_size {l x m y r} : size (@node3R Ξ± l x m y r) = size l + size m + size r + 2 := by dsimp [node3R, node', size]; rw [← add_assoc, ← add_assoc] theorem node4L_size {l x m y r} (hm : Sized m) : size (@node4L Ξ± l x m y r) = size l + size m + size r + 2 := by cases m <;> simp [node4L, node3L, node'] <;> [abel; (simp [size, hm.1]; abel)] theorem Sized.dual : βˆ€ {t : Ordnode Ξ±}, Sized t β†’ Sized (dual t) | nil, _ => ⟨⟩ | node _ l _ r, ⟨rfl, sl, sr⟩ => ⟨by simp [size_dual, add_comm], Sized.dual sr, Sized.dual sl⟩ theorem Sized.dual_iff {t : Ordnode Ξ±} : Sized (.dual t) ↔ Sized t := ⟨fun h => by rw [← dual_dual t]; exact h.dual, Sized.dual⟩ theorem Sized.rotateL {l x r} (hl : @Sized Ξ± l) (hr : Sized r) : Sized (rotateL l x r) := by cases r; Β· exact hl.node' hr rw [Ordnode.rotateL_node]; split_ifs Β· exact hl.node3L hr.2.1 hr.2.2 Β· exact hl.node4L hr.2.1 hr.2.2 theorem Sized.rotateR {l x r} (hl : @Sized Ξ± l) (hr : Sized r) : Sized (rotateR l x r) := Sized.dual_iff.1 <| by rw [dual_rotateR]; exact hr.dual.rotateL hl.dual theorem Sized.rotateL_size {l x r} (hm : Sized r) : size (@Ordnode.rotateL Ξ± l x r) = size l + size r + 1 := by cases r <;> simp [Ordnode.rotateL] simp only [hm.1] split_ifs <;> simp [node3L_size, node4L_size hm.2.1] <;> abel theorem Sized.rotateR_size {l x r} (hl : Sized l) : size (@Ordnode.rotateR Ξ± l x r) = size l + size r + 1 := by rw [← size_dual, dual_rotateR, hl.dual.rotateL_size, size_dual, size_dual, add_comm (size l)] theorem Sized.balance' {l x r} (hl : @Sized Ξ± l) (hr : Sized r) : Sized (balance' l x r) := by unfold balance'; split_ifs Β· exact hl.node' hr Β· exact hl.rotateL hr Β· exact hl.rotateR hr Β· exact hl.node' hr theorem size_balance' {l x r} (hl : @Sized Ξ± l) (hr : Sized r) : size (@balance' Ξ± l x r) = size l + size r + 1 := by unfold balance'; split_ifs Β· rfl Β· exact hr.rotateL_size Β· exact hl.rotateR_size Β· rfl /-! ## `All`, `Any`, `Emem`, `Amem` -/ theorem All.imp {P Q : Ξ± β†’ Prop} (H : βˆ€ a, P a β†’ Q a) : βˆ€ {t}, All P t β†’ All Q t | nil, _ => ⟨⟩ | node _ _ _ _, ⟨h₁, hβ‚‚, hβ‚ƒβŸ© => ⟨h₁.imp H, H _ hβ‚‚, h₃.imp H⟩ theorem Any.imp {P Q : Ξ± β†’ Prop} (H : βˆ€ a, P a β†’ Q a) : βˆ€ {t}, Any P t β†’ Any Q t | nil => id | node _ _ _ _ => Or.imp (Any.imp H) <| Or.imp (H _) (Any.imp H) theorem all_singleton {P : Ξ± β†’ Prop} {x : Ξ±} : All P (singleton x) ↔ P x := ⟨fun h => h.2.1, fun h => ⟨⟨⟩, h, ⟨⟩⟩⟩ theorem any_singleton {P : Ξ± β†’ Prop} {x : Ξ±} : Any P (singleton x) ↔ P x := ⟨by rintro (⟨⟨⟩⟩ | h | ⟨⟨⟩⟩); exact h, fun h => Or.inr (Or.inl h)⟩ theorem all_dual {P : Ξ± β†’ Prop} : βˆ€ {t : Ordnode Ξ±}, All P (dual t) ↔ All P t | nil => Iff.rfl | node _ _l _x _r => ⟨fun ⟨hr, hx, hl⟩ => ⟨all_dual.1 hl, hx, all_dual.1 hr⟩, fun ⟨hl, hx, hr⟩ => ⟨all_dual.2 hr, hx, all_dual.2 hl⟩⟩ theorem all_iff_forall {P : Ξ± β†’ Prop} : βˆ€ {t}, All P t ↔ βˆ€ x, Emem x t β†’ P x | nil => (iff_true_intro <| by rintro _ ⟨⟩).symm | node _ l x r => by simp [All, Emem, all_iff_forall, Any, or_imp, forall_and] theorem any_iff_exists {P : Ξ± β†’ Prop} : βˆ€ {t}, Any P t ↔ βˆƒ x, Emem x t ∧ P x | nil => ⟨by rintro ⟨⟩, by rintro ⟨_, ⟨⟩, _⟩⟩ | node _ l x r => by simp only [Emem]; simp [Any, any_iff_exists, or_and_right, exists_or] theorem emem_iff_all {x : Ξ±} {t} : Emem x t ↔ βˆ€ P, All P t β†’ P x := ⟨fun h _ al => all_iff_forall.1 al _ h, fun H => H _ <| all_iff_forall.2 fun _ => id⟩ theorem all_node' {P l x r} : @All Ξ± P (node' l x r) ↔ All P l ∧ P x ∧ All P r := Iff.rfl theorem all_node3L {P l x m y r} : @All Ξ± P (node3L l x m y r) ↔ All P l ∧ P x ∧ All P m ∧ P y ∧ All P r := by simp [node3L, all_node', and_assoc] theorem all_node3R {P l x m y r} : @All Ξ± P (node3R l x m y r) ↔ All P l ∧ P x ∧ All P m ∧ P y ∧ All P r := Iff.rfl theorem all_node4L {P l x m y r} : @All Ξ± P (node4L l x m y r) ↔ All P l ∧ P x ∧ All P m ∧ P y ∧ All P r := by cases m <;> simp [node4L, all_node', All, all_node3L, and_assoc] theorem all_node4R {P l x m y r} : @All Ξ± P (node4R l x m y r) ↔ All P l ∧ P x ∧ All P m ∧ P y ∧ All P r := by cases m <;> simp [node4R, all_node', All, all_node3R, and_assoc] theorem all_rotateL {P l x r} : @All Ξ± P (rotateL l x r) ↔ All P l ∧ P x ∧ All P r := by cases r <;> simp [rotateL, all_node']; split_ifs <;> simp [all_node3L, all_node4L, All, and_assoc] theorem all_rotateR {P l x r} : @All Ξ± P (rotateR l x r) ↔ All P l ∧ P x ∧ All P r := by rw [← all_dual, dual_rotateR, all_rotateL]; simp [all_dual, and_comm, and_left_comm, and_assoc] theorem all_balance' {P l x r} : @All Ξ± P (balance' l x r) ↔ All P l ∧ P x ∧ All P r := by rw [balance']; split_ifs <;> simp [all_node', all_rotateL, all_rotateR] /-! ### `toList` -/ theorem foldr_cons_eq_toList : βˆ€ (t : Ordnode Ξ±) (r : List Ξ±), t.foldr List.cons r = toList t ++ r | nil, r => rfl | node _ l x r, r' => by rw [foldr, foldr_cons_eq_toList l, foldr_cons_eq_toList r, ← List.cons_append, ← List.append_assoc, ← foldr_cons_eq_toList l]; rfl @[simp] theorem toList_nil : toList (@nil Ξ±) = [] := rfl @[simp] theorem toList_node (s l x r) : toList (@node Ξ± s l x r) = toList l ++ x :: toList r := by rw [toList, foldr, foldr_cons_eq_toList]; rfl theorem emem_iff_mem_toList {x : Ξ±} {t} : Emem x t ↔ x ∈ toList t := by unfold Emem; induction t <;> simp [Any, *, or_assoc] theorem length_toList' : βˆ€ t : Ordnode Ξ±, (toList t).length = t.realSize | nil => rfl | node _ l _ r => by rw [toList_node, List.length_append, List.length_cons, length_toList' l, length_toList' r]; rfl theorem length_toList {t : Ordnode Ξ±} (h : Sized t) : (toList t).length = t.size := by rw [length_toList', size_eq_realSize h] theorem equiv_iff {t₁ tβ‚‚ : Ordnode Ξ±} (h₁ : Sized t₁) (hβ‚‚ : Sized tβ‚‚) : Equiv t₁ tβ‚‚ ↔ toList t₁ = toList tβ‚‚ := and_iff_right_of_imp fun h => by rw [← length_toList h₁, h, length_toList hβ‚‚] /-! ### `mem` -/ theorem pos_size_of_mem [LE Ξ±] [@DecidableRel Ξ± (Β· ≀ Β·)] {x : Ξ±} {t : Ordnode Ξ±} (h : Sized t) (h_mem : x ∈ t) : 0 < size t := by cases t; Β· { contradiction }; Β· { simp [h.1] } /-! ### `(find/erase/split)(Min/Max)` -/ theorem findMin'_dual : βˆ€ (t) (x : Ξ±), findMin' (dual t) x = findMax' x t | nil, _ => rfl | node _ _ x r, _ => findMin'_dual r x theorem findMax'_dual (t) (x : Ξ±) : findMax' x (dual t) = findMin' t x := by rw [← findMin'_dual, dual_dual] theorem findMin_dual : βˆ€ t : Ordnode Ξ±, findMin (dual t) = findMax t | nil => rfl | node _ _ _ _ => congr_arg some <| findMin'_dual _ _ theorem findMax_dual (t : Ordnode Ξ±) : findMax (dual t) = findMin t := by rw [← findMin_dual, dual_dual] theorem dual_eraseMin : βˆ€ t : Ordnode Ξ±, dual (eraseMin t) = eraseMax (dual t) | nil => rfl | node _ nil x r => rfl | node _ (node sz l' y r') x r => by rw [eraseMin, dual_balanceR, dual_eraseMin (node sz l' y r'), dual, dual, dual, eraseMax] theorem dual_eraseMax (t : Ordnode Ξ±) : dual (eraseMax t) = eraseMin (dual t) := by rw [← dual_dual (eraseMin _), dual_eraseMin, dual_dual] theorem splitMin_eq : βˆ€ (s l) (x : Ξ±) (r), splitMin' l x r = (findMin' l x, eraseMin (node s l x r)) | _, nil, x, r => rfl | _, node ls ll lx lr, x, r => by rw [splitMin', splitMin_eq ls ll lx lr, findMin', eraseMin] theorem splitMax_eq : βˆ€ (s l) (x : Ξ±) (r), splitMax' l x r = (eraseMax (node s l x r), findMax' x r) | _, l, x, nil => rfl | _, l, x, node ls ll lx lr => by rw [splitMax', splitMax_eq ls ll lx lr, findMax', eraseMax] -- @[elab_as_elim] -- Porting note: unexpected eliminator resulting type theorem findMin'_all {P : Ξ± β†’ Prop} : βˆ€ (t) (x : Ξ±), All P t β†’ P x β†’ P (findMin' t x) | nil, _x, _, hx => hx | node _ ll lx _, _, ⟨h₁, hβ‚‚, _⟩, _ => findMin'_all ll lx h₁ hβ‚‚ -- @[elab_as_elim] -- Porting note: unexpected eliminator resulting type theorem findMax'_all {P : Ξ± β†’ Prop} : βˆ€ (x : Ξ±) (t), P x β†’ All P t β†’ P (findMax' x t) | _x, nil, hx, _ => hx | _, node _ _ lx lr, _, ⟨_, hβ‚‚, hβ‚ƒβŸ© => findMax'_all lx lr hβ‚‚ h₃ /-! ### `glue` -/ /-! ### `merge` -/ @[simp] theorem merge_nil_left (t : Ordnode Ξ±) : merge t nil = t := by cases t <;> rfl @[simp] theorem merge_nil_right (t : Ordnode Ξ±) : merge nil t = t := rfl @[simp] theorem merge_node {ls ll lx lr rs rl rx rr} : merge (@node Ξ± ls ll lx lr) (node rs rl rx rr) = if delta * ls < rs then balanceL (merge (node ls ll lx lr) rl) rx rr else if delta * rs < ls then balanceR ll lx (merge lr (node rs rl rx rr)) else glue (node ls ll lx lr) (node rs rl rx rr) := rfl /-! ### `insert` -/ theorem dual_insert [Preorder Ξ±] [IsTotal Ξ± (Β· ≀ Β·)] [@DecidableRel Ξ± (Β· ≀ Β·)] (x : Ξ±) : βˆ€ t : Ordnode Ξ±, dual (Ordnode.insert x t) = @Ordnode.insert Ξ±α΅’α΅ˆ _ _ x (dual t) | nil => rfl | node _ l y r => by have : @cmpLE Ξ±α΅’α΅ˆ _ _ x y = cmpLE y x := rfl rw [Ordnode.insert, dual, Ordnode.insert, this, ← cmpLE_swap x y] cases cmpLE x y <;> simp [Ordering.swap, Ordnode.insert, dual_balanceL, dual_balanceR, dual_insert] /-! ### `balance` properties -/ theorem balance_eq_balance' {l x r} (hl : Balanced l) (hr : Balanced r) (sl : Sized l) (sr : Sized r) : @balance Ξ± l x r = balance' l x r := by cases' l with ls ll lx lr Β· cases' r with rs rl rx rr Β· rfl Β· rw [sr.eq_node'] at hr ⊒ cases' rl with rls rll rlx rlr <;> cases' rr with rrs rrl rrx rrr <;> dsimp [balance, balance'] Β· rfl Β· have : size rrl = 0 ∧ size rrr = 0 := by have := balancedSz_zero.1 hr.1.symm rwa [size, sr.2.2.1, Nat.succ_le_succ_iff, Nat.le_zero, add_eq_zero_iff] at this cases sr.2.2.2.1.size_eq_zero.1 this.1 cases sr.2.2.2.2.size_eq_zero.1 this.2 obtain rfl : rrs = 1 := sr.2.2.1 rw [if_neg, if_pos, rotateL_node, if_pos]; Β· rfl all_goals dsimp only [size]; decide Β· have : size rll = 0 ∧ size rlr = 0 := by have := balancedSz_zero.1 hr.1 rwa [size, sr.2.1.1, Nat.succ_le_succ_iff, Nat.le_zero, add_eq_zero_iff] at this cases sr.2.1.2.1.size_eq_zero.1 this.1 cases sr.2.1.2.2.size_eq_zero.1 this.2 obtain rfl : rls = 1 := sr.2.1.1 rw [if_neg, if_pos, rotateL_node, if_neg]; Β· rfl all_goals dsimp only [size]; decide Β· symm; rw [zero_add, if_neg, if_pos, rotateL] Β· dsimp only [size_node]; split_ifs Β· simp [node3L, node']; abel Β· simp [node4L, node', sr.2.1.1]; abel Β· apply Nat.zero_lt_succ Β· exact not_le_of_gt (Nat.succ_lt_succ (add_pos sr.2.1.pos sr.2.2.pos)) Β· cases' r with rs rl rx rr Β· rw [sl.eq_node'] at hl ⊒ cases' ll with lls lll llx llr <;> cases' lr with lrs lrl lrx lrr <;> dsimp [balance, balance'] Β· rfl Β· have : size lrl = 0 ∧ size lrr = 0 := by have := balancedSz_zero.1 hl.1.symm rwa [size, sl.2.2.1, Nat.succ_le_succ_iff, Nat.le_zero, add_eq_zero_iff] at this cases sl.2.2.2.1.size_eq_zero.1 this.1 cases sl.2.2.2.2.size_eq_zero.1 this.2 obtain rfl : lrs = 1 := sl.2.2.1 rw [if_neg, if_pos, rotateR_node, if_neg]; Β· rfl all_goals dsimp only [size]; decide Β· have : size lll = 0 ∧ size llr = 0 := by have := balancedSz_zero.1 hl.1 rwa [size, sl.2.1.1, Nat.succ_le_succ_iff, Nat.le_zero, add_eq_zero_iff] at this cases sl.2.1.2.1.size_eq_zero.1 this.1 cases sl.2.1.2.2.size_eq_zero.1 this.2 obtain rfl : lls = 1 := sl.2.1.1 rw [if_neg, if_pos, rotateR_node, if_pos]; Β· rfl all_goals dsimp only [size]; decide Β· symm; rw [if_neg, if_pos, rotateR] Β· dsimp only [size_node]; split_ifs Β· simp [node3R, node']; abel Β· simp [node4R, node', sl.2.2.1]; abel Β· apply Nat.zero_lt_succ Β· exact not_le_of_gt (Nat.succ_lt_succ (add_pos sl.2.1.pos sl.2.2.pos)) Β· simp [balance, balance'] symm; rw [if_neg] Β· split_ifs with h h_1 Β· have rd : delta ≀ size rl + size rr := by have := lt_of_le_of_lt (Nat.mul_le_mul_left _ sl.pos) h rwa [sr.1, Nat.lt_succ_iff] at this cases' rl with rls rll rlx rlr Β· rw [size, zero_add] at rd exact absurd (le_trans rd (balancedSz_zero.1 hr.1.symm)) (by decide) cases' rr with rrs rrl rrx rrr Β· exact absurd (le_trans rd (balancedSz_zero.1 hr.1)) (by decide) dsimp [rotateL]; split_ifs Β· simp [node3L, node', sr.1]; abel Β· simp [node4L, node', sr.1, sr.2.1.1]; abel Β· have ld : delta ≀ size ll + size lr := by have := lt_of_le_of_lt (Nat.mul_le_mul_left _ sr.pos) h_1 rwa [sl.1, Nat.lt_succ_iff] at this cases' ll with lls lll llx llr Β· rw [size, zero_add] at ld exact absurd (le_trans ld (balancedSz_zero.1 hl.1.symm)) (by decide) cases' lr with lrs lrl lrx lrr Β· exact absurd (le_trans ld (balancedSz_zero.1 hl.1)) (by decide) dsimp [rotateR]; split_ifs Β· simp [node3R, node', sl.1]; abel Β· simp [node4R, node', sl.1, sl.2.2.1]; abel Β· simp [node'] Β· exact not_le_of_gt (add_le_add (Nat.succ_le_of_lt sl.pos) (Nat.succ_le_of_lt sr.pos)) theorem balanceL_eq_balance {l x r} (sl : Sized l) (sr : Sized r) (H1 : size l = 0 β†’ size r ≀ 1) (H2 : 1 ≀ size l β†’ 1 ≀ size r β†’ size r ≀ delta * size l) : @balanceL Ξ± l x r = balance l x r := by cases' r with rs rl rx rr Β· rfl Β· cases' l with ls ll lx lr Β· have : size rl = 0 ∧ size rr = 0 := by have := H1 rfl rwa [size, sr.1, Nat.succ_le_succ_iff, Nat.le_zero, add_eq_zero_iff] at this cases sr.2.1.size_eq_zero.1 this.1 cases sr.2.2.size_eq_zero.1 this.2 rw [sr.eq_node']; rfl Β· replace H2 : Β¬rs > delta * ls := not_lt_of_le (H2 sl.pos sr.pos) simp [balanceL, balance, H2]; split_ifs <;> simp [add_comm] /-- `Raised n m` means `m` is either equal or one up from `n`. -/ def Raised (n m : β„•) : Prop := m = n ∨ m = n + 1 theorem raised_iff {n m} : Raised n m ↔ n ≀ m ∧ m ≀ n + 1 := by constructor Β· rintro (rfl | rfl) Β· exact ⟨le_rfl, Nat.le_succ _⟩ Β· exact ⟨Nat.le_succ _, le_rfl⟩ Β· rintro ⟨h₁, hβ‚‚βŸ© rcases eq_or_lt_of_le h₁ with (rfl | h₁) Β· exact Or.inl rfl Β· exact Or.inr (le_antisymm hβ‚‚ h₁) theorem Raised.dist_le {n m} (H : Raised n m) : Nat.dist n m ≀ 1 := by cases' raised_iff.1 H with H1 H2; rwa [Nat.dist_eq_sub_of_le H1, tsub_le_iff_left] theorem Raised.dist_le' {n m} (H : Raised n m) : Nat.dist m n ≀ 1 := by rw [Nat.dist_comm]; exact H.dist_le theorem Raised.add_left (k) {n m} (H : Raised n m) : Raised (k + n) (k + m) := by rcases H with (rfl | rfl) Β· exact Or.inl rfl Β· exact Or.inr rfl theorem Raised.add_right (k) {n m} (H : Raised n m) : Raised (n + k) (m + k) := by rw [add_comm, add_comm m]; exact H.add_left _ theorem Raised.right {l x₁ xβ‚‚ r₁ rβ‚‚} (H : Raised (size r₁) (size rβ‚‚)) : Raised (size (@node' Ξ± l x₁ r₁)) (size (@node' Ξ± l xβ‚‚ rβ‚‚)) := by rw [node', size_node, size_node]; generalize size rβ‚‚ = m at H ⊒ rcases H with (rfl | rfl) Β· exact Or.inl rfl Β· exact Or.inr rfl theorem balanceL_eq_balance' {l x r} (hl : Balanced l) (hr : Balanced r) (sl : Sized l) (sr : Sized r) (H : (βˆƒ l', Raised l' (size l) ∧ BalancedSz l' (size r)) ∨ βˆƒ r', Raised (size r) r' ∧ BalancedSz (size l) r') : @balanceL Ξ± l x r = balance' l x r := by rw [← balance_eq_balance' hl hr sl sr, balanceL_eq_balance sl sr] Β· intro l0; rw [l0] at H rcases H with (⟨_, ⟨⟨⟩⟩ | ⟨⟨⟩⟩, H⟩ | ⟨r', e, H⟩) Β· exact balancedSz_zero.1 H.symm exact le_trans (raised_iff.1 e).1 (balancedSz_zero.1 H.symm) Β· intro l1 _ rcases H with (⟨l', e, H | ⟨_, Hβ‚‚βŸ©βŸ© | ⟨r', e, H | ⟨_, Hβ‚‚βŸ©βŸ©) Β· exact le_trans (le_trans (Nat.le_add_left _ _) H) (mul_pos (by decide) l1 : (0 : β„•) < _) Β· exact le_trans Hβ‚‚ (Nat.mul_le_mul_left _ (raised_iff.1 e).1) Β· cases raised_iff.1 e; unfold delta; omega Β· exact le_trans (raised_iff.1 e).1 Hβ‚‚ theorem balance_sz_dual {l r} (H : (βˆƒ l', Raised (@size Ξ± l) l' ∧ BalancedSz l' (@size Ξ± r)) ∨ βˆƒ r', Raised r' (size r) ∧ BalancedSz (size l) r') : (βˆƒ l', Raised l' (size (dual r)) ∧ BalancedSz l' (size (dual l))) ∨ βˆƒ r', Raised (size (dual l)) r' ∧ BalancedSz (size (dual r)) r' := by rw [size_dual, size_dual] exact H.symm.imp (Exists.imp fun _ => And.imp_right BalancedSz.symm) (Exists.imp fun _ => And.imp_right BalancedSz.symm) theorem size_balanceL {l x r} (hl : Balanced l) (hr : Balanced r) (sl : Sized l) (sr : Sized r) (H : (βˆƒ l', Raised l' (size l) ∧ BalancedSz l' (size r)) ∨ βˆƒ r', Raised (size r) r' ∧ BalancedSz (size l) r') : size (@balanceL Ξ± l x r) = size l + size r + 1 := by rw [balanceL_eq_balance' hl hr sl sr H, size_balance' sl sr] theorem all_balanceL {P l x r} (hl : Balanced l) (hr : Balanced r) (sl : Sized l) (sr : Sized r) (H : (βˆƒ l', Raised l' (size l) ∧ BalancedSz l' (size r)) ∨ βˆƒ r', Raised (size r) r' ∧ BalancedSz (size l) r') : All P (@balanceL Ξ± l x r) ↔ All P l ∧ P x ∧ All P r := by rw [balanceL_eq_balance' hl hr sl sr H, all_balance'] theorem balanceR_eq_balance' {l x r} (hl : Balanced l) (hr : Balanced r) (sl : Sized l) (sr : Sized r) (H : (βˆƒ l', Raised (size l) l' ∧ BalancedSz l' (size r)) ∨ βˆƒ r', Raised r' (size r) ∧ BalancedSz (size l) r') : @balanceR Ξ± l x r = balance' l x r := by rw [← dual_dual (balanceR l x r), dual_balanceR, balanceL_eq_balance' hr.dual hl.dual sr.dual sl.dual (balance_sz_dual H), ← dual_balance', dual_dual] theorem size_balanceR {l x r} (hl : Balanced l) (hr : Balanced r) (sl : Sized l) (sr : Sized r) (H : (βˆƒ l', Raised (size l) l' ∧ BalancedSz l' (size r)) ∨ βˆƒ r', Raised r' (size r) ∧ BalancedSz (size l) r') : size (@balanceR Ξ± l x r) = size l + size r + 1 := by rw [balanceR_eq_balance' hl hr sl sr H, size_balance' sl sr] theorem all_balanceR {P l x r} (hl : Balanced l) (hr : Balanced r) (sl : Sized l) (sr : Sized r) (H : (βˆƒ l', Raised (size l) l' ∧ BalancedSz l' (size r)) ∨ βˆƒ r', Raised r' (size r) ∧ BalancedSz (size l) r') : All P (@balanceR Ξ± l x r) ↔ All P l ∧ P x ∧ All P r := by rw [balanceR_eq_balance' hl hr sl sr H, all_balance'] /-! ### `bounded` -/ section variable [Preorder Ξ±] /-- `Bounded t lo hi` says that every element `x ∈ t` is in the range `lo < x < hi`, and also this property holds recursively in subtrees, making the full tree a BST. The bounds can be set to `lo = βŠ₯` and `hi = ⊀` if we care only about the internal ordering constraints. -/ def Bounded : Ordnode Ξ± β†’ WithBot Ξ± β†’ WithTop Ξ± β†’ Prop | nil, some a, some b => a < b | nil, _, _ => True | node _ l x r, o₁, oβ‚‚ => Bounded l o₁ x ∧ Bounded r (↑x) oβ‚‚ theorem Bounded.dual : βˆ€ {t : Ordnode Ξ±} {o₁ oβ‚‚}, Bounded t o₁ oβ‚‚ β†’ @Bounded Ξ±α΅’α΅ˆ _ (dual t) oβ‚‚ o₁ | nil, o₁, oβ‚‚, h => by cases o₁ <;> cases oβ‚‚ <;> trivial | node _ l x r, _, _, ⟨ol, Or⟩ => ⟨Or.dual, ol.dual⟩ theorem Bounded.dual_iff {t : Ordnode Ξ±} {o₁ oβ‚‚} : Bounded t o₁ oβ‚‚ ↔ @Bounded Ξ±α΅’α΅ˆ _ (.dual t) oβ‚‚ o₁ := ⟨Bounded.dual, fun h => by have := Bounded.dual h; rwa [dual_dual, OrderDual.Preorder.dual_dual] at this⟩ theorem Bounded.weak_left : βˆ€ {t : Ordnode Ξ±} {o₁ oβ‚‚}, Bounded t o₁ oβ‚‚ β†’ Bounded t βŠ₯ oβ‚‚ | nil, o₁, oβ‚‚, h => by cases oβ‚‚ <;> trivial | node _ l x r, _, _, ⟨ol, Or⟩ => ⟨ol.weak_left, Or⟩ theorem Bounded.weak_right : βˆ€ {t : Ordnode Ξ±} {o₁ oβ‚‚}, Bounded t o₁ oβ‚‚ β†’ Bounded t o₁ ⊀ | nil, o₁, oβ‚‚, h => by cases o₁ <;> trivial | node _ l x r, _, _, ⟨ol, Or⟩ => ⟨ol, Or.weak_right⟩ theorem Bounded.weak {t : Ordnode Ξ±} {o₁ oβ‚‚} (h : Bounded t o₁ oβ‚‚) : Bounded t βŠ₯ ⊀ := h.weak_left.weak_right theorem Bounded.mono_left {x y : Ξ±} (xy : x ≀ y) : βˆ€ {t : Ordnode Ξ±} {o}, Bounded t y o β†’ Bounded t x o | nil, none, _ => ⟨⟩ | nil, some _, h => lt_of_le_of_lt xy h | node _ _ _ _, _o, ⟨ol, or⟩ => ⟨ol.mono_left xy, or⟩ theorem Bounded.mono_right {x y : Ξ±} (xy : x ≀ y) : βˆ€ {t : Ordnode Ξ±} {o}, Bounded t o x β†’ Bounded t o y | nil, none, _ => ⟨⟩ | nil, some _, h => lt_of_lt_of_le h xy | node _ _ _ _, _o, ⟨ol, or⟩ => ⟨ol, or.mono_right xy⟩ theorem Bounded.to_lt : βˆ€ {t : Ordnode Ξ±} {x y : Ξ±}, Bounded t x y β†’ x < y | nil, _, _, h => h | node _ _ _ _, _, _, ⟨h₁, hβ‚‚βŸ© => lt_trans h₁.to_lt hβ‚‚.to_lt theorem Bounded.to_nil {t : Ordnode Ξ±} : βˆ€ {o₁ oβ‚‚}, Bounded t o₁ oβ‚‚ β†’ Bounded nil o₁ oβ‚‚ | none, _, _ => ⟨⟩ | some _, none, _ => ⟨⟩ | some _, some _, h => h.to_lt theorem Bounded.trans_left {t₁ tβ‚‚ : Ordnode Ξ±} {x : Ξ±} : βˆ€ {o₁ oβ‚‚}, Bounded t₁ o₁ x β†’ Bounded tβ‚‚ x oβ‚‚ β†’ Bounded tβ‚‚ o₁ oβ‚‚ | none, _, _, hβ‚‚ => hβ‚‚.weak_left | some _, _, h₁, hβ‚‚ => hβ‚‚.mono_left (le_of_lt h₁.to_lt) theorem Bounded.trans_right {t₁ tβ‚‚ : Ordnode Ξ±} {x : Ξ±} : βˆ€ {o₁ oβ‚‚}, Bounded t₁ o₁ x β†’ Bounded tβ‚‚ x oβ‚‚ β†’ Bounded t₁ o₁ oβ‚‚ | _, none, h₁, _ => h₁.weak_right | _, some _, h₁, hβ‚‚ => h₁.mono_right (le_of_lt hβ‚‚.to_lt) theorem Bounded.mem_lt : βˆ€ {t o} {x : Ξ±}, Bounded t o x β†’ All (Β· < x) t | nil, _, _, _ => ⟨⟩ | node _ _ _ _, _, _, ⟨h₁, hβ‚‚βŸ© => ⟨h₁.mem_lt.imp fun _ h => lt_trans h hβ‚‚.to_lt, hβ‚‚.to_lt, hβ‚‚.mem_lt⟩ theorem Bounded.mem_gt : βˆ€ {t o} {x : Ξ±}, Bounded t x o β†’ All (Β· > x) t | nil, _, _, _ => ⟨⟩ | node _ _ _ _, _, _, ⟨h₁, hβ‚‚βŸ© => ⟨h₁.mem_gt, h₁.to_lt, hβ‚‚.mem_gt.imp fun _ => lt_trans h₁.to_lt⟩ theorem Bounded.of_lt : βˆ€ {t o₁ oβ‚‚} {x : Ξ±}, Bounded t o₁ oβ‚‚ β†’ Bounded nil o₁ x β†’ All (Β· < x) t β†’ Bounded t o₁ x | nil, _, _, _, _, hn, _ => hn | node _ _ _ _, _, _, _, ⟨h₁, hβ‚‚βŸ©, _, ⟨_, alβ‚‚, alβ‚ƒβŸ© => ⟨h₁, hβ‚‚.of_lt alβ‚‚ alβ‚ƒβŸ© theorem Bounded.of_gt : βˆ€ {t o₁ oβ‚‚} {x : Ξ±}, Bounded t o₁ oβ‚‚ β†’ Bounded nil x oβ‚‚ β†’ All (Β· > x) t β†’ Bounded t x oβ‚‚ | nil, _, _, _, _, hn, _ => hn | node _ _ _ _, _, _, _, ⟨h₁, hβ‚‚βŸ©, _, ⟨al₁, alβ‚‚, _⟩ => ⟨h₁.of_gt alβ‚‚ al₁, hβ‚‚βŸ© theorem Bounded.to_sep {t₁ tβ‚‚ o₁ oβ‚‚} {x : Ξ±} (h₁ : Bounded t₁ o₁ (x : WithTop Ξ±)) (hβ‚‚ : Bounded tβ‚‚ (x : WithBot Ξ±) oβ‚‚) : t₁.All fun y => tβ‚‚.All fun z : Ξ± => y < z := by refine h₁.mem_lt.imp fun y yx => ?_ exact hβ‚‚.mem_gt.imp fun z xz => lt_trans yx xz end /-! ### `Valid` -/ section variable [Preorder Ξ±] /-- The validity predicate for an `Ordnode` subtree. This asserts that the `size` fields are correct, the tree is balanced, and the elements of the tree are organized according to the ordering. This version of `Valid` also puts all elements in the tree in the interval `(lo, hi)`. -/ structure Valid' (lo : WithBot Ξ±) (t : Ordnode Ξ±) (hi : WithTop Ξ±) : Prop where ord : t.Bounded lo hi sz : t.Sized bal : t.Balanced /-- The validity predicate for an `Ordnode` subtree. This asserts that the `size` fields are correct, the tree is balanced, and the elements of the tree are organized according to the ordering. -/ def Valid (t : Ordnode Ξ±) : Prop := Valid' βŠ₯ t ⊀ theorem Valid'.mono_left {x y : Ξ±} (xy : x ≀ y) {t : Ordnode Ξ±} {o} (h : Valid' y t o) : Valid' x t o := ⟨h.1.mono_left xy, h.2, h.3⟩ theorem Valid'.mono_right {x y : Ξ±} (xy : x ≀ y) {t : Ordnode Ξ±} {o} (h : Valid' o t x) : Valid' o t y := ⟨h.1.mono_right xy, h.2, h.3⟩ theorem Valid'.trans_left {t₁ tβ‚‚ : Ordnode Ξ±} {x : Ξ±} {o₁ oβ‚‚} (h : Bounded t₁ o₁ x) (H : Valid' x tβ‚‚ oβ‚‚) : Valid' o₁ tβ‚‚ oβ‚‚ := ⟨h.trans_left H.1, H.2, H.3⟩ theorem Valid'.trans_right {t₁ tβ‚‚ : Ordnode Ξ±} {x : Ξ±} {o₁ oβ‚‚} (H : Valid' o₁ t₁ x) (h : Bounded tβ‚‚ x oβ‚‚) : Valid' o₁ t₁ oβ‚‚ := ⟨H.1.trans_right h, H.2, H.3⟩ theorem Valid'.of_lt {t : Ordnode Ξ±} {x : Ξ±} {o₁ oβ‚‚} (H : Valid' o₁ t oβ‚‚) (h₁ : Bounded nil o₁ x) (hβ‚‚ : All (Β· < x) t) : Valid' o₁ t x := ⟨H.1.of_lt h₁ hβ‚‚, H.2, H.3⟩ theorem Valid'.of_gt {t : Ordnode Ξ±} {x : Ξ±} {o₁ oβ‚‚} (H : Valid' o₁ t oβ‚‚) (h₁ : Bounded nil x oβ‚‚) (hβ‚‚ : All (Β· > x) t) : Valid' x t oβ‚‚ := ⟨H.1.of_gt h₁ hβ‚‚, H.2, H.3⟩ theorem Valid'.valid {t o₁ oβ‚‚} (h : @Valid' Ξ± _ o₁ t oβ‚‚) : Valid t := ⟨h.1.weak, h.2, h.3⟩ theorem valid'_nil {o₁ oβ‚‚} (h : Bounded nil o₁ oβ‚‚) : Valid' o₁ (@nil Ξ±) oβ‚‚ := ⟨h, ⟨⟩, ⟨⟩⟩ theorem valid_nil : Valid (@nil Ξ±) := valid'_nil ⟨⟩ theorem Valid'.node {s l} {x : Ξ±} {r o₁ oβ‚‚} (hl : Valid' o₁ l x) (hr : Valid' x r oβ‚‚) (H : BalancedSz (size l) (size r)) (hs : s = size l + size r + 1) : Valid' o₁ (@node Ξ± s l x r) oβ‚‚ := ⟨⟨hl.1, hr.1⟩, ⟨hs, hl.2, hr.2⟩, ⟨H, hl.3, hr.3⟩⟩ theorem Valid'.dual : βˆ€ {t : Ordnode Ξ±} {o₁ oβ‚‚}, Valid' o₁ t oβ‚‚ β†’ @Valid' Ξ±α΅’α΅ˆ _ oβ‚‚ (dual t) o₁ | .nil, o₁, oβ‚‚, h => valid'_nil h.1.dual | .node _ l x r, o₁, oβ‚‚, ⟨⟨ol, Or⟩, ⟨rfl, sl, sr⟩, ⟨b, bl, br⟩⟩ => let ⟨ol', sl', bl'⟩ := Valid'.dual ⟨ol, sl, bl⟩ let ⟨or', sr', br'⟩ := Valid'.dual ⟨Or, sr, br⟩ ⟨⟨or', ol'⟩, ⟨by simp [size_dual, add_comm], sr', sl'⟩, ⟨by rw [size_dual, size_dual]; exact b.symm, br', bl'⟩⟩ theorem Valid'.dual_iff {t : Ordnode Ξ±} {o₁ oβ‚‚} : Valid' o₁ t oβ‚‚ ↔ @Valid' Ξ±α΅’α΅ˆ _ oβ‚‚ (.dual t) o₁ := ⟨Valid'.dual, fun h => by have := Valid'.dual h; rwa [dual_dual, OrderDual.Preorder.dual_dual] at this⟩ theorem Valid.dual {t : Ordnode Ξ±} : Valid t β†’ @Valid Ξ±α΅’α΅ˆ _ (.dual t) := Valid'.dual theorem Valid.dual_iff {t : Ordnode Ξ±} : Valid t ↔ @Valid Ξ±α΅’α΅ˆ _ (.dual t) := Valid'.dual_iff theorem Valid'.left {s l x r o₁ oβ‚‚} (H : Valid' o₁ (@Ordnode.node Ξ± s l x r) oβ‚‚) : Valid' o₁ l x := ⟨H.1.1, H.2.2.1, H.3.2.1⟩ theorem Valid'.right {s l x r o₁ oβ‚‚} (H : Valid' o₁ (@Ordnode.node Ξ± s l x r) oβ‚‚) : Valid' x r oβ‚‚ := ⟨H.1.2, H.2.2.2, H.3.2.2⟩ nonrec theorem Valid.left {s l x r} (H : Valid (@node Ξ± s l x r)) : Valid l := H.left.valid nonrec theorem Valid.right {s l x r} (H : Valid (@node Ξ± s l x r)) : Valid r := H.right.valid theorem Valid.size_eq {s l x r} (H : Valid (@node Ξ± s l x r)) : size (@node Ξ± s l x r) = size l + size r + 1 := H.2.1 theorem Valid'.node' {l} {x : Ξ±} {r o₁ oβ‚‚} (hl : Valid' o₁ l x) (hr : Valid' x r oβ‚‚) (H : BalancedSz (size l) (size r)) : Valid' o₁ (@node' Ξ± l x r) oβ‚‚ := hl.node hr H rfl theorem valid'_singleton {x : Ξ±} {o₁ oβ‚‚} (h₁ : Bounded nil o₁ x) (hβ‚‚ : Bounded nil x oβ‚‚) : Valid' o₁ (singleton x : Ordnode Ξ±) oβ‚‚ := (valid'_nil h₁).node (valid'_nil hβ‚‚) (Or.inl zero_le_one) rfl theorem valid_singleton {x : Ξ±} : Valid (singleton x : Ordnode Ξ±) := valid'_singleton ⟨⟩ ⟨⟩ theorem Valid'.node3L {l} {x : Ξ±} {m} {y : Ξ±} {r o₁ oβ‚‚} (hl : Valid' o₁ l x) (hm : Valid' x m y) (hr : Valid' y r oβ‚‚) (H1 : BalancedSz (size l) (size m)) (H2 : BalancedSz (size l + size m + 1) (size r)) : Valid' o₁ (@node3L Ξ± l x m y r) oβ‚‚ := (hl.node' hm H1).node' hr H2 theorem Valid'.node3R {l} {x : Ξ±} {m} {y : Ξ±} {r o₁ oβ‚‚} (hl : Valid' o₁ l x) (hm : Valid' x m y) (hr : Valid' y r oβ‚‚) (H1 : BalancedSz (size l) (size m + size r + 1)) (H2 : BalancedSz (size m) (size r)) : Valid' o₁ (@node3R Ξ± l x m y r) oβ‚‚ := hl.node' (hm.node' hr H2) H1 theorem Valid'.node4L_lemma₁ {a b c d : β„•} (lrβ‚‚ : 3 * (b + c + 1 + d) ≀ 16 * a + 9) (mrβ‚‚ : b + c + 1 ≀ 3 * d) (mm₁ : b ≀ 3 * c) : b < 3 * a + 1 := by omega theorem Valid'.node4L_lemmaβ‚‚ {b c d : β„•} (mrβ‚‚ : b + c + 1 ≀ 3 * d) : c ≀ 3 * d := by omega theorem Valid'.node4L_lemma₃ {b c d : β„•} (mr₁ : 2 * d ≀ b + c + 1) (mm₁ : b ≀ 3 * c) : d ≀ 3 * c := by omega theorem Valid'.node4L_lemmaβ‚„ {a b c d : β„•} (lr₁ : 3 * a ≀ b + c + 1 + d) (mrβ‚‚ : b + c + 1 ≀ 3 * d) (mm₁ : b ≀ 3 * c) : a + b + 1 ≀ 3 * (c + d + 1) := by omega theorem Valid'.node4L_lemmaβ‚… {a b c d : β„•} (lrβ‚‚ : 3 * (b + c + 1 + d) ≀ 16 * a + 9) (mr₁ : 2 * d ≀ b + c + 1) (mmβ‚‚ : c ≀ 3 * b) : c + d + 1 ≀ 3 * (a + b + 1) := by omega theorem Valid'.node4L {l} {x : Ξ±} {m} {y : Ξ±} {r o₁ oβ‚‚} (hl : Valid' o₁ l x) (hm : Valid' x m y) (hr : Valid' (↑y) r oβ‚‚) (Hm : 0 < size m) (H : size l = 0 ∧ size m = 1 ∧ size r ≀ 1 ∨ 0 < size l ∧ ratio * size r ≀ size m ∧ delta * size l ≀ size m + size r ∧ 3 * (size m + size r) ≀ 16 * size l + 9 ∧ size m ≀ delta * size r) : Valid' o₁ (@node4L Ξ± l x m y r) oβ‚‚ := by cases' m with s ml z mr; Β· cases Hm suffices BalancedSz (size l) (size ml) ∧ BalancedSz (size mr) (size r) ∧ BalancedSz (size l + size ml + 1) (size mr + size r + 1) from Valid'.node' (hl.node' hm.left this.1) (hm.right.node' hr this.2.1) this.2.2 rcases H with (⟨l0, m1, r0⟩ | ⟨l0, mr₁, lr₁, lrβ‚‚, mrβ‚‚βŸ©) Β· rw [hm.2.size_eq, Nat.succ_inj', add_eq_zero_iff] at m1 rw [l0, m1.1, m1.2]; revert r0; rcases size r with (_ | _ | _) <;> [decide; decide; (intro r0; unfold BalancedSz delta; omega)] Β· rcases Nat.eq_zero_or_pos (size r) with r0 | r0 Β· rw [r0] at mrβ‚‚; cases not_le_of_lt Hm mrβ‚‚ rw [hm.2.size_eq] at lr₁ lrβ‚‚ mr₁ mrβ‚‚ by_cases mm : size ml + size mr ≀ 1 Β· have r1 := le_antisymm ((mul_le_mul_left (by decide)).1 (le_trans mr₁ (Nat.succ_le_succ mm) : _ ≀ ratio * 1)) r0 rw [r1, add_assoc] at lr₁ have l1 := le_antisymm ((mul_le_mul_left (by decide)).1 (le_trans lr₁ (add_le_add_right mm 2) : _ ≀ delta * 1)) l0 rw [l1, r1] revert mm; cases size ml <;> cases size mr <;> intro mm Β· decide Β· rw [zero_add] at mm; rcases mm with (_ | ⟨⟨⟩⟩) decide Β· rcases mm with (_ | ⟨⟨⟩⟩); decide Β· rw [Nat.succ_add] at mm; rcases mm with (_ | ⟨⟨⟩⟩) rcases hm.3.1.resolve_left mm with ⟨mm₁, mmβ‚‚βŸ© rcases Nat.eq_zero_or_pos (size ml) with ml0 | ml0 Β· rw [ml0, mul_zero, Nat.le_zero] at mmβ‚‚ rw [ml0, mmβ‚‚] at mm; cases mm (by decide) have : 2 * size l ≀ size ml + size mr + 1 := by have := Nat.mul_le_mul_left ratio lr₁ rw [mul_left_comm, mul_add] at this have := le_trans this (add_le_add_left mr₁ _) rw [← Nat.succ_mul] at this exact (mul_le_mul_left (by decide)).1 this refine ⟨Or.inr ⟨?_, ?_⟩, Or.inr ⟨?_, ?_⟩, Or.inr ⟨?_, ?_⟩⟩ Β· refine (mul_le_mul_left (by decide)).1 (le_trans this ?_) rw [two_mul, Nat.succ_le_iff] refine add_lt_add_of_lt_of_le ?_ mmβ‚‚ simpa using (mul_lt_mul_right ml0).2 (by decide : 1 < 3) Β· exact Nat.le_of_lt_succ (Valid'.node4L_lemma₁ lrβ‚‚ mrβ‚‚ mm₁) Β· exact Valid'.node4L_lemmaβ‚‚ mrβ‚‚ Β· exact Valid'.node4L_lemma₃ mr₁ mm₁ Β· exact Valid'.node4L_lemmaβ‚„ lr₁ mrβ‚‚ mm₁ Β· exact Valid'.node4L_lemmaβ‚… lrβ‚‚ mr₁ mmβ‚‚ theorem Valid'.rotateL_lemma₁ {a b c : β„•} (H2 : 3 * a ≀ b + c) (hbβ‚‚ : c ≀ 3 * b) : a ≀ 3 * b := by omega theorem Valid'.rotateL_lemmaβ‚‚ {a b c : β„•} (H3 : 2 * (b + c) ≀ 9 * a + 3) (h : b < 2 * c) : b < 3 * a + 1 := by omega theorem Valid'.rotateL_lemma₃ {a b c : β„•} (H2 : 3 * a ≀ b + c) (h : b < 2 * c) : a + b < 3 * c := by omega theorem Valid'.rotateL_lemmaβ‚„ {a b : β„•} (H3 : 2 * b ≀ 9 * a + 3) : 3 * b ≀ 16 * a + 9 := by omega theorem Valid'.rotateL {l} {x : Ξ±} {r o₁ oβ‚‚} (hl : Valid' o₁ l x) (hr : Valid' x r oβ‚‚) (H1 : Β¬size l + size r ≀ 1) (H2 : delta * size l < size r) (H3 : 2 * size r ≀ 9 * size l + 5 ∨ size r ≀ 3) : Valid' o₁ (@rotateL Ξ± l x r) oβ‚‚ := by cases' r with rs rl rx rr; Β· cases H2 rw [hr.2.size_eq, Nat.lt_succ_iff] at H2 rw [hr.2.size_eq] at H3 replace H3 : 2 * (size rl + size rr) ≀ 9 * size l + 3 ∨ size rl + size rr ≀ 2 := H3.imp (@Nat.le_of_add_le_add_right _ 2 _) Nat.le_of_succ_le_succ have H3_0 : size l = 0 β†’ size rl + size rr ≀ 2 := by intro l0; rw [l0] at H3 exact (or_iff_right_of_imp fun h => (mul_le_mul_left (by decide)).1 (le_trans h (by decide))).1 H3 have H3p : size l > 0 β†’ 2 * (size rl + size rr) ≀ 9 * size l + 3 := fun l0 : 1 ≀ size l => (or_iff_left_of_imp <| by omega).1 H3 have ablem : βˆ€ {a b : β„•}, 1 ≀ a β†’ a + b ≀ 2 β†’ b ≀ 1 := by omega have hlp : size l > 0 β†’ Β¬size rl + size rr ≀ 1 := fun l0 hb => absurd (le_trans (le_trans (Nat.mul_le_mul_left _ l0) H2) hb) (by decide) rw [Ordnode.rotateL_node]; split_ifs with h Β· have rr0 : size rr > 0 := (mul_lt_mul_left (by decide)).1 (lt_of_le_of_lt (Nat.zero_le _) h : ratio * 0 < _) suffices BalancedSz (size l) (size rl) ∧ BalancedSz (size l + size rl + 1) (size rr) by exact hl.node3L hr.left hr.right this.1 this.2 rcases Nat.eq_zero_or_pos (size l) with l0 | l0 Β· rw [l0]; replace H3 := H3_0 l0 have := hr.3.1 rcases Nat.eq_zero_or_pos (size rl) with rl0 | rl0 Β· rw [rl0] at this ⊒ rw [le_antisymm (balancedSz_zero.1 this.symm) rr0] decide have rr1 : size rr = 1 := le_antisymm (ablem rl0 H3) rr0 rw [add_comm] at H3 rw [rr1, show size rl = 1 from le_antisymm (ablem rr0 H3) rl0] decide replace H3 := H3p l0 rcases hr.3.1.resolve_left (hlp l0) with ⟨_, hbβ‚‚βŸ© refine ⟨Or.inr ⟨?_, ?_⟩, Or.inr ⟨?_, ?_⟩⟩ Β· exact Valid'.rotateL_lemma₁ H2 hbβ‚‚ Β· exact Nat.le_of_lt_succ (Valid'.rotateL_lemmaβ‚‚ H3 h) Β· exact Valid'.rotateL_lemma₃ H2 h Β· exact le_trans hbβ‚‚ (Nat.mul_le_mul_left _ <| le_trans (Nat.le_add_left _ _) (Nat.le_add_right _ _)) Β· rcases Nat.eq_zero_or_pos (size rl) with rl0 | rl0 Β· rw [rl0, not_lt, Nat.le_zero, Nat.mul_eq_zero] at h replace h := h.resolve_left (by decide) erw [rl0, h, Nat.le_zero, Nat.mul_eq_zero] at H2 rw [hr.2.size_eq, rl0, h, H2.resolve_left (by decide)] at H1 cases H1 (by decide) refine hl.node4L hr.left hr.right rl0 ?_ rcases Nat.eq_zero_or_pos (size l) with l0 | l0 Β· replace H3 := H3_0 l0 rcases Nat.eq_zero_or_pos (size rr) with rr0 | rr0 Β· have := hr.3.1 rw [rr0] at this exact Or.inl ⟨l0, le_antisymm (balancedSz_zero.1 this) rl0, rr0.symm β–Έ zero_le_one⟩ exact Or.inl ⟨l0, le_antisymm (ablem rr0 <| by rwa [add_comm]) rl0, ablem rl0 H3⟩ exact Or.inr ⟨l0, not_lt.1 h, H2, Valid'.rotateL_lemmaβ‚„ (H3p l0), (hr.3.1.resolve_left (hlp l0)).1⟩ theorem Valid'.rotateR {l} {x : Ξ±} {r o₁ oβ‚‚} (hl : Valid' o₁ l x) (hr : Valid' x r oβ‚‚) (H1 : Β¬size l + size r ≀ 1) (H2 : delta * size r < size l) (H3 : 2 * size l ≀ 9 * size r + 5 ∨ size l ≀ 3) : Valid' o₁ (@rotateR Ξ± l x r) oβ‚‚ := by refine Valid'.dual_iff.2 ?_ rw [dual_rotateR] refine hr.dual.rotateL hl.dual ?_ ?_ ?_ Β· rwa [size_dual, size_dual, add_comm] Β· rwa [size_dual, size_dual] Β· rwa [size_dual, size_dual] theorem Valid'.balance'_aux {l} {x : Ξ±} {r o₁ oβ‚‚} (hl : Valid' o₁ l x) (hr : Valid' x r oβ‚‚) (H₁ : 2 * @size Ξ± r ≀ 9 * size l + 5 ∨ size r ≀ 3) (Hβ‚‚ : 2 * @size Ξ± l ≀ 9 * size r + 5 ∨ size l ≀ 3) : Valid' o₁ (@balance' Ξ± l x r) oβ‚‚ := by rw [balance']; split_ifs with h h_1 h_2 Β· exact hl.node' hr (Or.inl h) Β· exact hl.rotateL hr h h_1 H₁ Β· exact hl.rotateR hr h h_2 Hβ‚‚ Β· exact hl.node' hr (Or.inr ⟨not_lt.1 h_2, not_lt.1 h_1⟩) theorem Valid'.balance'_lemma {Ξ± l l' r r'} (H1 : BalancedSz l' r') (H2 : Nat.dist (@size Ξ± l) l' ≀ 1 ∧ size r = r' ∨ Nat.dist (size r) r' ≀ 1 ∧ size l = l') : 2 * @size Ξ± r ≀ 9 * size l + 5 ∨ size r ≀ 3 := by suffices @size Ξ± r ≀ 3 * (size l + 1) by rcases Nat.eq_zero_or_pos (size l) with l0 | l0 Β· apply Or.inr; rwa [l0] at this change 1 ≀ _ at l0; apply Or.inl; omega rcases H2 with (⟨hl, rfl⟩ | ⟨hr, rfl⟩) <;> rcases H1 with (h | ⟨_, hβ‚‚βŸ©) Β· exact le_trans (Nat.le_add_left _ _) (le_trans h (Nat.le_add_left _ _)) Β· exact le_trans hβ‚‚ (Nat.mul_le_mul_left _ <| le_trans (Nat.dist_tri_right _ _) (Nat.add_le_add_left hl _)) Β· exact le_trans (Nat.dist_tri_left' _ _) (le_trans (add_le_add hr (le_trans (Nat.le_add_left _ _) h)) (by omega)) Β· rw [Nat.mul_succ] exact le_trans (Nat.dist_tri_right' _ _) (add_le_add hβ‚‚ (le_trans hr (by decide))) theorem Valid'.balance' {l} {x : Ξ±} {r o₁ oβ‚‚} (hl : Valid' o₁ l x) (hr : Valid' x r oβ‚‚) (H : βˆƒ l' r', BalancedSz l' r' ∧ (Nat.dist (size l) l' ≀ 1 ∧ size r = r' ∨ Nat.dist (size r) r' ≀ 1 ∧ size l = l')) : Valid' o₁ (@balance' Ξ± l x r) oβ‚‚ := let ⟨_, _, H1, H2⟩ := H Valid'.balance'_aux hl hr (Valid'.balance'_lemma H1 H2) (Valid'.balance'_lemma H1.symm H2.symm) theorem Valid'.balance {l} {x : Ξ±} {r o₁ oβ‚‚} (hl : Valid' o₁ l x) (hr : Valid' x r oβ‚‚) (H : βˆƒ l' r', BalancedSz l' r' ∧ (Nat.dist (size l) l' ≀ 1 ∧ size r = r' ∨ Nat.dist (size r) r' ≀ 1 ∧ size l = l')) : Valid' o₁ (@balance Ξ± l x r) oβ‚‚ := by rw [balance_eq_balance' hl.3 hr.3 hl.2 hr.2]; exact hl.balance' hr H theorem Valid'.balanceL_aux {l} {x : Ξ±} {r o₁ oβ‚‚} (hl : Valid' o₁ l x) (hr : Valid' x r oβ‚‚) (H₁ : size l = 0 β†’ size r ≀ 1) (Hβ‚‚ : 1 ≀ size l β†’ 1 ≀ size r β†’ size r ≀ delta * size l) (H₃ : 2 * @size Ξ± l ≀ 9 * size r + 5 ∨ size l ≀ 3) : Valid' o₁ (@balanceL Ξ± l x r) oβ‚‚ := by rw [balanceL_eq_balance hl.2 hr.2 H₁ Hβ‚‚, balance_eq_balance' hl.3 hr.3 hl.2 hr.2] refine hl.balance'_aux hr (Or.inl ?_) H₃ rcases Nat.eq_zero_or_pos (size r) with r0 | r0 Β· rw [r0]; exact Nat.zero_le _ rcases Nat.eq_zero_or_pos (size l) with l0 | l0 Β· rw [l0]; exact le_trans (Nat.mul_le_mul_left _ (H₁ l0)) (by decide) replace Hβ‚‚ : _ ≀ 3 * _ := Hβ‚‚ l0 r0; omega theorem Valid'.balanceL {l} {x : Ξ±} {r o₁ oβ‚‚} (hl : Valid' o₁ l x) (hr : Valid' x r oβ‚‚) (H : (βˆƒ l', Raised l' (size l) ∧ BalancedSz l' (size r)) ∨ βˆƒ r', Raised (size r) r' ∧ BalancedSz (size l) r') : Valid' o₁ (@balanceL Ξ± l x r) oβ‚‚ := by rw [balanceL_eq_balance' hl.3 hr.3 hl.2 hr.2 H] refine hl.balance' hr ?_ rcases H with (⟨l', e, H⟩ | ⟨r', e, H⟩) Β· exact ⟨_, _, H, Or.inl ⟨e.dist_le', rfl⟩⟩ Β· exact ⟨_, _, H, Or.inr ⟨e.dist_le, rfl⟩⟩ theorem Valid'.balanceR_aux {l} {x : Ξ±} {r o₁ oβ‚‚} (hl : Valid' o₁ l x) (hr : Valid' x r oβ‚‚) (H₁ : size r = 0 β†’ size l ≀ 1) (Hβ‚‚ : 1 ≀ size r β†’ 1 ≀ size l β†’ size l ≀ delta * size r) (H₃ : 2 * @size Ξ± r ≀ 9 * size l + 5 ∨ size r ≀ 3) : Valid' o₁ (@balanceR Ξ± l x r) oβ‚‚ := by rw [Valid'.dual_iff, dual_balanceR] have := hr.dual.balanceL_aux hl.dual rw [size_dual, size_dual] at this exact this H₁ Hβ‚‚ H₃ theorem Valid'.balanceR {l} {x : Ξ±} {r o₁ oβ‚‚} (hl : Valid' o₁ l x) (hr : Valid' x r oβ‚‚) (H : (βˆƒ l', Raised (size l) l' ∧ BalancedSz l' (size r)) ∨ βˆƒ r', Raised r' (size r) ∧ BalancedSz (size l) r') : Valid' o₁ (@balanceR Ξ± l x r) oβ‚‚ := by rw [Valid'.dual_iff, dual_balanceR]; exact hr.dual.balanceL hl.dual (balance_sz_dual H) theorem Valid'.eraseMax_aux {s l x r o₁ oβ‚‚} (H : Valid' o₁ (.node s l x r) oβ‚‚) : Valid' o₁ (@eraseMax Ξ± (.node' l x r)) ↑(findMax' x r) ∧ size (.node' l x r) = size (eraseMax (.node' l x r)) + 1 := by have := H.2.eq_node'; rw [this] at H; clear this induction' r with rs rl rx rr _ IHrr generalizing l x o₁ Β· exact ⟨H.left, rfl⟩ have := H.2.2.2.eq_node'; rw [this] at H ⊒ rcases IHrr H.right with ⟨h, e⟩ refine ⟨Valid'.balanceL H.left h (Or.inr ⟨_, Or.inr e, H.3.1⟩), ?_⟩ rw [eraseMax, size_balanceL H.3.2.1 h.3 H.2.2.1 h.2 (Or.inr ⟨_, Or.inr e, H.3.1⟩)] rw [size_node, e]; rfl theorem Valid'.eraseMin_aux {s l} {x : Ξ±} {r o₁ oβ‚‚} (H : Valid' o₁ (.node s l x r) oβ‚‚) : Valid' ↑(findMin' l x) (@eraseMin Ξ± (.node' l x r)) oβ‚‚ ∧ size (.node' l x r) = size (eraseMin (.node' l x r)) + 1 := by have := H.dual.eraseMax_aux rwa [← dual_node', size_dual, ← dual_eraseMin, size_dual, ← Valid'.dual_iff, findMax'_dual] at this theorem eraseMin.valid : βˆ€ {t}, @Valid Ξ± _ t β†’ Valid (eraseMin t) | nil, _ => valid_nil | node _ l x r, h => by rw [h.2.eq_node']; exact h.eraseMin_aux.1.valid theorem eraseMax.valid {t} (h : @Valid Ξ± _ t) : Valid (eraseMax t) := by rw [Valid.dual_iff, dual_eraseMax]; exact eraseMin.valid h.dual theorem Valid'.glue_aux {l r o₁ oβ‚‚} (hl : Valid' o₁ l oβ‚‚) (hr : Valid' o₁ r oβ‚‚) (sep : l.All fun x => r.All fun y => x < y) (bal : BalancedSz (size l) (size r)) : Valid' o₁ (@glue Ξ± l r) oβ‚‚ ∧ size (glue l r) = size l + size r := by cases' l with ls ll lx lr; Β· exact ⟨hr, (zero_add _).symm⟩ cases' r with rs rl rx rr; Β· exact ⟨hl, rfl⟩ dsimp [glue]; split_ifs Β· rw [splitMax_eq] Β· cases' Valid'.eraseMax_aux hl with v e suffices H : _ by refine ⟨Valid'.balanceR v (hr.of_gt ?_ ?_) H, ?_⟩ Β· refine findMax'_all (P := fun a : Ξ± => Bounded nil (a : WithTop Ξ±) oβ‚‚) lx lr hl.1.2.to_nil (sep.2.2.imp ?_) exact fun x h => hr.1.2.to_nil.mono_left (le_of_lt h.2.1) Β· exact @findMax'_all _ (fun a => All (Β· > a) (.node rs rl rx rr)) lx lr sep.2.1 sep.2.2 Β· rw [size_balanceR v.3 hr.3 v.2 hr.2 H, add_right_comm, ← e, hl.2.1]; rfl refine Or.inl ⟨_, Or.inr e, ?_⟩ rwa [hl.2.eq_node'] at bal Β· rw [splitMin_eq] Β· cases' Valid'.eraseMin_aux hr with v e suffices H : _ by refine ⟨Valid'.balanceL (hl.of_lt ?_ ?_) v H, ?_⟩ Β· refine @findMin'_all (P := fun a : Ξ± => Bounded nil o₁ (a : WithBot Ξ±)) rl rx (sep.2.1.1.imp ?_) hr.1.1.to_nil exact fun y h => hl.1.1.to_nil.mono_right (le_of_lt h) Β· exact @findMin'_all _ (fun a => All (Β· < a) (.node ls ll lx lr)) rl rx (all_iff_forall.2 fun x hx => sep.imp fun y hy => all_iff_forall.1 hy.1 _ hx) (sep.imp fun y hy => hy.2.1) Β· rw [size_balanceL hl.3 v.3 hl.2 v.2 H, add_assoc, ← e, hr.2.1]; rfl refine Or.inr ⟨_, Or.inr e, ?_⟩ rwa [hr.2.eq_node'] at bal theorem Valid'.glue {l} {x : Ξ±} {r o₁ oβ‚‚} (hl : Valid' o₁ l x) (hr : Valid' x r oβ‚‚) : BalancedSz (size l) (size r) β†’ Valid' o₁ (@glue Ξ± l r) oβ‚‚ ∧ size (@glue Ξ± l r) = size l + size r := Valid'.glue_aux (hl.trans_right hr.1) (hr.trans_left hl.1) (hl.1.to_sep hr.1) theorem Valid'.merge_lemma {a b c : β„•} (h₁ : 3 * a < b + c + 1) (hβ‚‚ : b ≀ 3 * c) : 2 * (a + b) ≀ 9 * c + 5 := by omega theorem Valid'.merge_aux₁ {o₁ oβ‚‚ ls ll lx lr rs rl rx rr t} (hl : Valid' o₁ (@Ordnode.node Ξ± ls ll lx lr) oβ‚‚) (hr : Valid' o₁ (.node rs rl rx rr) oβ‚‚) (h : delta * ls < rs) (v : Valid' o₁ t rx) (e : size t = ls + size rl) : Valid' o₁ (.balanceL t rx rr) oβ‚‚ ∧ size (.balanceL t rx rr) = ls + rs := by rw [hl.2.1] at e rw [hl.2.1, hr.2.1, delta] at h rcases hr.3.1 with (H | ⟨hr₁, hrβ‚‚βŸ©); Β· omega suffices Hβ‚‚ : _ by suffices H₁ : _ by refine ⟨Valid'.balanceL_aux v hr.right H₁ Hβ‚‚ ?_, ?_⟩ Β· rw [e]; exact Or.inl (Valid'.merge_lemma h hr₁) Β· rw [balanceL_eq_balance v.2 hr.2.2.2 H₁ Hβ‚‚, balance_eq_balance' v.3 hr.3.2.2 v.2 hr.2.2.2, size_balance' v.2 hr.2.2.2, e, hl.2.1, hr.2.1] abel Β· rw [e, add_right_comm]; rintro ⟨⟩ intro _ _; rw [e]; unfold delta at hrβ‚‚ ⊒; omega theorem Valid'.merge_aux {l r o₁ oβ‚‚} (hl : Valid' o₁ l oβ‚‚) (hr : Valid' o₁ r oβ‚‚) (sep : l.All fun x => r.All fun y => x < y) : Valid' o₁ (@merge Ξ± l r) oβ‚‚ ∧ size (merge l r) = size l + size r := by induction' l with ls ll lx lr _ IHlr generalizing o₁ oβ‚‚ r Β· exact ⟨hr, (zero_add _).symm⟩ induction' r with rs rl rx rr IHrl _ generalizing o₁ oβ‚‚ Β· exact ⟨hl, rfl⟩ rw [merge_node]; split_ifs with h h_1 Β· cases' IHrl (hl.of_lt hr.1.1.to_nil <| sep.imp fun x h => h.2.1) hr.left (sep.imp fun x h => h.1) with v e exact Valid'.merge_aux₁ hl hr h v e Β· cases' IHlr hl.right (hr.of_gt hl.1.2.to_nil sep.2.1) sep.2.2 with v e have := Valid'.merge_aux₁ hr.dual hl.dual h_1 v.dual rw [size_dual, add_comm, size_dual, ← dual_balanceR, ← Valid'.dual_iff, size_dual, add_comm rs] at this exact this e Β· refine Valid'.glue_aux hl hr sep (Or.inr ⟨not_lt.1 h_1, not_lt.1 h⟩) theorem Valid.merge {l r} (hl : Valid l) (hr : Valid r) (sep : l.All fun x => r.All fun y => x < y) : Valid (@merge Ξ± l r) := (Valid'.merge_aux hl hr sep).1 theorem insertWith.valid_aux [IsTotal Ξ± (Β· ≀ Β·)] [@DecidableRel Ξ± (Β· ≀ Β·)] (f : Ξ± β†’ Ξ±) (x : Ξ±) (hf : βˆ€ y, x ≀ y ∧ y ≀ x β†’ x ≀ f y ∧ f y ≀ x) : βˆ€ {t o₁ oβ‚‚}, Valid' o₁ t oβ‚‚ β†’ Bounded nil o₁ x β†’ Bounded nil x oβ‚‚ β†’ Valid' o₁ (insertWith f x t) oβ‚‚ ∧ Raised (size t) (size (insertWith f x t)) | nil, o₁, oβ‚‚, _, bl, br => ⟨valid'_singleton bl br, Or.inr rfl⟩ | node sz l y r, o₁, oβ‚‚, h, bl, br => by rw [insertWith, cmpLE] split_ifs with h_1 h_2 <;> dsimp only Β· rcases h with ⟨⟨lx, xr⟩, hs, hb⟩ rcases hf _ ⟨h_1, h_2⟩ with ⟨xf, fx⟩ refine ⟨⟨⟨lx.mono_right (le_trans h_2 xf), xr.mono_left (le_trans fx h_1)⟩, hs, hb⟩, Or.inl rfl⟩ Β· rcases insertWith.valid_aux f x hf h.left bl (lt_of_le_not_le h_1 h_2) with ⟨vl, e⟩ suffices H : _ by refine ⟨vl.balanceL h.right H, ?_⟩ rw [size_balanceL vl.3 h.3.2.2 vl.2 h.2.2.2 H, h.2.size_eq] exact (e.add_right _).add_right _ exact Or.inl ⟨_, e, h.3.1⟩ Β· have : y < x := lt_of_le_not_le ((total_of (Β· ≀ Β·) _ _).resolve_left h_1) h_1 rcases insertWith.valid_aux f x hf h.right this br with ⟨vr, e⟩ suffices H : _ by refine ⟨h.left.balanceR vr H, ?_⟩ rw [size_balanceR h.3.2.1 vr.3 h.2.2.1 vr.2 H, h.2.size_eq] exact (e.add_left _).add_right _ exact Or.inr ⟨_, e, h.3.1⟩ theorem insertWith.valid [IsTotal Ξ± (Β· ≀ Β·)] [@DecidableRel Ξ± (Β· ≀ Β·)] (f : Ξ± β†’ Ξ±) (x : Ξ±) (hf : βˆ€ y, x ≀ y ∧ y ≀ x β†’ x ≀ f y ∧ f y ≀ x) {t} (h : Valid t) : Valid (insertWith f x t) := (insertWith.valid_aux _ _ hf h ⟨⟩ ⟨⟩).1 theorem insert_eq_insertWith [@DecidableRel Ξ± (Β· ≀ Β·)] (x : Ξ±) : βˆ€ t, Ordnode.insert x t = insertWith (fun _ => x) x t | nil => rfl | node _ l y r => by unfold Ordnode.insert insertWith; cases cmpLE x y <;> simp [insert_eq_insertWith] theorem insert.valid [IsTotal Ξ± (Β· ≀ Β·)] [@DecidableRel Ξ± (Β· ≀ Β·)] (x : Ξ±) {t} (h : Valid t) : Valid (Ordnode.insert x t) := by rw [insert_eq_insertWith]; exact insertWith.valid _ _ (fun _ _ => ⟨le_rfl, le_rfl⟩) h theorem insert'_eq_insertWith [@DecidableRel Ξ± (Β· ≀ Β·)] (x : Ξ±) : βˆ€ t, insert' x t = insertWith id x t | nil => rfl | node _ l y r => by unfold insert' insertWith; cases cmpLE x y <;> simp [insert'_eq_insertWith] theorem insert'.valid [IsTotal Ξ± (Β· ≀ Β·)] [@DecidableRel Ξ± (Β· ≀ Β·)] (x : Ξ±) {t} (h : Valid t) : Valid (insert' x t) := by rw [insert'_eq_insertWith]; exact insertWith.valid _ _ (fun _ => id) h theorem Valid'.map_aux {Ξ²} [Preorder Ξ²] {f : Ξ± β†’ Ξ²} (f_strict_mono : StrictMono f) {t a₁ aβ‚‚} (h : Valid' a₁ t aβ‚‚) : Valid' (Option.map f a₁) (map f t) (Option.map f aβ‚‚) ∧ (map f t).size = t.size := by induction t generalizing a₁ aβ‚‚ with | nil => simp only [map, size_nil, and_true]; apply valid'_nil cases a₁; Β· trivial cases aβ‚‚; Β· trivial simp only [Bounded] exact f_strict_mono h.ord | node _ _ _ _ t_ih_l t_ih_r => have t_ih_l' := t_ih_l h.left have t_ih_r' := t_ih_r h.right clear t_ih_l t_ih_r cases' t_ih_l' with t_l_valid t_l_size cases' t_ih_r' with t_r_valid t_r_size simp only [map, size_node, and_true] constructor Β· exact And.intro t_l_valid.ord t_r_valid.ord Β· constructor Β· rw [t_l_size, t_r_size]; exact h.sz.1 Β· constructor Β· exact t_l_valid.sz Β· exact t_r_valid.sz Β· constructor Β· rw [t_l_size, t_r_size]; exact h.bal.1 Β· constructor Β· exact t_l_valid.bal Β· exact t_r_valid.bal theorem map.valid {Ξ²} [Preorder Ξ²] {f : Ξ± β†’ Ξ²} (f_strict_mono : StrictMono f) {t} (h : Valid t) : Valid (map f t) := (Valid'.map_aux f_strict_mono h).1 theorem Valid'.erase_aux [@DecidableRel Ξ± (Β· ≀ Β·)] (x : Ξ±) {t a₁ aβ‚‚} (h : Valid' a₁ t aβ‚‚) : Valid' a₁ (erase x t) aβ‚‚ ∧ Raised (erase x t).size t.size := by induction t generalizing a₁ aβ‚‚ with | nil => simpa [erase, Raised] | node _ t_l t_x t_r t_ih_l t_ih_r => simp only [erase, size_node] have t_ih_l' := t_ih_l h.left have t_ih_r' := t_ih_r h.right clear t_ih_l t_ih_r cases' t_ih_l' with t_l_valid t_l_size cases' t_ih_r' with t_r_valid t_r_size cases cmpLE x t_x <;> rw [h.sz.1] Β· suffices h_balanceable : _ by constructor Β· exact Valid'.balanceR t_l_valid h.right h_balanceable Β· rw [size_balanceR t_l_valid.bal h.right.bal t_l_valid.sz h.right.sz h_balanceable] repeat apply Raised.add_right exact t_l_size left; exists t_l.size; exact And.intro t_l_size h.bal.1 Β· have h_glue := Valid'.glue h.left h.right h.bal.1 cases' h_glue with h_glue_valid h_glue_sized constructor Β· exact h_glue_valid Β· right; rw [h_glue_sized] Β· suffices h_balanceable : _ by constructor Β· exact Valid'.balanceL h.left t_r_valid h_balanceable Β· rw [size_balanceL h.left.bal t_r_valid.bal h.left.sz t_r_valid.sz h_balanceable] apply Raised.add_right apply Raised.add_left exact t_r_size right; exists t_r.size; exact And.intro t_r_size h.bal.1 theorem erase.valid [@DecidableRel Ξ± (Β· ≀ Β·)] (x : Ξ±) {t} (h : Valid t) : Valid (erase x t) := (Valid'.erase_aux x h).1 theorem size_erase_of_mem [@DecidableRel Ξ± (Β· ≀ Β·)] {x : Ξ±} {t a₁ aβ‚‚} (h : Valid' a₁ t aβ‚‚) (h_mem : x ∈ t) : size (erase x t) = size t - 1 := by induction t generalizing a₁ aβ‚‚ with | nil => contradiction | node _ t_l t_x t_r t_ih_l t_ih_r => have t_ih_l' := t_ih_l h.left have t_ih_r' := t_ih_r h.right clear t_ih_l t_ih_r dsimp only [Membership.mem, mem] at h_mem unfold erase revert h_mem; cases cmpLE x t_x <;> intro h_mem <;> dsimp only at h_mem ⊒ Β· have t_ih_l := t_ih_l' h_mem clear t_ih_l' t_ih_r' have t_l_h := Valid'.erase_aux x h.left cases' t_l_h with t_l_valid t_l_size rw [size_balanceR t_l_valid.bal h.right.bal t_l_valid.sz h.right.sz (Or.inl (Exists.intro t_l.size (And.intro t_l_size h.bal.1)))] rw [t_ih_l, h.sz.1] have h_pos_t_l_size := pos_size_of_mem h.left.sz h_mem revert h_pos_t_l_size; cases' t_l.size with t_l_size <;> intro h_pos_t_l_size Β· cases h_pos_t_l_size Β· simp [Nat.add_right_comm] Β· rw [(Valid'.glue h.left h.right h.bal.1).2, h.sz.1]; rfl Β· have t_ih_r := t_ih_r' h_mem clear t_ih_l' t_ih_r' have t_r_h := Valid'.erase_aux x h.right cases' t_r_h with t_r_valid t_r_size rw [size_balanceL h.left.bal t_r_valid.bal h.left.sz t_r_valid.sz (Or.inr (Exists.intro t_r.size (And.intro t_r_size h.bal.1)))] rw [t_ih_r, h.sz.1] have h_pos_t_r_size := pos_size_of_mem h.right.sz h_mem revert h_pos_t_r_size; cases' t_r.size with t_r_size <;> intro h_pos_t_r_size Β· cases h_pos_t_r_size Β· simp [Nat.add_assoc] end end Ordnode /-- An `Ordset Ξ±` is a finite set of values, represented as a tree. The operations on this type maintain that the tree is balanced and correctly stores subtree sizes at each level. The correctness property of the tree is baked into the type, so all operations on this type are correct by construction. -/ def Ordset (Ξ± : Type*) [Preorder Ξ±] := { t : Ordnode Ξ± // t.Valid } namespace Ordset open Ordnode variable [Preorder Ξ±] /-- O(1). The empty set. -/ nonrec def nil : Ordset Ξ± := ⟨nil, ⟨⟩, ⟨⟩, ⟨⟩⟩ /-- O(1). Get the size of the set. -/ def size (s : Ordset Ξ±) : β„• := s.1.size /-- O(1). Construct a singleton set containing value `a`. -/ protected def singleton (a : Ξ±) : Ordset Ξ± := ⟨singleton a, valid_singleton⟩ instance instEmptyCollection : EmptyCollection (Ordset Ξ±) := ⟨nil⟩ instance instInhabited : Inhabited (Ordset Ξ±) := ⟨nil⟩ instance instSingleton : Singleton Ξ± (Ordset Ξ±) := ⟨Ordset.singleton⟩ /-- O(1). Is the set empty? -/ def Empty (s : Ordset Ξ±) : Prop := s = βˆ… theorem empty_iff {s : Ordset Ξ±} : s = βˆ… ↔ s.1.empty := ⟨fun h => by cases h; exact rfl, fun h => by cases s with | mk s_val _ => cases s_val <;> [rfl; cases h]⟩ instance Empty.instDecidablePred : DecidablePred (@Empty Ξ± _) := fun _ => decidable_of_iff' _ empty_iff /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, this replaces it. -/ protected def insert [IsTotal Ξ± (Β· ≀ Β·)] [@DecidableRel Ξ± (Β· ≀ Β·)] (x : Ξ±) (s : Ordset Ξ±) : Ordset Ξ± := ⟨Ordnode.insert x s.1, insert.valid _ s.2⟩ instance instInsert [IsTotal Ξ± (Β· ≀ Β·)] [@DecidableRel Ξ± (Β· ≀ Β·)] : Insert Ξ± (Ordset Ξ±) := ⟨Ordset.insert⟩ /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, the set is returned as is. -/ nonrec def insert' [IsTotal Ξ± (Β· ≀ Β·)] [@DecidableRel Ξ± (Β· ≀ Β·)] (x : Ξ±) (s : Ordset Ξ±) : Ordset Ξ± := ⟨insert' x s.1, insert'.valid _ s.2⟩ section variable [@DecidableRel Ξ± (Β· ≀ Β·)] /-- O(log n). Does the set contain the element `x`? That is, is there an element that is equivalent to `x` in the order? -/ def mem (x : Ξ±) (s : Ordset Ξ±) : Bool := x ∈ s.val /-- O(log n). Retrieve an element in the set that is equivalent to `x` in the order, if it exists. -/ def find (x : Ξ±) (s : Ordset Ξ±) : Option Ξ± := Ordnode.find x s.val instance instMembership : Membership Ξ± (Ordset Ξ±) := ⟨fun x s => mem x s⟩ instance mem.decidable (x : Ξ±) (s : Ordset Ξ±) : Decidable (x ∈ s) := instDecidableEqBool _ _ theorem pos_size_of_mem {x : Ξ±} {t : Ordset Ξ±} (h_mem : x ∈ t) : 0 < size t := by simp? [Membership.mem, mem] at h_mem says simp only [Membership.mem, mem, Bool.decide_eq_true] at h_mem apply Ordnode.pos_size_of_mem t.property.sz h_mem end /-- O(log n). Remove an element from the set equivalent to `x`. Does nothing if there is no such element. -/ def erase [@DecidableRel Ξ± (Β· ≀ Β·)] (x : Ξ±) (s : Ordset Ξ±) : Ordset Ξ± := ⟨Ordnode.erase x s.val, Ordnode.erase.valid x s.property⟩ /-- O(n). Map a function across a tree, without changing the structure. -/ def map {Ξ²} [Preorder Ξ²] (f : Ξ± β†’ Ξ²) (f_strict_mono : StrictMono f) (s : Ordset Ξ±) : Ordset Ξ² := ⟨Ordnode.map f s.val, Ordnode.map.valid f_strict_mono s.property⟩ end Ordset
Data\PFunctor\Multivariate\Basic.lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Simon Hudon -/ import Mathlib.Control.Functor.Multivariate import Mathlib.Data.PFunctor.Univariate.Basic /-! # Multivariate polynomial functors. Multivariate polynomial functors are used for defining M-types and W-types. They map a type vector `Ξ±` to the type `Ξ£ a : A, B a ⟹ Ξ±`, with `A : Type` and `B : A β†’ TypeVec n`. They interact well with Lean's inductive definitions because they guarantee that occurrences of `Ξ±` are positive. -/ universe u v open MvFunctor /-- multivariate polynomial functors -/ @[pp_with_univ] structure MvPFunctor (n : β„•) where /-- The head type -/ A : Type u /-- The child family of types -/ B : A β†’ TypeVec.{u} n namespace MvPFunctor open MvFunctor (LiftP LiftR) variable {n m : β„•} (P : MvPFunctor.{u} n) /-- Applying `P` to an object of `Type` -/ @[coe] def Obj (Ξ± : TypeVec.{u} n) : Type u := Ξ£ a : P.A, P.B a ⟹ Ξ± instance : CoeFun (MvPFunctor.{u} n) (fun _ => TypeVec.{u} n β†’ Type u) where coe := Obj /-- Applying `P` to a morphism of `Type` -/ def map {Ξ± Ξ² : TypeVec n} (f : Ξ± ⟹ Ξ²) : P Ξ± β†’ P Ξ² := fun ⟨a, g⟩ => ⟨a, TypeVec.comp f g⟩ instance : Inhabited (MvPFunctor n) := ⟨⟨default, default⟩⟩ instance Obj.inhabited {Ξ± : TypeVec n} [Inhabited P.A] [βˆ€ i, Inhabited (Ξ± i)] : Inhabited (P Ξ±) := ⟨⟨default, fun _ _ => default⟩⟩ instance : MvFunctor.{u} P.Obj := ⟨@MvPFunctor.map n P⟩ theorem map_eq {Ξ± Ξ² : TypeVec n} (g : Ξ± ⟹ Ξ²) (a : P.A) (f : P.B a ⟹ Ξ±) : @MvFunctor.map _ P.Obj _ _ _ g ⟨a, f⟩ = ⟨a, g ⊚ f⟩ := rfl theorem id_map {Ξ± : TypeVec n} : βˆ€ x : P Ξ±, TypeVec.id <$$> x = x | ⟨_, _⟩ => rfl theorem comp_map {Ξ± Ξ² Ξ³ : TypeVec n} (f : Ξ± ⟹ Ξ²) (g : Ξ² ⟹ Ξ³) : βˆ€ x : P Ξ±, (g ⊚ f) <$$> x = g <$$> f <$$> x | ⟨_, _⟩ => rfl instance : LawfulMvFunctor.{u} P.Obj where id_map := @id_map _ P comp_map := @comp_map _ P /-- Constant functor where the input object does not affect the output -/ def const (n : β„•) (A : Type u) : MvPFunctor n := { A B := fun _ _ => PEmpty } section Const variable (n) {A : Type u} {Ξ± Ξ² : TypeVec.{u} n} /-- Constructor for the constant functor -/ def const.mk (x : A) {Ξ±} : const n A Ξ± := ⟨x, fun _ a => PEmpty.elim a⟩ variable {n} /-- Destructor for the constant functor -/ def const.get (x : const n A Ξ±) : A := x.1 @[simp] theorem const.get_map (f : Ξ± ⟹ Ξ²) (x : const n A Ξ±) : const.get (f <$$> x) = const.get x := by cases x rfl @[simp] theorem const.get_mk (x : A) : const.get (const.mk n x : const n A Ξ±) = x := rfl @[simp] theorem const.mk_get (x : const n A Ξ±) : const.mk n (const.get x) = x := by cases x dsimp [const.get, const.mk] congr with (_⟨⟩) end Const /-- Functor composition on polynomial functors -/ def comp (P : MvPFunctor.{u} n) (Q : Fin2 n β†’ MvPFunctor.{u} m) : MvPFunctor m where A := Ξ£ aβ‚‚ : P.1, βˆ€ i, P.2 aβ‚‚ i β†’ (Q i).1 B a i := Ξ£(j : _) (b : P.2 a.1 j), (Q j).2 (a.snd j b) i variable {P} {Q : Fin2 n β†’ MvPFunctor.{u} m} {Ξ± Ξ² : TypeVec.{u} m} /-- Constructor for functor composition -/ def comp.mk (x : P (fun i => Q i Ξ±)) : comp P Q Ξ± := ⟨⟨x.1, fun _ a => (x.2 _ a).1⟩, fun i a => (x.snd a.fst a.snd.fst).snd i a.snd.snd⟩ /-- Destructor for functor composition -/ def comp.get (x : comp P Q Ξ±) : P (fun i => Q i Ξ±) := ⟨x.1.1, fun i a => ⟨x.fst.snd i a, fun (j : Fin2 m) (b : (Q i).B _ j) => x.snd j ⟨i, ⟨a, b⟩⟩⟩⟩ theorem comp.get_map (f : Ξ± ⟹ Ξ²) (x : comp P Q Ξ±) : comp.get (f <$$> x) = (fun i (x : Q i Ξ±) => f <$$> x) <$$> comp.get x := by rfl @[simp] theorem comp.get_mk (x : P (fun i => Q i Ξ±)) : comp.get (comp.mk x) = x := by rfl @[simp] theorem comp.mk_get (x : comp P Q Ξ±) : comp.mk (comp.get x) = x := by rfl /- lifting predicates and relations -/ theorem liftP_iff {Ξ± : TypeVec n} (p : βˆ€ ⦃i⦄, Ξ± i β†’ Prop) (x : P Ξ±) : LiftP p x ↔ βˆƒ a f, x = ⟨a, f⟩ ∧ βˆ€ i j, p (f i j) := by constructor Β· rintro ⟨y, hy⟩ cases' h : y with a f refine ⟨a, fun i j => (f i j).val, ?_, fun i j => (f i j).property⟩ rw [← hy, h, map_eq] rfl rintro ⟨a, f, xeq, pf⟩ use ⟨a, fun i j => ⟨f i j, pf i j⟩⟩ rw [xeq]; rfl theorem liftP_iff' {Ξ± : TypeVec n} (p : βˆ€ ⦃i⦄, Ξ± i β†’ Prop) (a : P.A) (f : P.B a ⟹ Ξ±) : @LiftP.{u} _ P.Obj _ Ξ± p ⟨a, f⟩ ↔ βˆ€ i x, p (f i x) := by simp only [liftP_iff, Sigma.mk.inj_iff]; constructor Β· rintro ⟨_, _, ⟨⟩, _⟩ assumption Β· intro repeat' first |constructor|assumption theorem liftR_iff {Ξ± : TypeVec n} (r : βˆ€ ⦃i⦄, Ξ± i β†’ Ξ± i β†’ Prop) (x y : P Ξ±) : LiftR @r x y ↔ βˆƒ a fβ‚€ f₁, x = ⟨a, fβ‚€βŸ© ∧ y = ⟨a, fβ‚βŸ© ∧ βˆ€ i j, r (fβ‚€ i j) (f₁ i j) := by constructor Β· rintro ⟨u, xeq, yeq⟩ cases' h : u with a f use a, fun i j => (f i j).val.fst, fun i j => (f i j).val.snd constructor Β· rw [← xeq, h] rfl constructor Β· rw [← yeq, h] rfl intro i j exact (f i j).property rintro ⟨a, fβ‚€, f₁, xeq, yeq, h⟩ use ⟨a, fun i j => ⟨(fβ‚€ i j, f₁ i j), h i j⟩⟩ dsimp; constructor Β· rw [xeq] rfl rw [yeq]; rfl open Set MvFunctor theorem supp_eq {Ξ± : TypeVec n} (a : P.A) (f : P.B a ⟹ Ξ±) (i) : @supp.{u} _ P.Obj _ Ξ± (⟨a, f⟩ : P Ξ±) i = f i '' univ := by ext x; simp only [supp, image_univ, mem_range, mem_setOf_eq] constructor <;> intro h Β· apply @h fun i x => βˆƒ y : P.B a i, f i y = x rw [liftP_iff'] intros exact ⟨_, rfl⟩ Β· simp only [liftP_iff'] cases h subst x tauto end MvPFunctor /- Decomposing an n+1-ary pfunctor. -/ namespace MvPFunctor open TypeVec variable {n : β„•} (P : MvPFunctor.{u} (n + 1)) /-- Split polynomial functor, get an n-ary functor from an `n+1`-ary functor -/ def drop : MvPFunctor n where A := P.A B a := (P.B a).drop /-- Split polynomial functor, get a univariate functor from an `n+1`-ary functor -/ def last : PFunctor where A := P.A B a := (P.B a).last /-- append arrows of a polynomial functor application -/ abbrev appendContents {Ξ± : TypeVec n} {Ξ² : Type*} {a : P.A} (f' : P.drop.B a ⟹ Ξ±) (f : P.last.B a β†’ Ξ²) : P.B a ⟹ (Ξ± ::: Ξ²) := splitFun f' f end MvPFunctor
Data\PFunctor\Multivariate\M.lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro, Simon Hudon -/ import Mathlib.Data.PFunctor.Multivariate.Basic import Mathlib.Data.PFunctor.Univariate.M /-! # The M construction as a multivariate polynomial functor. M types are potentially infinite tree-like structures. They are defined as the greatest fixpoint of a polynomial functor. ## Main definitions * `M.mk` - constructor * `M.dest` - destructor * `M.corec` - corecursor: useful for formulating infinite, productive computations * `M.bisim` - bisimulation: proof technique to show the equality of infinite objects ## Implementation notes Dual view of M-types: * `mp`: polynomial functor * `M`: greatest fixed point of a polynomial functor Specifically, we define the polynomial functor `mp` as: * A := a possibly infinite tree-like structure without information in the nodes * B := given the tree-like structure `t`, `B t` is a valid path from the root of `t` to any given node. As a result `mp Ξ±` is made of a dataless tree and a function from its valid paths to values of `Ξ±` The difference with the polynomial functor of an initial algebra is that `A` is a possibly infinite tree. ## Reference * Jeremy Avigad, Mario M. Carneiro and Simon Hudon. [*Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019] -/ universe u open MvFunctor namespace MvPFunctor open TypeVec variable {n : β„•} (P : MvPFunctor.{u} (n + 1)) /-- A path from the root of a tree to one of its node -/ inductive M.Path : P.last.M β†’ Fin2 n β†’ Type u | root (x : P.last.M) (a : P.A) (f : P.last.B a β†’ P.last.M) (h : PFunctor.M.dest x = ⟨a, f⟩) (i : Fin2 n) (c : P.drop.B a i) : M.Path x i | child (x : P.last.M) (a : P.A) (f : P.last.B a β†’ P.last.M) (h : PFunctor.M.dest x = ⟨a, f⟩) (j : P.last.B a) (i : Fin2 n) (c : M.Path (f j) i) : M.Path x i instance M.Path.inhabited (x : P.last.M) {i} [Inhabited (P.drop.B x.head i)] : Inhabited (M.Path P x i) := let a := PFunctor.M.head x let f := PFunctor.M.children x ⟨M.Path.root _ a f (PFunctor.M.casesOn' x (r := fun _ => PFunctor.M.dest x = ⟨a, f⟩) <| by intros; simp [a, PFunctor.M.dest_mk, PFunctor.M.children_mk]; rfl) _ default⟩ /-- Polynomial functor of the M-type of `P`. `A` is a data-less possibly infinite tree whereas, for a given `a : A`, `B a` is a valid path in tree `a` so that `mp Ξ±` is made of a tree and a function from its valid paths to the values it contains -/ def mp : MvPFunctor n where A := P.last.M B := M.Path P /-- `n`-ary M-type for `P` -/ def M (Ξ± : TypeVec n) : Type _ := P.mp Ξ± instance mvfunctorM : MvFunctor P.M := by delta M; infer_instance instance inhabitedM {Ξ± : TypeVec _} [I : Inhabited P.A] [βˆ€ i : Fin2 n, Inhabited (Ξ± i)] : Inhabited (P.M Ξ±) := @Obj.inhabited _ (mp P) _ (@PFunctor.M.inhabited P.last I) _ /-- construct through corecursion the shape of an M-type without its contents -/ def M.corecShape {Ξ² : Type u} (gβ‚€ : Ξ² β†’ P.A) (gβ‚‚ : βˆ€ b : Ξ², P.last.B (gβ‚€ b) β†’ Ξ²) : Ξ² β†’ P.last.M := PFunctor.M.corec fun b => ⟨gβ‚€ b, gβ‚‚ b⟩ /-- Proof of type equality as an arrow -/ def castDropB {a a' : P.A} (h : a = a') : P.drop.B a ⟹ P.drop.B a' := fun _i b => Eq.recOn h b /-- Proof of type equality as a function -/ def castLastB {a a' : P.A} (h : a = a') : P.last.B a β†’ P.last.B a' := fun b => Eq.recOn h b /-- Using corecursion, construct the contents of an M-type -/ def M.corecContents {Ξ± : TypeVec.{u} n} {Ξ² : Type u} (gβ‚€ : Ξ² β†’ P.A) (g₁ : βˆ€ b : Ξ², P.drop.B (gβ‚€ b) ⟹ Ξ±) (gβ‚‚ : βˆ€ b : Ξ², P.last.B (gβ‚€ b) β†’ Ξ²) (x : _) (b : Ξ²) (h : x = M.corecShape P gβ‚€ gβ‚‚ b) : M.Path P x ⟹ Ξ± | _, M.Path.root x a f h' i c => have : a = gβ‚€ b := by rw [h, M.corecShape, PFunctor.M.dest_corec] at h' cases h' rfl g₁ b i (P.castDropB this i c) | _, M.Path.child x a f h' j i c => have hβ‚€ : a = gβ‚€ b := by rw [h, M.corecShape, PFunctor.M.dest_corec] at h' cases h' rfl have h₁ : f j = M.corecShape P gβ‚€ gβ‚‚ (gβ‚‚ b (castLastB P hβ‚€ j)) := by rw [h, M.corecShape, PFunctor.M.dest_corec] at h' cases h' rfl M.corecContents gβ‚€ g₁ gβ‚‚ (f j) (gβ‚‚ b (P.castLastB hβ‚€ j)) h₁ i c /-- Corecursor for M-type of `P` -/ def M.corec' {Ξ± : TypeVec n} {Ξ² : Type u} (gβ‚€ : Ξ² β†’ P.A) (g₁ : βˆ€ b : Ξ², P.drop.B (gβ‚€ b) ⟹ Ξ±) (gβ‚‚ : βˆ€ b : Ξ², P.last.B (gβ‚€ b) β†’ Ξ²) : Ξ² β†’ P.M Ξ± := fun b => ⟨M.corecShape P gβ‚€ gβ‚‚ b, M.corecContents P gβ‚€ g₁ gβ‚‚ _ _ rfl⟩ /-- Corecursor for M-type of `P` -/ def M.corec {Ξ± : TypeVec n} {Ξ² : Type u} (g : Ξ² β†’ P (Ξ±.append1 Ξ²)) : Ξ² β†’ P.M Ξ± := M.corec' P (fun b => (g b).fst) (fun b => dropFun (g b).snd) fun b => lastFun (g b).snd /-- Implementation of destructor for M-type of `P` -/ def M.pathDestLeft {Ξ± : TypeVec n} {x : P.last.M} {a : P.A} {f : P.last.B a β†’ P.last.M} (h : PFunctor.M.dest x = ⟨a, f⟩) (f' : M.Path P x ⟹ Ξ±) : P.drop.B a ⟹ Ξ± := fun i c => f' i (M.Path.root x a f h i c) /-- Implementation of destructor for M-type of `P` -/ def M.pathDestRight {Ξ± : TypeVec n} {x : P.last.M} {a : P.A} {f : P.last.B a β†’ P.last.M} (h : PFunctor.M.dest x = ⟨a, f⟩) (f' : M.Path P x ⟹ Ξ±) : βˆ€ j : P.last.B a, M.Path P (f j) ⟹ Ξ± := fun j i c => f' i (M.Path.child x a f h j i c) /-- Destructor for M-type of `P` -/ def M.dest' {Ξ± : TypeVec n} {x : P.last.M} {a : P.A} {f : P.last.B a β†’ P.last.M} (h : PFunctor.M.dest x = ⟨a, f⟩) (f' : M.Path P x ⟹ Ξ±) : P (Ξ±.append1 (P.M Ξ±)) := ⟨a, splitFun (M.pathDestLeft P h f') fun x => ⟨f x, M.pathDestRight P h f' x⟩⟩ /-- Destructor for M-types -/ def M.dest {Ξ± : TypeVec n} (x : P.M Ξ±) : P (Ξ± ::: P.M Ξ±) := M.dest' P (Sigma.eta <| PFunctor.M.dest x.fst).symm x.snd /-- Constructor for M-types -/ def M.mk {Ξ± : TypeVec n} : P (Ξ±.append1 (P.M Ξ±)) β†’ P.M Ξ± := M.corec _ fun i => appendFun id (M.dest P) <$$> i theorem M.dest'_eq_dest' {Ξ± : TypeVec n} {x : P.last.M} {a₁ : P.A} {f₁ : P.last.B a₁ β†’ P.last.M} (h₁ : PFunctor.M.dest x = ⟨a₁, fβ‚βŸ©) {aβ‚‚ : P.A} {fβ‚‚ : P.last.B aβ‚‚ β†’ P.last.M} (hβ‚‚ : PFunctor.M.dest x = ⟨aβ‚‚, fβ‚‚βŸ©) (f' : M.Path P x ⟹ Ξ±) : M.dest' P h₁ f' = M.dest' P hβ‚‚ f' := by cases h₁.symm.trans hβ‚‚; rfl theorem M.dest_eq_dest' {Ξ± : TypeVec n} {x : P.last.M} {a : P.A} {f : P.last.B a β†’ P.last.M} (h : PFunctor.M.dest x = ⟨a, f⟩) (f' : M.Path P x ⟹ Ξ±) : M.dest P ⟨x, f'⟩ = M.dest' P h f' := M.dest'_eq_dest' _ _ _ _ theorem M.dest_corec' {Ξ± : TypeVec.{u} n} {Ξ² : Type u} (gβ‚€ : Ξ² β†’ P.A) (g₁ : βˆ€ b : Ξ², P.drop.B (gβ‚€ b) ⟹ Ξ±) (gβ‚‚ : βˆ€ b : Ξ², P.last.B (gβ‚€ b) β†’ Ξ²) (x : Ξ²) : M.dest P (M.corec' P gβ‚€ g₁ gβ‚‚ x) = ⟨gβ‚€ x, splitFun (g₁ x) (M.corec' P gβ‚€ g₁ gβ‚‚ ∘ gβ‚‚ x)⟩ := rfl theorem M.dest_corec {Ξ± : TypeVec n} {Ξ² : Type u} (g : Ξ² β†’ P (Ξ±.append1 Ξ²)) (x : Ξ²) : M.dest P (M.corec P g x) = appendFun id (M.corec P g) <$$> g x := by trans Β· apply M.dest_corec' cases' g x with a f; dsimp rw [MvPFunctor.map_eq]; congr conv_rhs => rw [← split_dropFun_lastFun f, appendFun_comp_splitFun] rfl theorem M.bisim_lemma {Ξ± : TypeVec n} {a₁ : (mp P).A} {f₁ : (mp P).B a₁ ⟹ Ξ±} {a' : P.A} {f' : (P.B a').drop ⟹ Ξ±} {f₁' : (P.B a').last β†’ M P Ξ±} (e₁ : M.dest P ⟨a₁, fβ‚βŸ© = ⟨a', splitFun f' f₁'⟩) : βˆƒ (g₁' : _)(e₁' : PFunctor.M.dest a₁ = ⟨a', g₁'⟩), f' = M.pathDestLeft P e₁' f₁ ∧ f₁' = fun x : (last P).B a' => ⟨g₁' x, M.pathDestRight P e₁' f₁ x⟩ := by generalize ef : @splitFun n _ (append1 Ξ± (M P Ξ±)) f' f₁' = ff at e₁ let he₁' := PFunctor.M.dest a₁ rcases e₁' : he₁' with ⟨a₁', g₁'⟩ rw [M.dest_eq_dest' _ e₁'] at e₁ cases e₁; exact ⟨_, e₁', splitFun_inj ef⟩ theorem M.bisim {Ξ± : TypeVec n} (R : P.M Ξ± β†’ P.M Ξ± β†’ Prop) (h : βˆ€ x y, R x y β†’ βˆƒ a f f₁ fβ‚‚, M.dest P x = ⟨a, splitFun f fβ‚βŸ© ∧ M.dest P y = ⟨a, splitFun f fβ‚‚βŸ© ∧ βˆ€ i, R (f₁ i) (fβ‚‚ i)) (x y) (r : R x y) : x = y := by cases' x with a₁ f₁ cases' y with aβ‚‚ fβ‚‚ dsimp [mp] at * have : a₁ = aβ‚‚ := by refine PFunctor.M.bisim (fun a₁ aβ‚‚ => βˆƒ x y, R x y ∧ x.1 = a₁ ∧ y.1 = aβ‚‚) ?_ _ _ ⟨⟨a₁, fβ‚βŸ©, ⟨aβ‚‚, fβ‚‚βŸ©, r, rfl, rfl⟩ rintro _ _ ⟨⟨a₁, fβ‚βŸ©, ⟨aβ‚‚, fβ‚‚βŸ©, r, rfl, rfl⟩ rcases h _ _ r with ⟨a', f', f₁', fβ‚‚', e₁, eβ‚‚, h'⟩ rcases M.bisim_lemma P e₁ with ⟨g₁', e₁', rfl, rfl⟩ rcases M.bisim_lemma P eβ‚‚ with ⟨gβ‚‚', eβ‚‚', _, rfl⟩ rw [e₁', eβ‚‚'] exact ⟨_, _, _, rfl, rfl, fun b => ⟨_, _, h' b, rfl, rfl⟩⟩ subst this congr with (i p) induction' p with x a f h' i c x a f h' i c p IH <;> try rcases h _ _ r with ⟨a', f', f₁', fβ‚‚', e₁, eβ‚‚, h''⟩ rcases M.bisim_lemma P e₁ with ⟨g₁', e₁', rfl, rfl⟩ rcases M.bisim_lemma P eβ‚‚ with ⟨gβ‚‚', eβ‚‚', e₃, rfl⟩ cases h'.symm.trans e₁' cases h'.symm.trans eβ‚‚' Β· exact (congr_fun (congr_fun e₃ i) c : _) Β· exact IH _ _ (h'' _) theorem M.bisimβ‚€ {Ξ± : TypeVec n} (R : P.M Ξ± β†’ P.M Ξ± β†’ Prop) (hβ‚€ : Equivalence R) (h : βˆ€ x y, R x y β†’ (id ::: Quot.mk R) <$$> M.dest _ x = (id ::: Quot.mk R) <$$> M.dest _ y) (x y) (r : R x y) : x = y := by apply M.bisim P R _ _ _ r clear r x y introv Hr specialize h _ _ Hr clear Hr revert h rcases M.dest P x with ⟨ax, fx⟩ rcases M.dest P y with ⟨ay, fy⟩ intro h rw [map_eq, map_eq] at h injection h with hβ‚€ h₁ subst ay simp? at h₁ says simp only [heq_eq_eq] at h₁ have Hdrop : dropFun fx = dropFun fy := by replace h₁ := congr_arg dropFun h₁ simpa using h₁ exists ax, dropFun fx, lastFun fx, lastFun fy rw [split_dropFun_lastFun, Hdrop, split_dropFun_lastFun] simp only [true_and] intro i replace h₁ := congr_fun (congr_fun h₁ Fin2.fz) i simp only [TypeVec.comp, appendFun, splitFun] at h₁ replace h₁ := Quot.exact _ h₁ rw [hβ‚€.eqvGen_iff] at h₁ exact h₁ theorem M.bisim' {Ξ± : TypeVec n} (R : P.M Ξ± β†’ P.M Ξ± β†’ Prop) (h : βˆ€ x y, R x y β†’ (id ::: Quot.mk R) <$$> M.dest _ x = (id ::: Quot.mk R) <$$> M.dest _ y) (x y) (r : R x y) : x = y := by have := M.bisimβ‚€ P (EqvGen R) ?_ ?_ Β· solve_by_elim [EqvGen.rel] Β· apply EqvGen.is_equivalence Β· clear r x y introv Hr have : βˆ€ x y, R x y β†’ EqvGen R x y := @EqvGen.rel _ R induction Hr Β· rw [← Quot.factor_mk_eq R (EqvGen R) this] rwa [appendFun_comp_id, ← MvFunctor.map_map, ← MvFunctor.map_map, h] all_goals aesop theorem M.dest_map {Ξ± Ξ² : TypeVec n} (g : Ξ± ⟹ Ξ²) (x : P.M Ξ±) : M.dest P (g <$$> x) = (appendFun g fun x => g <$$> x) <$$> M.dest P x := by cases' x with a f rw [map_eq] conv => rhs rw [M.dest, M.dest', map_eq, appendFun_comp_splitFun] rfl theorem M.map_dest {Ξ± Ξ² : TypeVec n} (g : (Ξ± ::: P.M Ξ±) ⟹ (Ξ² ::: P.M Ξ²)) (x : P.M Ξ±) (h : βˆ€ x : P.M Ξ±, lastFun g x = (dropFun g <$$> x : P.M Ξ²)) : g <$$> M.dest P x = M.dest P (dropFun g <$$> x) := by rw [M.dest_map]; congr apply eq_of_drop_last_eq <;> simp ext1; apply h end MvPFunctor
Data\PFunctor\Multivariate\W.lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Simon Hudon -/ import Mathlib.Data.PFunctor.Multivariate.Basic /-! # The W construction as a multivariate polynomial functor. W types are well-founded tree-like structures. They are defined as the least fixpoint of a polynomial functor. ## Main definitions * `W_mk` - constructor * `W_dest - destructor * `W_rec` - recursor: basis for defining functions by structural recursion on `P.W Ξ±` * `W_rec_eq` - defining equation for `W_rec` * `W_ind` - induction principle for `P.W Ξ±` ## Implementation notes Three views of M-types: * `wp`: polynomial functor * `W`: data type inductively defined by a triple: shape of the root, data in the root and children of the root * `W`: least fixed point of a polynomial functor Specifically, we define the polynomial functor `wp` as: * A := a tree-like structure without information in the nodes * B := given the tree-like structure `t`, `B t` is a valid path (specified inductively by `W_path`) from the root of `t` to any given node. As a result `wp Ξ±` is made of a dataless tree and a function from its valid paths to values of `Ξ±` ## Reference * Jeremy Avigad, Mario M. Carneiro and Simon Hudon. [*Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019] -/ universe u v namespace MvPFunctor open TypeVec open MvFunctor variable {n : β„•} (P : MvPFunctor.{u} (n + 1)) /-- A path from the root of a tree to one of its node -/ inductive WPath : P.last.W β†’ Fin2 n β†’ Type u | root (a : P.A) (f : P.last.B a β†’ P.last.W) (i : Fin2 n) (c : P.drop.B a i) : WPath ⟨a, f⟩ i | child (a : P.A) (f : P.last.B a β†’ P.last.W) (i : Fin2 n) (j : P.last.B a) (c : WPath (f j) i) : WPath ⟨a, f⟩ i instance WPath.inhabited (x : P.last.W) {i} [I : Inhabited (P.drop.B x.head i)] : Inhabited (WPath P x i) := ⟨match x, I with | ⟨a, f⟩, I => WPath.root a f i (@default _ I)⟩ /-- Specialized destructor on `WPath` -/ def wPathCasesOn {Ξ± : TypeVec n} {a : P.A} {f : P.last.B a β†’ P.last.W} (g' : P.drop.B a ⟹ Ξ±) (g : βˆ€ j : P.last.B a, P.WPath (f j) ⟹ Ξ±) : P.WPath ⟨a, f⟩ ⟹ Ξ± := by intro i x match x with | WPath.root _ _ i c => exact g' i c | WPath.child _ _ i j c => exact g j i c /-- Specialized destructor on `WPath` -/ def wPathDestLeft {Ξ± : TypeVec n} {a : P.A} {f : P.last.B a β†’ P.last.W} (h : P.WPath ⟨a, f⟩ ⟹ Ξ±) : P.drop.B a ⟹ Ξ± := fun i c => h i (WPath.root a f i c) /-- Specialized destructor on `WPath` -/ def wPathDestRight {Ξ± : TypeVec n} {a : P.A} {f : P.last.B a β†’ P.last.W} (h : P.WPath ⟨a, f⟩ ⟹ Ξ±) : βˆ€ j : P.last.B a, P.WPath (f j) ⟹ Ξ± := fun j i c => h i (WPath.child a f i j c) theorem wPathDestLeft_wPathCasesOn {Ξ± : TypeVec n} {a : P.A} {f : P.last.B a β†’ P.last.W} (g' : P.drop.B a ⟹ Ξ±) (g : βˆ€ j : P.last.B a, P.WPath (f j) ⟹ Ξ±) : P.wPathDestLeft (P.wPathCasesOn g' g) = g' := rfl theorem wPathDestRight_wPathCasesOn {Ξ± : TypeVec n} {a : P.A} {f : P.last.B a β†’ P.last.W} (g' : P.drop.B a ⟹ Ξ±) (g : βˆ€ j : P.last.B a, P.WPath (f j) ⟹ Ξ±) : P.wPathDestRight (P.wPathCasesOn g' g) = g := rfl theorem wPathCasesOn_eta {Ξ± : TypeVec n} {a : P.A} {f : P.last.B a β†’ P.last.W} (h : P.WPath ⟨a, f⟩ ⟹ Ξ±) : P.wPathCasesOn (P.wPathDestLeft h) (P.wPathDestRight h) = h := by ext i x; cases x <;> rfl theorem comp_wPathCasesOn {Ξ± Ξ² : TypeVec n} (h : Ξ± ⟹ Ξ²) {a : P.A} {f : P.last.B a β†’ P.last.W} (g' : P.drop.B a ⟹ Ξ±) (g : βˆ€ j : P.last.B a, P.WPath (f j) ⟹ Ξ±) : h ⊚ P.wPathCasesOn g' g = P.wPathCasesOn (h ⊚ g') fun i => h ⊚ g i := by ext i x; cases x <;> rfl /-- Polynomial functor for the W-type of `P`. `A` is a data-less well-founded tree whereas, for a given `a : A`, `B a` is a valid path in tree `a` so that `Wp.obj Ξ±` is made of a tree and a function from its valid paths to the values it contains -/ def wp : MvPFunctor n where A := P.last.W B := P.WPath /-- W-type of `P` -/ -- Porting note(#5171): used to have @[nolint has_nonempty_instance] def W (Ξ± : TypeVec n) : Type _ := P.wp Ξ± instance mvfunctorW : MvFunctor P.W := by delta MvPFunctor.W; infer_instance /-! First, describe operations on `W` as a polynomial functor. -/ /-- Constructor for `wp` -/ def wpMk {Ξ± : TypeVec n} (a : P.A) (f : P.last.B a β†’ P.last.W) (f' : P.WPath ⟨a, f⟩ ⟹ Ξ±) : P.W Ξ± := ⟨⟨a, f⟩, f'⟩ def wpRec {Ξ± : TypeVec n} {C : Type*} (g : βˆ€ (a : P.A) (f : P.last.B a β†’ P.last.W), P.WPath ⟨a, f⟩ ⟹ Ξ± β†’ (P.last.B a β†’ C) β†’ C) : βˆ€ (x : P.last.W) (_ : P.WPath x ⟹ Ξ±), C | ⟨a, f⟩, f' => g a f f' fun i => wpRec g (f i) (P.wPathDestRight f' i) theorem wpRec_eq {Ξ± : TypeVec n} {C : Type*} (g : βˆ€ (a : P.A) (f : P.last.B a β†’ P.last.W), P.WPath ⟨a, f⟩ ⟹ Ξ± β†’ (P.last.B a β†’ C) β†’ C) (a : P.A) (f : P.last.B a β†’ P.last.W) (f' : P.WPath ⟨a, f⟩ ⟹ Ξ±) : P.wpRec g ⟨a, f⟩ f' = g a f f' fun i => P.wpRec g (f i) (P.wPathDestRight f' i) := rfl -- Note: we could replace Prop by Type* and obtain a dependent recursor theorem wp_ind {Ξ± : TypeVec n} {C : βˆ€ x : P.last.W, P.WPath x ⟹ Ξ± β†’ Prop} (ih : βˆ€ (a : P.A) (f : P.last.B a β†’ P.last.W) (f' : P.WPath ⟨a, f⟩ ⟹ Ξ±), (βˆ€ i : P.last.B a, C (f i) (P.wPathDestRight f' i)) β†’ C ⟨a, f⟩ f') : βˆ€ (x : P.last.W) (f' : P.WPath x ⟹ Ξ±), C x f' | ⟨a, f⟩, f' => ih a f f' fun _i => wp_ind ih _ _ /-! Now think of W as defined inductively by the data ⟨a, f', f⟩ where - `a : P.A` is the shape of the top node - `f' : P.drop.B a ⟹ Ξ±` is the contents of the top node - `f : P.last.B a β†’ P.last.W` are the subtrees -/ /-- Constructor for `W` -/ def wMk {Ξ± : TypeVec n} (a : P.A) (f' : P.drop.B a ⟹ Ξ±) (f : P.last.B a β†’ P.W Ξ±) : P.W Ξ± := let g : P.last.B a β†’ P.last.W := fun i => (f i).fst let g' : P.WPath ⟨a, g⟩ ⟹ Ξ± := P.wPathCasesOn f' fun i => (f i).snd ⟨⟨a, g⟩, g'⟩ /-- Recursor for `W` -/ def wRec {Ξ± : TypeVec n} {C : Type*} (g : βˆ€ a : P.A, P.drop.B a ⟹ Ξ± β†’ (P.last.B a β†’ P.W Ξ±) β†’ (P.last.B a β†’ C) β†’ C) : P.W Ξ± β†’ C | ⟨a, f'⟩ => let g' (a : P.A) (f : P.last.B a β†’ P.last.W) (h : P.WPath ⟨a, f⟩ ⟹ Ξ±) (h' : P.last.B a β†’ C) : C := g a (P.wPathDestLeft h) (fun i => ⟨f i, P.wPathDestRight h i⟩) h' P.wpRec g' a f' /-- Defining equation for the recursor of `W` -/ theorem wRec_eq {Ξ± : TypeVec n} {C : Type*} (g : βˆ€ a : P.A, P.drop.B a ⟹ Ξ± β†’ (P.last.B a β†’ P.W Ξ±) β†’ (P.last.B a β†’ C) β†’ C) (a : P.A) (f' : P.drop.B a ⟹ Ξ±) (f : P.last.B a β†’ P.W Ξ±) : P.wRec g (P.wMk a f' f) = g a f' f fun i => P.wRec g (f i) := by rw [wMk, wRec]; dsimp; rw [wpRec_eq] dsimp only [wPathDestLeft_wPathCasesOn, wPathDestRight_wPathCasesOn] congr /-- Induction principle for `W` -/ theorem w_ind {Ξ± : TypeVec n} {C : P.W Ξ± β†’ Prop} (ih : βˆ€ (a : P.A) (f' : P.drop.B a ⟹ Ξ±) (f : P.last.B a β†’ P.W Ξ±), (βˆ€ i, C (f i)) β†’ C (P.wMk a f' f)) : βˆ€ x, C x := by intro x; cases' x with a f apply @wp_ind n P Ξ± fun a f => C ⟨a, f⟩ intro a f f' ih' dsimp [wMk] at ih let ih'' := ih a (P.wPathDestLeft f') fun i => ⟨f i, P.wPathDestRight f' i⟩ dsimp at ih''; rw [wPathCasesOn_eta] at ih'' apply ih'' apply ih' theorem w_cases {Ξ± : TypeVec n} {C : P.W Ξ± β†’ Prop} (ih : βˆ€ (a : P.A) (f' : P.drop.B a ⟹ Ξ±) (f : P.last.B a β†’ P.W Ξ±), C (P.wMk a f' f)) : βˆ€ x, C x := P.w_ind fun a f' f _ih' => ih a f' f /-- W-types are functorial -/ def wMap {Ξ± Ξ² : TypeVec n} (g : Ξ± ⟹ Ξ²) : P.W Ξ± β†’ P.W Ξ² := fun x => g <$$> x theorem wMk_eq {Ξ± : TypeVec n} (a : P.A) (f : P.last.B a β†’ P.last.W) (g' : P.drop.B a ⟹ Ξ±) (g : βˆ€ j : P.last.B a, P.WPath (f j) ⟹ Ξ±) : (P.wMk a g' fun i => ⟨f i, g i⟩) = ⟨⟨a, f⟩, P.wPathCasesOn g' g⟩ := rfl theorem w_map_wMk {Ξ± Ξ² : TypeVec n} (g : Ξ± ⟹ Ξ²) (a : P.A) (f' : P.drop.B a ⟹ Ξ±) (f : P.last.B a β†’ P.W Ξ±) : g <$$> P.wMk a f' f = P.wMk a (g ⊚ f') fun i => g <$$> f i := by show _ = P.wMk a (g ⊚ f') (MvFunctor.map g ∘ f) have : MvFunctor.map g ∘ f = fun i => ⟨(f i).fst, g ⊚ (f i).snd⟩ := by ext i : 1 dsimp [Function.comp_def] cases f i rfl rw [this] have : f = fun i => ⟨(f i).fst, (f i).snd⟩ := by ext1 x cases f x rfl rw [this] dsimp rw [wMk_eq, wMk_eq] have h := MvPFunctor.map_eq P.wp g rw [h, comp_wPathCasesOn] -- TODO: this technical theorem is used in one place in constructing the initial algebra. -- Can it be avoided? /-- Constructor of a value of `P.obj (Ξ± ::: Ξ²)` from components. Useful to avoid complicated type annotation -/ abbrev objAppend1 {Ξ± : TypeVec n} {Ξ² : Type u} (a : P.A) (f' : P.drop.B a ⟹ Ξ±) (f : P.last.B a β†’ Ξ²) : P (Ξ± ::: Ξ²) := ⟨a, splitFun f' f⟩ theorem map_objAppend1 {Ξ± Ξ³ : TypeVec n} (g : Ξ± ⟹ Ξ³) (a : P.A) (f' : P.drop.B a ⟹ Ξ±) (f : P.last.B a β†’ P.W Ξ±) : appendFun g (P.wMap g) <$$> P.objAppend1 a f' f = P.objAppend1 a (g ⊚ f') fun x => P.wMap g (f x) := by rw [objAppend1, objAppend1, map_eq, appendFun, ← splitFun_comp]; rfl /-! Yet another view of the W type: as a fixed point for a multivariate polynomial functor. These are needed to use the W-construction to construct a fixed point of a qpf, since the qpf axioms are expressed in terms of `map` on `P`. -/ /-- Constructor for the W-type of `P` -/ def wMk' {Ξ± : TypeVec n} : P (Ξ± ::: P.W Ξ±) β†’ P.W Ξ± | ⟨a, f⟩ => P.wMk a (dropFun f) (lastFun f) /-- Destructor for the W-type of `P` -/ def wDest' {Ξ± : TypeVec.{u} n} : P.W Ξ± β†’ P (Ξ±.append1 (P.W Ξ±)) := P.wRec fun a f' f _ => ⟨a, splitFun f' f⟩ theorem wDest'_wMk {Ξ± : TypeVec n} (a : P.A) (f' : P.drop.B a ⟹ Ξ±) (f : P.last.B a β†’ P.W Ξ±) : P.wDest' (P.wMk a f' f) = ⟨a, splitFun f' f⟩ := by rw [wDest', wRec_eq] theorem wDest'_wMk' {Ξ± : TypeVec n} (x : P (Ξ±.append1 (P.W Ξ±))) : P.wDest' (P.wMk' x) = x := by cases' x with a f; rw [wMk', wDest'_wMk, split_dropFun_lastFun] end MvPFunctor
Data\PFunctor\Univariate\Basic.lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import Mathlib.Data.W.Basic /-! # Polynomial functors This file defines polynomial functors and the W-type construction as a polynomial functor. (For the M-type construction, see pfunctor/M.lean.) -/ -- "W", "Idx" universe u v v₁ vβ‚‚ v₃ /-- A polynomial functor `P` is given by a type `A` and a family `B` of types over `A`. `P` maps any type `Ξ±` to a new type `P Ξ±`, which is defined as the sigma type `Ξ£ x, P.B x β†’ Ξ±`. An element of `P Ξ±` is a pair `⟨a, f⟩`, where `a` is an element of a type `A` and `f : B a β†’ Ξ±`. Think of `a` as the shape of the object and `f` as an index to the relevant elements of `Ξ±`. -/ @[pp_with_univ] structure PFunctor where /-- The head type -/ A : Type u /-- The child family of types -/ B : A β†’ Type u namespace PFunctor instance : Inhabited PFunctor := ⟨⟨default, default⟩⟩ variable (P : PFunctor.{u}) {Ξ± : Type v₁} {Ξ² : Type vβ‚‚} {Ξ³ : Type v₃} /-- Applying `P` to an object of `Type` -/ @[coe] def Obj (Ξ± : Type v) := Ξ£ x : P.A, P.B x β†’ Ξ± instance : CoeFun PFunctor.{u} (fun _ => Type v β†’ Type (max u v)) where coe := Obj /-- Applying `P` to a morphism of `Type` -/ def map (f : Ξ± β†’ Ξ²) : P Ξ± β†’ P Ξ² := fun ⟨a, g⟩ => ⟨a, f ∘ g⟩ instance Obj.inhabited [Inhabited P.A] [Inhabited Ξ±] : Inhabited (P Ξ±) := ⟨⟨default, default⟩⟩ instance : Functor.{v, max u v} P.Obj where map := @map P /-- We prefer `PFunctor.map` to `Functor.map` because it is universe-polymorphic. -/ @[simp] theorem map_eq_map {Ξ± Ξ² : Type v} (f : Ξ± β†’ Ξ²) (x : P Ξ±) : f <$> x = P.map f x := rfl @[simp] protected theorem map_eq (f : Ξ± β†’ Ξ²) (a : P.A) (g : P.B a β†’ Ξ±) : P.map f ⟨a, g⟩ = ⟨a, f ∘ g⟩ := rfl @[simp] protected theorem id_map : βˆ€ x : P Ξ±, P.map id x = x := fun ⟨_, _⟩ => rfl @[simp] protected theorem map_map (f : Ξ± β†’ Ξ²) (g : Ξ² β†’ Ξ³) : βˆ€ x : P Ξ±, P.map g (P.map f x) = P.map (g ∘ f) x := fun ⟨_, _⟩ => rfl instance : LawfulFunctor.{v, max u v} P.Obj where map_const := rfl id_map x := P.id_map x comp_map f g x := P.map_map f g x |>.symm /-- re-export existing definition of W-types and adapt it to a packaged definition of polynomial functor -/ def W := WType P.B /- inhabitants of W types is awkward to encode as an instance assumption because there needs to be a value `a : P.A` such that `P.B a` is empty to yield a finite tree -/ -- Porting note(#5171): this linter isn't ported yet. -- attribute [nolint has_nonempty_instance] W variable {P} /-- root element of a W tree -/ def W.head : W P β†’ P.A | ⟨a, _f⟩ => a /-- children of the root of a W tree -/ def W.children : βˆ€ x : W P, P.B (W.head x) β†’ W P | ⟨_a, f⟩ => f /-- destructor for W-types -/ def W.dest : W P β†’ P (W P) | ⟨a, f⟩ => ⟨a, f⟩ /-- constructor for W-types -/ def W.mk : P (W P) β†’ W P | ⟨a, f⟩ => ⟨a, f⟩ @[simp] theorem W.dest_mk (p : P (W P)) : W.dest (W.mk p) = p := by cases p; rfl @[simp] theorem W.mk_dest (p : W P) : W.mk (W.dest p) = p := by cases p; rfl variable (P) /-- `Idx` identifies a location inside the application of a pfunctor. For `F : PFunctor`, `x : F Ξ±` and `i : F.Idx`, `i` can designate one part of `x` or is invalid, if `i.1 β‰  x.1` -/ def Idx := Ξ£ x : P.A, P.B x instance Idx.inhabited [Inhabited P.A] [Inhabited (P.B default)] : Inhabited P.Idx := ⟨⟨default, default⟩⟩ variable {P} /-- `x.iget i` takes the component of `x` designated by `i` if any is or returns a default value -/ def Obj.iget [DecidableEq P.A] {Ξ±} [Inhabited Ξ±] (x : P Ξ±) (i : P.Idx) : Ξ± := if h : i.1 = x.1 then x.2 (cast (congr_arg _ h) i.2) else default @[simp] theorem fst_map (x : P Ξ±) (f : Ξ± β†’ Ξ²) : (P.map f x).1 = x.1 := by cases x; rfl @[simp] theorem iget_map [DecidableEq P.A] [Inhabited Ξ±] [Inhabited Ξ²] (x : P Ξ±) (f : Ξ± β†’ Ξ²) (i : P.Idx) (h : i.1 = x.1) : (P.map f x).iget i = f (x.iget i) := by simp only [Obj.iget, fst_map, *, dif_pos, eq_self_iff_true] cases x rfl end PFunctor /- Composition of polynomial functors. -/ namespace PFunctor /-- functor composition for polynomial functors -/ def comp (Pβ‚‚ P₁ : PFunctor.{u}) : PFunctor.{u} := ⟨Σ aβ‚‚ : Pβ‚‚.1, Pβ‚‚.2 aβ‚‚ β†’ P₁.1, fun aβ‚‚a₁ => Ξ£ u : Pβ‚‚.2 aβ‚‚a₁.1, P₁.2 (aβ‚‚a₁.2 u)⟩ /-- constructor for composition -/ def comp.mk (Pβ‚‚ P₁ : PFunctor.{u}) {Ξ± : Type} (x : Pβ‚‚ (P₁ Ξ±)) : comp Pβ‚‚ P₁ Ξ± := ⟨⟨x.1, Sigma.fst ∘ x.2⟩, fun aβ‚‚a₁ => (x.2 aβ‚‚a₁.1).2 aβ‚‚a₁.2⟩ /-- destructor for composition -/ def comp.get (Pβ‚‚ P₁ : PFunctor.{u}) {Ξ± : Type} (x : comp Pβ‚‚ P₁ Ξ±) : Pβ‚‚ (P₁ Ξ±) := ⟨x.1.1, fun aβ‚‚ => ⟨x.1.2 aβ‚‚, fun a₁ => x.2 ⟨aβ‚‚, aβ‚βŸ©βŸ©βŸ© end PFunctor /- Lifting predicates and relations. -/ namespace PFunctor variable {P : PFunctor.{u}} open Functor theorem liftp_iff {Ξ± : Type u} (p : Ξ± β†’ Prop) (x : P Ξ±) : Liftp p x ↔ βˆƒ a f, x = ⟨a, f⟩ ∧ βˆ€ i, p (f i) := by constructor Β· rintro ⟨y, hy⟩ cases' h : y with a f refine ⟨a, fun i => (f i).val, ?_, fun i => (f i).property⟩ rw [← hy, h, map_eq_map, PFunctor.map_eq] congr rintro ⟨a, f, xeq, pf⟩ use ⟨a, fun i => ⟨f i, pf i⟩⟩ rw [xeq]; rfl theorem liftp_iff' {Ξ± : Type u} (p : Ξ± β†’ Prop) (a : P.A) (f : P.B a β†’ Ξ±) : @Liftp.{u} P.Obj _ Ξ± p ⟨a, f⟩ ↔ βˆ€ i, p (f i) := by simp only [liftp_iff, Sigma.mk.inj_iff]; constructor <;> intro h Β· rcases h with ⟨a', f', heq, h'⟩ cases heq assumption repeat' first |constructor|assumption theorem liftr_iff {Ξ± : Type u} (r : Ξ± β†’ Ξ± β†’ Prop) (x y : P Ξ±) : Liftr r x y ↔ βˆƒ a fβ‚€ f₁, x = ⟨a, fβ‚€βŸ© ∧ y = ⟨a, fβ‚βŸ© ∧ βˆ€ i, r (fβ‚€ i) (f₁ i) := by constructor Β· rintro ⟨u, xeq, yeq⟩ cases' h : u with a f use a, fun i => (f i).val.fst, fun i => (f i).val.snd constructor Β· rw [← xeq, h] rfl constructor Β· rw [← yeq, h] rfl intro i exact (f i).property rintro ⟨a, fβ‚€, f₁, xeq, yeq, h⟩ use ⟨a, fun i => ⟨(fβ‚€ i, f₁ i), h i⟩⟩ constructor Β· rw [xeq] rfl rw [yeq]; rfl open Set theorem supp_eq {Ξ± : Type u} (a : P.A) (f : P.B a β†’ Ξ±) : @supp.{u} P.Obj _ Ξ± (⟨a, f⟩ : P Ξ±) = f '' univ := by ext x; simp only [supp, image_univ, mem_range, mem_setOf_eq] constructor <;> intro h Β· apply @h fun x => βˆƒ y : P.B a, f y = x rw [liftp_iff'] intro exact ⟨_, rfl⟩ Β· simp only [liftp_iff'] cases h subst x tauto end PFunctor
Data\PFunctor\Univariate\M.lean
/- Copyright (c) 2017 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Data.PFunctor.Univariate.Basic /-! # M-types M types are potentially infinite tree-like structures. They are defined as the greatest fixpoint of a polynomial functor. -/ universe u v w open Nat Function open List variable (F : PFunctor.{u}) -- Porting note: the β™― tactic is never used -- local prefix:0 "β™―" => cast (by first |simp [*]|cc|solve_by_elim) namespace PFunctor namespace Approx /-- `CofixA F n` is an `n` level approximation of an M-type -/ inductive CofixA : β„• β†’ Type u | continue : CofixA 0 | intro {n} : βˆ€ a, (F.B a β†’ CofixA n) β†’ CofixA (succ n) /-- default inhabitant of `CofixA` -/ protected def CofixA.default [Inhabited F.A] : βˆ€ n, CofixA F n | 0 => CofixA.continue | succ n => CofixA.intro default fun _ => CofixA.default n instance [Inhabited F.A] {n} : Inhabited (CofixA F n) := ⟨CofixA.default F n⟩ theorem cofixA_eq_zero : βˆ€ x y : CofixA F 0, x = y | CofixA.continue, CofixA.continue => rfl variable {F} /-- The label of the root of the tree for a non-trivial approximation of the cofix of a pfunctor. -/ def head' : βˆ€ {n}, CofixA F (succ n) β†’ F.A | _, CofixA.intro i _ => i /-- for a non-trivial approximation, return all the subtrees of the root -/ def children' : βˆ€ {n} (x : CofixA F (succ n)), F.B (head' x) β†’ CofixA F n | _, CofixA.intro _ f => f theorem approx_eta {n : β„•} (x : CofixA F (n + 1)) : x = CofixA.intro (head' x) (children' x) := by cases x; rfl /-- Relation between two approximations of the cofix of a pfunctor that state they both contain the same data until one of them is truncated -/ inductive Agree : βˆ€ {n : β„•}, CofixA F n β†’ CofixA F (n + 1) β†’ Prop | continu (x : CofixA F 0) (y : CofixA F 1) : Agree x y | intro {n} {a} (x : F.B a β†’ CofixA F n) (x' : F.B a β†’ CofixA F (n + 1)) : (βˆ€ i : F.B a, Agree (x i) (x' i)) β†’ Agree (CofixA.intro a x) (CofixA.intro a x') /-- Given an infinite series of approximations `approx`, `AllAgree approx` states that they are all consistent with each other. -/ def AllAgree (x : βˆ€ n, CofixA F n) := βˆ€ n, Agree (x n) (x (succ n)) @[simp] theorem agree_trival {x : CofixA F 0} {y : CofixA F 1} : Agree x y := by constructor theorem agree_children {n : β„•} (x : CofixA F (succ n)) (y : CofixA F (succ n + 1)) {i j} (hβ‚€ : HEq i j) (h₁ : Agree x y) : Agree (children' x i) (children' y j) := by cases' h₁ with _ _ _ _ _ _ hagree; cases hβ‚€ apply hagree /-- `truncate a` turns `a` into a more limited approximation -/ def truncate : βˆ€ {n : β„•}, CofixA F (n + 1) β†’ CofixA F n | 0, CofixA.intro _ _ => CofixA.continue | succ _, CofixA.intro i f => CofixA.intro i <| truncate ∘ f theorem truncate_eq_of_agree {n : β„•} (x : CofixA F n) (y : CofixA F (succ n)) (h : Agree x y) : truncate y = x := by induction n <;> cases x <;> cases y Β· rfl Β· -- cases' h with _ _ _ _ _ hβ‚€ h₁ cases h simp only [truncate, Function.comp, true_and_iff, eq_self_iff_true, heq_iff_eq] -- Porting note: used to be `ext y` rename_i n_ih a f y h₁ suffices (fun x => truncate (y x)) = f by simp [this] funext y apply n_ih apply h₁ variable {X : Type w} variable (f : X β†’ F X) /-- `sCorec f i n` creates an approximation of height `n` of the final coalgebra of `f` -/ def sCorec : X β†’ βˆ€ n, CofixA F n | _, 0 => CofixA.continue | j, succ _ => CofixA.intro (f j).1 fun i => sCorec ((f j).2 i) _ theorem P_corec (i : X) (n : β„•) : Agree (sCorec f i n) (sCorec f i (succ n)) := by induction' n with n n_ih generalizing i constructor cases' f i with y g constructor introv apply n_ih /-- `Path F` provides indices to access internal nodes in `Corec F` -/ def Path (F : PFunctor.{u}) := List F.Idx instance Path.inhabited : Inhabited (Path F) := ⟨[]⟩ open List Nat instance CofixA.instSubsingleton : Subsingleton (CofixA F 0) := ⟨by rintro ⟨⟩ ⟨⟩; rfl⟩ theorem head_succ' (n m : β„•) (x : βˆ€ n, CofixA F n) (Hconsistent : AllAgree x) : head' (x (succ n)) = head' (x (succ m)) := by suffices βˆ€ n, head' (x (succ n)) = head' (x 1) by simp [this] clear m n intro n cases' hβ‚€ : x (succ n) with _ iβ‚€ fβ‚€ cases' h₁ : x 1 with _ i₁ f₁ dsimp only [head'] induction' n with n n_ih Β· rw [h₁] at hβ‚€ cases hβ‚€ trivial Β· have H := Hconsistent (succ n) cases' hβ‚‚ : x (succ n) with _ iβ‚‚ fβ‚‚ rw [hβ‚€, hβ‚‚] at H apply n_ih (truncate ∘ fβ‚€) rw [hβ‚‚] cases' H with _ _ _ _ _ _ hagree congr funext j dsimp only [comp_apply] rw [truncate_eq_of_agree] apply hagree end Approx open Approx /-- Internal definition for `M`. It is needed to avoid name clashes between `M.mk` and `M.cases_on` and the declarations generated for the structure -/ structure MIntl where /-- An `n`-th level approximation, for each depth `n` -/ approx : βˆ€ n, CofixA F n /-- Each approximation agrees with the next -/ consistent : AllAgree approx /-- For polynomial functor `F`, `M F` is its final coalgebra -/ def M := MIntl F theorem M.default_consistent [Inhabited F.A] : βˆ€ n, Agree (default : CofixA F n) default | 0 => Agree.continu _ _ | succ n => Agree.intro _ _ fun _ => M.default_consistent n instance M.inhabited [Inhabited F.A] : Inhabited (M F) := ⟨{ approx := default consistent := M.default_consistent _ }⟩ instance MIntl.inhabited [Inhabited F.A] : Inhabited (MIntl F) := show Inhabited (M F) by infer_instance namespace M theorem ext' (x y : M F) (H : βˆ€ i : β„•, x.approx i = y.approx i) : x = y := by cases x cases y congr with n apply H variable {X : Type*} variable (f : X β†’ F X) variable {F} /-- Corecursor for the M-type defined by `F`. -/ protected def corec (i : X) : M F where approx := sCorec f i consistent := P_corec _ _ /-- given a tree generated by `F`, `head` gives us the first piece of data it contains -/ def head (x : M F) := head' (x.1 1) /-- return all the subtrees of the root of a tree `x : M F` -/ def children (x : M F) (i : F.B (head x)) : M F := let H := fun n : β„• => @head_succ' _ n 0 x.1 x.2 { approx := fun n => children' (x.1 _) (cast (congr_arg _ <| by simp only [head, H]) i) consistent := by intro n have P' := x.2 (succ n) apply agree_children _ _ _ P' trans i Β· apply cast_heq symm apply cast_heq } /-- select a subtree using an `i : F.Idx` or return an arbitrary tree if `i` designates no subtree of `x` -/ def ichildren [Inhabited (M F)] [DecidableEq F.A] (i : F.Idx) (x : M F) : M F := if H' : i.1 = head x then children x (cast (congr_arg _ <| by simp only [head, H']) i.2) else default theorem head_succ (n m : β„•) (x : M F) : head' (x.approx (succ n)) = head' (x.approx (succ m)) := head_succ' n m _ x.consistent theorem head_eq_head' : βˆ€ (x : M F) (n : β„•), head x = head' (x.approx <| n + 1) | ⟨_, h⟩, _ => head_succ' _ _ _ h theorem head'_eq_head : βˆ€ (x : M F) (n : β„•), head' (x.approx <| n + 1) = head x | ⟨_, h⟩, _ => head_succ' _ _ _ h theorem truncate_approx (x : M F) (n : β„•) : truncate (x.approx <| n + 1) = x.approx n := truncate_eq_of_agree _ _ (x.consistent _) /-- unfold an M-type -/ def dest : M F β†’ F (M F) | x => ⟨head x, fun i => children x i⟩ namespace Approx /-- generates the approximations needed for `M.mk` -/ protected def sMk (x : F (M F)) : βˆ€ n, CofixA F n | 0 => CofixA.continue | succ n => CofixA.intro x.1 fun i => (x.2 i).approx n protected theorem P_mk (x : F (M F)) : AllAgree (Approx.sMk x) | 0 => by constructor | succ n => by constructor introv apply (x.2 i).consistent end Approx /-- constructor for M-types -/ protected def mk (x : F (M F)) : M F where approx := Approx.sMk x consistent := Approx.P_mk x /-- `Agree' n` relates two trees of type `M F` that are the same up to depth `n` -/ inductive Agree' : β„• β†’ M F β†’ M F β†’ Prop | trivial (x y : M F) : Agree' 0 x y | step {n : β„•} {a} (x y : F.B a β†’ M F) {x' y'} : x' = M.mk ⟨a, x⟩ β†’ y' = M.mk ⟨a, y⟩ β†’ (βˆ€ i, Agree' n (x i) (y i)) β†’ Agree' (succ n) x' y' @[simp] theorem dest_mk (x : F (M F)) : dest (M.mk x) = x := rfl @[simp] theorem mk_dest (x : M F) : M.mk (dest x) = x := by apply ext' intro n dsimp only [M.mk] induction' n with n Β· apply @Subsingleton.elim _ CofixA.instSubsingleton dsimp only [Approx.sMk, dest, head] cases' h : x.approx (succ n) with _ hd ch have h' : hd = head' (x.approx 1) := by rw [← head_succ' n, h, head'] Β· split injections Β· apply x.consistent revert ch rw [h'] intros ch h congr ext a dsimp only [children] generalize hh : cast _ a = a'' rw [cast_eq_iff_heq] at hh revert a'' rw [h] intros _ hh cases hh rfl theorem mk_inj {x y : F (M F)} (h : M.mk x = M.mk y) : x = y := by rw [← dest_mk x, h, dest_mk] /-- destructor for M-types -/ protected def cases {r : M F β†’ Sort w} (f : βˆ€ x : F (M F), r (M.mk x)) (x : M F) : r x := suffices r (M.mk (dest x)) by rw [← mk_dest x] exact this f _ /-- destructor for M-types -/ protected def casesOn {r : M F β†’ Sort w} (x : M F) (f : βˆ€ x : F (M F), r (M.mk x)) : r x := M.cases f x /-- destructor for M-types, similar to `casesOn` but also gives access directly to the root and subtrees on an M-type -/ protected def casesOn' {r : M F β†’ Sort w} (x : M F) (f : βˆ€ a f, r (M.mk ⟨a, f⟩)) : r x := M.casesOn x (fun ⟨a, g⟩ => f a g) theorem approx_mk (a : F.A) (f : F.B a β†’ M F) (i : β„•) : (M.mk ⟨a, f⟩).approx (succ i) = CofixA.intro a fun j => (f j).approx i := rfl @[simp] theorem agree'_refl {n : β„•} (x : M F) : Agree' n x x := by induction' n with _ n_ih generalizing x <;> induction x using PFunctor.M.casesOn' <;> constructor <;> try rfl intros apply n_ih theorem agree_iff_agree' {n : β„•} (x y : M F) : Agree (x.approx n) (y.approx <| n + 1) ↔ Agree' n x y := by constructor <;> intro h Β· induction' n with _ n_ih generalizing x y Β· constructor Β· induction x using PFunctor.M.casesOn' induction y using PFunctor.M.casesOn' simp only [approx_mk] at h cases' h with _ _ _ _ _ _ hagree constructor <;> try rfl intro i apply n_ih apply hagree Β· induction' n with _ n_ih generalizing x y Β· constructor Β· cases' h with _ _ _ a x' y' induction' x using PFunctor.M.casesOn' with x_a x_f induction' y using PFunctor.M.casesOn' with y_a y_f simp only [approx_mk] have h_a_1 := mk_inj β€ΉM.mk ⟨x_a, x_f⟩ = M.mk ⟨a, x'βŸ©β€Ί cases h_a_1 replace h_a_2 := mk_inj β€ΉM.mk ⟨y_a, y_f⟩ = M.mk ⟨a, y'βŸ©β€Ί cases h_a_2 constructor intro i apply n_ih simp [*] @[simp] theorem cases_mk {r : M F β†’ Sort*} (x : F (M F)) (f : βˆ€ x : F (M F), r (M.mk x)) : PFunctor.M.cases f (M.mk x) = f x := by dsimp only [M.mk, PFunctor.M.cases, dest, head, Approx.sMk, head'] cases x; dsimp only [Approx.sMk] simp only [Eq.mpr] apply congrFun rfl @[simp] theorem casesOn_mk {r : M F β†’ Sort*} (x : F (M F)) (f : βˆ€ x : F (M F), r (M.mk x)) : PFunctor.M.casesOn (M.mk x) f = f x := cases_mk x f @[simp] theorem casesOn_mk' {r : M F β†’ Sort*} {a} (x : F.B a β†’ M F) (f : βˆ€ (a) (f : F.B a β†’ M F), r (M.mk ⟨a, f⟩)) : PFunctor.M.casesOn' (M.mk ⟨a, x⟩) f = f a x := @cases_mk F r ⟨a, x⟩ (fun ⟨a, g⟩ => f a g) /-- `IsPath p x` tells us if `p` is a valid path through `x` -/ inductive IsPath : Path F β†’ M F β†’ Prop | nil (x : M F) : IsPath [] x | cons (xs : Path F) {a} (x : M F) (f : F.B a β†’ M F) (i : F.B a) : x = M.mk ⟨a, f⟩ β†’ IsPath xs (f i) β†’ IsPath (⟨a, i⟩ :: xs) x theorem isPath_cons {xs : Path F} {a a'} {f : F.B a β†’ M F} {i : F.B a'} : IsPath (⟨a', i⟩ :: xs) (M.mk ⟨a, f⟩) β†’ a = a' := by generalize h : M.mk ⟨a, f⟩ = x rintro (_ | ⟨_, _, _, _, rfl, _⟩) cases mk_inj h rfl theorem isPath_cons' {xs : Path F} {a} {f : F.B a β†’ M F} {i : F.B a} : IsPath (⟨a, i⟩ :: xs) (M.mk ⟨a, f⟩) β†’ IsPath xs (f i) := by generalize h : M.mk ⟨a, f⟩ = x rintro (_ | ⟨_, _, _, _, rfl, hp⟩) cases mk_inj h exact hp /-- follow a path through a value of `M F` and return the subtree found at the end of the path if it is a valid path for that value and return a default tree -/ def isubtree [DecidableEq F.A] [Inhabited (M F)] : Path F β†’ M F β†’ M F | [], x => x | ⟨a, i⟩ :: ps, x => PFunctor.M.casesOn' (r := fun _ => M F) x (fun a' f => if h : a = a' then isubtree ps (f <| cast (by rw [h]) i) else default (Ξ± := M F) ) /-- similar to `isubtree` but returns the data at the end of the path instead of the whole subtree -/ def iselect [DecidableEq F.A] [Inhabited (M F)] (ps : Path F) : M F β†’ F.A := fun x : M F => head <| isubtree ps x theorem iselect_eq_default [DecidableEq F.A] [Inhabited (M F)] (ps : Path F) (x : M F) (h : Β¬IsPath ps x) : iselect ps x = head default := by induction' ps with ps_hd ps_tail ps_ih generalizing x Β· exfalso apply h constructor Β· cases' ps_hd with a i induction' x using PFunctor.M.casesOn' with x_a x_f simp only [iselect, isubtree] at ps_ih ⊒ by_cases h'' : a = x_a Β· subst x_a simp only [dif_pos, eq_self_iff_true, casesOn_mk'] rw [ps_ih] intro h' apply h constructor <;> try rfl apply h' Β· simp [*] @[simp] theorem head_mk (x : F (M F)) : head (M.mk x) = x.1 := Eq.symm <| calc x.1 = (dest (M.mk x)).1 := by rw [dest_mk] _ = head (M.mk x) := rfl theorem children_mk {a} (x : F.B a β†’ M F) (i : F.B (head (M.mk ⟨a, x⟩))) : children (M.mk ⟨a, x⟩) i = x (cast (by rw [head_mk]) i) := by apply ext'; intro n; rfl @[simp] theorem ichildren_mk [DecidableEq F.A] [Inhabited (M F)] (x : F (M F)) (i : F.Idx) : ichildren i (M.mk x) = x.iget i := by dsimp only [ichildren, PFunctor.Obj.iget] congr with h @[simp] theorem isubtree_cons [DecidableEq F.A] [Inhabited (M F)] (ps : Path F) {a} (f : F.B a β†’ M F) {i : F.B a} : isubtree (⟨_, i⟩ :: ps) (M.mk ⟨a, f⟩) = isubtree ps (f i) := by simp only [isubtree, ichildren_mk, PFunctor.Obj.iget, dif_pos, isubtree, M.casesOn_mk']; rfl @[simp] theorem iselect_nil [DecidableEq F.A] [Inhabited (M F)] {a} (f : F.B a β†’ M F) : iselect nil (M.mk ⟨a, f⟩) = a := rfl @[simp] theorem iselect_cons [DecidableEq F.A] [Inhabited (M F)] (ps : Path F) {a} (f : F.B a β†’ M F) {i} : iselect (⟨a, i⟩ :: ps) (M.mk ⟨a, f⟩) = iselect ps (f i) := by simp only [iselect, isubtree_cons] theorem corec_def {X} (f : X β†’ F X) (xβ‚€ : X) : M.corec f xβ‚€ = M.mk (F.map (M.corec f) (f xβ‚€)) := by dsimp only [M.corec, M.mk] congr with n cases' n with n Β· dsimp only [sCorec, Approx.sMk] Β· dsimp only [sCorec, Approx.sMk] cases f xβ‚€ dsimp only [PFunctor.map] congr theorem ext_aux [Inhabited (M F)] [DecidableEq F.A] {n : β„•} (x y z : M F) (hx : Agree' n z x) (hy : Agree' n z y) (hrec : βˆ€ ps : Path F, n = ps.length β†’ iselect ps x = iselect ps y) : x.approx (n + 1) = y.approx (n + 1) := by induction' n with n n_ih generalizing x y z Β· specialize hrec [] rfl induction x using PFunctor.M.casesOn' induction y using PFunctor.M.casesOn' simp only [iselect_nil] at hrec subst hrec simp only [approx_mk, true_and_iff, eq_self_iff_true, heq_iff_eq, zero_eq, CofixA.intro.injEq, heq_eq_eq, eq_iff_true_of_subsingleton, and_self] Β· cases hx cases hy induction x using PFunctor.M.casesOn' induction y using PFunctor.M.casesOn' subst z iterate 3 (have := mk_inj β€Ή_β€Ί; cases this) rename_i n_ih a f₃ fβ‚‚ hAgreeβ‚‚ _ _ hβ‚‚ _ _ f₁ h₁ hAgree₁ clr simp only [approx_mk, true_and_iff, eq_self_iff_true, heq_iff_eq] have := mk_inj h₁ cases this; clear h₁ have := mk_inj hβ‚‚ cases this; clear hβ‚‚ congr ext i apply n_ih Β· solve_by_elim Β· solve_by_elim introv h specialize hrec (⟨_, i⟩ :: ps) (congr_arg _ h) simp only [iselect_cons] at hrec exact hrec open PFunctor.Approx attribute [local instance] Classical.propDecidable theorem ext [Inhabited (M F)] (x y : M F) (H : βˆ€ ps : Path F, iselect ps x = iselect ps y) : x = y := by apply ext'; intro i induction' i with i i_ih Β· cases x.approx 0 cases y.approx 0 constructor Β· apply ext_aux x y x Β· rw [← agree_iff_agree'] apply x.consistent Β· rw [← agree_iff_agree', i_ih] apply y.consistent introv H' dsimp only [iselect] at H cases H' apply H ps section Bisim variable (R : M F β†’ M F β†’ Prop) local infixl:50 " ~ " => R /-- Bisimulation is the standard proof technique for equality between infinite tree-like structures -/ structure IsBisimulation : Prop where /-- The head of the trees are equal -/ head : βˆ€ {a a'} {f f'}, M.mk ⟨a, f⟩ ~ M.mk ⟨a', f'⟩ β†’ a = a' /-- The tails are equal -/ tail : βˆ€ {a} {f f' : F.B a β†’ M F}, M.mk ⟨a, f⟩ ~ M.mk ⟨a, f'⟩ β†’ βˆ€ i : F.B a, f i ~ f' i theorem nth_of_bisim [Inhabited (M F)] (bisim : IsBisimulation R) (s₁ sβ‚‚) (ps : Path F) : (R s₁ sβ‚‚) β†’ IsPath ps s₁ ∨ IsPath ps sβ‚‚ β†’ iselect ps s₁ = iselect ps sβ‚‚ ∧ βˆƒ (a : _) (f f' : F.B a β†’ M F), isubtree ps s₁ = M.mk ⟨a, f⟩ ∧ isubtree ps sβ‚‚ = M.mk ⟨a, f'⟩ ∧ βˆ€ i : F.B a, f i ~ f' i := by intro hβ‚€ hh induction' s₁ using PFunctor.M.casesOn' with a f induction' sβ‚‚ using PFunctor.M.casesOn' with a' f' obtain rfl : a = a' := bisim.head hβ‚€ induction' ps with i ps ps_ih generalizing a f f' Β· exists rfl, a, f, f', rfl, rfl apply bisim.tail hβ‚€ cases' i with a' i obtain rfl : a = a' := by rcases hh with hh|hh <;> cases isPath_cons hh <;> rfl dsimp only [iselect] at ps_ih ⊒ have h₁ := bisim.tail hβ‚€ i induction' h : f i using PFunctor.M.casesOn' with aβ‚€ fβ‚€ induction' h' : f' i using PFunctor.M.casesOn' with a₁ f₁ simp only [h, h', isubtree_cons] at ps_ih ⊒ rw [h, h'] at h₁ obtain rfl : aβ‚€ = a₁ := bisim.head h₁ apply ps_ih _ _ _ h₁ rw [← h, ← h'] apply Or.imp isPath_cons' isPath_cons' hh theorem eq_of_bisim [Nonempty (M F)] (bisim : IsBisimulation R) : βˆ€ s₁ sβ‚‚, R s₁ sβ‚‚ β†’ s₁ = sβ‚‚ := by inhabit M F introv Hr; apply ext introv by_cases h : IsPath ps s₁ ∨ IsPath ps sβ‚‚ Β· have H := nth_of_bisim R bisim _ _ ps Hr h exact H.left Β· rw [not_or] at h cases' h with hβ‚€ h₁ simp only [iselect_eq_default, *, not_false_iff] end Bisim universe u' v' /-- corecursor for `M F` with swapped arguments -/ def corecOn {X : Type*} (xβ‚€ : X) (f : X β†’ F X) : M F := M.corec f xβ‚€ variable {P : PFunctor.{u}} {Ξ± : Type*} theorem dest_corec (g : Ξ± β†’ P Ξ±) (x : Ξ±) : M.dest (M.corec g x) = P.map (M.corec g) (g x) := by rw [corec_def, dest_mk] theorem bisim (R : M P β†’ M P β†’ Prop) (h : βˆ€ x y, R x y β†’ βˆƒ a f f', M.dest x = ⟨a, f⟩ ∧ M.dest y = ⟨a, f'⟩ ∧ βˆ€ i, R (f i) (f' i)) : βˆ€ x y, R x y β†’ x = y := by introv h' haveI := Inhabited.mk x.head apply eq_of_bisim R _ _ _ h'; clear h' x y constructor <;> introv ih <;> rcases h _ _ ih with ⟨a'', g, g', hβ‚€, h₁, hβ‚‚βŸ© <;> clear h Β· replace hβ‚€ := congr_arg Sigma.fst hβ‚€ replace h₁ := congr_arg Sigma.fst h₁ simp only [dest_mk] at hβ‚€ h₁ rw [hβ‚€, h₁] Β· simp only [dest_mk] at hβ‚€ h₁ cases hβ‚€ cases h₁ apply hβ‚‚ theorem bisim' {Ξ± : Type*} (Q : Ξ± β†’ Prop) (u v : Ξ± β†’ M P) (h : βˆ€ x, Q x β†’ βˆƒ a f f', M.dest (u x) = ⟨a, f⟩ ∧ M.dest (v x) = ⟨a, f'⟩ ∧ βˆ€ i, βˆƒ x', Q x' ∧ f i = u x' ∧ f' i = v x' ) : βˆ€ x, Q x β†’ u x = v x := fun x Qx => let R := fun w z : M P => βˆƒ x', Q x' ∧ w = u x' ∧ z = v x' @M.bisim P R (fun _ _ ⟨x', Qx', xeq, yeq⟩ => let ⟨a, f, f', ux'eq, vx'eq, h'⟩ := h x' Qx' ⟨a, f, f', xeq.symm β–Έ ux'eq, yeq.symm β–Έ vx'eq, h'⟩) _ _ ⟨x, Qx, rfl, rfl⟩ -- for the record, show M_bisim follows from _bisim' theorem bisim_equiv (R : M P β†’ M P β†’ Prop) (h : βˆ€ x y, R x y β†’ βˆƒ a f f', M.dest x = ⟨a, f⟩ ∧ M.dest y = ⟨a, f'⟩ ∧ βˆ€ i, R (f i) (f' i)) : βˆ€ x y, R x y β†’ x = y := fun x y Rxy => let Q : M P Γ— M P β†’ Prop := fun p => R p.fst p.snd bisim' Q Prod.fst Prod.snd (fun p Qp => let ⟨a, f, f', hx, hy, h'⟩ := h p.fst p.snd Qp ⟨a, f, f', hx, hy, fun i => ⟨⟨f i, f' i⟩, h' i, rfl, rfl⟩⟩) ⟨x, y⟩ Rxy theorem corec_unique (g : Ξ± β†’ P Ξ±) (f : Ξ± β†’ M P) (hyp : βˆ€ x, M.dest (f x) = P.map f (g x)) : f = M.corec g := by ext x apply bisim' (fun _ => True) _ _ _ _ trivial clear x intro x _ cases' gxeq : g x with a f' have hβ‚€ : M.dest (f x) = ⟨a, f ∘ f'⟩ := by rw [hyp, gxeq, PFunctor.map_eq] have h₁ : M.dest (M.corec g x) = ⟨a, M.corec g ∘ f'⟩ := by rw [dest_corec, gxeq, PFunctor.map_eq] refine ⟨_, _, _, hβ‚€, h₁, ?_⟩ intro i exact ⟨f' i, trivial, rfl, rfl⟩ /-- corecursor where the state of the computation can be sent downstream in the form of a recursive call -/ def corec₁ {Ξ± : Type u} (F : βˆ€ X, (Ξ± β†’ X) β†’ Ξ± β†’ P X) : Ξ± β†’ M P := M.corec (F _ id) /-- corecursor where it is possible to return a fully formed value at any point of the computation -/ def corec' {Ξ± : Type u} (F : βˆ€ {X : Type u}, (Ξ± β†’ X) β†’ Ξ± β†’ M P βŠ• P X) (x : Ξ±) : M P := corec₁ (fun _ rec (a : M P βŠ• Ξ±) => let y := a >>= F (rec ∘ Sum.inr) match y with | Sum.inr y => y | Sum.inl y => P.map (rec ∘ Sum.inl) (M.dest y)) (@Sum.inr (M P) _ x) end M end PFunctor
Data\Pi\Interval.lean
/- Copyright (c) 2021 YaΓ«l Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: YaΓ«l Dillies -/ 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).card = ∏ i, (Icc (a i) (b i)).card := card_piFinset _ theorem card_Ico : (Ico a b).card = (∏ i, (Icc (a i) (b i)).card) - 1 := by rw [card_Ico_eq_card_Icc_sub_one, card_Icc] theorem card_Ioc : (Ioc a b).card = (∏ i, (Icc (a i) (b i)).card) - 1 := by rw [card_Ioc_eq_card_Icc_sub_one, card_Icc] theorem card_Ioo : (Ioo a b).card = (∏ i, (Icc (a i) (b i)).card) - 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] theorem card_Iic : (Iic b).card = ∏ i, (Iic (b i)).card := card_piFinset _ theorem card_Iio : (Iio b).card = (∏ i, (Iic (b i)).card) - 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] theorem card_Ici : (Ici a).card = ∏ i, (Ici (a i)).card := card_piFinset _ theorem card_Ioi : (Ioi a).card = (∏ i, (Ici (a i)).card) - 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).card = ∏ i, (uIcc (a i) (b i)).card := card_Icc _ _ end Lattice end Pi
Data\PNat\Basic.lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Ralf Stephan, Neil Strickland, Ruben Van de Velde -/ import Mathlib.Data.PNat.Equiv import Mathlib.Algebra.Order.Ring.Nat import Mathlib.Data.Set.Basic import Mathlib.Algebra.GroupWithZero.Divisibility import Mathlib.Algebra.Order.Positive.Ring import Mathlib.Order.Hom.Basic /-! # The positive natural numbers This file develops the type `β„•+` or `PNat`, the subtype of natural numbers that are positive. It is defined in `Data.PNat.Defs`, but most of the development is deferred to here so that `Data.PNat.Defs` can have very few imports. -/ deriving instance AddLeftCancelSemigroup, AddRightCancelSemigroup, AddCommSemigroup, LinearOrderedCancelCommMonoid, Add, Mul, Distrib for PNat namespace PNat -- Porting note: this instance is no longer automatically inferred in Lean 4. instance instWellFoundedLT : WellFoundedLT β„•+ := WellFoundedRelation.isWellFounded instance instIsWellOrder : IsWellOrder β„•+ (Β· < Β·) where @[simp] theorem one_add_natPred (n : β„•+) : 1 + n.natPred = n := by rw [natPred, add_tsub_cancel_iff_le.mpr <| show 1 ≀ (n : β„•) from n.2] @[simp] theorem natPred_add_one (n : β„•+) : n.natPred + 1 = n := (add_comm _ _).trans n.one_add_natPred @[mono] theorem natPred_strictMono : StrictMono natPred := fun m _ h => Nat.pred_lt_pred m.2.ne' h @[mono] theorem natPred_monotone : Monotone natPred := natPred_strictMono.monotone theorem natPred_injective : Function.Injective natPred := natPred_strictMono.injective @[simp] theorem natPred_lt_natPred {m n : β„•+} : m.natPred < n.natPred ↔ m < n := natPred_strictMono.lt_iff_lt @[simp] theorem natPred_le_natPred {m n : β„•+} : m.natPred ≀ n.natPred ↔ m ≀ n := natPred_strictMono.le_iff_le @[simp] theorem natPred_inj {m n : β„•+} : m.natPred = n.natPred ↔ m = n := natPred_injective.eq_iff @[simp, norm_cast] lemma val_ofNat (n : β„•) [NeZero n] : ((no_index (OfNat.ofNat n) : β„•+) : β„•) = OfNat.ofNat n := rfl @[simp] lemma mk_ofNat (n : β„•) (h : 0 < n) : @Eq β„•+ (⟨no_index (OfNat.ofNat n), h⟩ : β„•+) (haveI : NeZero n := ⟨h.ne'⟩; OfNat.ofNat n) := rfl end PNat namespace Nat @[mono] theorem succPNat_strictMono : StrictMono succPNat := fun _ _ => Nat.succ_lt_succ @[mono] theorem succPNat_mono : Monotone succPNat := succPNat_strictMono.monotone @[simp] theorem succPNat_lt_succPNat {m n : β„•} : m.succPNat < n.succPNat ↔ m < n := succPNat_strictMono.lt_iff_lt @[simp] theorem succPNat_le_succPNat {m n : β„•} : m.succPNat ≀ n.succPNat ↔ m ≀ n := succPNat_strictMono.le_iff_le theorem succPNat_injective : Function.Injective succPNat := succPNat_strictMono.injective @[simp] theorem succPNat_inj {n m : β„•} : succPNat n = succPNat m ↔ n = m := succPNat_injective.eq_iff end Nat namespace PNat open Nat /-- We now define a long list of structures on `β„•+` induced by similar structures on `β„•`. Most of these behave in a completely obvious way, but there are a few things to be said about subtraction, division and powers. -/ @[simp, norm_cast] theorem coe_inj {m n : β„•+} : (m : β„•) = n ↔ m = n := SetCoe.ext_iff @[simp, norm_cast] theorem add_coe (m n : β„•+) : ((m + n : β„•+) : β„•) = m + n := rfl /-- `coe` promoted to an `AddHom`, that is, a morphism which preserves addition. -/ def coeAddHom : AddHom β„•+ β„• where toFun := Coe.coe map_add' := add_coe instance covariantClass_add_le : CovariantClass β„•+ β„•+ (Β· + Β·) (Β· ≀ Β·) := Positive.covariantClass_add_le instance covariantClass_add_lt : CovariantClass β„•+ β„•+ (Β· + Β·) (Β· < Β·) := Positive.covariantClass_add_lt instance contravariantClass_add_le : ContravariantClass β„•+ β„•+ (Β· + Β·) (Β· ≀ Β·) := Positive.contravariantClass_add_le instance contravariantClass_add_lt : ContravariantClass β„•+ β„•+ (Β· + Β·) (Β· < Β·) := Positive.contravariantClass_add_lt /-- The order isomorphism between β„• and β„•+ given by `succ`. -/ @[simps! (config := .asFn) apply] def _root_.OrderIso.pnatIsoNat : β„•+ ≃o β„• where toEquiv := Equiv.pnatEquivNat map_rel_iff' := natPred_le_natPred @[simp] theorem _root_.OrderIso.pnatIsoNat_symm_apply : OrderIso.pnatIsoNat.symm = Nat.succPNat := rfl theorem lt_add_one_iff : βˆ€ {a b : β„•+}, a < b + 1 ↔ a ≀ b := Nat.lt_add_one_iff theorem add_one_le_iff : βˆ€ {a b : β„•+}, a + 1 ≀ b ↔ a < b := Nat.add_one_le_iff instance instOrderBot : OrderBot β„•+ where bot := 1 bot_le a := a.property @[simp] theorem bot_eq_one : (βŠ₯ : β„•+) = 1 := rfl /-- Strong induction on `β„•+`, with `n = 1` treated separately. -/ def caseStrongInductionOn {p : β„•+ β†’ Sort*} (a : β„•+) (hz : p 1) (hi : βˆ€ n, (βˆ€ m, m ≀ n β†’ p m) β†’ p (n + 1)) : p a := by apply strongInductionOn a rintro ⟨k, kprop⟩ hk cases' k with k Β· exact (lt_irrefl 0 kprop).elim cases' k with k Β· exact hz exact hi ⟨k.succ, Nat.succ_pos _⟩ fun m hm => hk _ (Nat.lt_succ_iff.2 hm) /-- An induction principle for `β„•+`: it takes values in `Sort*`, so it applies also to Types, not only to `Prop`. -/ @[elab_as_elim] def recOn (n : β„•+) {p : β„•+ β†’ Sort*} (p1 : p 1) (hp : βˆ€ n, p n β†’ p (n + 1)) : p n := by rcases n with ⟨n, h⟩ induction' n with n IH Β· exact absurd h (by decide) Β· cases' n with n Β· exact p1 Β· exact hp _ (IH n.succ_pos) @[simp] theorem recOn_one {p} (p1 hp) : @PNat.recOn 1 p p1 hp = p1 := rfl @[simp] theorem recOn_succ (n : β„•+) {p : β„•+ β†’ Sort*} (p1 hp) : @PNat.recOn (n + 1) p p1 hp = hp n (@PNat.recOn n p p1 hp) := by cases' n with n h cases n <;> [exact absurd h (by decide); rfl] @[simp] theorem ofNat_le_ofNat {m n : β„•} [NeZero m] [NeZero n] : (no_index (OfNat.ofNat m) : β„•+) ≀ no_index (OfNat.ofNat n) ↔ OfNat.ofNat m ≀ OfNat.ofNat n := .rfl @[simp] theorem ofNat_lt_ofNat {m n : β„•} [NeZero m] [NeZero n] : (no_index (OfNat.ofNat m) : β„•+) < no_index (OfNat.ofNat n) ↔ OfNat.ofNat m < OfNat.ofNat n := .rfl @[simp] theorem ofNat_inj {m n : β„•} [NeZero m] [NeZero n] : (no_index (OfNat.ofNat m) : β„•+) = no_index (OfNat.ofNat n) ↔ OfNat.ofNat m = OfNat.ofNat n := Subtype.mk_eq_mk @[simp, norm_cast] theorem mul_coe (m n : β„•+) : ((m * n : β„•+) : β„•) = m * n := rfl /-- `PNat.coe` promoted to a `MonoidHom`. -/ def coeMonoidHom : β„•+ β†’* β„• where toFun := Coe.coe map_one' := one_coe map_mul' := mul_coe @[simp] theorem coe_coeMonoidHom : (coeMonoidHom : β„•+ β†’ β„•) = Coe.coe := rfl @[simp] theorem le_one_iff {n : β„•+} : n ≀ 1 ↔ n = 1 := le_bot_iff theorem lt_add_left (n m : β„•+) : n < m + n := lt_add_of_pos_left _ m.2 theorem lt_add_right (n m : β„•+) : n < n + m := (lt_add_left n m).trans_eq (add_comm _ _) @[simp, norm_cast] theorem pow_coe (m : β„•+) (n : β„•) : ↑(m ^ n) = (m : β„•) ^ n := rfl /-- b is greater one if any a is less than b -/ theorem one_lt_of_lt {a b : β„•+} (hab : a < b) : 1 < b := bot_le.trans_lt hab theorem add_one (a : β„•+) : a + 1 = succPNat a := rfl theorem lt_succ_self (a : β„•+) : a < succPNat a := lt.base a /-- Subtraction a - b is defined in the obvious way when a > b, and by a - b = 1 if a ≀ b. -/ instance instSub : Sub β„•+ := ⟨fun a b => toPNat' (a - b : β„•)⟩ theorem sub_coe (a b : β„•+) : ((a - b : β„•+) : β„•) = ite (b < a) (a - b : β„•) 1 := by change (toPNat' _ : β„•) = ite _ _ _ split_ifs with h Β· exact toPNat'_coe (tsub_pos_of_lt h) Β· rw [tsub_eq_zero_iff_le.mpr (le_of_not_gt h : (a : β„•) ≀ b)] rfl theorem sub_le (a b : β„•+) : a - b ≀ a := by rw [← coe_le_coe, sub_coe] split_ifs with h Β· exact Nat.sub_le a b Β· exact a.2 theorem le_sub_one_of_lt {a b : β„•+} (hab : a < b) : a ≀ b - (1 : β„•+) := by rw [← coe_le_coe, sub_coe] split_ifs with h Β· exact Nat.le_pred_of_lt hab Β· exact hab.le.trans (le_of_not_lt h) theorem add_sub_of_lt {a b : β„•+} : a < b β†’ a + (b - a) = b := fun h => PNat.eq <| by rw [add_coe, sub_coe, if_pos h] exact add_tsub_cancel_of_le h.le /-- If `n : β„•+` is different from `1`, then it is the successor of some `k : β„•+`. -/ theorem exists_eq_succ_of_ne_one : βˆ€ {n : β„•+} (_ : n β‰  1), βˆƒ k : β„•+, n = k + 1 | ⟨1, _⟩, h₁ => False.elim <| h₁ rfl | ⟨n + 2, _⟩, _ => ⟨⟨n + 1, by simp⟩, rfl⟩ /-- Lemmas with div, dvd and mod operations -/ theorem modDivAux_spec : βˆ€ (k : β„•+) (r q : β„•) (_ : Β¬(r = 0 ∧ q = 0)), ((modDivAux k r q).1 : β„•) + k * (modDivAux k r q).2 = r + k * q | k, 0, 0, h => (h ⟨rfl, rfl⟩).elim | k, 0, q + 1, _ => by change (k : β„•) + (k : β„•) * (q + 1).pred = 0 + (k : β„•) * (q + 1) rw [Nat.pred_succ, Nat.mul_succ, zero_add, add_comm] | k, r + 1, q, _ => rfl theorem mod_add_div (m k : β„•+) : (mod m k + k * div m k : β„•) = m := by let hβ‚€ := Nat.mod_add_div (m : β„•) (k : β„•) have : Β¬((m : β„•) % (k : β„•) = 0 ∧ (m : β„•) / (k : β„•) = 0) := by rintro ⟨hr, hq⟩ rw [hr, hq, mul_zero, zero_add] at hβ‚€ exact (m.ne_zero hβ‚€.symm).elim have := modDivAux_spec k ((m : β„•) % (k : β„•)) ((m : β„•) / (k : β„•)) this exact this.trans hβ‚€ theorem div_add_mod (m k : β„•+) : (k * div m k + mod m k : β„•) = m := (add_comm _ _).trans (mod_add_div _ _) theorem mod_add_div' (m k : β„•+) : (mod m k + div m k * k : β„•) = m := by rw [mul_comm] exact mod_add_div _ _ theorem div_add_mod' (m k : β„•+) : (div m k * k + mod m k : β„•) = m := by rw [mul_comm] exact div_add_mod _ _ theorem mod_le (m k : β„•+) : mod m k ≀ m ∧ mod m k ≀ k := by change (mod m k : β„•) ≀ (m : β„•) ∧ (mod m k : β„•) ≀ (k : β„•) rw [mod_coe] split_ifs with h Β· have hm : (m : β„•) > 0 := m.pos rw [← Nat.mod_add_div (m : β„•) (k : β„•), h, zero_add] at hm ⊒ by_cases h₁ : (m : β„•) / (k : β„•) = 0 Β· rw [h₁, mul_zero] at hm exact (lt_irrefl _ hm).elim Β· let hβ‚‚ : (k : β„•) * 1 ≀ k * (m / k) := -- Porting note: Specified type of `hβ‚‚` explicitly because `rw` could not unify -- `succ 0` with `1`. Nat.mul_le_mul_left (k : β„•) (Nat.succ_le_of_lt (Nat.pos_of_ne_zero h₁)) rw [mul_one] at hβ‚‚ exact ⟨hβ‚‚, le_refl (k : β„•)⟩ Β· exact ⟨Nat.mod_le (m : β„•) (k : β„•), (Nat.mod_lt (m : β„•) k.pos).le⟩ theorem dvd_iff {k m : β„•+} : k ∣ m ↔ (k : β„•) ∣ (m : β„•) := by constructor <;> intro h Β· rcases h with ⟨_, rfl⟩ apply dvd_mul_right Β· rcases h with ⟨a, h⟩ obtain ⟨n, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (n := a) <| by rintro rfl simp only [mul_zero, ne_zero] at h use ⟨n.succ, n.succ_pos⟩ rw [← coe_inj, h, mul_coe, mk_coe] theorem dvd_iff' {k m : β„•+} : k ∣ m ↔ mod m k = k := by rw [dvd_iff] rw [Nat.dvd_iff_mod_eq_zero]; constructor Β· intro h apply PNat.eq rw [mod_coe, if_pos h] Β· intro h by_cases h' : (m : β„•) % (k : β„•) = 0 Β· exact h' Β· replace h : (mod m k : β„•) = (k : β„•) := congr_arg _ h rw [mod_coe, if_neg h'] at h exact ((Nat.mod_lt (m : β„•) k.pos).ne h).elim theorem le_of_dvd {m n : β„•+} : m ∣ n β†’ m ≀ n := by rw [dvd_iff'] intro h rw [← h] apply (mod_le n m).left theorem mul_div_exact {m k : β„•+} (h : k ∣ m) : k * divExact m k = m := by apply PNat.eq; rw [mul_coe] change (k : β„•) * (div m k).succ = m rw [← div_add_mod m k, dvd_iff'.mp h, Nat.mul_succ] theorem dvd_antisymm {m n : β„•+} : m ∣ n β†’ n ∣ m β†’ m = n := fun hmn hnm => (le_of_dvd hmn).antisymm (le_of_dvd hnm) theorem dvd_one_iff (n : β„•+) : n ∣ 1 ↔ n = 1 := ⟨fun h => dvd_antisymm h (one_dvd n), fun h => h.symm β–Έ dvd_refl 1⟩ theorem pos_of_div_pos {n : β„•+} {a : β„•} (h : a ∣ n) : 0 < a := by apply pos_iff_ne_zero.2 intro hzero rw [hzero] at h exact PNat.ne_zero n (eq_zero_of_zero_dvd h) end PNat
Data\PNat\Defs.lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Neil Strickland -/ import Mathlib.Algebra.NeZero import Mathlib.Data.Nat.Defs import Mathlib.Order.Basic import Mathlib.Tactic.Coe import Mathlib.Tactic.Lift import Mathlib.Init.Data.Int.Order /-! # The positive natural numbers This file contains the definitions, and basic results. Most algebraic facts are deferred to `Data.PNat.Basic`, as they need more imports. -/ /-- `β„•+` is the type of positive natural numbers. It is defined as a subtype, and the VM representation of `β„•+` is the same as `β„•` because the proof is not stored. -/ def PNat := { n : β„• // 0 < n } deriving DecidableEq, LinearOrder @[inherit_doc] notation "β„•+" => PNat instance : One β„•+ := ⟨⟨1, Nat.zero_lt_one⟩⟩ /-- The underlying natural number -/ @[coe] def PNat.val : β„•+ β†’ β„• := Subtype.val instance coePNatNat : Coe β„•+ β„• := ⟨PNat.val⟩ instance : Repr β„•+ := ⟨fun n n' => reprPrec n.1 n'⟩ instance (n : β„•) [NeZero n] : OfNat β„•+ n := ⟨⟨n, Nat.pos_of_ne_zero <| NeZero.ne n⟩⟩ namespace PNat -- Note: similar to Subtype.coe_mk @[simp] theorem mk_coe (n h) : (PNat.val (⟨n, h⟩ : β„•+) : β„•) = n := rfl /-- Predecessor of a `β„•+`, as a `β„•`. -/ def natPred (i : β„•+) : β„• := i - 1 @[simp] theorem natPred_eq_pred {n : β„•} (h : 0 < n) : natPred (⟨n, h⟩ : β„•+) = n.pred := rfl end PNat namespace Nat /-- Convert a natural number to a positive natural number. The positivity assumption is inferred by `dec_trivial`. -/ def toPNat (n : β„•) (h : 0 < n := by decide) : β„•+ := ⟨n, h⟩ /-- Write a successor as an element of `β„•+`. -/ def succPNat (n : β„•) : β„•+ := ⟨succ n, succ_pos n⟩ @[simp] theorem succPNat_coe (n : β„•) : (succPNat n : β„•) = succ n := rfl @[simp] theorem natPred_succPNat (n : β„•) : n.succPNat.natPred = n := rfl @[simp] theorem _root_.PNat.succPNat_natPred (n : β„•+) : n.natPred.succPNat = n := Subtype.eq <| succ_pred_eq_of_pos n.2 /-- Convert a natural number to a `PNat`. `n+1` is mapped to itself, and `0` becomes `1`. -/ def toPNat' (n : β„•) : β„•+ := succPNat (pred n) @[simp] theorem toPNat'_zero : Nat.toPNat' 0 = 1 := rfl @[simp] theorem toPNat'_coe : βˆ€ n : β„•, (toPNat' n : β„•) = ite (0 < n) n 1 | 0 => rfl | m + 1 => by rw [if_pos (succ_pos m)] rfl end Nat namespace PNat open Nat /-- We now define a long list of structures on β„•+ induced by similar structures on β„•. Most of these behave in a completely obvious way, but there are a few things to be said about subtraction, division and powers. -/ -- Porting note: no `simp` because simp can prove it theorem mk_le_mk (n k : β„•) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : β„•+) ≀ ⟨k, hk⟩ ↔ n ≀ k := Iff.rfl -- Porting note: no `simp` because simp can prove it theorem mk_lt_mk (n k : β„•) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : β„•+) < ⟨k, hk⟩ ↔ n < k := Iff.rfl @[simp, norm_cast] theorem coe_le_coe (n k : β„•+) : (n : β„•) ≀ k ↔ n ≀ k := Iff.rfl @[simp, norm_cast] theorem coe_lt_coe (n k : β„•+) : (n : β„•) < k ↔ n < k := Iff.rfl @[simp] theorem pos (n : β„•+) : 0 < (n : β„•) := n.2 theorem eq {m n : β„•+} : (m : β„•) = n β†’ m = n := Subtype.eq theorem coe_injective : Function.Injective (fun (a : β„•+) => (a : β„•)) := Subtype.coe_injective @[simp] theorem ne_zero (n : β„•+) : (n : β„•) β‰  0 := n.2.ne' instance _root_.NeZero.pnat {a : β„•+} : NeZero (a : β„•) := ⟨a.ne_zero⟩ theorem toPNat'_coe {n : β„•} : 0 < n β†’ (n.toPNat' : β„•) = n := succ_pred_eq_of_pos @[simp] theorem coe_toPNat' (n : β„•+) : (n : β„•).toPNat' = n := eq (toPNat'_coe n.pos) @[simp] theorem one_le (n : β„•+) : (1 : β„•+) ≀ n := n.2 @[simp] theorem not_lt_one (n : β„•+) : Β¬n < 1 := not_lt_of_le n.one_le instance : Inhabited β„•+ := ⟨1⟩ -- Some lemmas that rewrite `PNat.mk n h`, for `n` an explicit numeral, into explicit numerals. @[simp] theorem mk_one {h} : (⟨1, h⟩ : β„•+) = (1 : β„•+) := rfl @[norm_cast] theorem one_coe : ((1 : β„•+) : β„•) = 1 := rfl @[simp, norm_cast] theorem coe_eq_one_iff {m : β„•+} : (m : β„•) = 1 ↔ m = 1 := Subtype.coe_injective.eq_iff' one_coe instance : WellFoundedRelation β„•+ := measure (fun (a : β„•+) => (a : β„•)) /-- Strong induction on `β„•+`. -/ def strongInductionOn {p : β„•+ β†’ Sort*} (n : β„•+) : (βˆ€ k, (βˆ€ m, m < k β†’ p m) β†’ p k) β†’ p n | IH => IH _ fun a _ => strongInductionOn a IH termination_by n.1 /-- We define `m % k` and `m / k` in the same way as for `β„•` except that when `m = n * k` we take `m % k = k` and `m / k = n - 1`. This ensures that `m % k` is always positive and `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def modDivAux : β„•+ β†’ β„• β†’ β„• β†’ β„•+ Γ— β„• | k, 0, q => ⟨k, q.pred⟩ | _, r + 1, q => ⟨⟨r + 1, Nat.succ_pos r⟩, q⟩ /-- `mod_div m k = (m % k, m / k)`. We define `m % k` and `m / k` in the same way as for `β„•` except that when `m = n * k` we take `m % k = k` and `m / k = n - 1`. This ensures that `m % k` is always positive and `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def modDiv (m k : β„•+) : β„•+ Γ— β„• := modDivAux k ((m : β„•) % (k : β„•)) ((m : β„•) / (k : β„•)) /-- We define `m % k` in the same way as for `β„•` except that when `m = n * k` we take `m % k = k` This ensures that `m % k` is always positive. -/ def mod (m k : β„•+) : β„•+ := (modDiv m k).1 /-- We define `m / k` in the same way as for `β„•` except that when `m = n * k` we take `m / k = n - 1`. This ensures that `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def div (m k : β„•+) : β„• := (modDiv m k).2 theorem mod_coe (m k : β„•+) : (mod m k : β„•) = ite ((m : β„•) % (k : β„•) = 0) (k : β„•) ((m : β„•) % (k : β„•)) := by dsimp [mod, modDiv] cases (m : β„•) % (k : β„•) with | zero => rw [if_pos rfl] rfl | succ n => rw [if_neg n.succ_ne_zero] rfl theorem div_coe (m k : β„•+) : (div m k : β„•) = ite ((m : β„•) % (k : β„•) = 0) ((m : β„•) / (k : β„•)).pred ((m : β„•) / (k : β„•)) := by dsimp [div, modDiv] cases (m : β„•) % (k : β„•) with | zero => rw [if_pos rfl] rfl | succ n => rw [if_neg n.succ_ne_zero] rfl /-- If `h : k | m`, then `k * (div_exact m k) = m`. Note that this is not equal to `m / k`. -/ def divExact (m k : β„•+) : β„•+ := ⟨(div m k).succ, Nat.succ_pos _⟩ end PNat section CanLift instance Nat.canLiftPNat : CanLift β„• β„•+ (↑) (fun n => 0 < n) := ⟨fun n hn => ⟨Nat.toPNat' n, PNat.toPNat'_coe hn⟩⟩ instance Int.canLiftPNat : CanLift β„€ β„•+ (↑) ((0 < Β·)) := ⟨fun n hn => ⟨Nat.toPNat' (Int.natAbs n), by rw [Nat.toPNat'_coe, if_pos (Int.natAbs_pos.2 hn.ne'), Int.natAbs_of_nonneg hn.le]⟩⟩ end CanLift
Data\PNat\Equiv.lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Ralf Stephan, Neil Strickland, Ruben Van de Velde -/ import Mathlib.Data.PNat.Defs import Mathlib.Logic.Equiv.Defs /-! # The equivalence between `β„•+` and `β„•` -/ /-- An equivalence between `β„•+` and `β„•` given by `PNat.natPred` and `Nat.succPNat`. -/ @[simps (config := .asFn)] def _root_.Equiv.pnatEquivNat : β„•+ ≃ β„• where toFun := PNat.natPred invFun := Nat.succPNat left_inv := PNat.succPNat_natPred right_inv := Nat.natPred_succPNat
Data\PNat\Factors.lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland -/ import Mathlib.Algebra.BigOperators.Group.Multiset import Mathlib.Data.PNat.Prime import Mathlib.Data.Nat.Factors import Mathlib.Data.Multiset.Sort /-! # Prime factors of nonzero naturals This file defines the factorization of a nonzero natural number `n` as a multiset of primes, the multiplicity of `p` in this factors multiset being the p-adic valuation of `n`. ## Main declarations * `PrimeMultiset`: Type of multisets of prime numbers. * `FactorMultiset n`: Multiset of prime factors of `n`. -/ -- Porting note: `deriving` contained Inhabited, CanonicallyOrderedAddCommMonoid, DistribLattice, -- SemilatticeSup, OrderBot, Sub, OrderedSub /-- The type of multisets of prime numbers. Unique factorization gives an equivalence between this set and β„•+, as we will formalize below. -/ def PrimeMultiset := Multiset Nat.Primes deriving Inhabited, CanonicallyOrderedAddCommMonoid, DistribLattice, SemilatticeSup, Sub instance : OrderBot PrimeMultiset where bot_le := by simp only [bot_le, forall_const] instance : OrderedSub PrimeMultiset where tsub_le_iff_right _ _ _ := Multiset.sub_le_iff_le_add namespace PrimeMultiset -- `@[derive]` doesn't work for `meta` instances unsafe instance : Repr PrimeMultiset := by delta PrimeMultiset; infer_instance /-- The multiset consisting of a single prime -/ def ofPrime (p : Nat.Primes) : PrimeMultiset := ({p} : Multiset Nat.Primes) theorem card_ofPrime (p : Nat.Primes) : Multiset.card (ofPrime p) = 1 := rfl /-- We can forget the primality property and regard a multiset of primes as just a multiset of positive integers, or a multiset of natural numbers. In the opposite direction, if we have a multiset of positive integers or natural numbers, together with a proof that all the elements are prime, then we can regard it as a multiset of primes. The next block of results records obvious properties of these coercions. -/ def toNatMultiset : PrimeMultiset β†’ Multiset β„• := fun v => v.map Coe.coe instance coeNat : Coe PrimeMultiset (Multiset β„•) := ⟨toNatMultiset⟩ /-- `PrimeMultiset.coe`, the coercion from a multiset of primes to a multiset of naturals, promoted to an `AddMonoidHom`. -/ def coeNatMonoidHom : PrimeMultiset β†’+ Multiset β„• := { Multiset.mapAddMonoidHom Coe.coe with toFun := Coe.coe } @[simp] theorem coe_coeNatMonoidHom : (coeNatMonoidHom : PrimeMultiset β†’ Multiset β„•) = Coe.coe := rfl theorem coeNat_injective : Function.Injective (Coe.coe : PrimeMultiset β†’ Multiset β„•) := Multiset.map_injective Nat.Primes.coe_nat_injective theorem coeNat_ofPrime (p : Nat.Primes) : (ofPrime p : Multiset β„•) = {(p : β„•)} := rfl theorem coeNat_prime (v : PrimeMultiset) (p : β„•) (h : p ∈ (v : Multiset β„•)) : p.Prime := by rcases Multiset.mem_map.mp h with ⟨⟨_, hp'⟩, ⟨_, h_eq⟩⟩ exact h_eq β–Έ hp' /-- Converts a `PrimeMultiset` to a `Multiset β„•+`. -/ def toPNatMultiset : PrimeMultiset β†’ Multiset β„•+ := fun v => v.map Coe.coe instance coePNat : Coe PrimeMultiset (Multiset β„•+) := ⟨toPNatMultiset⟩ /-- `coePNat`, the coercion from a multiset of primes to a multiset of positive naturals, regarded as an `AddMonoidHom`. -/ def coePNatMonoidHom : PrimeMultiset β†’+ Multiset β„•+ := { Multiset.mapAddMonoidHom Coe.coe with toFun := Coe.coe } @[simp] theorem coe_coePNatMonoidHom : (coePNatMonoidHom : PrimeMultiset β†’ Multiset β„•+) = Coe.coe := rfl theorem coePNat_injective : Function.Injective (Coe.coe : PrimeMultiset β†’ Multiset β„•+) := Multiset.map_injective Nat.Primes.coe_pnat_injective theorem coePNat_ofPrime (p : Nat.Primes) : (ofPrime p : Multiset β„•+) = {(p : β„•+)} := rfl theorem coePNat_prime (v : PrimeMultiset) (p : β„•+) (h : p ∈ (v : Multiset β„•+)) : p.Prime := by rcases Multiset.mem_map.mp h with ⟨⟨_, hp'⟩, ⟨_, h_eq⟩⟩ exact h_eq β–Έ hp' instance coeMultisetPNatNat : Coe (Multiset β„•+) (Multiset β„•) := ⟨fun v => v.map Coe.coe⟩ theorem coePNat_nat (v : PrimeMultiset) : ((v : Multiset β„•+) : Multiset β„•) = (v : Multiset β„•) := by change (v.map (Coe.coe : Nat.Primes β†’ β„•+)).map Subtype.val = v.map Subtype.val rw [Multiset.map_map] congr /-- The product of a `PrimeMultiset`, as a `β„•+`. -/ def prod (v : PrimeMultiset) : β„•+ := (v : Multiset PNat).prod theorem coe_prod (v : PrimeMultiset) : (v.prod : β„•) = (v : Multiset β„•).prod := by let h : (v.prod : β„•) = ((v.map Coe.coe).map Coe.coe).prod := PNat.coeMonoidHom.map_multiset_prod v.toPNatMultiset rw [Multiset.map_map] at h have : (Coe.coe : β„•+ β†’ β„•) ∘ (Coe.coe : Nat.Primes β†’ β„•+) = Coe.coe := funext fun p => rfl rw [this] at h; exact h theorem prod_ofPrime (p : Nat.Primes) : (ofPrime p).prod = (p : β„•+) := Multiset.prod_singleton _ /-- If a `Multiset β„•` consists only of primes, it can be recast as a `PrimeMultiset`. -/ def ofNatMultiset (v : Multiset β„•) (h : βˆ€ p : β„•, p ∈ v β†’ p.Prime) : PrimeMultiset := @Multiset.pmap β„• Nat.Primes Nat.Prime (fun p hp => ⟨p, hp⟩) v h theorem to_ofNatMultiset (v : Multiset β„•) (h) : (ofNatMultiset v h : Multiset β„•) = v := by dsimp [ofNatMultiset, toNatMultiset] have : (fun p h => (Coe.coe : Nat.Primes β†’ β„•) ⟨p, h⟩) = fun p _ => id p := by funext p h rfl rw [Multiset.map_pmap, this, Multiset.pmap_eq_map, Multiset.map_id] theorem prod_ofNatMultiset (v : Multiset β„•) (h) : ((ofNatMultiset v h).prod : β„•) = (v.prod : β„•) := by rw [coe_prod, to_ofNatMultiset] /-- If a `Multiset β„•+` consists only of primes, it can be recast as a `PrimeMultiset`. -/ def ofPNatMultiset (v : Multiset β„•+) (h : βˆ€ p : β„•+, p ∈ v β†’ p.Prime) : PrimeMultiset := @Multiset.pmap β„•+ Nat.Primes PNat.Prime (fun p hp => ⟨(p : β„•), hp⟩) v h theorem to_ofPNatMultiset (v : Multiset β„•+) (h) : (ofPNatMultiset v h : Multiset β„•+) = v := by dsimp [ofPNatMultiset, toPNatMultiset] have : (fun (p : β„•+) (h : p.Prime) => (Coe.coe : Nat.Primes β†’ β„•+) ⟨p, h⟩) = fun p _ => id p := by funext p h apply Subtype.eq rfl rw [Multiset.map_pmap, this, Multiset.pmap_eq_map, Multiset.map_id] theorem prod_ofPNatMultiset (v : Multiset β„•+) (h) : ((ofPNatMultiset v h).prod : β„•+) = v.prod := by dsimp [prod] rw [to_ofPNatMultiset] /-- Lists can be coerced to multisets; here we have some results about how this interacts with our constructions on multisets. -/ def ofNatList (l : List β„•) (h : βˆ€ p : β„•, p ∈ l β†’ p.Prime) : PrimeMultiset := ofNatMultiset (l : Multiset β„•) h theorem prod_ofNatList (l : List β„•) (h) : ((ofNatList l h).prod : β„•) = l.prod := by have := prod_ofNatMultiset (l : Multiset β„•) h rw [Multiset.prod_coe] at this exact this /-- If a `List β„•+` consists only of primes, it can be recast as a `PrimeMultiset` with the coercion from lists to multisets. -/ def ofPNatList (l : List β„•+) (h : βˆ€ p : β„•+, p ∈ l β†’ p.Prime) : PrimeMultiset := ofPNatMultiset (l : Multiset β„•+) h theorem prod_ofPNatList (l : List β„•+) (h) : (ofPNatList l h).prod = l.prod := by have := prod_ofPNatMultiset (l : Multiset β„•+) h rw [Multiset.prod_coe] at this exact this /-- The product map gives a homomorphism from the additive monoid of multisets to the multiplicative monoid β„•+. -/ theorem prod_zero : (0 : PrimeMultiset).prod = 1 := by exact Multiset.prod_zero theorem prod_add (u v : PrimeMultiset) : (u + v).prod = u.prod * v.prod := by change (coePNatMonoidHom (u + v)).prod = _ rw [coePNatMonoidHom.map_add] exact Multiset.prod_add _ _ theorem prod_smul (d : β„•) (u : PrimeMultiset) : (d β€’ u).prod = u.prod ^ d := by induction d with | zero => simp only [Nat.zero_eq, zero_nsmul, pow_zero, prod_zero] | succ n ih => rw [succ_nsmul, prod_add, ih, pow_succ] end PrimeMultiset namespace PNat /-- The prime factors of n, regarded as a multiset -/ def factorMultiset (n : β„•+) : PrimeMultiset := PrimeMultiset.ofNatList (Nat.primeFactorsList n) (@Nat.prime_of_mem_primeFactorsList n) /-- The product of the factors is the original number -/ theorem prod_factorMultiset (n : β„•+) : (factorMultiset n).prod = n := eq <| by dsimp [factorMultiset] rw [PrimeMultiset.prod_ofNatList] exact Nat.prod_primeFactorsList n.ne_zero theorem coeNat_factorMultiset (n : β„•+) : (factorMultiset n : Multiset β„•) = (Nat.primeFactorsList n : Multiset β„•) := PrimeMultiset.to_ofNatMultiset (Nat.primeFactorsList n) (@Nat.prime_of_mem_primeFactorsList n) end PNat namespace PrimeMultiset /-- If we start with a multiset of primes, take the product and then factor it, we get back the original multiset. -/ theorem factorMultiset_prod (v : PrimeMultiset) : v.prod.factorMultiset = v := by apply PrimeMultiset.coeNat_injective suffices toNatMultiset (PNat.factorMultiset (prod v)) = toNatMultiset v by exact this rw [v.prod.coeNat_factorMultiset, PrimeMultiset.coe_prod] rcases v with ⟨l⟩ --unfold_coes dsimp [PrimeMultiset.toNatMultiset] rw [Multiset.prod_coe] let l' := l.map (Coe.coe : Nat.Primes β†’ β„•) have : βˆ€ p : β„•, p ∈ l' β†’ p.Prime := fun p hp => by rcases List.mem_map.mp hp with ⟨⟨_, hp'⟩, ⟨_, h_eq⟩⟩ exact h_eq β–Έ hp' exact Multiset.coe_eq_coe.mpr (@Nat.primeFactorsList_unique _ l' rfl this).symm end PrimeMultiset namespace PNat /-- Positive integers biject with multisets of primes. -/ def factorMultisetEquiv : β„•+ ≃ PrimeMultiset where toFun := factorMultiset invFun := PrimeMultiset.prod left_inv := prod_factorMultiset right_inv := PrimeMultiset.factorMultiset_prod /-- Factoring gives a homomorphism from the multiplicative monoid β„•+ to the additive monoid of multisets. -/ theorem factorMultiset_one : factorMultiset 1 = 0 := by simp [factorMultiset, PrimeMultiset.ofNatList, PrimeMultiset.ofNatMultiset] theorem factorMultiset_mul (n m : β„•+) : factorMultiset (n * m) = factorMultiset n + factorMultiset m := by let u := factorMultiset n let v := factorMultiset m have : n = u.prod := (prod_factorMultiset n).symm; rw [this] have : m = v.prod := (prod_factorMultiset m).symm; rw [this] rw [← PrimeMultiset.prod_add] repeat' rw [PrimeMultiset.factorMultiset_prod] theorem factorMultiset_pow (n : β„•+) (m : β„•) : factorMultiset (n ^ m) = m β€’ factorMultiset n := by let u := factorMultiset n have : n = u.prod := (prod_factorMultiset n).symm rw [this, ← PrimeMultiset.prod_smul] repeat' rw [PrimeMultiset.factorMultiset_prod] /-- Factoring a prime gives the corresponding one-element multiset. -/ theorem factorMultiset_ofPrime (p : Nat.Primes) : (p : β„•+).factorMultiset = PrimeMultiset.ofPrime p := by apply factorMultisetEquiv.symm.injective change (p : β„•+).factorMultiset.prod = (PrimeMultiset.ofPrime p).prod rw [(p : β„•+).prod_factorMultiset, PrimeMultiset.prod_ofPrime] /-- We now have four different results that all encode the idea that inequality of multisets corresponds to divisibility of positive integers. -/ theorem factorMultiset_le_iff {m n : β„•+} : factorMultiset m ≀ factorMultiset n ↔ m ∣ n := by constructor Β· intro h rw [← prod_factorMultiset m, ← prod_factorMultiset m] apply Dvd.intro (n.factorMultiset - m.factorMultiset).prod rw [← PrimeMultiset.prod_add, PrimeMultiset.factorMultiset_prod, add_tsub_cancel_of_le h, prod_factorMultiset] Β· intro h rw [← mul_div_exact h, factorMultiset_mul] exact le_self_add theorem factorMultiset_le_iff' {m : β„•+} {v : PrimeMultiset} : factorMultiset m ≀ v ↔ m ∣ v.prod := by let h := @factorMultiset_le_iff m v.prod rw [v.factorMultiset_prod] at h exact h end PNat namespace PrimeMultiset theorem prod_dvd_iff {u v : PrimeMultiset} : u.prod ∣ v.prod ↔ u ≀ v := by let h := @PNat.factorMultiset_le_iff' u.prod v rw [u.factorMultiset_prod] at h exact h.symm theorem prod_dvd_iff' {u : PrimeMultiset} {n : β„•+} : u.prod ∣ n ↔ u ≀ n.factorMultiset := by let h := @prod_dvd_iff u n.factorMultiset rw [n.prod_factorMultiset] at h exact h end PrimeMultiset namespace PNat /-- The gcd and lcm operations on positive integers correspond to the inf and sup operations on multisets. -/ theorem factorMultiset_gcd (m n : β„•+) : factorMultiset (gcd m n) = factorMultiset m βŠ“ factorMultiset n := by apply le_antisymm Β· apply le_inf_iff.mpr; constructor <;> apply factorMultiset_le_iff.mpr Β· exact gcd_dvd_left m n Β· exact gcd_dvd_right m n Β· rw [← PrimeMultiset.prod_dvd_iff, prod_factorMultiset] apply dvd_gcd <;> rw [PrimeMultiset.prod_dvd_iff'] Β· exact inf_le_left Β· exact inf_le_right theorem factorMultiset_lcm (m n : β„•+) : factorMultiset (lcm m n) = factorMultiset m βŠ” factorMultiset n := by apply le_antisymm Β· rw [← PrimeMultiset.prod_dvd_iff, prod_factorMultiset] apply lcm_dvd <;> rw [← factorMultiset_le_iff'] Β· exact le_sup_left Β· exact le_sup_right Β· apply sup_le_iff.mpr; constructor <;> apply factorMultiset_le_iff.mpr Β· exact dvd_lcm_left m n Β· exact dvd_lcm_right m n /-- The number of occurrences of p in the factor multiset of m is the same as the p-adic valuation of m. -/ theorem count_factorMultiset (m : β„•+) (p : Nat.Primes) (k : β„•) : (p : β„•+) ^ k ∣ m ↔ k ≀ m.factorMultiset.count p := by rw [Multiset.le_count_iff_replicate_le, ← factorMultiset_le_iff, factorMultiset_pow, factorMultiset_ofPrime] congr! 2 apply Multiset.eq_replicate.mpr constructor Β· rw [Multiset.card_nsmul, PrimeMultiset.card_ofPrime, mul_one] Β· intro q h rw [PrimeMultiset.ofPrime, Multiset.nsmul_singleton _ k] at h exact Multiset.eq_of_mem_replicate h end PNat namespace PrimeMultiset theorem prod_inf (u v : PrimeMultiset) : (u βŠ“ v).prod = PNat.gcd u.prod v.prod := by let n := u.prod let m := v.prod change (u βŠ“ v).prod = PNat.gcd n m have : u = n.factorMultiset := u.factorMultiset_prod.symm; rw [this] have : v = m.factorMultiset := v.factorMultiset_prod.symm; rw [this] rw [← PNat.factorMultiset_gcd n m, PNat.prod_factorMultiset] theorem prod_sup (u v : PrimeMultiset) : (u βŠ” v).prod = PNat.lcm u.prod v.prod := by let n := u.prod let m := v.prod change (u βŠ” v).prod = PNat.lcm n m have : u = n.factorMultiset := u.factorMultiset_prod.symm; rw [this] have : v = m.factorMultiset := v.factorMultiset_prod.symm; rw [this] rw [← PNat.factorMultiset_lcm n m, PNat.prod_factorMultiset] end PrimeMultiset