There are existing gcd
implementations in Python, and LCM is definable in terms of gcd
, so you may as well avoid reinventing the wheel. Specifically:
gcd(a, b) x lcm(a, b) = a x b
With Python 3.5 and higher, there is an accelerated gcd
function on the math
module, so lcm
can simplify to:
from math import gcd
def getLCM(a, b):
return a * b // gcd(a, b)
On older Python, it's not accelerated, but fractions.gcd
is a decent implementation provided for you, so you can use it instead, or to use the best possible gcd
on whatever version you run on, a nested import attempt works:
try:
from math import gcd
except ImportError:
from fractions import gcd
Your nlcm
loop could also be simplified: You don't need to destructively iterate manually, just loop:
def nlcm(num):
temp = 1
for x in num:
temp = getLCM(temp, x)
return temp
Or if you want to get clever, use reduce
(functools.reduce
on Python 3.x) since it does exactly what that simplified loop is already doing:
from functools import reduce
def nlcm(nums):
return reduce(getLCM, nums, 1)