2

我已经解决了欧拉问题 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")   
4

1 回答 1

1

不用单独计算每个三角形数,而是使用生成器来获取三角形数

from timeit import timeit

def triangle_numbers():
    count = 1
    num = 0
    while True:
        num += count
        count += 1
        yield num

def count_divisors(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

print(timeit('next(num for num in triangle_numbers() if count_divisors(num) >= 500)', 
             globals=globals(), number=1))

在我的机器上给我3.8404819999996107(秒)。您可能还可以改进除数计数。

nthtriangle真正让你慢下来的是在你的循环中numberoffactors不止一次打电话!另外,这些电话print不是免费的。

于 2018-02-12T16:29:05.953 回答