How to identify and print all the perfect numbers in some closed interval [ 2, n ] using Python?


A perfect number is a positive integer that is equal to the sum of its proper divisors. The smallest perfect number is 6, which is the sum of 1, 2, and 3.

You can find perfect numbers within a given range by testing each number for the given condition in the given range. 

example

def print_perfect_nums(start, end):
   for i in range(start, end + 1):
   sum1 = 0
   for x in range(1, i):
      # Check if a divisor, if it is, add to sum
      if(i % x == 0):
         sum1 = sum1 + x
         if (sum1 == i):
            print(i)
print_perfect_nums(1, 300)

Output

This will give the output

6
28

Updated on: 05-Mar-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements