import Mathlib.NumberTheory.Divisors import Mathlib.Data.Finset.Max import Math.DivisorSequence.Cofactor import Math.DivisorSequence.ProperDivisorsMax namespace Math.DivisorSequence open Finset /-- If `6 ∣ n` and `1 < n`, then `n/3` is in `n.properDivisors.erase (n/2)`. This is a small helper to build the nonemptiness proof needed for `max'`. -/ lemma div_three_mem_erase_div_two {n : ℕ} (h6 : 6 ∣ n) (hn1 : 1 < n) : n / 3 ∈ (n.properDivisors).erase (n / 2) := by classical have hn0 : n ≠ 0 := Nat.ne_of_gt (lt_trans Nat.zero_lt_one hn1) have h3 : 3 ∣ n := dvd_trans (by decide : 3 ∣ 6) h6 have h2 : 2 ∣ n := dvd_trans (by decide : 2 ∣ 6) h6 have hlt : n / 3 < n / 2 := by -- compare by divisibility: `n/3 < n/2 ↔ 2 < 3`. have := (Nat.div_lt_div_left (a := n) (b := 3) (c := 2) hn0 h3 h2) have : n / 3 < n / 2 ↔ 2 < 3 := this simpa using this.2 (by decide : (2:ℕ) < 3) have hne : n / 3 ≠ n / 2 := ne_of_lt hlt refine Finset.mem_erase.2 ?_ refine ⟨hne, ?_⟩ -- membership in `properDivisors` refine (Nat.mem_properDivisors).2 ?_ constructor · exact Nat.div_dvd_of_dvd h3 · exact Nat.div_lt_self (Nat.pos_of_ne_zero hn0) (by decide : 1 < 3) /-- For `n` divisible by `6` and `n>1`, the second largest proper divisor is `n/3`. More precisely, after erasing the maximum proper divisor `n/2` from `n.properDivisors`, the maximum of what remains is `n/3`. This uses the cofactor lemma: any proper divisor `> n/3` must be `n/2`. -/ theorem max'_erase_div_two_eq_div_three {n : ℕ} (h6 : 6 ∣ n) (hn1 : 1 < n) : ((n.properDivisors).erase (n / 2)).max' (by classical exact ⟨n/3, div_three_mem_erase_div_two (n := n) h6 hn1⟩ ) = n / 3 := by classical -- Use the `max'_eq_iff` characterization. refine (Finset.max'_eq_iff (s := (n.properDivisors).erase (n/2)) (H := (by exact ⟨n/3, div_three_mem_erase_div_two (n := n) h6 hn1⟩)) (a := n/3)).2 ?_ constructor · -- membership exact div_three_mem_erase_div_two (n := n) h6 hn1 · intro b hb -- show `b ≤ n/3` have hbpd : b ∈ n.properDivisors := (Finset.mem_erase.1 hb).2 have hbne : b ≠ n/2 := (Finset.mem_erase.1 hb).1 by_contra hgt have hgt' : n/3 < b := lt_of_not_ge hgt have : b = n/2 := eq_div_two_of_mem_properDivisors_of_div_three_lt (n := n) (d := b) hbpd hgt' exact hbne this end Math.DivisorSequence