Check Perfect Number in Python

Beginner
⏱️ 10 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Number Theory

What You’ll Learn

A perfect number equals the sum of its proper divisors. For example, 6 is perfect because 1 + 2 + 3 = 6. This tutorial covers the definition, deficient/abundant neighbors, a live checker, worked Python examples, edge cases, and complexity.

Definition

s(n) = n

Proper divisor sum equals the number.

Proper Divisors

Exclude n

Positive divisors of n except n itself.

Scan to n//2

Simple loop

No proper divisor exceeds n // 2.

Classify

s(n) vs n

Deficient, perfect, or abundant.

Live Preview

Try 28 / 12

See divisors, sum, and verdict live.

Rare

6, 28, 496…

Perfect numbers are uncommon.

Introduction

A perfect number is a positive integer whose proper divisors add up to the number itself. Using s(n) for that sum: perfect means s(n) = n, deficient means s(n) < n, and abundant means s(n) > n.

Equivalently, if sigma(n) is the sum of all positive divisors, then perfect means sigma(n) = 2n. One is never perfect: by convention s(1) = 0.

Why it matters?

It is a classic divisor-sum interview problem that connects loops, modulo, and number-theory vocabulary.

Key Highlights

s(n) = n

Proper divisors sum to n.

Exclude n

Do not add the number itself.

1 Is Not

s(1) = 0 by convention.

Class Neighbors

Deficient / abundant too.

In short: sum divisors from 1 to n // 2; perfect when that sum equals n.

📝 Problem & Approach

Given a positive integer n, decide whether it is perfect by comparing the sum of its proper divisors with n.

python
# 6:  1 + 2 + 3 = 6        -> perfect
# 28: 1+2+4+7+14 = 28      -> perfect
# 10: 1 + 2 + 5 = 8        -> deficient
# 12: 1+2+3+4+6 = 16       -> abundant

Inputs & Outputs

ItemTypeDescription
n / numberintPositive integer to classify.
ReturnboolTrue when proper divisor sum equals n.
ClassificationtextDeficient, perfect, or abundant.

Minimal workflow

Pseudocode
function proper_divisor_sum(n):
    sum = 0
    for i from 1 to floor(n / 2):
        if n mod i == 0:
            sum = sum + i
    return sum

function is_perfect(n):
    if n < 2:
        return false
    return proper_divisor_sum(n) == n

Method comparison

MethodIdeaNotes
Scan to n // 2Add every proper divisorInterview default — clearest
Pair to sqrt(n)Add i and n // iFaster; careful with squares
sigma(n) = 2nAll-divisor sumEquivalent definition

⚡ Quick Reference

