Skip to main content

How to check if a number is a perfect number in Python

How to check if a number is a perfect number in Python.

Here's a step-by-step tutorial on how to check if a number is a perfect number in Python:

Step 1: Understanding Perfect Numbers

  • A perfect number is a positive integer that is equal to the sum of its proper divisors.
  • Proper divisors of a number are all the positive divisors of that number, excluding the number itself.

Step 2: Writing a Function to Check for Perfect Numbers

  • Let's start by writing a function called is_perfect_number() that takes a number as input and returns True if it is a perfect number, and False otherwise.

Step 3: Calculating the Sum of Proper Divisors

  • To check if a number is perfect, we need to calculate the sum of its proper divisors.
  • Iterate through all the numbers from 1 to n (excluding n) and check if it divides n evenly.
  • If a number divides n evenly, add it to a running total.

Step 4: Implementing the Function

  • Let's implement the is_perfect_number() function using the steps mentioned above.
def is_perfect_number(n):
# ### Step 3: Calculating the Sum of Proper Divisors
sum_of_divisors = 0
for i in range(1, n):
if n % i == 0:
sum_of_divisors += i

# ### Step 4: Checking if the Number is Perfect
if sum_of_divisors == n:
return True
else:
return False

Step 5: Testing the Function

  • Now, let's test the is_perfect_number() function with some example inputs.
print(is_perfect_number(6))   # Output: True, as 6 = 1 + 2 + 3
print(is_perfect_number(28)) # Output: True, as 28 = 1 + 2 + 4 + 7 + 14
print(is_perfect_number(12)) # Output: False, as 12 != 1 + 2 + 3 + 4 + 6

Step 6: Further Optimization

  • The above implementation works correctly, but it can be optimized further.
  • We only need to iterate up to the square root of the number, as any factor beyond the square root will have a corresponding factor on the other side of the square root.
  • This optimization reduces the time complexity of the function from O(n) to O(sqrt(n)).
import math

def is_perfect_number(n):
sum_of_divisors = 0
for i in range(1, int(math.sqrt(n)) + 1):
if n % i == 0:
sum_of_divisors += i
if i != n // i: # Check if the divisor is not the same as the quotient
sum_of_divisors += n // i

if sum_of_divisors == n:
return True
else:
return False

Step 7: Testing the Optimized Function

  • Let's test the optimized version of the function with the same example inputs.
print(is_perfect_number(6))   # Output: True
print(is_perfect_number(28)) # Output: True
print(is_perfect_number(12)) # Output: False

That's it! You now have a detailed step-by-step tutorial on how to check if a number is a perfect number in Python.