Emmanuel Akinfulubi

JavaScriptMath

Amicable numbers in JavaScript

Intermediate · 4 min read

Some numbers have a strange relationship with their own divisors. Add up the divisors of 6 (leaving out 6 itself) and you get 1 + 2 + 3 = 6, the number you started with. Some pairs of numbers do the same thing to each other: the divisors of 220 add up to 284, and the divisors of 284 add up to 220. Pairs like that are called amicable numbers, from the Latin word for friendly.

In this tutorial you will write one small function that adds up a number's divisors, and then use it to sort numbers into groups, find every perfect number below ten thousand and find the amicable pairs below 1300. It is a good exercise in writing a fast loop and in spotting the one edge case that quietly breaks it. You need to know for loops, % and arrow functions.

Proper divisors and the aliquot sum

A divisor of a number divides it exactly, with nothing left over. A proper divisor is any divisor except the number itself. The proper divisors of 12 are 1, 2, 3, 4 and 6.

Adding up the proper divisors gives a number called the aliquot sum. For 12 it is 16. Comparing that sum with the number puts every number in one of three groups:

  • Perfect: the sum equals the number (6, 28).
  • Abundant: the sum is bigger (12, because 16 > 12).
  • Deficient: the sum is smaller (8, whose proper divisors 1, 2, 4 add to 7).

Two different numbers are amicable when each one's aliquot sum is the other number.

Divisors come in pairs

You could test every number from 1 to n - 1, but there is a faster way. Divisors come in pairs: 12 is 2 * 6 and 3 * 4. If you find the small half of a pair, n / d gives you the big half for free. The small half is never bigger than the square root of n, so a loop that runs while d * d <= n finds every pair.

Here is the exercise. Have a go on your own first if you like, then read on and we will build it together.

101 Perfect numbers, and the pairs that point at each other

fair

Sum the proper divisors of a number and use that to classify it as perfect, abundant or deficient. Find every perfect number below ten thousand, then find the amicable pairs below 1300 — two numbers where each is the sum of the other's proper divisors.

Stuck? Three hints, smallest first
  1. 1. Proper divisors exclude the number itself, so start the total at 1 and skip the pair n / 1.
  2. 2. Loop d while d * d <= n and add both d and n / d, minding the case where they are equal.
  3. 3. Euclid: 2 ** (p - 1) * (2 ** p - 1) is perfect whenever the second factor is prime.

Step 1: add up the divisor pairs

Step 1

const aliquotSum = (n) => {
  if (n < 2) return 0;
  let total = 1;
  for (let d = 2; d * d <= n; d++) {
    if (n % d === 0) {
      total += d;
      const pair = n / d;
      if (pair !== d) total += pair;
    }
  }
  return total;
};
console.log([1, 6, 8, 12, 28, 97].map(aliquotSum)); // [ 0, 6, 7, 16, 28, 1 ]

Three details make this right:

  • total starts at 1, because 1 divides everything. The loop then starts at d = 2. If it started at 1, the pair n / 1 would add n itself, which is not a proper divisor.
  • 1 has no proper divisors, so the guard at the top returns 0 for it.
  • When d * d === n, the two halves of the pair are the same number. The line if (pair !== d) stops it being added twice.

A prime like 97 only divides by 1 and itself, so its aliquot sum is 1.

Step 2: the wrong turn, counting the square root twice

That last check is easy to leave out. Here is the same loop without it:

Step 2

const sloppySum = (n) => {
  let total = 1;
  for (let d = 2; d * d <= n; d++) {
    if (n % d === 0) total += d + n / d;
  }
  return total;
};
console.log(aliquotSum(16), sloppySum(16)); // 15 19

The proper divisors of 16 are 1, 2, 4 and 8, which add to 15. The sloppy version adds 4 twice, because 4 * 4 = 16. Every perfect square goes wrong in this way, so 16 would be called abundant when it is really deficient.

Step 3: classify a number

Step 3

const classify = (n) => {
  const s = aliquotSum(n);
  return s === n ? 'perfect' : s > n ? 'abundant' : 'deficient';
};
console.log([1, 6, 8, 12, 28, 97].map(classify)); // [ 'deficient', 'perfect', 'deficient', 'abundant', 'perfect', 'deficient' ]

Two ternaries, ? :, read like a short if-else chain: equal means perfect, bigger means abundant, anything else is deficient.

Step 4: find the perfect numbers

Step 4

const perfectUpTo = (limit) => {
  const out = [];
  for (let n = 2; n <= limit; n++) if (aliquotSum(n) === n) out.push(n);
  return out;
};
console.log(perfectUpTo(10000)); // [ 6, 28, 496, 8128 ]

Ten thousand numbers, and only four are perfect. They get rare very quickly.

Step 5: find the amicable pairs

For each a, work out b = aliquotSum(a), then check that b points back at a.

Step 5

const amicableUnder = (limit) => {
  const out = [];
  for (let a = 2; a < limit; a++) {
    const b = aliquotSum(a);
    if (b > a && b < limit && aliquotSum(b) === a) out.push([a, b]);
  }
  return out;
};
console.log(JSON.stringify(amicableUnder(1300))); // [[220,284],[1184,1210]]

The test b > a does three jobs at once. Each pair is reported once, as [220, 284], and never again as [284, 220]. It skips half of the second aliquotSum calls. And it leaves out a === b, which would be a perfect number, not a pair.

Step 6: name the rule in a function

Step 6

const isAmicablePair = (a, b) => a !== b && aliquotSum(a) === b && aliquotSum(b) === a;
console.log(isAmicablePair(220, 284), isAmicablePair(6, 6)); // true false

6 is its own aliquot sum, but a number can't be friends with itself. Writing a !== b into the function makes that rule visible to anyone who reads it.

Step 7: build perfect numbers directly

Over two thousand years ago, Euclid found a formula: 2 ** (p - 1) * (2 ** p - 1) is perfect whenever 2 ** p - 1 is prime. Later, Euler proved every even perfect number has this form.

Step 7

const euclidPerfect = (p) => 2 ** (p - 1) * (2 ** p - 1);
console.log([2, 3, 5, 7].map(euclidPerfect));          // [ 6, 28, 496, 8128 ]
console.log(euclidPerfect(13), aliquotSum(33550336)); // 33550336 33550336

p = 13 jumps straight to the fifth perfect number, 33550336, far past where the search loop would be quick. The aliquot sum confirms it.

The full solution

The answer panel has aliquotSum, classify, isAmicablePair, both searches and Euclid's formula, and prints every result above. Press Run to see the output.

The answer

// Sum of proper divisors. Starts at 1 and never adds n itself.
const aliquotSum = (n) => {
  if (n < 2) return 0;
  let total = 1;
  for (let d = 2; d * d <= n; d++) {
    if (n % d === 0) {
      total += d;
      const pair = n / d;
      if (pair !== d) total += pair;
    }
  }
  return total;
};

const classify = (n) => {
  const s = aliquotSum(n);
  return s === n ? 'perfect' : s > n ? 'abundant' : 'deficient';
};

const isAmicablePair = (a, b) => a !== b && aliquotSum(a) === b && aliquotSum(b) === a;

const perfectUpTo = (limit) => {
  const out = [];
  for (let n = 2; n <= limit; n++) if (aliquotSum(n) === n) out.push(n);
  return out;
};

const amicableUnder = (limit) => {
  const out = [];
  for (let a = 2; a < limit; a++) {
    const b = aliquotSum(a);
    if (b > a && b < limit && aliquotSum(b) === a) out.push([a, b]);
  }
  return out;
};

const euclidPerfect = (p) => 2 ** (p - 1) * (2 ** p - 1);

// Computed once: each of these walks a lot of divisors.
const perfects = perfectUpTo(10000);
const amicable = amicableUnder(1300);

console.log('aliquot sums   :', [1, 6, 8, 12, 28, 97].map(aliquotSum));
console.log('classified     :', [1, 6, 8, 12, 28, 97].map(classify));
console.log('perfect <= 1e4 :', perfects);
console.log('220 and 284    :', aliquotSum(220), aliquotSum(284));
console.log('amicable < 1300:', amicable);
console.log('Euclid-Euler   :', [2, 3, 5, 7, 13].map(euclidPerfect));
console.log('the fifth one  :', euclidPerfect(13), 'is perfect:', aliquotSum(33550336) === 33550336);

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('there are four perfect numbers below ten thousand', perfects, [6, 28, 496, 8128]);
test('each one is the sum of its own proper divisors, which is the definition', [6, 28, 496, 8128].map(aliquotSum), [6, 28, 496, 8128]);
test('12 is abundant, 8 is deficient, and a prime is the most deficient there is', [aliquotSum(12), aliquotSum(8), aliquotSum(97), [12, 8, 97].map(classify)], [16, 7, 1, ['abundant', 'deficient', 'deficient']]);
test('220 and 284 each sum to the other, which is what amicable means', [aliquotSum(220), aliquotSum(284)], [284, 220]);
test('and they are the smallest such pair, with 1184 and 1210 next', amicable, [[220, 284], [1184, 1210]]);
test('Euclid and Euler build perfect numbers from Mersenne primes', [2, 3, 5, 7].map(euclidPerfect), [6, 28, 496, 8128]);
test('p = 13 gives the fifth one at once, and it checks out', [euclidPerfect(13), aliquotSum(33550336) === 33550336], [33550336, true]);
test('a perfect number is not amicable with itself: the pair must be distinct', [isAmicablePair(6, 6), isAmicablePair(220, 284)], [false, true]);
test('1 has no proper divisors at all, so the guard has to return 0', [aliquotSum(1), classify(1)], [0, 'deficient']);

aliquotSum is the divisor loop from exercise 100 with two adjustments, and both are easy to get wrong. It starts the total at 1 and begins d at 2, because the pair (1, n) would otherwise contribute n itself. And when d * d === n the two halves of the pair are the same number, so adding both would double-count the square root — that is the if (pair !== d) line, and without it every perfect square is misclassified.

Searching to ten thousand finds exactly four perfect numbers: 6, 28, 496, 8128. That is not a coincidence of the range — they thin out savagely. Euclid proved that 2 ** (p - 1) * (2 ** p - 1) is perfect whenever 2 ** p - 1 is prime, and Euler proved every even perfect number has that form. So finding the next one means finding the next Mersenne prime, which is why only 52 are known. Whether an odd perfect number exists is still open after two thousand years.

Amicable pairs are the same idea applied to two numbers. The search has one detail worth noting: the b > a test both halves the work and stops each pair being reported twice, and it also excludes a === b, which would be a perfect number rather than an amicable pair. Naming that distinction in the predicate is cheaper than explaining it later.

Common mistakes

  • Starting the loop at d = 1. The pair n / 1 adds the number itself, so every number looks abundant.
  • Adding the square root twice. Without if (pair !== d), every perfect square gets the wrong sum.
  • Reporting each pair twice. Without b > a, you get [220, 284] and [284, 220], and perfect numbers sneak in as pairs with themselves.

Try it yourself

  1. Count how many numbers from 1 to 100 are abundant. (12 is the first one.)
  2. Extend amicableUnder to 10000 and see which new pairs turn up.
  3. Find the smallest odd abundant number. (Hint: it is just under a thousand.)

Keep practising

Newsletter

New writing, when it lands.

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