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
dis a divisor of two numbersaandb, fora>=b, thendis also a divisor ofa−kbfor any integerk.This is true because
dis still a factor ofaandb, which can be taken out from each expression
This implies that the GCD of
aandbis the same as the GCD ofband
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