Python: Check if a Number is a Perfect Number
A perfect number is a number that equals the sum of all its proper divisors (divisors other than itself). For example, 6 is a perfect number because its proper divisors are 1, 2, 3, and 1 + 2 + 3 = 6.
The following is a Python program to determine whether a number is a perfect number:
Example
def is_perfect_number(n):
if n < 2:
return False
sum_of_factors = 1
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
sum_of_factors += i
if i != n // i:
sum_of_factors += n // i
return sum_of_factors == n
# Test
number = 28
if is_perfect_number(number):
print(f"{number} is a perfect number")
else:
print(f"{number} is not a perfect number")
if n < 2:
return False
sum_of_factors = 1
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
sum_of_factors += i
if i != n // i:
sum_of_factors += n // i
return sum_of_factors == n
# Test
number = 28
if is_perfect_number(number):
print(f"{number} is a perfect number")
else:
print(f"{number} is not a perfect number")
Code explanation:
is_perfect_number(n)The function is used to determine whether a numbernis a perfect number.- First, check
nwhether it is less than 2, because numbers less than 2 cannot be perfect numbers. sum_of_factorsInitialize it to 1, because 1 is a divisor of all positive integers.- Use a
forloop to iterate from 2 tonthe square root of the number, and check whether each number is a divisor ofnthe number. - If
iYesnit is a factor of the number, then add itiandn // itosum_of_factorsthe sum. - Finally, if
sum_of_factorsthe sum equalsn, thennthe number is a perfect number, returnTrue, otherwise returnFalse。
Output result:
28 是一个完全数Other extensions
Python3 Examples