The least common multiple (LCM) of two integers is the smallest positive number that is divisible by both.
Remember
lcm(a, b) = smallest positive m such that
m % a == 0 and m % b == 0
Identity (nonnegative a, b):
gcd(a, b) × lcm(a, b) = a × b
⇒ lcm(a, b) = |a × b| / gcd(a, b)
Example: a = 12, b = 18
Multiples of 12: 12, 24, 36, 48, …
Multiples of 18: 18, 36, 54, …
First shared = 36
Check: gcd(12, 18) = 6 → 12 × 18 / 6 = 36
a
b
gcd
lcm
12
18
6
36
7
5
1
35
0
15
15
0
Approach
How to Find LCM in PHP
Four clear steps — prefer the GCD formula in interviews and real code.
Take absolute values with abs() so negatives do not change the LCM.
If either value is 0, return 0.
Compute gcd($a, $b) with Euclid’s algorithm.
Return |a / gcd × b| (divide before multiply to reduce product size).
Method
Idea
Time
Best for
GCD formula
|a / gcd × b|
O(log min)
Interviews, production
Multiple scan
Increase by max(a, b) until both divide
O(lcm / max)
Teaching the definition
Pseudocode
Pseudocode
function Gcd(a, b):
a = abs(a), b = abs(b)
while b != 0:
t = b
b = a mod b
a = t
return a
function Lcm(a, b):
a = abs(a), b = abs(b)
if a == 0 or b == 0:
return 0
g = Gcd(a, b)
return (a / g) * b
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
Meaning
Smallest positive multiple of both
Formula
lcm = |a × b| / gcd(a, b)
Safe order
Divide by gcd first, then multiply
Zero
lcm(0, n) = 0
Three numbers
lcm(lcm(a, b), c)
Classic check
lcm(12, 18) === 36
Try it
Live Preview
Enter two integers to see their GCD and LCM.
Whole numbers (absolute values used). Tap a chip or type a pair.
Result
a = 12, b = 18
gcd(12, 18) = 6
lcm = |12 × 18| / 6 = 36