Finding perfect numbers in JavaScript

A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly.

For example:

28 is a perfect number, because
28 = 1 + 2 + 4 + 7 + 14

We are required to write a JavaScript function that takes in a number, say n, and determines whether or not n is a perfect number.

How Perfect Numbers Work

To check if a number is perfect, we need to:

  • Find all divisors of the number (excluding the number itself)
  • Sum these divisors
  • Check if the sum equals the original number

Method 1: Basic Approach

This method checks all numbers from 1 to n-1 to find divisors:

function isPerfectBasic(num) {
    if (num 

true
true
false

Method 2: Optimized Approach

This optimized version only checks up to the square root of the number, making it much faster for large numbers:

function isPerfectOptimized(num) {
    if (num  num) return false;
        }
    }
    
    return sum === num;
}

console.log(isPerfectOptimized(6));
console.log(isPerfectOptimized(28));
console.log(isPerfectOptimized(496)); // Third perfect number
true
true
true

Finding Multiple Perfect Numbers

function findPerfectNumbers(limit) {
    const perfectNumbers = [];
    
    for (let i = 2; i 

Perfect numbers up to 1000:
[ 6, 28, 496 ]

Comparison

Method Time Complexity Best For
Basic Approach O(n) Small numbers, learning
Optimized Approach O(?n) Large numbers, production

Key Points

  • Perfect numbers are rare - only 51 are known to exist
  • The first few perfect numbers are: 6, 28, 496, 8128
  • All known perfect numbers are even (it's unknown if odd perfect numbers exist)
  • The optimized approach is significantly faster for large numbers

Conclusion

Perfect numbers can be efficiently found using the optimized square root approach. The basic method helps understand the concept, while the optimized version is practical for larger computations.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements