【问题标题】:Euler 12 need optimizationEuler 12 需要优化
【发布时间】: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


【解决方案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(秒)。您可能还可以改进除数计数。

真正让你慢下来的是在你的循环中不止一次调用nthtrianglenumberoffactors!另外,拨打print 的电话不是免费的。

【讨论】:

    猜你喜欢
    • 2011-03-23
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 2015-07-17
    • 1970-01-01
    • 2017-04-02
    相关资源
    最近更新 更多