Greatest Common Divisor & Least Common Multiple

Euclid’s GCD Algorithm:

Stein’s GCD Algorithm:

Extensions:

  1. Given integers a and b, a slight extension of Euclid's gcd algorithm enables us to find integers x and y

    ax + by = gcd(a, b)
  2. One step further, we can find intergers u and v
    au + bv = 0

    or

    |au| = |bv| = lcm(a, b)
  3. Example 1: a = 51, b = 21

    51 = 2 * 21 + 9 9 = 51 - 2 * 21
    21 = 2 * 9 + 3 3 = 21 - 2 * 9
    = 21 - 2 * (51 - 2 * 21)
    = -2 * 51 + 5 * 21
    9 = 3 * 3 + 0 0 = 9 - 3 * 3
    = 51 - 2 * 21 - 3 * (-2 * 51 + 5 * 21)
    = 7 * 51 - 17 * 21

    Thus x = -2, y = 5 works, and gcd(51, 21) = 3;
    u = 7, v = -17 works, and lcm(51, 21) = 51 * 7 = 21 * 17 = 357.
    Example 2: a = 101, b = 12

    101 = 8 * 12 + 5 5 = 101 - 8 * 12
    12 = 2 * 5 + 2 2 = 12 - 2 * 5
    = 12 - 2 * (101 - 8 * 12)
    = -2 * 101 + 17 * 12
    5 = 2 * 2 + 1 1 = 5 - 2 * 2
    = 101 - 8 * 12 - 2 * (-2 * 101 + 17 * 12)
    = 5 * 101 - 42 * 12
    2 = 2 * 1 + 0 0 = 2 - 2 * 1
    = -2 * 101 + 17 * 12 - 2 * (5 * 101 - 42 * 12)
    = -12 * 101 + 101 * 12

    Thus x = 5, y = -42 works, and gcd(101, 12) = 1;
    u = -12, v = 101, and lcm(101, 12) = 12 * 101 = 1212.

  4. From the second extension, it can be deduced by replacing all minus by plus in the second column that
    |au| + |bv| = 2*lcm(a, b)

    Thus, we've got an lcm algorithm derived from Euclid's gcd algorithm.

Euclid-based LCM Algorithm:

Variant of Euclid-based LCM Algorithm:


Leave a Comment