Algo-Sim › Math & Geometry

GCD and LCM (Euclid)

Easy · Math & Geometry · step through it in Java, Python and C++ on your own input

Euclid’s algorithm: replace (a, b) with (b, a mod b) until b is 0. O(log min(a, b)) steps; the LCM follows as a / gcd × b.

Problem

Given two positive integers a and b, return [gcd, lcm]: their greatest common divisor and least common multiple. Avoid trying every divisor, and compute the LCM without overflowing.

Constraints

Edge cases to test

Follow-up questions

Why compute a / gcd × b for the LCM?
Dividing first keeps the intermediate value small; a × b / gcd can overflow even when the LCM fits.
How do you also get the Bézout coefficients?
Extended Euclid returns x, y with ax + by = gcd: the basis for modular inverses when the modulus is not prime.

Solution

Java

public long[] gcdLcm(int a, int b) {
    int g = gcd(a, b);
    return new long[] { g, (long) a / g * b };  // multiply in 64 bits
}

private int gcd(int a, int b) {
    while (b != 0) {
        int r = a % b;
        a = b;
        b = r;
    }
    return a;
}

Python

def gcd_lcm(a, b):
    g = gcd(a, b)
    return [g, a // g * b]  # divide first


def gcd(a, b):
    while b != 0:
        r = a % b
        a, b = b, r
    return a

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<long long> gcdLcm(int a, int b) {
        int g = gcd(a, b);
        return vector<long long>{g, 1LL * a / g * b}; // multiply in 64 bits
    }

    int gcd(int a, int b) {
        while (b != 0) {
            int r = a % b;
            a = b;
            b = r;
        }
        return a;
    }
};

More Math & Geometry problems