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.
C
#include <stdio.h>
int is_perfect(int n)
{
int i, sum = 0;
if (n <= 1)
return 0;
for (i = 1; i < n; i++)
{
if (n % i == 0)
sum += i;
}
return sum == n;
}
int main(void)
{
int number = 28;
if (is_perfect(number))
printf("%d is perfect\n", number);
else
printf("%d is not perfect\n", number);
return 0;
}
Output
28 is perfect
How It Works
Return 0 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 sum.
After the loop, compare sum == n.
For 28, the sum is 28, so the function returns 1 (true).
Example 2 — √n Pairing
Walk only up to √n and add both halves of each divisor pair, skipping n.
C
#include <stdio.h>
int is_perfect(int n)
{
int i, pair, sum;
if (n <= 1)
return 0;
sum = 1; /* 1 is always a proper divisor for n > 1 */
for (i = 2; i * i <= n; i++)
{
if (n % i == 0)
{
sum += i;
pair = n / i;
if (pair != i && pair != n)
sum += pair;
}
}
return sum == n;
}
int main(void)
{
printf("%s\n", is_perfect(6) ? "1" : "0");
printf("%s\n", is_perfect(28) ? "1" : "0");
printf("%s\n", is_perfect(12) ? "1" : "0");
printf("%s\n", is_perfect(10) ? "1" : "0");
return 0;
}
Output
1
1
0
0
How It Works
Seed sum = 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.