GoalPattern
Loop boundrange(1, n // 2 + 1)
Is divisor?if n % i == 0: total += i
Perfect?return total == n
Deficienttotal < n
Abundanttotal > n
Guard 1if n < 2: return False

📋 Perfect vs Deficient vs Abundant

Same divisor sum — different comparisons to n.

Perfect
s(n) = n

This page — e.g. 6, 28

Deficient
s(n) < n

Most numbers, including primes

Abundant
s(n) > n

e.g. 12 — related topic

Interview tip
exclude n

Proper divisors only

Context

When This Problem Shows Up

Reach for a proper-divisor sum whenever you need to classify perfection.

  1. Number-theory warm-ups

    Divisors, sums, and classification.

  2. Modulo practice

    Find all divisors with %.

  3. Bridge to abundant

    Same sum, different comparison.

  4. Range hunting

    Find the rare perfect values in a band.

  5. Not for huge scans

    Naive O(n) per check gets costly fast.

Key benefit: one clear loop that teaches proper divisors, classification, and the famous examples 6 and 28.

🔮 Live Preview

Enter a positive integer and inspect proper divisors, sum, and verdict.

Use whole numbers n >= 1.

Live result
Press “Run check” to see the result.

Examples Gallery

Three complete Python programs — check 28, list perfect numbers from 1 to 50, and classify deficient/perfect/abundant. Click View Output to reveal sample console results.

📚 Getting Started

A reusable helper and the classic example 28.

Example 1 — Check One Number

Test a fixed value (28) with a helper function.

python
def is_perfect_number(number: int) -> bool:
    total = 0
    for i in range(1, number // 2 + 1):
        if number % i == 0:
            total += i
    return total == number


number = 28
if is_perfect_number(number):
    print(f"{number} is a perfect number.")
else:
    print(f"{number} is not a perfect number.")

How It Works

The loop adds every proper divisor of 28: 1, 2, 4, 7, and 14. Their sum is 28, so the helper returns True.

⚡ Hunting in a Range

Reuse the helper to find the rare perfect values nearby.

Example 2 — Perfect Numbers in Range 1 to 50

Print all perfect numbers in a small interval.

python
def is_perfect_number(num: int) -> bool:
    total = 0
    for i in range(1, num // 2 + 1):
        if num % i == 0:
            total += i
    return total == num


print("Perfect Numbers in the range 1 to 50:")
for i in range(1, 51):
    if is_perfect_number(i):
        print(i, end=" ")

How It Works

Within 1..50 only 6 and 28 are perfect. That rarity is typical — the next known values jump much larger.

Example 3 — Classify Deficient / Perfect / Abundant

Reuse the same sum to label each sample number.

python
def proper_divisor_sum(n: int) -> int:
    if n < 2:
        return 0
    total = 0
    for i in range(1, n // 2 + 1):
        if n % i == 0:
            total += i
    return total


def classify(n: int) -> str:
    s = proper_divisor_sum(n)
    if s == n:
        return "perfect"
    if s < n:
        return "deficient"
    return "abundant"


for value in (6, 10, 12, 28, 1):
    print(f"{value}: {classify(value)} (s={proper_divisor_sum(value)})")

How It Works

One sum drives three labels. Perfect is the equality case; deficient and abundant are the strict inequalities.

🧠 How the Algorithm Decides

1

Start sum at 0

Accumulate proper divisors only.

Init
2

Scan 1 .. n//2

Add i whenever n % i == 0.

Loop
3

Compare to n

Equal means perfect; else deficient/abundant.

Rule
=

Return the verdict

Bool for perfect, or a class label.

🔎 Worked Walkthrough — 28

Trace the proper-divisor sum for n = 28.

i28 % iAdd?total
10Yes1
20Yes3
40Yes7
70Yes14
140Yes28

total 28 equals n — perfect.

Use Cases

Where perfect-number checks show up beyond the interview prompt.

1. Interview Classics

Divisor loops and equality checks.

Example: is_perfect(28).

2. Classification Sets

Label deficient / perfect / abundant.

Example: Example 3.

3. Range Searches

Find rare perfect values in a band.

Example: 6 and 28 in 1..50.

4. Teaching Divisors

Show what “proper” excludes.

Example: do not add n.

5. Bridge to Abundant

Same sum, greater-than test.

Example: related topic.

6. Next: Perfect Square

Another “perfect” naming cousin.

Example: related CTA.

Pro Tip: open with “proper divisors exclude n; perfect means sum equals n” before coding.

Advantages

Why the n//2 scan works well for beginners and interviews.

  1. 1. Easy to Trace

    Dry-run 6 or 28 on paper and watch the sum grow.

  2. 2. Clear Bound

    Stopping at n // 2 avoids adding n by mistake.

  3. 3. Extends to Classes

    Same sum powers deficient/abundant labels.

  4. 4. Speeds Up Later

    You can upgrade to sqrt pairing when needed.

Pro Tip: lead with the n//2 scan; mention sqrt pairing only as an optimization aside.

Usage Tips

Small habits that keep perfect-number solutions interview-ready.

  1. 1. Exclude n Itself

    Proper divisors stop at n // 2.

  2. 2. Guard Small n

    Treat n < 2 as not perfect.

  3. 3. Name the Classes

    Mention deficient and abundant alongside perfect.

  4. 4. Know 6 and 28

    Use them as quick sanity checks.

  5. 5. Optimize Later

    sqrt pairing is optional after the clear O(n) version.

Pro Tip: dry-run 6, 10, and 12 — if those three classes match, your sum logic is correct.

Common Pitfalls

Mistakes that commonly break perfect-number programs.

  1. 1. Including n in the Sum

    Adding the number itself doubles the definition.

    → Stop at n // 2.

  2. 2. Calling 1 Perfect

    Thinking 1 divides itself uniquely.

    → s(1) = 0; 1 is not perfect.

  3. 3. Confusing With Perfect Square

    Different “perfect” concept entirely.

    → This page is about divisor sums.

  4. 4. Off-by-One Bound

    Using range(1, n // 2) and missing n // 2.

    → Use range(1, n // 2 + 1).

  5. 5. Huge Naive Scans

    Checking every n up to millions with O(n) each.

    → Use smaller ranges or faster pairing.

Edge Cases

Handle these before claiming the check is complete.

n = 1

Not perfect

Proper divisor sum is 0, not 1.

Prime

Always deficient

Only proper divisor is 1, so sum < n.

Exclude n

Proper divisors only

Adding n itself breaks the definition.

6 / 28

Classic yes cases

Use them as sanity checks.

12

Abundant sample

s(12) = 16 > 12.

Odd?

Open problem

No odd perfect number is known.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • First four. 6, 28, 496, and 8128.
  • sigma form. Perfect ⇔ sigma(n) = 2n.
  • Even via Mersenne. Even perfect numbers relate to Mersenne primes.
  • Odd unknown. No odd perfect number has been found.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Prove 28

  • List proper divisors
  • Confirm sum = 28

2. Find 6 and 28

  • Reproduce Example 2
  • No other hits in 1..50

3. Classify 10 and 12

  • Deficient vs abundant
  • Match Example 3

4. Reject 1

  • Show s(1) = 0
  • Assert not perfect

Notes

  • Definition: perfect means proper divisor sum equals n.
  • Loop: check divisors from 1 to n // 2 with modulo.
  • Edge case: 1 is not perfect.
  • You can test divisors only up to sqrt(n) and add divisor pairs. Perfect numbers are rare, so broad brute-force scans are expensive.

Quick Takeaway: sum proper divisors to n // 2; perfect when that sum equals n.

⏱️ Time and Space Complexity

TaskTimeExtra space
Single check with n // 2 scanO(n)O(1)
Single check with sqrt(n) pairingO(sqrt(n))O(1)
Range scan 1..U (naive)O(U²)O(1)

For interview demos, the O(n) scan is fine; mention pairing when asked about speed.

Wrap Up

🎉 Conclusion

A perfect number equals the sum of its proper divisors. Loop from 1 to n // 2, add every divisor, and compare with n — remembering that 1 is not perfect and that perfect values are rare.

Practice the three examples above, then continue to checking perfect squares.

s(n) = n means perfect; exclude n from the divisor sum.

💡 Best Practices

✅ Do

  • Exclude n from the sum
  • Loop to n // 2 inclusive
  • Reject n < 2 early
  • Sanity-check with 6 and 28
  • Name deficient / abundant too

❌ Don’t

  • Add n into the divisor sum
  • Call 1 perfect
  • Confuse with perfect squares
  • Miss the +1 in range end
  • Brute-force huge ranges blindly

Key Takeaways

Knowledge Unlocked

Five things to remember about perfect numbers

Classify divisor sums the interview-friendly way.

5
Core concepts
/ 02

Bound

to n // 2

Loop
1 03

Edge

1 not perfect

Guard
<> 04

Classes

def / abun

Neighbors
O 05

Cost

O(n) naive

Analysis

❓ Frequently Asked Questions

A positive integer is perfect if the sum of its proper divisors equals the number itself.
No. Its proper divisor sum is treated as 0, not 1.
If proper divisor sum is less than n it is deficient, if greater than n it is abundant.
No proper divisor of n can be larger than n // 2.
Yes. It is mathematically equivalent to proper-divisor sum equals n.
No, they are very rare.
Positive divisors of n excluding n itself. For 6 they are 1, 2, and 3.
Scan only up to sqrt(n) and add divisor pairs, being careful not to double-count squares.
Yes. 1 + 2 + 4 + 7 + 14 = 28.

Did you Know? 🔊

The first four perfect numbers are 6, 28, 496, and 8128. Whether any odd perfect number exists is still unknown.

Continue to Perfect Square

Learn how to check whether a number is a perfect square in Python.

Perfect square tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful