我试图解决项目欧拉问题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