The greatest common divisor (GCD) is the largest positive integer dividing both inputs. The least common multiple (LCM) is the smallest nonnegative common multiple; Python defines LCM as 0 when either input is zero. The original page title uses LCD; the standard term here is LCM.
Run the Python examples, compare expected outputs, modify the code, and complete guided exercises.
View on GitHubfrom math import gcd, lcm
a, b = 20, 12
print("GCD:", gcd(a, b))
print("LCM:", lcm(a, b))
Output:
GCD: 4
LCM: 60
Both functions are available in the standard math module in Python 3.9 or newer.
Euclid’s algorithm repeatedly replaces (a, b) with (b, a % b) until the second value becomes zero.
def gcd_recursive(a, b):
if b == 0:
return abs(a)
return gcd_recursive(b, a % b)
print(gcd_recursive(85, 20))
Output:
5
A loop avoids recursion and is the standard handwritten implementation.
def get_gcd(a, b):
while b:
a, b = b, a % b
return abs(a)
for pair in ((85, 20), (54, 24), (-12, 18)):
print(pair, get_gcd(*pair))
Output:
(85, 20) 5
(54, 24) 6
(-12, 18) 6
The original example asks for two integers. Here the result is safely positive.
from math import gcd
a = int(input("First number: "))
b = int(input("Second number: "))
print("GCD:", gcd(a, b))
Output:
GCD: 5
For nonzero inputs, abs(a*b) // gcd(a,b) computes LCM. Guard zero first to avoid division by zero.
from math import gcd
def get_lcm(a, b):
if a == 0 or b == 0:
return 0
return abs(a * b) // gcd(a, b)
for a, b in ((20, 12), (0, 12), (-6, 8)):
print(a, b, get_lcm(a, b))
Output:
20 12 60
0 12 0
-6 8 24
math.gcd() and math.lcm() handle signs and zeros. math.lcm() was introduced in Python 3.9.
from math import gcd, lcm
for a, b in ((0, 0), (0, 12), (-6, 8), (18, 24)):
print((a, b), "gcd", gcd(a, b), "lcm", lcm(a, b))
Output:
(0, 0) gcd 0 lcm 0
(0, 12) gcd 12 lcm 0
(-6, 8) gcd 2 lcm 24
(18, 24) gcd 6 lcm 72
Modern Python can find the GCD and LCM of more than two arguments.
from math import gcd, lcm
print(gcd(18, 24, 30))
print(lcm(4, 6, 10))
Output:
6
60
input() returns a string. Convert and validate the value before doing arithmetic.Try GCD and LCM for (12,18), (0,24), (-6,8) and (0,0). Use the companion practice notebook for runnable examples and self-checks.
math.gcd() returns a nonnegative result.
It is 0 in Python.
No. It was added in Python 3.9; use the guarded GCD formula on older versions.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.