PythonMastery

Perfect number program in Python

Check whether a number is perfect, like 28 = 1 + 2 + 4 + 7 + 14, and find all perfect numbers below 10,000 with a faster divisor loop.

A perfect number is equal to the sum of its proper divisors (all its divisors except the number itself). The divisors of 28 are 1, 2, 4, 7 and 14, and 1 + 2 + 4 + 7 + 14 = 28.

The program

python
n = int(input("Enter a number: "))

divisors = [i for i in range(1, n // 2 + 1) if n % i == 0]
total = sum(divisors)

print("Proper divisors:", divisors)
print("Sum:", total)

if n > 1 and total == n:
    print(f"{n} is a perfect number")
else:
    print(f"{n} is not a perfect number")

Typed in this example: 28. Press Run to type your own.

output
Enter a number: 28
Proper divisors: [1, 2, 4, 7, 14]
Sum: 28
28 is a perfect number

How it works

A faster check for many numbers

Divisors come in pairs: if i divides n, then n // i does too (for 28: 2 and 14, 4 and 7). So the loop only needs to go up to the square root of n:

python
import math


def is_perfect(n):
    if n < 2:
        return False
    total = 1
    for i in range(2, math.isqrt(n) + 1):
        if n % i == 0:
            total += i
            if n // i != i:
                total += n // i
    return total == n


print(*[n for n in range(1, 10000) if is_perfect(n)])
output
6 28 496 8128

Learn the idea: Loops: for, while, and the Pythonic Patterns, Functions & Scoping