-
-
Save efrenfuentes/47a86f8cf64f1052775532691308143f to your computer and use it in GitHub Desktop.
GCD and LCM functions in Python for several numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Greatest common divisor of 1 or more numbers. | |
from functools import reduce | |
def gcd(*numbers): | |
""" | |
Return the greatest common divisor of 1 or more integers | |
Examples | |
-------- | |
>>> gcd(5) | |
5 | |
>>> gcd(30, 40) | |
10 | |
>>> gcd(120, 40, 60) | |
20 | |
""" | |
# Am I terrible for doing it this way? | |
from math 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 of 1 or more integers. | |
Examples | |
-------- | |
>>> lcm(5) | |
5 | |
>>> lcm(30, 40) | |
120 | |
>>> lcm(120, 40, 60) | |
120 | |
""" | |
def lcm(a, b): | |
return (a * b) // gcd(a, b) | |
return 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