我正在努力解决欧拉问题 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)