Skip to main content
 首页 » 编程设计

python之一个非常基本的 Python 程序的运行时崩溃

2025年05月04日8itcoder

我在安装了 Python 2.6 的 Windows XP PC 上工作,我试图解决 Project Euler 问题,但每当我执行代码时,解释器都会挂起。我已经通过 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 才会递减

应该是这样的:

while x > 0: 
    if num%x == 0: 
        if ifprime(x): 
                print "I've found a prime! " 
                print x 
                prime[len(prime):] = [x] 
    x -= 1