Cover Image for Perfect Number in Python
214 views

Perfect Number in Python

The number theory, a perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). A proper divisor of a number is a positive integer that evenly divides the number without leaving a remainder.

To check if a number is a perfect number in Python, you can follow these steps:

  1. Find the proper divisors of the number.
  2. Sum the proper divisors.
  3. Compare the sum to the original number.

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

def is_perfect_number(num):
    if num <= 0:
        return False

    # Find the proper divisors and initialize the sum
    divisors = []
    for i in range(1, num):
        if num % i == 0:
            divisors.append(i)

    divisor_sum = sum(divisors)

    # Check if the sum of divisors equals the original number
    return divisor_sum == num

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

In this code:

  • We define the is_perfect_number function, which takes an integer num as input.
  • We first check if num is less than or equal to 0. Perfect numbers are defined for positive integers, so negative numbers and zero are excluded.
  • We iterate through all numbers from 1 to num - 1 to find the proper divisors of num. If a number i evenly divides num, we add it to the divisors list.
  • We calculate the sum of the proper divisors.
  • Finally, we check if the sum of divisors is equal to the original number. If they are equal, we return True, indicating that num is a perfect number; otherwise, we return False.

You can use this program to check whether a given positive integer is a perfect number or not.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS