DSA problem
Perfect Number
Given an integer N, determine whether it is a perfect number. A perfect number is a positive integer equal to the sum of its proper divisors (all positive divisors excluding the number itself).
The first few perfect numbers are 6 (1 + 2 + 3), 28 (1 + 2 + 4 + 7 + 14), and 496. To check, sum all divisors of N except N itself and test whether the total equals N.
The naive approach scans every number from 1 to N-1 in O(N). The optimized approach scans only up to sqrt(N): for each divisor i, both i and N / i are divisors, so add both - being careful not to double-count when i == N / i (a perfect square) and not to add N itself. This brings the cost down to O(sqrt(N)). Perfect numbers are rare (only 51 are known) and are deeply connected to Mersenne primes; this problem reinforces the sqrt(N) optimization for divisor problems.
Examples
N = 28trueN = 12falseN = 6trueConstraints
- 1 <= N <= 10^9
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.