挣扎于欧拉12,慢代码- Python



我正在努力做欧拉第12题。我不想知道答案,也不想知道如何修改代码。我只是希望你能给我指明正确的方向。我运行了这个代码大约10分钟,得到了一个不正确的答案。这让我相信我的假设,一个大于500个因数的三角形数不会有任何大于10000的因数是不正确的。我想我需要使用一个更快的质数生成器,并让程序停止迭代通过列表这么多。我不确定如何做后者。

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)

我当然是在发帖几分钟后才想到的。

在我的prime_factorization函数中

如果n % I == 0:当n % I == 0时,

这将导致程序遗漏因子并遍历整个素数列表。

最新更新