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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!