Functional Weave
Code in Python

math.gcd-lcm@2.0.0

impl/python/lcm.py

452 bytes · the Python implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

from .math_gcd_lcm_gcd import gcd  ← gcd, another function of this group · built into the same file, even by a slim install

_MAX_SAFE = 9007199254740991


def lcm(a: int, b: int) -> int:
    """Least common multiple, never negative; 0 when either input is 0."""
    g = gcd(a, b)
    if g == 0:
        return 0
    # Divide before multiplying: a * b overflows long before the lcm does.
    result = abs(a) // g * abs(b)
    if result > _MAX_SAFE:
        raise ValueError("the lcm of %d and %d exceeds 2^53 - 1" % (a, b))
    return result