【发布时间】:2012-11-10 07:09:00
【问题描述】:
我正在尝试用 Python 解决 Project Euler 问题 3:
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 i in xrange(len(primes))。 -
另一方面,这是一种非常低效的方法。 O(n² / log n)。
标签: python