Python 練習實例19

Python 100例 Python 100例

題目:一個數如果恰好等於它的因數之和,這個數就稱為"完數"。例如6=1+2+3.編程找出1000以內的所有完數。

程式分析:請參照程式Python 練習實例14

程式源代碼:

實例(Python 2.0+)

#!/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]

以上實例輸出結果為:

6
1 2 3
28
1 2 4 7 14
496
1 2 4 8 16 31 62 124 248

Python 100例 Python 100例