GCD (Greatest Common Divisor), in mathematics, is refered to the largest number that divides two or more non-zero integers without a remainder. For example, the GCD of 8 and 12 is 4.
LCM (Least Common Multiple), in mathematics, is the smallest positive number that is a multiple of both numbers. For example, the LCM of 8 and 12 is 24.
The releation between GCD and LCM is the following:
A popular algorithm in math, to compute the GCD is called Euclidean Algorithm, which iteratively substracts the small number from a larger one. This can be defined in the following python code:
def gcd(a, b):
if a == 0:
return b
while b:
if a > b:
a -= b
else:
b -= a
return a
The recurisve implementation is shorter, and can be found below:
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
A more efficient implementation using non-recursive structure in Python is as follows:
def gcd(a, b):
while b:
a, b = b, a % b
return a
It is noted that
a, b = b, a % b
is to swap a and b with the new values b and the remainder of a / b.
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: Codeforces: C. Letter
Next Post: O(n) High-precision Division Between Two Integers