Python Check Whether a Number Is a Perfect Number
A perfect number is a number equal to 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 Python program checks 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
Testing
number
=
28
if
is_perfect_number
(
number
)
:
(
f
"{number} is a perfect number"
)
else
:
(
f
"{number} is not a perfect number"
)
Code analysis:
is_perfect_number(n)The function is used to determine whether a numbernis a perfect number.- First check whether
nis less than 2, because a number less than 2 cannot be a perfect number. sum_of_factorsInitialize to 1, because 1 is a divisor of every positive integer.- Use a
forloop that iterates from 2 up tonthe square root, checking whether each value isna divisor of the number. - If both the
iIsnIf it is a divisor, then add it toiandn // itosum_of_factorsit. - Finally, if
sum_of_factorsEqualn, thennis a perfect number, returnTrue; otherwise, returnsFalse。
Output result:
28 是一个完全数
Python3 Examples