我試圖解決項目歐拉問題3在Python:歐拉項目在Python
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
我知道我的計劃是低效和超大的,但我只是想知道爲什麼它不工作? 下面的代碼:
def check(z):
# checks if the given integer is prime
for i in range(2, z):
if z % i == 0:
return False
break
i = i+1
return True
def primegen(y):
# generates a list of prime integers in the given range
tab = []
while y >= 2:
if check(y) == True:
tab.append(y)
i = i-1
def mainfuntion(x):
# main function; prints the largest prime factor of the given integer
primegen(x)
for i in range(len(tab)):
if x % tab[i] == 0:
print tab[i]
break
mainfuntion(600851475143)
而這裏的錯誤:
for i in range(2, z):
OverflowError: range() result has too many items
您在'primegen'中混合了'i'和'y'。至於錯誤,請嘗試'xrange'。 –
像你在做的那樣,在'mainfunction'裏面引用變量'tab'是個壞習慣。你對'primegen()'的調用可以返回素數列表,你可以給一個變量賦值:'primes = primegen(x)',然後下一行'for xrange(len(primes))'。 – jozzas
歡迎來到Stackoverflow。我爲你格式化了代碼,但請看看[this](http://stackoverflow.com/editing-help)和[this](http://meta.stackexchange.com/a/22189),以及格式化代碼塊下次正確。 – BrtH