脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python找出完数的方法

python找出完数的方法

2021-04-18 00:51Guo_Apple Python

今天小编就为大家分享一篇python找出完数的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# -*- coding: utf-8 -*-
# 要求:用python方法找出1000以内的所有完数,并输出。
def f(n):
 list = []
 for i in range(2, n + 1):
  for j in range(2, i / 2):
   if i % j == 0 and j <= (i / j):
    list.append(j)
    list.append(i / j)
 
  if sum(list) + 1 == i:
   print i
  list = []
 
if __name__=="__main__":
 n=int(raw_input("请输入最大范围:"))
 f(n)

运行结果:

?
1
2
3
4
请输入最大范围:1000
6
28
496

总结:

sum可以直接对列表进行求和!

原文链接:https://blog.csdn.net/Guo_Apple/article/details/69944712

延伸 · 阅读

精彩推荐