Skip to content

Commit 0950f17

Browse files
kim-emleanprover-community-mathlib4-botbryangingechen
committed
chore: adaptations for batteries#1395 (better Newton starting point for Nat.sqrt) (leanprover-community#29142)
This PR adapts the proofs in Mathlib about `Nat.sqrt`, for the changes proposed in batteries#1395 which makes `Nat.sqrt` much faster on large numbers. This should not be merged before that PR, and the lakefile needs fixing up. Co-authored-by: leanprover-community-mathlib4-bot <leanprover-community-mathlib4-bot@users.noreply.github.com> Co-authored-by: Kim Morrison <kim@tqft.net> Co-authored-by: Bryan Gin-ge Chen <bryangingechen@gmail.com>
1 parent 068ec5b commit 0950f17

2 files changed

Lines changed: 14 additions & 5 deletions

File tree

Mathlib/Data/Nat/Sqrt.lean

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -98,9 +98,12 @@ private lemma sqrt_isSqrt (n : ℕ) : IsSqrt n (sqrt n) := by
9898
simp only [Nat.mul_add, Nat.add_mul, Nat.one_mul, Nat.mul_one, ← Nat.add_assoc]
9999
rw [Nat.lt_add_one_iff, Nat.add_assoc, ← Nat.mul_two]
100100
refine le_trans (Nat.le_of_eq (div_add_mod' (n + 2) 2).symm) ?_
101-
rw [Nat.add_comm, Nat.add_le_add_iff_right, add_mod_right]
102-
simp only [Nat.zero_lt_two, add_div_right, succ_mul_succ]
103-
refine le_trans (b := 1) ?_ ?_ <;> grind
101+
rw [show (n + 2) / 2 * 2 + (n + 2) % 2 = n + 2 by grind]
102+
simp only [shiftLeft_eq, Nat.one_mul]
103+
refine Nat.le_of_lt (Nat.le_trans lt_log2_self (le_add_right_of_le ?_))
104+
rw [← Nat.pow_add]
105+
apply Nat.pow_le_pow_right (by decide)
106+
grind
104107

105108
lemma sqrt_le (n : ℕ) : sqrt n * sqrt n ≤ n := (sqrt_isSqrt n).left
106109

@@ -169,8 +172,14 @@ lemma sqrt_eq' (n : ℕ) : sqrt (n ^ 2) = n := sqrt_add_eq' n (zero_le _)
169172
lemma sqrt_succ_le_succ_sqrt (n : ℕ) : sqrt n.succ ≤ n.sqrt.succ :=
170173
le_of_lt_succ <| sqrt_lt.2 <| (have := sqrt_le_add n; by grind)
171174

175+
@[simp]
176+
lemma log2_two : (2 : ℕ).log2 = 1 := by simp [log2]
177+
178+
@[simp]
179+
lemma sqrt_two : sqrt 2 = 1 := by simp [sqrt, sqrt.iter]
180+
172181
lemma add_one_sqrt_le_of_ne_zero {n : ℕ} (hn : n ≠ 0) : (n + 1).sqrt ≤ n :=
173-
le_induction le_rfl (fun n _ ih ↦ le_trans n.succ.sqrt_succ_le_succ_sqrt (succ_le_succ ih)) n
182+
le_induction (by simp) (fun n _ ih ↦ le_trans n.succ.sqrt_succ_le_succ_sqrt (succ_le_succ ih)) n
174183
(Nat.pos_of_ne_zero hn)
175184

176185
lemma exists_mul_self (x : ℕ) : (∃ n, n * n = x) ↔ sqrt x * sqrt x = x :=

lake-manifest.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@
6565
"type": "git",
6666
"subDir": null,
6767
"scope": "leanprover-community",
68-
"rev": "76408f09466811154e0e42329962de19f95d178b",
68+
"rev": "eebfdee629c3f3298929216d61839d4702524d42",
6969
"name": "batteries",
7070
"manifestFile": "lake-manifest.json",
7171
"inputRev": "main",

0 commit comments

Comments
 (0)