The code which is common for both the implementations:
from math import sqrt
def factors(x):
num = 2
sq = int(sqrt(x))
for i in range(2, sq):
if (x % i) == 0:
num += 2
return num + ((1 if sq == sqrt(x) else 2) if x % sq == 0 else 0)
1. Implementation which doesn't make use of a generator function:
i = 1
while True:
if factors(i * (i+1) * 0.5) > 500:
print(int(i * (i+1) * 0.5))
break
i += 1
2. Implementation which makes use of a generator function:
def triangle():
i = 1
while True:
yield int(0.5 * i * (i + 1))
i += 1
t = triangle()
while True:
num = t.__next__()
if factors(num) > 500:
print(num)
break
The Question:
The first implementation takes about 4 seconds while the second one takes approximately 8.2 seconds. Why is there such a big difference between the run times of the two implementations?