Python Practice › Loop Programs › Program 38

Perfect numbers from 1 to n

MediumLoop Programs · 38 of 90

Write a Python program to print all perfect numbers from 1 to n.

Advertisement
Input
n = 10000
Output
[6, 28, 496, 8128]

Approach

  1. Find divisors in pairs up to √n to keep the loop fast.

Solution

Python
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])
Output
[6, 28, 496, 8128]

Line by line

Line 4

Only divisors up to √n are tried.

Lines 5-8

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.

More loop programs

← All 90 Loop Programs

Leave a Comment