2

I have solved euler problem 12, but it needs some optimization. I have read on the euler forums, but it has not helped me optimized it. However, I have managed to get the solution, I just need to speed it up. It currently takes 4 minutes to run. Here is my code:

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")   
05bs001
  • 41
  • 7
  • To reach more people I suggest you add the `Optimization` tag to your question. – A. Smoliak Feb 12 '18 at 15:54
  • When you work on Euler Project problems you usually find that it's necessary to seek an optimal approach, rather than trying to optimise an approach that is inherently inefficient. – Bill Bell Feb 12 '18 at 16:06

1 Answers1

1

Instead of calculating each triangle number individually, use a generator to get the triangle numbers

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))

Gives me 3.8404819999996107 (seconds) on my machine. You could probably also improve the divisor counting.

What's really slowing you down is calling nthtriangle and numberoffactors more than once in your loop! Plus, those calls to print aren't free.

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96