If the sum of all factors of a number ( exclusive itself ) is equal to the number, then the number is said to be perfect. E.g 6

Perfect number in Python

Steps to Check Perfect Number in Python

  1. Take a number as input.
  2. Calculate the sum of all its factors(excluding itself)
  3. Check if the sum of its factors is equal to the input number.
  4. If YES then its a perfect number, else it is not.

Check Whether a number is Perfect in Python

num = int(input("Enter a number \n"))
sumOfFactors = 0

#Calculating the sum of Factors
for i in range(1,num):
    if num%i == 0:
        sumOfFactors += i;

if sumOfFactors == num:
    print("Perfect Number")
else:
    print("Not a Perfect Number")

Output

Perfect number in Python

Find all Perfect Numbers in the Range

def isPerfect(num):
  sumOfFactors = 0

  #Calculating the sum of Factors
  for i in range(1,num):
      if num%i == 0:
          sumOfFactors += i

  return sumOfFactors == num
     

lower = int(input("Enter lower interval \n"))
upper = int(input("Enter upper interval \n"))

print("Perfect Numbers between {x} and {y}:".format(x=lower,y=upper))
for i in range(lower,upper):
   if isPerfect(i):
     print(i)

Output

Enter lower interval
1
Enter upper interval
100
Perfect Numbers between 1 and 100:
6
28

That’s all we need to write in order to check a perfect number in python. If you have any doubt’s then comment below.

Leave a Reply

two × three =