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

PythonProgramming

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
raja
Published on 20-Apr-2018 08:16:26
Advertisements