GCD and LCM
Greatest Common Denominator and Least Common Multiple
GCD (Greatest Common Denominator)
How to find the greatest common denominator (gcd) of two numbers quickly?
Euclid's method of finding GCD
Time Complexity:
Space Complexity:
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
Euclid's algorithm works because it leverages two fundamental properties of the greatest common divisor (GCD):
If
d
is a divisor of two numbersa
andb
, fora
>=b
, thend
is also a divisor ofa−kb
for any integerk
.This is true because
d
is still a factor ofa
andb
, which can be taken out from each expression
This implies that the GCD of
a
andb
is the same as the GCD ofb
and
LCM (Least Common Multiple)
To find the LCM, there is a math formula that relates LCM to GCD, which makes calculation easy.
int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
Here is a great proof by ChatGPT that explains why:
Last updated