Start with the simple loop so every proper divisor is obvious. Then use the √n method when you want the same answer faster.
Example 1 — Simple Loop
Sum every divisor from 1 to n - 1, then compare with n.
python
def is_perfect(n):
if n <= 1:
return False
total = 0
for i in range(1, n):
if n % i == 0:
total += i
return total == n
number = 28
if is_perfect(number):
print(f"{number} is perfect")
else:
print(f"{number} is not perfect")
Output
28 is perfect
How It Works
Return False for n <= 1 — 1 is not perfect.
Loop i from 1 to n - 1 so n itself is never added.
When n % i == 0, i is a proper divisor — add it to total.
After the loop, compare total == n.
For 28, the sum is 28, so the function returns True.
Example 2 — √n Pairing
Walk only up to √n and add both halves of each divisor pair, skipping n.
python
def is_perfect(n):
if n <= 1:
return False
total = 1 # 1 is always a proper divisor for n > 1
i = 2
while i * i <= n:
if n % i == 0:
total += i
pair = n // i
if pair != i and pair != n:
total += pair
i += 1
return total == n
print(is_perfect(6)) # True
print(is_perfect(28)) # True
print(is_perfect(12)) # False
print(is_perfect(10)) # False
Output
True
True
False
False
How It Works
Seed total = 1 because every n > 1 is divisible by 1.
Loop while i * i <= n so you only scan up to √n.
When i divides n, add i and usually its pair n // i.
Skip the pair when it equals i (perfect square) or equals n (would not be proper).
Same answers as Example 1, in O(√n) time.
Edge Cases & Pitfalls
Check these before calling the solution done.
1
Not perfect
Treat n <= 1 as false before summing.
Include n?
Exclude itself
Proper divisors never include n. Adding it breaks the definition.
√n pair
Do not double-count
When i == n // i, add the square-root divisor once.
Negatives
Positive only
Perfect numbers are defined for positive integers.
Analysis
Time and Space Complexity
Program
Time
Extra space
Simple loop
O(n)
O(1)
√n pairing
O(√n)
O(1)
Both answers are the same. Prefer √n when n grows beyond small demo values.
Remember
Key Takeaways
Definition: sum of proper divisors equals n.
Exclude: never add n itself to the sum.
Family: deficient / perfect / abundant by comparing sum and n.
Test set: 6 → yes; 28 → yes; 12 → no; 10 → no.
One line: add every positive divisor of n except n, then check equality.
Frequently Asked Questions
A positive integer equal to the sum of its proper divisors (positive divisors excluding itself). Example: 6 = 1 + 2 + 3.
No. The sum of proper divisors of 1 is usually taken as 0, which is not equal to 1.
Compare the proper-divisor sum s with n: s < n deficient, s == n perfect, s > n abundant.
6, 28, 496, and 8128 are the first four perfect numbers.
A loop to n-1 is O(n). Pairing divisors up to √n is O(√n). Both use O(1) extra space.