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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.