Find Greatest Common Factor (Maths series)
2 minutes read
The GCF (or HCF) is the largest positive whole number that divides all the given numbers with no remainder. The GCF of 18 and 27 is 9.
Here are factor trees for both. Break each number down into prime factors, then multiply the ones they share. Both have 3 × 3, so the GCF is 9:
18
/ \
2 9
/ \
3 3
27
/ \
3 9
/ \
3 3
Problem
A real life example:
- A baker has 24 chocolate muffins and 36 vanilla muffins.
- He wants to pack them into as many boxes as possible, with the same mix of muffins in every box and none left over.
Solution
Use the subtraction form of Euclid's algorithm:
- Subtract the smaller number from the larger one
- Replace the larger number with the result, and repeat with the new pair
- Stop when the two numbers are equal. That number is the GCF (one more subtraction gives zero)
In the example the larger number is 36 and the smaller is 24:
36 - 24 = 12
24 - 12 = 12
12 - 12 = 0
The GCF is 12, so the baker can fill 12 boxes, each with 2 chocolate and 3 vanilla muffins, and nothing is left over.
In JavaScript:
function gcf(num1, num2) {
const max = Math.max(num1, num2);
const min = Math.min(num1, num2);
const diff = max - min;
if (diff > 0) return gcf(min, diff);
return min;
}
Example:
gcf(24, 36); // 12
GCF for more than two numbers
With more than two numbers, work through the list two at a time: find the GCF of the first two, then the GCF of that result and the next number, and so on. For 20, 50 and 125:
answer = GCF(GCF(125, 50), 20)
= GCF(25, 20)
= 5
The GCF function, updated to take any number of arguments:
// accept any number of arguments
function gcf(...args) {
// more than two: fold the list down two at a time
if (args.length > 2) {
const [first, second, ...rest] = args;
return gcf(gcf(first, second), ...rest);
}
// two numbers: same as before
const [num1, num2] = args;
const max = Math.max(num1, num2);
const min = Math.min(num1, num2);
const diff = max - min;
if (diff > 0) return gcf(min, diff);
return min;
}
Example:
gcf(20, 50, 125); // 5
The GCF goes by other names too: the Highest Common Factor (HCF) and the Greatest Common Divisor (GCD).
Maths meets programming
Helping my son, Omer, prepare for the 11+ test got me interested in maths again. I've been programming for over 20 years, so I kept turning the formulas we covered into code. These posts are my notes from that.
These problems are simple and you'll find them solved on plenty of coding sites. This is just me working through them.