Prime factorization of a number in JavaScript
Intermediate · 4 min read
Every whole number above 1 can be written as primes multiplied together, in exactly one way. 360 is 2 times 2 times 2 times 3 times 3 times 5. Finding that list is called prime factorization. It is how you count divisors, simplify fractions and find common multiples, and it shows up often in coding puzzles.
In this tutorial you will write factorise(n), which returns the prime factors in order, repeats included, so 360 gives [2, 2, 2, 3, 3, 5]. Then you will group the repeats into powers, and factorize the largest safe integer in JavaScript, a sixteen-digit number. You need to know for and while loops, % and arrays. A prime is a whole number above 1 that only divides by 1 and itself.
The idea: divide out each factor completely
Start with the smallest prime, 2. While the number divides by 2, write down a 2 and divide. When it no longer divides, move on to 3, then 4, then 5, and so on.
For 360: divide by 2 three times (360, 180, 90, 45). 45 doesn't divide by 2, so try 3: twice (45, 15, 5). Then 4 doesn't divide 5, and 5 divides once, leaving 1. The list is 2, 2, 2, 3, 3, 5.
You might worry about 4, which isn't prime. It can never divide the number at that point, because every 2 was already divided out. The same goes for every other non-prime, so only primes ever land in the list.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
34 Prime factorisation
fairBreak a number into its prime factors with multiplicity, so 360 gives [2, 2, 2, 3, 3, 5]. Then present the same thing as exponents, and factorise Number.MAX_SAFE_INTEGER.
Stuck? Three hints, smallest first
- 1. Divide out each factor completely before moving on, so the number itself shrinks as you go.
- 2. The loop bound
d * d <= nis checked against the shrinking n, which is why this is fast on numbers with a large prime factor. - 3. Whatever is left above 1 when the loop ends is itself prime, so push it.
Step 1: divide out one factor
Start with just the 2s, to see the while loop in action:
let n = 360;
const twos = [];
while (n % 2 === 0) {
twos.push(2);
n /= 2;
}
console.log(twos, n); // [ 2, 2, 2 ] 45
n /= 2 is short for n = n / 2. The loop keeps going while 2 still fits, then stops with 45 left over.
Step 2: try every divisor
Wrap that in a for loop over d, and stop when d * d is bigger than n:
function factoriseTry(n) {
const out = [];
for (let d = 2; d * d <= n; d++) {
while (n % d === 0) {
out.push(d);
n /= d;
}
}
return out;
}
console.log(factoriseTry(360)); // [ 2, 2, 2, 3, 3 ]
console.log(factoriseTry(97)); // []
The 5 is missing from 360, and 97 has no factors at all. That is the wrong turn. After dividing out the 3s, n is 5, and 3 * 3 is already bigger than 5, so the loop stops before it reaches 5. For 97, the loop stops at 9 without finding anything.
Step 3: keep what is left
Whatever is left above 1 when the loop ends must itself be prime. If it had a smaller factor, the loop would have found it. So add it to the list:
function factorise(n) {
const out = [];
for (let d = 2; d * d <= n; d++) {
while (n % d === 0) {
out.push(d);
n /= d;
}
}
if (n > 1) out.push(n);
return out;
}
console.log(factorise(360)); // [ 2, 2, 2, 3, 3, 5 ]
console.log(factorise(97)); // [ 97 ]
console.log(factorise(1)); // []
That one line is what lets the loop stop early. 1 has no prime factors, so it gives an empty list.
Step 4: check it multiplies back
Multiplying the factors together should give the number back. reduce combines a list into one value, here by multiplying, starting from 1:
console.log(factorise(360).reduce((a, b) => a * b, 1)); // 360
Step 5: group into powers
360 is often written as 2³ × 3² × 5: each prime with how many times it appears, its exponent. Since the factors come out in order, equal ones sit next to each other. Walk the list and either add to the last group or start a new one:
const exponents = (n) => {
const groups = [];
for (const p of factorise(n)) {
const last = groups.at(-1);
if (last && last[0] === p) last[1]++;
else groups.push([p, 1]);
}
return groups;
};
console.log(exponents(360)); // [ [ 2, 3 ], [ 3, 2 ], [ 5, 1 ] ]
console.log(exponents(1000000)); // [ [ 2, 6 ], [ 5, 6 ] ]
groups.at(-1) reads the last group, or undefined when the list is empty. Each group is a pair: [prime, exponent].
Step 6: count divisors from the powers
There is a neat use for those exponents. Add 1 to each and multiply them together, and you get how many divisors the number has:
const divisorCount = (n) => exponents(n).reduce((acc, [, e]) => acc * (e + 1), 1);
console.log(divisorCount(360)); // 24
For 360 that is (3 + 1) × (2 + 1) × (1 + 1) = 24. The [, e] skips the first item of each pair and names the second one e.
Step 7: a huge number
console.log(factorise(600851475143)); // [ 71, 839, 1471, 6857 ]
console.log(factorise(Number.MAX_SAFE_INTEGER)); // [ 6361, 69431, 20394401 ]
Number.MAX_SAFE_INTEGER is 9007199254740991, the largest whole number JavaScript can store exactly. Its square root is about 95 million, which sounds like a lot of loop. But n shrinks as factors come out. After 6361 and 69431 are divided out, n is 20394401, whose square root is under 4600, and the loop condition follows n down. So it finishes quickly.
The full solution
The answer panel builds factorise, exponents and divisorCount, then factorizes 360, a million, 600851475143 and Number.MAX_SAFE_INTEGER. The checks underneath confirm each list, that the factors multiply back, and that 360 has 24 divisors. Press Run to see the output.
function factorise(n) {
const out = [];
for (let d = 2; d * d <= n; d++) {
while (n % d === 0) {
out.push(d);
n /= d; // n shrinks, so the bound tightens as we go
}
}
if (n > 1) out.push(n); // the last cofactor is prime
return out;
}
// The same information, one entry per distinct prime.
const exponents = (n) => {
const groups = [];
for (const p of factorise(n)) {
const last = groups.at(-1);
if (last && last[0] === p) last[1]++;
else groups.push([p, 1]);
}
return groups;
};
const divisorCount = (n) => exponents(n).reduce((acc, [, e]) => acc * (e + 1), 1);
console.log('360 :', factorise(360));
console.log('as powers :', exponents(360));
console.log('1000000 :', exponents(1000000));
console.log('MAX_SAFE :', factorise(Number.MAX_SAFE_INTEGER));
console.log('a big one :', factorise(600851475143));
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 2 cubed times 3 squared times 5', factorise(360), [2, 2, 2, 3, 3, 5]);
test('in exponent form', exponents(360), [[2, 3], [3, 2], [5, 1]]);
test('the factors multiply back to the number', factorise(360).reduce((a, b) => a * b, 1), 360);
test('1 has no prime factors, and a prime has exactly itself', [factorise(1), factorise(97)], [[], [97]]);
test('a million is 2 to the 6th times 5 to the 6th', exponents(1000000), [[2, 6], [5, 6]]);
test('360 therefore has 24 divisors, from (3+1)(2+1)(1+1)', divisorCount(360), 24);
test('600851475143 splits into four primes', factorise(600851475143), [71, 839, 1471, 6857]);
test('and MAX_SAFE_INTEGER into three', factorise(Number.MAX_SAFE_INTEGER), [6361, 69431, 20394401]);
test('and those three multiply back to it exactly', 6361 * 69431 * 20394401 === Number.MAX_SAFE_INTEGER, true);
The shrinking n is what makes this practical. Factorising 9007199254740991 looks like it should test divisors up to 94,906,265 — its root — but after 6361 and 69431 are divided out the remaining cofactor is 20394401, whose own root is under 4600, and the loop bound follows the value down. Only a number that is prime, or the product of two primes of similar size, actually costs the full sqrt(n).
The trailing if (n > 1) is not a tidy-up, it is the whole reason the loop can stop at the root. Once no divisor at or below sqrt(n) remains, what is left cannot be composite, so it is emitted directly rather than searched for.
Common mistakes
- Forgetting
if (n > 1) out.push(n). The last prime factor goes missing, and a prime returns an empty list. - Using
ifinstead ofwhile. Each factor is taken out only once, so 360 gives[2, 3, 4, 15], and neither 4 nor 15 is prime. - Checking only primes as divisors. You don't need a prime list. Non-prime divisors never match, because their factors were already divided out.
Try it yourself
- Factorize 2024 and write it in power form.
- Write
largestPrimeFactor(n)usingfactorise. What is it for 13195? - Use
divisorCountto find the smallest number with exactly 12 divisors.