Python Exercise Example 19
**Question:** If a number is exactly equal to the sum of its factors, it is called a "perfect number". For example, 6 = 1 + 2 + 3. Write a program to find all perfect numbers within 1000.
**Program analysis:** Please refer to the programPython Exercise Example 14.
Program source code:
Example
#!/usr/bin/python
-- coding: UTF-8 --
from
sys
import
stdout
for
j
in
range
(
2
,
1001
)
:
k
=
[
]
n
= -
1
s
=
j
for
i
in
range
(
1
,
j
)
:
if
j
%
i
==
0
:
n
+=
1
s
-=
i
k
.
append
(
i
)
if
s
==
0
:
(
j
)
for
i
in
range
(
n
)
:
stdout
.
write
(
str
(
k
[
i
]
)
)
stdout
.
write
(
'
'
)
(
k
[
n
]
)
The output of the above example is:
6
1 2 3
28
1 2 4 7 14
496
1 2 4 8 16 31 62 124 248
Python 100 Examples