Count divisors from prime factors in JavaScript
Intermediate · 5 min read
Every whole number above 1 can be built by multiplying primes together, and in only one way. 360 is 2 * 2 * 2 * 3 * 3 * 5, and no other set of primes gives 360. Writing a number this way is called prime factorization. It is the starting point for simplifying fractions, finding common denominators and much of the math behind encryption.
In this tutorial you will factorize a number by trial division, group the result into pairs like "2 to the power 3", and then use those powers to count a number's divisors and add them up, without listing a single one. You will finish with the slowest small case for this method: the square of a four-digit prime. You need to know while loops, % and reduce.
Primes and divisors
A prime is a whole number above 1 that only divides by 1 and itself: 2, 3, 5, 7, 11 and so on. A divisor of a number is anything that divides it exactly. The divisors of 12 are 1, 2, 3, 4, 6 and 12.
Trial division
To factorize, try dividing by 2 as many times as you can, then by 3, then by 4, then by 5, and so on. Each time a division works, you have found a prime factor. You can stop early: once the candidate squared is bigger than what's left, whatever is left must be prime.
Here is the exercise. Have a go on your own first if you like, then read on and we will build it together.
100 Prime factorisation, and what the exponents tell you
fairFactorise a number by trial division, group the result into base-and-exponent pairs, and use those exponents to count the divisors and total them without listing any. Then check the hardest small case for trial division: the square of a four-digit prime.
Stuck? Three hints, smallest first
- 1. Divide out each candidate completely before moving on, so every factor you push is prime.
- 2. Stop when
d * d > x. Whatever is left above 1 is the final prime factor. - 3. From
2**3 * 3**2 * 5the divisor count is4 * 3 * 2.
Step 1: trial division
const factorise = (n) => {
const factors = [];
let x = n;
for (let d = 2; d * d <= x; d++) {
while (x % d === 0) {
factors.push(d);
x /= d;
}
}
if (x > 1) factors.push(x);
return factors;
};
console.log(factorise(360)); // [ 2, 2, 2, 3, 3, 5 ]
console.log(factorise(13195)); // [ 5, 7, 13, 29 ]
The while loop divides out each d completely before moving on. That is why you never need to check whether d is prime. Take d = 4: by then every 2 has already been divided out, so 4 can't divide what's left. Any d that still divides x must be prime.
The loop condition uses x, which shrinks as factors come out, not the original n. For 360, after dividing out three 2s and two 3s, x is 5, and the loop ends after d = 3, because 4 * 4 is more than 5.
Step 2: the wrong turn, dropping the last line
The line if (x > 1) factors.push(x) is easy to forget. Without it:
const factoriseNoTail = (n) => {
const factors = [];
let x = n;
for (let d = 2; d * d <= x; d++) {
while (x % d === 0) {
factors.push(d);
x /= d;
}
}
return factors;
};
console.log(factoriseNoTail(360), factoriseNoTail(97)); // [ 2, 2, 2, 3, 3 ] []
The last 5 of 360 is lost, and the prime 97 gets an empty list. The final factor is always bigger than the square root of what's left, so the loop never reaches it.
Step 3: small cases
console.log(factorise(97), factorise(1), factorise(2)); // [ 97 ] [] [ 2 ]
console.log(factorise(1024).length); // 10
A prime factorizes to itself. 1 has no prime factors, so the list is empty. 1024 is 2 multiplied ten times.
Step 4: group into powers
const grouped = (n) => {
const pairs = [];
for (const p of factorise(n)) {
const last = pairs[pairs.length - 1];
if (last && last[0] === p) last[1]++;
else pairs.push([p, 1]);
}
return pairs;
};
console.log(JSON.stringify(grouped(360))); // [[2,3],[3,2],[5,1]]
The factors come out in order, so equal primes sit next to each other. If the prime matches the last pair, add one to its count. Otherwise start a new pair. The result reads as 2³ * 3² * 5¹. JSON.stringify prints the nested arrays on one line.
Step 5: count divisors from the powers
Any divisor of 360 is made by choosing how many 2s (0 to 3), how many 3s (0 to 2) and how many 5s (0 or 1) to use. That is 4 * 3 * 2 = 24 choices, and each gives a different divisor.
const divisorCount = (n) => grouped(n).reduce((c, pair) => c * (pair[1] + 1), 1);
console.log(divisorCount(360)); // 24
For each pair, multiply by the power plus one. No divisor is ever listed.
Step 6: add up divisors from the powers
The divisors made from 2s alone add up to 1 + 2 + 4 + 8. For 3s, it's 1 + 3 + 9, and for 5s, 1 + 5. Multiply those sums together and you get the total of all divisors. A sum like 1 + 2 + 4 + 8 has a shortcut, (p ** (a + 1) - 1) / (p - 1): here (16 - 1) / 1 = 15.
const divisorSum = (n) =>
grouped(n).reduce((s, pair) => s * ((pair[0] ** (pair[1] + 1) - 1) / (pair[0] - 1)), 1);
console.log(divisorSum(360)); // 1170
15 * 13 * 6 = 1170.
Step 7: check by listing
To be sure, list the divisors the slow way and compare.
const add = (a, b) => a + b;
const divisors = (n) => {
const out = [];
for (let d = 1; d * d <= n; d++) {
if (n % d === 0) {
out.push(d);
if (d !== n / d) out.push(n / d);
}
}
return out.sort((a, b) => a - b);
};
console.log(divisors(360).length, divisors(360).reduce(add, 0)); // 24 1170
Divisors come in pairs, like 8 and 45 (8 * 45 = 360), so the loop only needs to go up to the square root. d !== n / d stops a square root from being counted twice.
Step 8: the slow case
console.log(factorise(9973 * 9973), 9973 * 9973); // [ 9973, 9973 ] 99460729
9973 is prime, so nothing divides 99460729 until d reaches 9973. The loop tries almost ten thousand candidates. It is still fast here, but for numbers with only huge prime factors, trial division gets slow, and that is what keeps some kinds of encryption safe.
The full solution
The answer panel has factorise, grouped, divisorCount, divisorSum, divisors and a check that the factors multiply back to the number, and prints every case above, including 0 and -12 (both give an empty list). Press Run to see the output.
const add = (a, b) => a + b;
const factorise = (n) => {
const factors = [];
let x = n;
for (let d = 2; d * d <= x; d++) {
while (x % d === 0) {
factors.push(d);
x /= d;
}
}
if (x > 1) factors.push(x);
return factors;
};
const grouped = (n) => {
const pairs = [];
for (const p of factorise(n)) {
const last = pairs[pairs.length - 1];
if (last && last[0] === p) last[1]++;
else pairs.push([p, 1]);
}
return pairs;
};
// Both of these read the answer off the exponents, listing nothing.
const divisorCount = (n) => grouped(n).reduce((c, pair) => c * (pair[1] + 1), 1);
const divisorSum = (n) =>
grouped(n).reduce((s, pair) => s * ((pair[0] ** (pair[1] + 1) - 1) / (pair[0] - 1)), 1);
const divisors = (n) => {
const out = [];
for (let d = 1; d * d <= n; d++) {
if (n % d === 0) {
out.push(d);
if (d !== n / d) out.push(n / d);
}
}
return out.sort((a, b) => a - b);
};
const rebuilds = (n) => factorise(n).reduce((p, q) => p * q, 1) === n;
console.log('360 :', factorise(360));
console.log('97, 1, 2 :', factorise(97), factorise(1), factorise(2));
console.log('1024, 13195:', factorise(1024).length, 'twos and', factorise(13195));
console.log('grouped :', grouped(360), grouped(5040));
console.log('9973 * 9973:', factorise(9973 * 9973), 'which is', 9973 * 9973);
console.log('divisors of 360 :', divisors(360));
console.log('count, from pairs:', divisorCount(360), 'from the list:', divisors(360).length);
console.log('sum, from pairs :', divisorSum(360), 'from the list:', divisors(360).reduce(add, 0));
console.log('zero and negative:', factorise(0), factorise(-12), '<- the loop never starts');
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('360 is three twos, two threes and a five', factorise(360), [2, 2, 2, 3, 3, 5]);
test('a prime factorises to itself, and 1 to an empty list', [factorise(97), factorise(1), factorise(2)], [[97], [], [2]]);
test('1024 is ten twos, and 13195 is 5 times 7 times 13 times 29', [factorise(1024).length, factorise(13195)], [10, [5, 7, 13, 29]]);
test('grouping gives base and exponent pairs', [grouped(360), grouped(5040)], [[[2, 3], [3, 2], [5, 1]], [[2, 4], [3, 2], [5, 1], [7, 1]]]);
test('the factors multiply back to the number every time', [360, 97, 1024, 13195, 9973 * 9973].map(rebuilds), [true, true, true, true, true]);
test('the square of a four-digit prime is the slowest small case, and still works', [factorise(9973 * 9973), 9973 * 9973], [[9973, 9973], 99460729]);
test('360 has 24 divisors, which the exponents give without listing any', [divisorCount(360), divisors(360).length], [24, 24]);
test('and they sum to 1170, again read straight off the exponents', [divisorSum(360), divisors(360).reduce(add, 0)], [1170, 1170]);
test('exactly half the divisors are at or below the square root, which is why trial division stops there', [divisors(360).filter((d) => d * d <= 360).length, divisors(360).length / 2], [12, 12]);
Trial division is correct here for a reason that is easy to miss: because each candidate d is divided out completely before d increases, any d that still divides x must be prime — all its smaller prime factors are already gone. So there is no need to test primality inside the loop.
The stopping condition d * d <= x uses the shrinking x, not the original n, which is what makes it fast: after dividing out the small primes the bound collapses. And it must be paired with the if (x > 1) line afterwards, because the last remaining factor is above the square root of what is left. Drop that line and every prime returns an empty list.
The exponents are worth more than the factor list. A number p**a * q**b has (a + 1) * (b + 1) divisors, because a divisor picks an independent exponent for each prime, and their total is the product of the geometric sums. Both are computed here from three pairs rather than by enumerating 24 divisors — the same reasoning scales to numbers far too large to list. Note the guard that is missing: 0 and negatives fall straight through and return an empty list, which is the loop being honest about a question it was never asked.
Common mistakes
- Forgetting
if (x > 1)after the loop. The last prime factor is lost, and primes give an empty list. - Stopping at the square root of
ninstead ofx. It still works, but it misses the speed-up from the shrinkingx. - Not dividing each factor out completely. Use
while, notif, or 360 gives[2, 3, 4, 15]instead of primes.
Try it yourself
- Factorize 5040 and use
groupedto write it as powers. How many divisors does it have? - Write
isPrime(n)usingfactorise. What should it return for 1? - Add a guard to
factorisethat returnsnullfor 0, negatives and decimals.