zach
zach

Reputation: 319

Struggling with Euler 12, Slow Code - Python

I'm struggling with Euler Problem 12. I do not want the answer or exact code changes that'll get me there. I'm just looking to be pointed in the right direction. I ran this code for about 10 minutes and came up with an answer which was incorrect. This leads me to believe that my assumption that a triangle number with > 500 divisors would not have any factors > 10000 is incorrect. I'm thinking I need to use a faster prime generator AND get the program to stop iterating through lists so much. I am not sure how to do the latter.

def eratosthenes_sieve(limit):
    primes = {}
    listofprimes = []
    for i in range(2, limit + 1):
        primes[i] = True

    for i in primes:
        factors = range(i, limit + 1, i)
        for f in factors[1:limit + 1]:
            primes[f] = False

    for i in primes:
        if primes[i] == True:
            listofprimes.append(i)
    return listofprimes


def prime_factorization(n):
    global primal
    prime_factors = {}
    for i in primal:
        if n < i:
            i = primal[0]
        if n % i == 0:
            if i not in prime_factors.keys():
                prime_factors[i] = 1
            else:
                prime_factors[i] += 1
            n = n / i
        if n in primal:
            if n not in prime_factors.keys():
                prime_factors[n] = 1
            else:
                prime_factors[n] += 1
            return prime_factors
    return prime_factors    

def divisor_function(input):
    x = 1
    for exp in input.values():
        x *= exp + 1
    return x

def triangle(th):
    terms = []
    for each in range(1, th+1):
        terms.append(each)
    return sum(terms)

z = 1
primal = eratosthenes_sieve(10000)
found = False
while found == False:
triz = triangle(z)
number_of_divisors = divisor_function(prime_factorization(triz))

if number_of_divisors > 300:
    print "GETTING CLOSE!! ********************************"
if number_of_divisors > 400:
    print "SUPER DUPER CLOSE!!! *********************************************************"
if number_of_divisors < 501:
    print "Nope. Not %s...Only has %s divisors." % (triz, number_of_divisors)

    z += 1
else:
    found = True
    print "We found it!"
    print "The first triangle number with over 500 divisors is %s!" % triangle(z)

Upvotes: 3

Views: 120

Answers (1)

zach
zach

Reputation: 319

Of course I figure it out minutes after posting.

In my prime_factorization function.

if n % i == 0: should have been while n % i == 0.

That was causing the program to miss factors and run through the entire list of primes.

Upvotes: 1

Related Questions