October 13, 2024

Python Program to Check for Perfect Numbers

A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding itself. For example, 6 is a perfect number because its proper divisors (1, 2, and 3) sum up to 6.

1. Example of Perfect Number Check

Here’s a Python program to determine if a given number is a perfect number:

def is_perfect_number(n):
    if n < 1:
        return False
    
    # Calculate the sum of proper divisors
    sum_of_divisors = 0
    for i in range(1, n):
        if n % i == 0:
            sum_of_divisors += i
    
    # Check if the sum of proper divisors is equal to the number
    return sum_of_divisors == n

# Example usage
number = 28
if is_perfect_number(number):
    print(f"{number} is a perfect number.")
else:
    print(f"{number} is not a perfect number.")
    

2. Explanation

  • Function Definition: The is_perfect_number function takes an integer n as input.
  • Checking Divisors: The function iterates through all numbers from 1 to n-1, adding up those that are divisors of n.
  • Sum Comparison: After summing the proper divisors, the function checks if this sum is equal to the original number n.
  • Example Usage: The program checks if the number 28 is perfect and prints the result.

3. Alternative Approach: Optimized Solution

The above method works well but is not the most efficient. Here’s a more optimized approach that only checks up to the square root of the number:

import math

def is_perfect_number_optimized(n):
    if n < 1:
        return False
    
    # Initialize the sum of proper divisors
    sum_of_divisors = 1
    
    # Check divisors from 2 to the square root of n
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            sum_of_divisors += i
            if i != n // i:
                sum_of_divisors += n // i
    
    # Check if the sum of proper divisors is equal to the number
    return sum_of_divisors == n

# Example usage
number = 28
if is_perfect_number_optimized(number):
    print(f"{number} is a perfect number.")
else:
    print(f"{number} is not a perfect number.")
    

4. Explanation of Optimized Solution

  • Improved Efficiency: This method only iterates up to the square root of the number, reducing the number of iterations needed.
  • Sum Calculation: For each divisor found, both the divisor and its complementary divisor are added to the sum.
  • Example Usage: Similar to the previous example, but with improved performance for larger numbers.

5. Conclusion

Determining whether a number is perfect can be done efficiently using these methods. The optimized solution is particularly useful for larger numbers, demonstrating the importance of algorithmic efficiency in numerical computations.