LCM using recursive?

ComputerGuy22 picture ComputerGuy22 · Sep 23, 2015 · Viewed 7.4k times · Source

Here is my code:

def lcm(a, b):
    if b == 0:
        return a
    return a * b / lcm(a, b)

print lcm(5,3)

This is what I could manage so far, any idea on how to find the LCM (least common multiple) of two numbers using recursive and one function?

Answer

tsh picture tsh · Nov 2, 2018

We have lcm(a, b) * gcd(a, b) = a * b. So we can write the following equation:

lcm(a, b) = a; if a % b == 0
lcm(a, b) ; if a % b != 0
= a * b / gcd(a, b)
= a * b / gcd(b, a % b)
= a * b / (b * (a % b) / lcm(b, a % b))
= a / (a % b) * lcm(b, a % b)

And translate to Python, we have:

def lcm(a, b):
  t = a % b
  if t == 0: return a
  return a * lcm(b, t) / t