ccompiler.inOnline C Compiler & Docs
C Example Code2026-03-252 min read

Check if an integer is a perfect number in C by summing its proper divisors. Optimized O(sqrt(n)) algorithm with working source code.

What is a Perfect Number?

A perfect number is a positive integer that is equal to the sum of its positive proper divisors (excluding the number itself).

Classic Examples:

  • 6: Divisors are $1, 2, 3 → 1 + 2 + 3 = 6$ (Perfect)
  • 28: Divisors are $1, 2, 4, 7, 14 → 1 + 2 + 4 + 7 + 14 = 28$ (Perfect)
  • 496: Divisors sum to $496$ (Perfect)

Optimized C Implementation (O(√n))

Instead of looping up to n, we loop up to $√n$ and add complementary divisor pairs:

c (ISO Standard)
#include <stdio.h>
#include <stdbool.h>
#include <math.h>

bool isPerfectNumber(int n) {
    if (n <= 1) return false;

    int sum = 1; /* 1 is always a proper divisor */
    int root = (int)sqrt(n);

    for (int i = 2; i <= root; i++) {
        if (n % i == 0) {
            sum += i;
            if (i != n / i) {
                sum += n / i; /* Add complementary pair */
            }
        }
    }

    return sum == n;
}

int main() {
    int testCases[] = {6, 28, 496, 8128, 12, 100};
    int count = sizeof(testCases) / sizeof(testCases[0]);

    printf("Testing Perfect Numbers in C:\n\n");
    for (int i = 0; i < count; i++) {
        int val = testCases[i];
        if (isPerfectNumber(val)) {
            printf("  %d is a PERFECT number.\n", val);
        } else {
            printf("  %d is NOT a perfect number.\n", val);
        }
    }

    return 0;
}

Sample Output

text (ISO Standard)
Testing Perfect Numbers in C:

  6 is a PERFECT number.
  28 is a PERFECT number.
  496 is a PERFECT number.
  8128 is a PERFECT number.
  12 is NOT a perfect number.
  100 is NOT a perfect number.

Complexity Analysis

  • Time Complexity: O(√n) optimized divisor search.
  • Space Complexity: O(1) constant memory.

Related C Examples & Tutorials