Perfect Number

Easy

Topics
Math

A perfect number equals the sum of its positive divisors excluding itself. Given an integer n, return true if it is a perfect number.

Example 1

divisors124714
Cells are the proper divisors of 28 (so 28 itself is excluded). They sum to 28, which equals n, so the answer is true. Divisors come in pairs around √n, so the scan only runs to √28.
Cells are the proper divisors, found in pairs up to the square root.
Input:  n = 28
Output: true
Explanation: 28 = 1 + 2 + 4 + 7 + 14.

Example 2

divisors1
They sum to 1, which is not n, so the answer is false.
Input:  n = 7
Output: false

Constraints

  • 1 <= n <= 10^8
Editorial — intuition, approach, complexity and pitfalls

Intuition

A perfect number equals the sum of its proper divisors. Testing every candidate from 1 to n-1 is O(n), which at n up to 10^8 is too slow.

The saving is that divisors come in pairs: if i divides n then so does n / i, and one of the pair is always at most sqrt(n). So iterate i only to sqrt(n) and add both members of each pair, which reduces the work to O(sqrt n) — 10^4 iterations at the limit.

Two details. Start the sum at 1 and the loop at 2, because 1 is always a proper divisor and we must not add n itself. And when n is a perfect square, i and n / i coincide, so adding both would double-count — hence the i != n // i check.

Approach

  1. Reject n <= 1.
  2. Sum 1 plus each divisor pair found for i from 2 while i * i <= n, skipping the duplicate on a perfect square.
  3. Compare the sum to n.

Dry Run

n = 28

total starts at 1
i=2   28 % 2 == 0  -> add 2 and 14          total 17
i=3   no
i=4   28 % 4 == 0  -> add 4 and 7           total 28
i=5   25 <= 28, no
i=6   36 > 28, loop ends

28 == 28 -> true

n = 16 (perfect square)
total 1; i=2 adds 2 and 8 -> 11; i=4 has 4 == 16//4,
so add 4 only once -> 15;  15 != 16 -> false

Complexity

  • Time — O(sqrt n): about 10^4 iterations at the upper bound, against O(n) for the naive scan.
  • Space — O(1).

Common Pitfalls

  • Double-counting the square root on a perfect square. 16 would otherwise sum to 19.
  • Including n itself among the divisors, which makes every number look non-perfect — or starting the loop at 1, which adds n via the pair.
  • Writing the loop bound as i <= sqrt(n) using floating point. i * i <= n is exact and avoids the boundary case.
  • Forgetting n = 1, whose only proper divisor sum is 0, so it is not perfect.

Full Solution — all languages

class Solution:
    def checkPerfectNumber(self, n):
        if n <= 1:
            return False
        total, i = 1, 2
        while i * i <= n:
            if n % i == 0:
                total += i
                if i != n // i:
                    total += n // i
            i += 1
        return total == n
SensAI
Beta
Tap the mic to stop voice mode