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
- 1 ≤ a, b ≤ 10⁹
- lcm(a, b) fits in a 64-bit integer
Edge cases to test
- One argument 0: gcd(a, 0) = a
- Equal numbers
- Coprime numbers
Follow-up questions
- Why compute
a / gcd × bfor the LCM? - Dividing first keeps the intermediate value small;
a × b / gcdcan 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 aC++
#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
- Plus One (Easy)
- Happy Number (Easy)
- Count Primes (Sieve of Eratosthenes) (Medium)
- Pow(x, n) (Medium)
- Count Good Numbers (mod 1e9+7) (Medium)
- Multiply Strings (Medium)
- Reverse Integer (Medium)
- String to Integer (atoi) (Medium)
- Detect Squares (Medium)
- Random Pick with Weight (Medium)
- Shuffle an Array (Medium)
- Linked List Random Node (Medium)
- Pascal's Triangle (Easy)
- nCr mod p (Medium)
- Max Points on a Line (Hard)