Python Code Example: least common multiple

This code defines two functions gcd and lcm. The gcd function computes the greatest common divisor between two integers a and b using the Euclidean algorithm. The lcm function computes the least common multiple of a and b by dividing the product of a and b by the result of gcd(a, b).

At the end of the code, the values of a and b are set to 20 and 8 respectively and the least common multiple is calculated and printed to the console.

def gcd(a, b):
    if a == 0:
        return b
    elif b == 0:
        return a
    elif a > b:
        return gcd(a - b, b)
    else:
        return gcd(a, b - a)


def lcm(a, b):
    return a * b / gcd(a, b)


a, b = 20, 8

print("Least common multiple is: " + str(lcm(a, b)))
Output
Least common multiple is: 40.0