Python Practice Example 19

Python 100例Python 100 Examples

Problem:If a number is exactly equal to the sum of its factors, this number is called a "perfect number". For example, 6=1+2+3. Program to find all perfect numbers within 1000.

Program analysis:Please refer to the programPython Practice 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: print (j) for i in range(n): stdout.write(str(k[i])) stdout.write(' ') print (k[n])

The output result 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例Python 100 Examples

Other extensions