我在一台安装了python2.6的windowsxp电脑上工作,我试图解决projecteuler问题,但每当我执行代码时,解释器就会挂起。我已经通过PyScripter、IDLE和MonkeyStudio对它进行了调试,但是即使对于15这样的小值,它仍然不起作用。在
我只是不明白为什么。你能帮帮我吗?在
代码如下:
"""Project Euler Problem 3
Author: A"""
num = 15
prime = [1]
x = long (round(num/2))
def ifprime (x):
""" Defining the function that checks if the number is prime or not"""
""" Checking if the passed number is prime or not"""
y = long(round(x/2))
while y > 0:
if x%y == 0:
return False
y -= 1
return True
while x > 0:
if num%x == 0:
if ifprime(x):
print "I've found a prime! "
print x
prime[len(prime):] = [x]
x -= 1
您的x-=1语句缩进了一个级别。在
只有当num%x为0时,x才会递减
应该是这样的:
你有一个无限循环:
x -= 1
永远不会在num%x == 0
条件下被调用,这种情况永远不会发生(因为x
从不更改其值)。在当
num
为15时,x
从7开始。那么,num % x
为1,因此条件为假,x
不递减,因此无限循环。在除了别人指出的以外,你的
ifprime
是错误的。您正在检查while y > 0
,当然,它最多测试y = 1
,因此总是返回false。在为了优化的目的,你不必测试最多
x/2
,你可以测试最多sqrt(x)
,这就足够了。在相关问题 更多 >
编程相关推荐