我最近开始学习python,为了熟悉这些概念,我开始解决euler问题。我一直在努力解决
Euler's problem number 12
但是,我的代码运行了很长一段时间(超过10分钟,并且仍在运行)。我上网查了一下,运行了这段代码,令人惊讶的是只花了11秒。但我无法理解两者之间的区别。非常感谢有人能帮我理解
我的代码第1章:
from time import time
import math
def divisors(n):
n = int(n)
sqrt = int(math.sqrt(n))
result = sum(2 for i in range(1, sqrt+1) if n%i == 0)
for i in range(1, n+1):
if i**2 == n:
result = result - 1
return result
i = 1
num = 0
a = 0
t = time()
while a < 500:
num = num+i
print(num, i)
i = i+1
a = divisors(num)
print(a)
tt = time() - t
print(tt)
我的代码2
from time import time
import math
def divisors(n):
n = int(n)
sqrt = int(math.sqrt(n))
for i in range(1, n+1):
result = sum(2
for i in range(1, sqrt+1) if n%i == 0)
if i**2 == n:
result = result - 1
return result
i = 1
num = 0
a = 0
t = time()
while a < 500:
num = num+i
print(num, i)
i = i+1
a = divisors(num)
print(a)
tt = time() - t
print(tt)
用了11秒的代码:
import math
from time import time
t = time()
def divisors(n):
number_of_factors = 0
for i in range(1, int(math.ceil(math.sqrt(n)))):
if n % i == 0:
number_of_factors +=2
else:
continue
return number_of_factors
x=1
for y in range(2,1000000):
x += y
if divisors(x) >= 500:
print x
break
tt = time()-t
print tt