Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Check Whether a Number Is a Perfect Number

Python Check Whether a Number Is a Perfect Number

Document Object Reference Manual Python3 Examples

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

)

:

   

print

(

f

"{number} is a perfect number"

)

else

:

   

print

(

f

"{number} is not a perfect number"

)

Code analysis:

  1. is_perfect_number(n) The function is used to determine whether a number n is a perfect number.
  2. First check whether n is less than 2, because a number less than 2 cannot be a perfect number.
  3. sum_of_factors Initialize to 1, because 1 is a divisor of every positive integer.
  4. Use a for loop that iterates from 2 up to n the square root, checking whether each value is n a divisor of the number.
  5. If both the i Is n If it is a divisor, then add it to i and n // i to sum_of_factors it.
  6. Finally, if sum_of_factors Equal n, then n is a perfect number, return True; otherwise, returns False。

Output result:

28 是一个完全数

Document Object Reference Manual Python3 Examples