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
n % i == 0is true whenidividesnwith no remainder.- No proper divisor can be bigger than half of n, so the loop stops at
n // 2. n > 1excludes 1 (its only proper divisor list is empty, with sum 0) and also 0 and negative numbers, which are not perfect.
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
totalstarts at 1, because 1 divides every number.if n // i != istops a square root from being counted twice (for 16, the divisor 4 pairs with itself).- For 8128 the loop runs about 90 times instead of about 4,000. Perfect numbers are rare: the fifth one is 33,550,336.