LearnFrenzy
Sign in Take a free test

Loops · Loops Coding Problems · Question 10

Perfect numbers up to 10,000 in JavaScript Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

A perfect number equals the sum of its proper divisors (6 = 1 + 2 + 3). Find all perfect numbers up to 10,000 efficiently.

Solution
main.js
function sumProperDivisors(n) {
  if (n === 1) return 0;
  let sum = 1;                              // 1 divides everything
  for (let d = 2; d * d <= n; d++) {
    if (n % d === 0) {
      sum += d;
      const pair = n / d;
      if (pair !== d) sum += pair;          // add the partner divisor once
    }
  }
  return sum;
}

const perfect = [];
for (let n = 2; n <= 10000; n++) {
  if (sumProperDivisors(n) === n) perfect.push(n);
}
console.log(perfect.join(", "));

Output Verified by running it on Node.js

6, 28, 496, 8128

Divisors come in pairs (d, n / d), so looping only to √n finds them all: about 100 steps for n = 10,000 instead of 10,000. The pair !== d check avoids counting a square root twice.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links