0

SPOJ Prime 生成器 我的 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
4

2 回答 2

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
于 2013-01-07T02:49:33.070 回答
0

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

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

于 2012-05-04T04:12:03.543 回答