欧拉 12 需要优化
Euler 12 need optimization
我已经解决了euler problem 12,但它需要一些优化。我在 euler 论坛上阅读过,但它并没有帮助我优化它。但是,我已经设法得到解决方案,我只需要加快速度。目前 运行 需要 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")
不用单独计算每个三角形编号,而是使用生成器来获取三角形编号
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
不是免费的。
我已经解决了euler problem 12,但它需要一些优化。我在 euler 论坛上阅读过,但它并没有帮助我优化它。但是,我已经设法得到解决方案,我只需要加快速度。目前 运行 需要 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")
不用单独计算每个三角形编号,而是使用生成器来获取三角形编号
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
不是免费的。