GCD / LCM
Beginner · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
The GCD of two numbers is the biggest number that divides both exactly; the LCM is the smallest number that both divide into. GCD simplifies and shares things evenly, while LCM tells you when two repeating events line up again.
Practical use cases
- Web app: Cron jobs that run together. One scheduled task runs every 4 hours and another every 6 hours. The LCM, 12, tells you they will fire at the same moment every 12 hours, when your server may be doubly loaded. You can then move one task by an hour to avoid the clash.
- Web app: Image resizing with the right ratio. An upload page must show a 1920 by 1080 photo as a small thumbnail without squashing it. Dividing both sizes by their GCD, 120, reveals the shape as 16 by 9. The page then picks any size with that ratio and the picture looks right.
- System: Fractions and encryption. Software that shows 6/8 as 3/4 divides top and bottom by their GCD. Encryption key generation also checks that two numbers share no common factor except 1, using the same fast Euclid method, which needs only a few steps even for numbers hundreds of digits long.
The story: The Ribbon and the Lamps
For Diwali, Aarav had two ribbons for decorating the door: one 48 cm long, the other 18 cm. His mother said, "Cut both into pieces of the same length, and don't waste an inch. Make the pieces as long as you can." Aarav tried 2 cm (works, but too small), then 3 cm, then 6 cm. Six worked for both, and nothing longer did. That 6 is the greatest common divisor, the GCD.
But trying lengths one by one is slow. Mira knew a faster way, a trick 2,000 years old, from a Greek called Euclid. "Lay the short ribbon along the long one. 18 fits twice into 48 and leaves 12 over. Whatever length fits both ribbons also fits that leftover 12. So now ask the same question about 18 and 12." Then 12 and 6. Then 6 and 0. "Stop! The answer is 6."
Later that night the two little lamps by the temple blinked: one every 48 seconds, the other every 18. "When will they blink together again?" Kabir asked. This is the opposite question: the least common multiple (LCM), the first time both timetables meet. Count 48, 96, 144 and 18, 36 ... 144. They meet at 144 seconds.
Mira noticed the two are linked: the GCD tells you how much the numbers overlap, and so LCM = a ÷ GCD × b. Find the GCD the quick way, and the LCM comes free.
How to spot this problem, and where you need it
You need to simplify a ratio, split things into equal groups of the largest possible size, or find when two repeating schedules coincide, and trial and error is clumsy.
Signs you need it
- Two repeating cycles, like billing every 14 days and reports every 10 days, and the question is when they meet again.
- You want to reduce a fraction or ratio, such as screen sizes or recipe quantities, to its simplest form.
- The task is to cut things into equal pieces with no leftover, using the biggest piece possible.
Where to use it in a project
- Scheduling features: finding when two recurring jobs, subscriptions or reminders fall on the same day.
- Layout and media code: keeping aspect ratios and grid sizes tidy, for thumbnails, banners and print sizes.
The solution
For the GCD, use Euclid's method: divide the bigger number by the smaller and keep the remainder; then repeat with the smaller number and that remainder until the remainder is zero. The last non-zero number is the GCD. For the LCM, multiply the two numbers and divide by the GCD. Both take only a few steps even for huge numbers.
Payoff: Before: testing every number up to the limit by hand. After: Euclid's method finds the GCD of two 10-digit numbers in about 15 steps.
Explain it like I am 8
GCD is the biggest block that builds both of two towers exactly. LCM is the first number you land on if two frogs jump at different step sizes starting from zero: the first spot where both frogs land together.
How it works, step by step
- GCD question: what is the biggest number that divides both a and b with nothing left over?
- Euclid's step: replace (a, b) by (b, a mod b). The common divisors do not change, but the numbers shrink fast.
- Repeat until b becomes 0. The remaining a is the GCD.
- LCM from GCD:
lcm = a / gcd * b(divide first so the number stays small). - Quick check: GCD × LCM equals a × b for two numbers.
The code in four languages
PHP
<?php
// Euclid: keep replacing (a, b) with (b, a mod b) until b is 0.
function gcd(int $a, int $b): int {
while ($b !== 0) {
[$a, $b] = [$b, $a % $b];
}
return $a;
}
// LCM from GCD. Divide first to avoid a huge intermediate number.
function lcm(int $a, int $b): int {
return intdiv($a, gcd($a, $b)) * $b;
}
echo "gcd(48, 18) = " . gcd(48, 18) . "
"; // 6
echo "lcm(48, 18) = " . lcm(48, 18) . "
"; // 144
echo "gcd(17, 5) = " . gcd(17, 5) . "
"; // 1 (no shared divisor)
// Simplify the fraction 18/48 using the GCD.
$g = gcd(18, 48);
echo "18/48 = " . (18 / $g) . "/" . (48 / $g) . "
"; // 3/8JavaScript
// Euclid: keep replacing (a, b) with (b, a mod b) until b is 0.
function gcd(a, b) {
while (b !== 0) {
[a, b] = [b, a % b];
}
return a;
}
// LCM from GCD. Divide first to avoid a huge intermediate number.
function lcm(a, b) {
return (a / gcd(a, b)) * b;
}
console.log("gcd(48, 18) = " + gcd(48, 18)); // 6
console.log("lcm(48, 18) = " + lcm(48, 18)); // 144
console.log("gcd(17, 5) = " + gcd(17, 5)); // 1 (no shared divisor)
// Simplify the fraction 18/48 using the GCD.
const g = gcd(18, 48);
console.log("18/48 = " + (18 / g) + "/" + (48 / g)); // 3/8Java
public class Main {
// Euclid: keep replacing (a, b) with (b, a mod b) until b is 0.
static int gcd(int a, int b) {
while (b != 0) {
int rest = a % b;
a = b;
b = rest;
}
return a;
}
// LCM from GCD. Divide first to avoid a huge intermediate number.
static int lcm(int a, int b) {
return a / gcd(a, b) * b;
}
public static void main(String[] args) {
System.out.println("gcd(48, 18) = " + gcd(48, 18)); // 6
System.out.println("lcm(48, 18) = " + lcm(48, 18)); // 144
System.out.println("gcd(17, 5) = " + gcd(17, 5)); // 1 (no shared divisor)
// Simplify the fraction 18/48 using the GCD.
int g = gcd(18, 48);
System.out.println("18/48 = " + (18 / g) + "/" + (48 / g)); // 3/8
}
}Go
package main
import "fmt"
// gcd uses Euclid: keep replacing (a, b) with (b, a mod b) until b is 0.
func gcd(a, b int) int {
for b != 0 {
a, b = b, a%b
}
return a
}
// lcm from gcd. Divide first to avoid a huge intermediate number.
func lcm(a, b int) int {
return a / gcd(a, b) * b
}
func main() {
fmt.Println("gcd(48, 18) =", gcd(48, 18)) // 6
fmt.Println("lcm(48, 18) =", lcm(48, 18)) // 144
fmt.Println("gcd(17, 5) =", gcd(17, 5)) // 1 (no shared divisor)
// Simplify the fraction 18/48 using the GCD.
g := gcd(18, 48)
fmt.Printf("18/48 = %d/%d\n", 18/g, 48/g) // 3/8
}Time: O(log(min(a, b))) · Extra space: O(1). The numbers shrink very quickly in Euclid's method, so even huge inputs need only a handful of steps.
Watch out for
- Looping through every number up to min(a, b) to find the GCD. It works but is far slower than Euclid.
- Computing LCM as
a * b / gcdand overflowing on big inputs. Divide first:a / gcd * b. - Forgetting that gcd(a, 0) = a, which is the stopping rule of the loop.
Quick check
- What is GCD(12, 18)?
- 3
- 6
- 36
- What is LCM(4, 6)?
- 24
- 2
- 12
- In Euclid's algorithm, (a, b) becomes...
- (b, a mod b)
- (a - 1, b - 1)
- (a + b, b)