-- Lagrange's four-square theorem: every natural number is a sum of four -- squares, by the prime case and the product identity along a prime -- factorization. -- Part of Cumulus, the Grace17 mathematics library. -- Copyright (c) 2026 Grant Passmore. -- Released under the Apache License 2.0. See LICENSE in the repository root. -- Authors: Grant Passmore module Grace.Cumulus.NumberTheory.FourSquares import Grace.Cumulus.NumberTheory.FourSquaresDescent import Grace.Cumulus.NumberTheory.Factorization -- Products of primes theorem SumOfFourSquares.listProduct (xs : List(ℕ)) requires primes : PrimeList(xs) shows SumOfFourSquares(∏ xs) proof induction xs | List.nil => intro primes rw listProduct.nil exact SumOfFourSquares.one | List.cons(x, rest) using ih => intro primes have head := PrimeList.head at x, rest with primes have tail := PrimeList.tail at x, rest with primes have restSum := ih with tail have headSum := lagrange.prime at x with head rw listProduct.cons exact SumOfFourSquares.mul at x, ∏ rest with headSum, restSum -- Lagrange's theorem theorem SumOfFourSquares.all (n : Nat) shows SumOfFourSquares(n) proof by_cases zero : n = 0 . rw zero exact SumOfFourSquares.zero . obtain ⟨xs, xsList, primes, product⟩ := primeFactorization.exists at n with zero rw ← product exact SumOfFourSquares.listProduct at xs with primes theorem lagrange.four_squares (n : Nat) shows ∃ a, Nat(a) ∧ ∃ b, Nat(b) ∧ ∃ c, Nat(c) ∧ ∃ d, Nat(d) ∧ a * a + b * b + c * c + d * d = n proof obtain ⟨a, aNat, b, bNat, c, cNat, d, dNat, equation⟩ := SumOfFourSquares.all at n symm at equation refine ⟨a, aNat, b, bNat, c, cNat, d, dNat, equation⟩