另外一種方法:其時間複雜度更好
程序代码:
import math
def isPerfect(num):
""" Determine whether a natural number is a perfect number """
if num <= 0: return False
i = 1
s = 0
while i <= math.sqrt(num):
if num % i == 0:
s += i
if i*i != num:
s += (num/i)
i += 1
return (s-num) == num
def main():
""" Find the perfect number """
for n in range(1,99999): # 這裡我改成更大數值做測試,完全沒有問題
if isPerfect(n):
print(n)
if __name__ == '__main__':
""" Program entry """
main()
如果想算出極大數值,可以用梅森質數:
prime = [2, 3, 5, 7, 13, 17, 19, 31] # 梅森質數
isPerfect = lambda p: (1<<(p-1))*((1<<p)-1)
for i in prime:
print(isPerfect(i))
輸出:
程序代码:
6
28
496
8128
33550336
8589869056
137438691328
2305843008139952128
[此贴子已经被作者于2021-9-2 11:08编辑过]