lcm (Least Common Multiple)

Tags: [math], [lcm], [gcd]

Link: https://zh.wikipedia.org/wiki/最小公倍數

Given two integers a and b, calculate the Least Common Multiple.


Solution: Using gcd to calculate the lcm

def get_lcm(a, b):
    if not a:
        return b
    if not b:
        return a

    a = abs(a)
    b = abs(b)

    gcd = get_gcd(a, b)
    lcm = a * b / gcd
    return lcm

def get_gcd(a, b):
    r = a % b
    # base case
    if r == 0:
        return b
    return get_gcd(b, r)

if __name__ == '__main__':
    print 'Program is working'

    # a = -10
    # b = 15

    a = 0
    b = 0

    lcm = get_lcm(a, b)
    print lcm

    print 'Program is end'

Revelation:

Note:

results matching ""

    No results matching ""