
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:
- Find the proper divisors of the number.
- Sum the proper divisors.
- 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 integernum
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 ofnum
. If a numberi
evenly dividesnum
, we add it to thedivisors
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 thatnum
is a perfect number; otherwise, we returnFalse
.
You can use this program to check whether a given positive integer is a perfect number or not.