Emmanuel Akinfulubi

JavaScriptMath

Find all divisors of a number in JavaScript

Intermediate · 4 min read

A divisor of a number is any whole number that divides it with nothing left over. The divisors of 12 are 1, 2, 3, 4, 6 and 12. You need them to lay out items in a neat grid (12 photos fit as 3 by 4 or 2 by 6), to split a bill evenly, and in many number puzzles.

In this tutorial you will write divisors(n), which lists every divisor in order from smallest to largest. The trick is to loop only as far as the square root of n, which turns a million steps into a thousand. Along the way you will discover which numbers have an odd number of divisors, and why. You need to know for loops, % and arrays.

Divisors come in pairs

Every time d divides n, so does n / d. For 36:

  • 1 pairs with 36
  • 2 pairs with 18
  • 3 pairs with 12
  • 4 pairs with 9
  • 6 pairs with 6

In each pair, the smaller number is at most the square root of n (here 6). So if you check d from 1 up to the root, each hit gives you two divisors at once: the small one, d, and its partner, n / d.

Here is the exercise. Try it yourself first if you like, then read on and we will build it together.

35 Every divisor, found in pairs

fair

List all divisors of a number in ascending order, looping only as far as the square root. Then find which numbers have an odd number of divisors, and say why.

Stuck? Three hints, smallest first
  1. 1. Each d that divides n hands you a second divisor for free: n / d.
  2. 2. Collect the small ones going up and the partners going down, then join them.
  3. 3. When d === n / d the pair is a single number, so push it once.

Step 1: the slow, obvious way

Check every number from 1 to n:

Step 1

const slowDivisors = (n) => {
  const out = [];
  for (let d = 1; d <= n; d++) if (n % d === 0) out.push(d);
  return out;
};
console.log(slowDivisors(36)); // [ 1, 2, 3, 4, 6, 9, 12, 18, 36 ]

It is correct and already sorted. But for a million it makes a million checks. Let's do better.

Step 2: loop to the root, collect both partners

Keep two lists: small for the divisors you find going up, and large for their partners. Stop when d * d passes n:

Step 2

function divisorsTry(n) {
  const small = [];
  const large = [];
  for (let d = 1; d * d <= n; d++) {
    if (n % d !== 0) continue;
    small.push(d);
    large.push(n / d);
  }
  return [...small, ...large.reverse()];
}
console.log(divisorsTry(36)); // [ 1, 2, 3, 4, 6, 6, 9, 12, 18, 36 ]

continue skips to the next d when it doesn't divide. The small divisors come out going up (1, 2, 3, 4, 6), and their partners come out going down (36, 18, 12, 9, 6). Reversing large makes it go up too, and [...small, ...large] joins the two lists into one.

But look: 6 appears twice. 36 is 6 times 6, so 6 is its own partner. That is the wrong turn.

Step 3: skip the duplicate root

Only push the partner when it is a different number:

Step 3

let iterations = 0;
function divisors(n) {
  if (!Number.isInteger(n) || n < 1) return [];
  const small = [];
  const large = [];
  for (let d = 1; d * d <= n; d++) {
    iterations++;
    if (n % d !== 0) continue;
    small.push(d);
    if (d !== n / d) large.push(n / d);
  }
  return [...small, ...large.reverse()];
}
console.log(divisors(36)); // [ 1, 2, 3, 4, 6, 9, 12, 18, 36 ]
console.log(divisors(1), divisors(13)); // [ 1 ] [ 1, 13 ]

The guard at the top returns an empty list for 0, negatives and fractions, which don't have a normal list of divisors. The iterations counter is only there to measure the work. A prime like 13 has exactly two divisors, 1 and itself.

Step 4: measure the saving

Step 4

iterations = 0;
const ofMillion = divisors(1000000);
console.log(ofMillion.length, iterations); // 49 1000

A million has 49 divisors, found in 1000 loop steps instead of a million. The square root of a million is 1000, so that is exactly how far the loop goes.

Step 5: which numbers have an odd count?

Divisors arrive in pairs, so you would expect an even count. Let's check 1 to 50:

