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
Steps to Check Perfect Number in Python
- Take a number as input.
- Calculate the sum of all its factors(excluding itself)
- Check if the sum of its factors is equal to the input number.
- If YES then its a perfect number, else it is not.
Check Whether a number is Perfect in Python
1 2 3 4 5 6 7 8 9 10 11 12 | 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
Find all Perfect Numbers in the Range
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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
1 2 3 4 5 6 7 | 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.