Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
community creator

How to determine if a number is a perfect number in python

Sai Venkatesh Raju

A number is a perfect number if the sum of its factors (excluding itself) is equal to the number.

Example

  1. 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.

  2. 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 numbersnatural 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:

  1. Boundaries:
    We need to compute the sum of all factors (excluding itself) of given number – this means that iterationfor/while/do…while is involved. The number itself must not be part of the sum; so, let’s start at 11 and go down to 11 as that is the least possible factor that a non-negative integer could have.
  2. 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.
  3. Tracking:
    We will keep track of the sumthe sum is set to 0 before the loop starts 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.
# 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

python
community creator
RELATED COURSES

View all Courses

Keep Exploring