Step 5

const oddCount = [];
for (let n = 1; n <= 50; n++) if (divisors(n).length % 2 === 1) oddCount.push(n);
console.log(oddCount); // [ 1, 4, 9, 16, 25, 36, 49 ]

They are all perfect squares: numbers like 49 that are a whole number times itself. In a perfect square, the root is its own partner, so it is counted once, and the count becomes odd. divisors(49) is [1, 7, 49]: three divisors, with 7 alone in the middle.

Step 6: the pairs multiply back

One more check. The first and last divisors multiply to n, and so do the second and second to last, and so on:

Step 6

const d36 = divisors(36);
console.log(d36[0] * d36[d36.length - 1], d36[1] * d36[d36.length - 2]); // 36 36

The full solution

The answer panel builds divisors with its counter, lists the divisors of 36, 1 and 13, finds the odd counts up to 50, and measures a million. The checks underneath confirm each list, that the output is already sorted, that 360 has 24 divisors, and that every pair for a million multiplies back to a million. Press Run to see the output.

The answer

let iterations = 0;

function divisors(n) {
  if (!Number.isInteger(n) || n < 1) return [];
  const small = [];
  const large = [];
  for (let d = 1; d * d <= n; d++) {
    iterations++;
    if (n % d !== 0) continue;
    small.push(d);
    if (d !== n / d) large.push(n / d);      // skip the partner of a square root
  }
  return [...small, ...large.reverse()];
}

const oddCount = [];
for (let n = 1; n <= 50; n++) if (divisors(n).length % 2 === 1) oddCount.push(n);

iterations = 0;
const ofMillion = divisors(1000000);
const workForMillion = iterations;

console.log('divisors of 36 :', divisors(36));
console.log('of 1 and of 13 :', divisors(1), divisors(13));
console.log('odd count up to 50:', oddCount);
console.log('1e6 has', ofMillion.length, 'divisors, found in', workForMillion, 'iterations');
console.log('sum for 36     :', divisors(36).reduce((a, b) => a + b, 0));

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.

9 checks

test('the divisors of 36, ascending', divisors(36), [1, 2, 3, 4, 6, 9, 12, 18, 36]);
test('1 divides only itself, and a prime has two divisors', [divisors(1), divisors(13)], [[1], [1, 13]]);
test('they come out sorted without a sort call', same(divisors(360), divisors(360).slice().sort((a, b) => a - b)), true);
test('360 has 24 of them, matching the exponent formula', divisors(360).length, 24);
test('only perfect squares have an odd number', oddCount, [1, 4, 9, 16, 25, 36, 49]);
test('because the root is its own partner', divisors(49), [1, 7, 49]);
test('a million has 49 divisors', ofMillion.length, 49);
test('found in 1000 iterations rather than a million', workForMillion, 1000);
test('and they pair up to the number itself', ofMillion.map((d, i) => d * ofMillion[ofMillion.length - 1 - i]).every((p) => p === 1000000), true);

The pairing is the idea, and it explains the odd-count result: divisors arrive two at a time, d with n / d, so the total is even — unless some d equals its own partner, which happens exactly when n is a perfect square. That is the cheapest perfect-square test there is, and exercise 47 uses the arithmetic version of it.

Watch the ordering. The small divisors come out ascending and their partners come out descending, so reversing the second list and concatenating gives sorted output for free. Pushing n / d as you go and sorting at the end works too, and costs a comparison sort for information you already had.

Common mistakes

  • Pushing the partner of a square root. 36 lists 6 twice. Check d !== n / d first.
  • Forgetting to reverse the partners. They come out largest first, so the joined list isn't in order.
  • Looping to n. It works but costs a million steps for a million. Stop at d * d <= n.

Try it yourself

  1. Find which number below 100 has the most divisors.
  2. Write gridShapes(n) that returns each pair [rows, columns] that fits n items exactly, such as [3, 4] for 12.
  3. Use the odd-count rule to write isPerfectSquare(n), then compare it with Number.isInteger(Math.sqrt(n)) for 1 to 100.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.