How to determine if a number is a perfect number in python
A number is a perfect number if the sum of its factors (excluding itself) is equal to the number.
Example
-
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:
- Boundaries:
We need to compute the sum of all factors (excluding itself) of given number – this means that is involved. The number itself must not be part of the sum; so, let’s start at and go down to as that is the least possible factor that a non-negative integer could have.iteration for/while/do…while - Differentiate between wanted and unwanted entities:
Here, the wanted entities are the factors of the given number. We can utilize the mod operator to differentiate between factors and non-factors. - Tracking:
We will keep track of the of factors. Once the loop is complete, we will compare the sum with the number to figure out whether our number is perfect or non-perfect.sum the sum is set to 0 before the loop starts
# 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 notdef 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 sumwhile count!=0:if num%count == 0: # when num is divisible by count with 0 as remainder, it means count is a factor of numsum += count # adding factor to the sumcount-=1 # decrementing count to explore the next numberif sum == num: # Comparing sum with num, to get the verdict of perfect/non-perfect numberprint(num,"is a perfect number")else:print(num,"is not a perfect number")#Invoking the function#PerfectNumbersPerfect_Number(6) # Calling the function and giving 6 as input to check whether it is a perfect number or notPerfect_Number(28)#Not a perfect numberPerfect_Number(63)