2012-05-04 65 views
0
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 
+0

請編輯您的問題問題的代碼,請選擇代碼,然後按CTRL + k然後保存。 –

回答

0

對於每個號碼>= 11您遞歸調用isPrime。如果數量足夠大,則會發生堆棧溢出錯誤。

SPOJ上的Prime Generator問題有很大數量限制。嘗試使用大數字運行程序,如999900000 1000000000

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 
相關問題