[Python] Optimise the solution to Project Euler 12 (Python)

Discussão em 'Python' iniciado por Stack, Setembro 16, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following code for Project Euler Problem 12. However, it takes a very long time to execute. Does anyone have any suggestions for speeding it up?

    n = input("Enter number: ")
    def genfact(n):
    t = []
    for i in xrange(1, n+1):
    if n%i == 0:
    t.append(i)
    return t

    print "Numbers of divisors: ", len(genfact(n))
    print

    m = input("Enter the number of triangle numbers to check: ")
    print
    for i in xrange (2, m+2):
    a = sum(xrange(i))
    b = len(genfact(a))
    if b > 500:
    print a


    For n, I enter an arbitrary number such as 6 just to check whether it indeed returns the length of the list of the number of factors. For m, I enter entered 80 000 000

    It works relatively quickly for small numbers. If I enter b > 50 ; it returns 28 for a, which is correct.

    Continue reading...

Compartilhe esta Página