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

2024-10-02 08:16:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一台安装了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

Tags: orthe代码numberreturnifisnot
3条回答

您的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

你有一个无限循环:

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),这就足够了。在

import math

def ifprime (x): 

    y = math.ceil(math.sqrt(x))

    while y > 1:
        if x % y == 0:
            return False
        y -= 1

    return True

相关问题 更多 >

    热门问题