Find all factors of a number in JavaScript
Beginner · 4 min read
The factors of a number are all the whole numbers that divide it exactly. The factors of 12 are 1, 2, 3, 4, 6 and 12. You need them to simplify fractions, to split items into equal groups ("can 36 chairs go in equal rows?") and in many number puzzles.
In this tutorial you will write factors(n), which returns every factor in order. You will make it fast by finding factors in pairs, and use a Set to deal neatly with perfect squares. At the end you will see how factors differ from prime factors. You need to know for loops, arrays and the % operator.
Testing one factor
% gives the remainder after dividing. If the remainder is 0, the number divides exactly:
console.log(12 % 4); // 0, so 4 is a factor of 12
console.log(12 % 5); // 2, so 5 is not
The slow way to list factors is to test every number from 1 to n. That works, but for a large number it does a lot of useless checks.
Factors come in pairs
Whenever i divides n, so does n / i. For 12 the pairs are 1 × 12, 2 × 6 and 3 × 4. In each pair, the smaller number is at most the square root of n. So you only need to test i while i * i <= n, and each hit gives you two factors.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
13 Compute the factors of a number
easyList all the factors of a positive integer, in order.
Stuck? Three hints, smallest first
- 1. Pair them: when
idividesn, so doesn / i. - 2. That finds them out of order, so sort numerically at the end.
- 3. A perfect square has an odd number of factors, because one pairs with itself.
Step 1: find the pairs
Loop up to the square root, and push both numbers of each pair into an array:
function factorsArray(n) {
const found = [];
for (let i = 1; i * i <= n; i++) {
if (n % i !== 0) continue;
found.push(i, n / i);
}
return found;
}
console.log(factorsArray(12)); // [ 1, 12, 2, 6, 3, 4 ]
continue skips to the next i when i doesn't divide n. For 12, the loop only tries 1, 2 and 3, because 4 * 4 is already 16.
All six factors are there, but out of order. And there is a hidden problem.
Step 2: the perfect square problem
Try 36:
console.log(factorsArray(36)); // [ 1, 36, 2, 18, 3, 12, 4, 9, 6, 6 ]
6 is in the list twice. 36 is a perfect square, 6 × 6, so at i = 6 the pair is the same number twice.
A Set fixes this without any special case. A Set is a collection that keeps only one copy of each value. Adding something that is already there does nothing:
const s = new Set();
s.add(6);
s.add(6);
console.log(s.size); // 1
Step 3: use a Set, then sort
Swap the array for a Set, turn it back into an array with [...found], and sort it:
function factors(n) {
if (!Number.isInteger(n) || n < 1) return [];
const found = new Set();
for (let i = 1; i * i <= n; i++) {
if (n % i !== 0) continue;
found.add(i);
found.add(n / i);
}
return [...found].sort((a, b) => a - b);
}
console.log(factors(12)); // [ 1, 2, 3, 4, 6, 12 ]
console.log(factors(36)); // [ 1, 2, 3, 4, 6, 9, 12, 18, 36 ]
console.log(factors(13)); // [ 1, 13 ]
console.log(factors(0)); // []
The sort needs (a, b) => a - b. Without it, sort compares numbers as text and puts 12 before 2.
The first line refuses zero, negative numbers and decimals by returning an empty list. Every whole number divides 0, so "the factors of 0" has no useful answer.
Notice the counts: 12 has six factors, an even number, because they all come in pairs. 36 has nine, an odd number, because 6 pairs with itself. Only perfect squares have an odd number of factors.
Step 4: factors versus prime factors
People often mix these up. The factors of 12 are every number that divides it. Its prime factors are the primes you multiply together to make it: 2 × 2 × 3. The answer includes primeFactors to show the difference. It keeps dividing by the smallest number that fits:
const primeFactors = (n) => {
const out = [];
let left = n;
for (let d = 2; d * d <= left; d++) {
while (left % d === 0) { out.push(d); left /= d; }
}
if (left > 1) out.push(left);
return out;
};
console.log(primeFactors(12)); // [ 2, 2, 3 ]
console.log(primeFactors(360)); // [ 2, 2, 2, 3, 3, 5 ]
left /= d means left = left / d. Whatever is left at the end, if it is above 1, is itself prime. Multiplying the prime factors back together always gives n, which is an easy way to check the result.
The full solution
The panel has factors and primeFactors. It prints both for six numbers, including the prime 13 and the perfect square 36, then compares the factor counts of 36 and 35. Press Run to see them.
// Pairing, so the loop runs to sqrt(n) rather than n.
function factors(n) {
if (!Number.isInteger(n) || n < 1) return [];
const found = new Set();
for (let i = 1; i * i <= n; i++) {
if (n % i !== 0) continue;
found.add(i);
found.add(n / i); // the Set handles the sqrt case for free
}
return [...found].sort((a, b) => a - b);
}
const primeFactors = (n) => {
const out = [];
let left = n;
for (let d = 2; d * d <= left; d++) {
while (left % d === 0) { out.push(d); left /= d; }
}
if (left > 1) out.push(left);
return out;
};
for (const n of [12, 28, 36, 13, 1, 100]) {
console.log(String(n).padEnd(5), 'factors:', factors(n).join(', '), ' | prime factors:', primeFactors(n).join(' x '));
}
console.log('--- a perfect square has an odd count ---');
console.log('36 has', factors(36).length, 'factors, because 6 pairs with itself');
console.log('35 has', factors(35).length);
Output
19 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 19 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the factors of 12', factors(12), [1, 2, 3, 4, 6, 12]);
test('of 28', factors(28), [1, 2, 4, 7, 14, 28]);
test('of a prime, just 1 and itself', factors(13), [1, 13]);
test('of 1, just 1', factors(1), [1]);
test('of 100', factors(100), [1, 2, 4, 5, 10, 20, 25, 50, 100]);
test('they come out sorted', factors(36).every((f, i, a) => i === 0 || f > a[i - 1]), true);
test('1 is always a factor', factors(97)[0], 1);
test('and n itself is always the last', factors(97).at(-1), 97);
test('every factor really divides n', factors(36).every((f) => 36 % f === 0), true);
test('and nothing is missing', factors(36).length, Array.from({ length: 36 }, (_, i) => i + 1).filter((d) => 36 % d === 0).length);
test('a perfect square has an odd number of factors', factors(36).length % 2, 1);
test('while other numbers have an even number', factors(35).length % 2, 0);
test('zero has no factors by this definition', factors(0), []);
test('nor does a negative number', factors(-12), []);
test('nor a decimal', factors(6.5), []);
test('the prime factors multiply back to n', primeFactors(12).reduce((a, b) => a * b, 1), 12);
test('and for a larger number', primeFactors(360).reduce((a, b) => a * b, 1), 360);
test('a prime has itself as its only prime factor', primeFactors(13), [13]);
test('12 is 2 x 2 x 3', primeFactors(12), [2, 2, 3]);
The Set earns its place here: pairing finds i and n / i together, and for a perfect square those are the same number, so a plain array would contain 6 twice for n = 36. The Set handles it with no special case, and the assertion that a perfect square has an odd number of factors is the check that it worked.
Pairing also means the loop runs to √n instead of n, at the cost of finding the factors out of order — hence the numeric sort at the end, which needs the comparator like every numeric sort.
primeFactors is a different question worth having beside it: the factors of 12 are 1, 2, 3, 4, 6, 12, while its prime factorisation is 2 × 2 × 3. The assertion multiplying the prime factors back to n is a good self-check, since it fails if any factor is missed or repeated wrongly.
Common mistakes
- Looping all the way to
n. It works, but it is far slower than stopping at the square root. - Pushing both pair numbers into an array. Perfect squares get their middle factor twice. Use a
Set. - Sorting without a compare function.
[1, 12, 2]sorted as text stays[1, 12, 2]. Use(a, b) => a - b.
Try it yourself
- Write
commonFactors(a, b)that returns the factors both numbers share. For 12 and 18 you should get[1, 2, 3, 6]. - Find every number from 1 to 100 that has exactly 3 factors. What do they have in common?
- Check that
primeFactors(n).reduce((a, b) => a * b, 1)gives backnfor ten different numbers.