标题: python完数代码的优化 [打印本页] 作者: kaifei 时间: 2018-8-1 18:22 标题: python完数代码的优化 在学习期间,学到了循环,写了完数的题目如下:from time import timestart = time()
for num in range(1, 10001):
my_sum = 0
for i in range(1, num):
if num % i == 0:
my_sum += i
if num == my_sum:
print(num)
end = time()
print((end-start), "秒")
进行优化后的代码:
from time import time
from math import sqrt
start = time()
for num in range(2, 10001):
my_sum = 1
for i in range(2, int(sqrt(num))+1):
if num % i == 0:
my_sum += i
if i != num // i:
my_sum += num // i
if num == my_sum:
print(num)
end = time()
print((end-start), "秒")