Zulip Chat Archive
Stream: Is there code for X?
Topic: gcd of a finite set of nats
Stepan Holub (Aug 18 2025 at 13:32):
I need to work with gcd of a (finite) set or list of natural numbers. Is there already a suitable way to do that without defining it from scratch, like
def gcd_of_list (L : List Nat) : Nat := foldr Nat.gcd 0 L
Aaron Liu (Aug 18 2025 at 13:35):
Stepan Holub (Aug 18 2025 at 13:51):
Indeed, looks simple. But I am unable to make it work for Nat. The f in the definition
def gcd (s : Finset β) (f : β → α) : α :=
s.fold GCDMonoid.gcd 0 f
should be identity
fun x => x
I guess. But I am unable to explain to Lean that Nat is an instance of CancelCommMonoidWithZero, NormalizedGCDMonoid.
To start, I would like to get claim of the form
example (s : Finset ℕ) (n : ℕ) (mem: n ∈ s) : Finset.gcd s ∣ n
(the function is missing here, but I am unable to fit anything in)
Aaron Liu (Aug 18 2025 at 13:53):
Do you have the correct imports?
Aaron Liu (Aug 18 2025 at 13:54):
#min_imports tells me
import Mathlib.Algebra.GCDMonoid.Finset
import Mathlib.Algebra.GCDMonoid.Nat
Stepan Holub (Aug 18 2025 at 13:58):
Of course, I tried to make necessary imports. But I was not successful. (That is why I dare to ask the chat.)
Ruben Van de Velde (Aug 18 2025 at 13:59):
As a tip, you can probably use import Mathlib to be sure you've got everything
Stepan Holub (Aug 18 2025 at 14:03):
Imported whole mathlib, and writing
example (s : Finset ℕ) (n : ℕ) (mem: n ∈ s) : Finset.gcd (fun x => x) s ∣ n
I get
Application type mismatch: In the application
Finset.gcd ?m.700 s
the argument
s
has type
Finset ℕ : Type
but is expected to have type
?m.135 → ℕ : Type (max ?u.132 0)
Ruben Van de Velde (Aug 18 2025 at 14:05):
The set comes first
Stepan Holub (Aug 18 2025 at 14:07):
Oops. Yes. That is what the message says. Thank you. Now it is accepted.
Stepan Holub (Aug 18 2025 at 14:10):
Now it works:
example (s : Finset ℕ) (n : ℕ) (mem: n ∈ s) : Finset.gcd s (fun x => x) ∣ n := by exact Finset.gcd_dvd mem
Thank both very much.
Last updated: Dec 20 2025 at 21:32 UTC