Python: Check if a Number is a Perfect Number

Document 对象参考手册Python3 Examples

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")

Code explanation:

  1. is_perfect_number(n)The function is used to determine whether a numbernis a perfect number.
  2. First, checknwhether it is less than 2, because numbers less than 2 cannot be perfect numbers.
  3. sum_of_factorsInitialize it to 1, because 1 is a divisor of all positive integers.
  4. Use aforloop to iterate from 2 tonthe square root of the number, and check whether each number is a divisor ofnthe number.
  5. IfiYesnit is a factor of the number, then add itiandn // itosum_of_factorsthe sum.
  6. Finally, ifsum_of_factorsthe sum equalsn, thennthe number is a perfect number, returnTrue, otherwise returnFalse。

Output result:

28 是一个完全数

Document 对象参考手册Python3 Examples

Other extensions