| 网站首页 | 业界新闻 | 小组 | 交易 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛

```def is_perfect (n):
'''判断一个自然数是否为完美数'''
s = 0
for i in range(1,n):
if n % i == 0:
s += i
return s == n
def main():
'''寻找完美数'''
for n in range(1,10000):
if is_perfect(n):
print(n)

if __name__ == '__main__':
'''程序入口'''
main()
```

is_perfect 里的return前面去掉一个tab。在for里直接return了。

```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编辑过]

• 7
• 1/1页
• 1