A number is a perfect number if the sum of its factors (excluding itself) is equal to the number.
Consider 63
Factors of 63, excluding itself, are: 1, 3, 7, 9, and 21
The sum of its factors are: 1 + 3 + 7 + 9 + 21 = 41
So, 63 is not a perfect number.
Consider 6
Factors of 6, excluding itself, are: 1, 2, and 3
The sum of its factors are: 1 + 2 + 3 = 6
So, 6 is a perfect number.\
Fun fact: 6 is the first perfect number in the set of
. Natural numbers natural numbers are whole even numbers
So, now we understand what a perfect number is and how to determine if a given number is a perfect number.
Let’s write a program capturing our approach.
Points to consider:
# Function to determine if given number is a perfect number # Input: Number (Range: [1, sys.maxsize]) # Output: A string detailing if given number is perfect or not def Perfect_Number(num): count=num-1 # count will be our iterator and facilitate our exit from the loop when needed (i.e. when its value = 0) sum=0 # our tracking variable sum while count!=0: if num%count == 0: # when num is divisible by count with 0 as remainder, it means count is a factor of num sum += count # adding factor to the sum count-=1 # decrementing count to explore the next number if sum == num: # Comparing sum with num, to get the verdict of perfect/non-perfect number print(num,"is a perfect number") else: print(num,"is not a perfect number") #Invoking the function #PerfectNumbers Perfect_Number(6) # Calling the function and giving 6 as input to check whether it is a perfect number or not Perfect_Number(28) #Not a perfect number Perfect_Number(63)
RELATED TAGS
CONTRIBUTOR
View all Courses