I have written this code for solving Euler Project No 12, but my code runs slow.
How can I make it running faster? I have read some suggests about finding divisors, but I do not understand the logic of using sqrt
for n
.
Can you explain the logic of it?
Here's my code:
def sumdiv(n):
l=[d for d in range(1,int(n/2)+1) if n%d==0] # used n/2 to short loop
return len(l)+1 # added n itself
trnums=[1,3]
while sumdiv(trnums[-1])<=501:
k=trnums[-1]-trnums[-2]+1
trnums.append(trnums[-1]+k)
print(trnums[-2:])