[英]Why am I getting “runtime error (NZEC)” for this python code?(SPOJ Anti blot system)
[英]SPOJ Prime Generator My python code is giving a Runtime Error NZEC, why?
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
由於輸入中有額外的空白區域,您將獲得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
對於每個>= 11
您遞歸調用isPrime
。 如果數量足夠大,將發生堆棧溢出錯誤。
SPOJ上的Prime Generator問題有很大的限制。 嘗試使用大數字運行程序,例如999900000 1000000000
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.