【发布时间】:2018-02-12 15:43:47
【问题描述】:
我已经解决了euler problem 12,但它需要一些优化。我在欧拉论坛上阅读过,但它并没有帮助我优化它。但是,我已经设法得到了解决方案,我只需要加快速度。目前运行需要 4 分钟。这是我的代码:
import time
def nthtriangle(n):
return (n * (n + 1)) / 2
def numberofnfactors(n):
count = 0
if n==1:
return 1
for i in range(1, 1 + int(n ** 0.5)):
if n % i == 0:
count += 2
return count
def FirstTriangleNumberWithoverxdivisors(divisors):
found = False
counter = 1
while not found:
print(int(nthtriangle(counter)), " ", numberofnfactors(nthtriangle(counter)))
if numberofnfactors(nthtriangle(counter)) > divisors:
print(" first triangle with over ",divisors, " divisors is ", int(nthtriangle(counter)))
found = True
break
counter += 1
start_time = time.time()
FirstTriangleNumberWithoverxdivisors(500)
print("My program took", time.time() - start_time, "to run")
【问题讨论】:
-
为了覆盖更多人,我建议您在问题中添加
Optimization标签。 -
当您处理欧拉计划问题时,您通常会发现有必要寻求一种最佳方法,而不是试图优化一种本质上效率低下的方法。
标签: python-3.x optimization refactoring triangular