Write a Python function to check if a number is a perfect number.
Posted by FrankMl
Last Updated: August 28, 2024
Checking for Perfect Numbers in Python
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 divisors (1, 2, and 3) sum up to 6 (1 + 2 + 3 = 6). To determine whether a given number is a perfect number, you can implement a Python function that checks this condition. Below is a function that accomplishes this task:
def is_perfect_number(n):
    """
    Check if a number is a perfect number.

    A perfect number is equal to the sum of its proper divisors (excluding itself).

    Parameters:
    n (int): The number to check.

    Returns:
    bool: True if n is a perfect number, False otherwise.
    """
    if n < 1:
        return False  # Perfect numbers are positive integers

    sum_of_divisors = 0
    
    # Loop to find all divisors of n
    for i in range(1, n // 2 + 1):  # Check up to n/2 for proper divisors
        if n % i == 0:  # If i is a divisor
            sum_of_divisors += i
            
    return sum_of_divisors == n  # Check if the sum of divisors equals 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.")
How the Function Works
1. Input Check: The function first checks if the input number n is a positive integer. If not, it immediately returns False, since perfect numbers must be positive. 2. Finding Divisors: The function initializes a variable sum_of_divisors to store the sum of the proper divisors. A loop iterates from 1 to n // 2, checking each integer to see if it is a divisor of n. If it is, that value is added to sum_of_divisors. 3. Final Check: The function compares sum_of_divisors with the original number n. If they are equal, it returns True, indicating that n is a perfect number; otherwise, it returns False.
Example Cases
- 6: Proper divisors are 1, 2, 3. Sum = 1 + 2 + 3 = 6 (Perfect) - 28: Proper divisors are 1, 2, 4, 7, 14. Sum = 1 + 2 + 4 + 7 + 14 = 28 (Perfect) - 12: Proper divisors are 1, 2, 3, 4, 6. Sum = 1 + 2 + 3 + 4 + 6 = 16 (Not Perfect) This function serves as an effective tool for checking perfect numbers in Python and can be easily modified or expanded as necessary.
Related Content