我正在与Euler Problem 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)
答案 0 :(得分:1)
当然,我在发布后几分钟就知道了。
在我的prime_factorization函数中。
如果n%i == 0:应该是n%i == 0。
这导致程序遗漏因素并贯穿整个素数列表。