Perfect numbers from 1 to n
Write a Python program to print all perfect numbers from 1 to n.
n = 10000
[6, 28, 496, 8128]
Approach
- Find divisors in pairs up to √n to keep the loop fast.
Solution
def divisor_sum(n): total = 1 d = 2 while d * d <= n: if n % d == 0: total += d if d != n // d: total += n // d d += 1 return total print([n for n in range(2, 10001) if divisor_sum(n) == n])[6, 28, 496, 8128]
Line by line
Only divisors up to √n are tried.
Each divisor d comes with a partner n // d; both are added, except when they are the same number.
Learn the concept
New to this topic? Read the lesson, then come back.