Skip to content

Instantly share code, notes, and snippets.

@qqpann
Forked from endolith/gcd_and_lcm.py
Created August 12, 2017 13:03
Show Gist options
  • Save qqpann/9219542157b7e36cbdf1023db48afcbf to your computer and use it in GitHub Desktop.
Save qqpann/9219542157b7e36cbdf1023db48afcbf to your computer and use it in GitHub Desktop.
GCD and LCM functions in Python
# 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"""
from fractions import gcd
return reduce(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) // gcd(a, b)
return reduce(lcm, numbers, 1)
# Assuming numbers are positive integers...
@qqpann
Copy link
Author

qqpann commented Aug 12, 2017

python3 requires
from functools import reduce

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment