Check if a number is a perfect number in JavaScript
Intermediate · 4 min read
A perfect number is a number that equals the sum of its proper divisors. 6 is the first: its divisors, apart from 6 itself, are 1, 2 and 3, and 1 + 2 + 3 = 6. The next ones are 28, 496 and 8128, and then they get very rare. Perfect numbers have been studied for over two thousand years, and checking for them is a great exercise in loops and divisors.
In this tutorial you will write isPerfect(n). You will start with a simple version that tests every number, then speed it up with the square-root trick, and fix the one bug that trick likes to introduce. You need to know for loops and the % operator.
Divisors and proper divisors
A divisor of n is a number that divides it with nothing left over. % gives the remainder, so d is a divisor when n % d === 0. A proper divisor is any divisor except n itself:
console.log(28 % 7); // 0, so 7 divides 28
console.log(28 % 5); // 3, so 5 does not
The proper divisors of 28 are 1, 2, 4, 7 and 14, which add up to 28. So 28 is perfect.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
12 Is the number perfect?
fairA perfect number equals the sum of its proper divisors. 6 is the first, because 1 + 2 + 3 = 6. Then 28, 496 and 8128.
Stuck? Three hints, smallest first
- 1. Proper divisors exclude the number itself.
- 2. You only need to test up to the square root: each divisor found gives its partner.
- 3. When
i * i === n, addionce, not twice.
Step 1: the direct version
Test every number from 1 up to n - 1, and add up the ones that divide n:
function isPerfectSimple(n) {
if (!Number.isInteger(n) || n < 2) return false;
let sum = 0;
for (let i = 1; i < n; i++) if (n % i === 0) sum += i;
return sum === n;
}
console.log(isPerfectSimple(6)); // true
console.log(isPerfectSimple(28)); // true
console.log(isPerfectSimple(12)); // false
The first line rejects anything that isn't a whole number of at least 2. 1 has no proper divisors, so it can't be perfect. The loop stops at i < n, so n itself is never added.
This is correct, but for 8128 it tries over eight thousand numbers.
Step 2: divisors come in pairs
Every divisor has a partner. For 28: 1 × 28, 2 × 14 and 4 × 7. When you find i, you also get n / i for free. And one of each pair is always at most the square root of n, so you only need to loop while i * i <= n. For 28, that means trying 2 to 5 instead of 1 to 27.
Two details keep n itself out of the sum:
- The pair
1 × 28includes 28, which is not a proper divisor. So start the sum at1and the loop at2. - Every other pair is added as both numbers.
Step 3: the square-root version, with a bug
Here is a first try at the fast version. To see what it is doing, it returns the sum of the divisors instead of true or false:
function divisorSumBuggy(n) {
let sum = 1;
for (let i = 2; i * i <= n; i++) {
if (n % i === 0) sum += i + n / i;
}
return sum;
}
console.log(divisorSumBuggy(28)); // 28
console.log(divisorSumBuggy(16)); // 19
28 is right. 16 is not. Look at the pairs for 16: 2 × 8 and 4 × 4. At i = 4, the partner 16 / 4 is also 4, so the code adds 4 twice. The proper divisors of 16 are 1, 2, 4 and 8, which add up to 15, not 19.
A perfect check would still say "no" for 16, because 19 isn't 16 either. But the total is wrong, and anything built on it breaks. A number is called abundant when its divisors add up to more than itself. With this sum, 16 would wrongly count as abundant, since 19 is more than 16.
Step 4: add the middle divisor once
When i is exactly the square root, its partner is itself. Add the partner only when it is different:
function isPerfect(n) {
if (!Number.isInteger(n) || n < 2) return false;
let sum = 1;
for (let i = 2; i * i <= n; i++) {
if (n % i !== 0) continue;
sum += i;
const partner = n / i;
if (partner !== i) sum += partner;
}
return sum === n;
}
console.log(isPerfect(496)); // true
console.log(isPerfect(8128)); // true
console.log(isPerfect(16)); // false
continue skips the rest of this turn of the loop and moves to the next i. It keeps the main path of the loop flat instead of nesting everything inside an if.
Step 5: check it against the definition
A good habit with a fast version is to compare it against the slow, obvious one. The answer lists the proper divisors directly, so you can see the sum:
const properDivisors = (n) => Array.from({ length: n - 1 }, (_, i) => i + 1).filter((d) => n % d === 0);
console.log(properDivisors(28).join(' + ')); // '1 + 2 + 4 + 7 + 14'
const found = [];
for (let n = 2; n <= 10000; n++) if (isPerfect(n)) found.push(n);
console.log(found); // [ 6, 28, 496, 8128 ]
Array.from({ length: n - 1 }, (_, i) => i + 1) makes the numbers 1 to n - 1, and filter keeps the divisors. Up to 10,000, only four perfect numbers exist, and the fast version finds exactly those.
The full solution
The panel has isPerfectSimple, the fixed isPerfect and properDivisors. It prints the four perfect numbers up to 10,000, the divisors of 6, 28 and 496, and the divisor sum for 16. Press Run to see them.
// The direct version: test every number below n.
function isPerfectSimple(n) {
if (!Number.isInteger(n) || n < 2) return false;
let sum = 0;
for (let i = 1; i < n; i++) if (n % i === 0) sum += i;
return sum === n;
}
/* Faster: divisors come in pairs, so stop at the square root and add both.
Two details: start the sum at 1 and the loop at 2, so n itself is excluded;
and when i is exactly the square root, add it once. */
function isPerfect(n) {
if (!Number.isInteger(n) || n < 2) return false;
let sum = 1; // 1 is always a proper divisor
for (let i = 2; i * i <= n; i++) {
if (n % i !== 0) continue;
sum += i;
const partner = n / i;
if (partner !== i) sum += partner; // not twice for a perfect square
}
return sum === n;
}
const properDivisors = (n) => Array.from({ length: n - 1 }, (_, i) => i + 1).filter((d) => n % d === 0);
const found = [];
for (let n = 2; n <= 10000; n++) if (isPerfect(n)) found.push(n);
console.log('perfect numbers up to 10000:', found);
console.log('6 =', properDivisors(6).join(' + '));
console.log('28 =', properDivisors(28).join(' + '));
console.log('496 divisors:', properDivisors(496).join(', '));
console.log('--- the square-root detail ---');
console.log('divisors of 16 found by pairing: 1, 2, 8, 4 — and 4 only once, since 4 x 4 = 16');
console.log('sum for 16 is', properDivisors(16).reduce((a, b) => a + b, 0), 'so 16 is not perfect');
Output
15 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 15 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('6 is perfect', isPerfect(6), true);
test('and its divisors add up', properDivisors(6).reduce((a, b) => a + b, 0), 6);
test('28 is perfect', isPerfect(28), true);
test('496 is perfect', isPerfect(496), true);
test('8128 is perfect', isPerfect(8128), true);
test('those four are the only ones up to 10000', found, [6, 28, 496, 8128]);
test('1 is not perfect', isPerfect(1), false);
test('0 is not', isPerfect(0), false);
test('a negative number is not', isPerfect(-6), false);
test('a decimal is not', isPerfect(6.5), false);
test('12 is not, its divisors sum to 16', isPerfect(12), false);
test('and 16 is not, being a perfect square', isPerfect(16), false);
test('which is where the double-counting bug would show', properDivisors(16).reduce((a, b) => a + b, 0), 15);
test('the simple version agrees for 1 to 500', Array.from({ length: 500 }, (_, i) => isPerfect(i + 1) === isPerfectSimple(i + 1)).every(Boolean), true);
test('every perfect number found is confirmed by listing its divisors', found.every((n) => properDivisors(n).reduce((a, b) => a + b, 0) === n), true);
Pairing divisors is the same square-root idea as the prime check, with one extra wrinkle: when i * i === n, the divisor and its partner are the same number and adding both counts it twice. For 16 that turns a sum of 15 into 19 and reports 16 as perfect. The assertion checking properDivisors(16) sums to 15 is what pins that down, and 16 is in the test set for exactly that reason.
Starting sum at 1 and the loop at 2 is how n itself stays out of the total — the divisor pair of 1 is n, which is not a proper divisor.
All four perfect numbers under 10,000 are found and each is independently confirmed by listing its divisors, so the fast version is checked against a definition rather than against my expectations.
Common mistakes
- Adding
nto its own sum. Then every number's total is too big. Start at 1 and loop from 2, or stop the simple loop ati < n. - Adding the square root twice. For a perfect square like 16 or 36, the middle divisor pairs with itself. Add it once.
- Calling 1 perfect. It has no proper divisors, so the sum is 0. Reject
n < 2first.
Try it yourself
- Write
isAbundant(n), which istruewhen the proper divisors add up to more thann. 12 is abundant, because 1 + 2 + 3 + 4 + 6 = 16. - Add a counter to both
isPerfectSimpleandisPerfect, and compare how many times each loop runs for 8128. - Write
divisorSum(n)that returns the sum, and use it to build bothisPerfectandisAbundant.