SPOJ Prime Generator我的python代码给出运行时错误NZEC,为什么?

时间:2012-05-04 04:02:39

标签: python

SPOJ Prime Generator我的python代码给出了运行时错误NZEC,为什么?

testcases = raw_input(" ")

def isPrime(n):
    result = True
    if n != 0 and n != 1 and n % 2 != 0 and n % 5 != 0 and n % 7 != 0 and n % 9 != 0:
        if n > 9:
            for i in range(11,n):
                if isPrime(i):
                    if n % i == 0:
                        result = False
            return result
        else:
            return result
    else:
        return False

for count in range(0,testcases):
    m,n = raw_input(" ").split()
    m = int(m)
    n = int(n)
    for i in range(m,n+1):
        if isPrime(i):
            print i

2 个答案:

答案 0 :(得分:2)

由于输入中有额外的空格,您将获得NZEC。设计代码来处理这种情况并不困难。立即获取输入并用空格标记它。看看我是如何做到的。

def isPrime(n):
    result = True
    if n != 0 and n != 1 and n % 2 != 0 and n % 5 != 0 and n % 7 != 0 and n % 9 != 0:
        if n > 9:
            for i in range(11,n):
                if isPrime(i):
                    if n % i == 0:
                        result = False
            return result
        else:
            return result
    else:
        return False

def main():    # Don't leave the code in the global namespace, it runs slower
    import sys
    tokenizedInput = map(int, sys.stdin.read().split())    # Read at once, tokenize
    testcases = tokenizedInput[0]
    readAt = 1    # Position to begin reading
    for count in range(0,testcases):
        m,n = tokenizedInput[readAt:readAt+2]    # Read the tokenized input
        for i in range(m,n+1):
            if isPrime(i):
                print i
        print    # You need to separate two outputs by a line
        readAt = readAt + 2

main()

这将让你摆脱NZEC。但是,您的算法效率低且不正确。对于

的示例输入测试用例
2
1 10
3 5

您修改的代码现在输出

3

3

预期输出

2
3
5
7

3
5

答案 1 :(得分:0)

对于每个号码>= 11,您递归调用isPrime。如果数字足够大,将发生堆栈溢出错误。

SPOJ上的Prime Generator问题有很大的限制。尝试使用大数字运行您的程序,例如999900000 1000000000