Skip to content

Instantly share code, notes, and snippets.

@randomdude999
Forked from endolith/gcd_and_lcm.py
Last active November 4, 2017 12:52
Show Gist options
  • Save randomdude999/81fd0e857e23060b0cb18324faf001e5 to your computer and use it in GitHub Desktop.
Save randomdude999/81fd0e857e23060b0cb18324faf001e5 to your computer and use it in GitHub Desktop.
GCD and LCM functions in Python
import math
import functools
# Greatest common divisor of more than 2 numbers. Am I terrible for doing it this way?
def gcd(*numbers):
"""Return the greatest common divisor of the given integers"""
return functools.reduce(math.gcd, numbers)
# Least common multiple is not in standard libraries? It's in gmpy, but this is simple enough:
def lcm(*numbers):
"""Return lowest common multiple."""
def lcm(a, b):
return (a * b) // math.gcd(a, b)
return functools.reduce(lcm, numbers, 1)
# Assuming numbers are positive integers...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment