2012-10-13 90 views
1
def primetest(x): 
    if x < 2: 
     return False 
    if x == 2: 
     return True 
    if x % 2 == 0: 
     return False 
    for i in range(3,(x**0.5)+1): 
     if x % i == 0: 
      return False 
    return True 

def nthprime(n): 
    primes = [] 
    x = 2 
    while len(primes) < n: 
     if primetest(x) == True: 
      primes.append(x) 
      x = x + 1 
    return list(-1) 

print nthprime(10001) 

每當我嘗試運行它時,它說「print nthprime(10001)」是無效的語法。語法無效; nth素數

-prime測試是測試一個數字是否爲素數,nthprime會創建一個特定數字列表並返回列表的最後一個元素。

回答

1

print是Python 3中的一個函數,而不是語句。你應該改變的代碼到你的最後一行:

print(nthprime(10001)) 
0

在您的代碼:

def nthprime(n): 
    primes = [] 
    x = 2 
    while len(primes) < n: 
     if primetest(x) == True: 
      primes.append(x) 
      x = x + 1 
    return list(-1) // this is the error 

我想你的意思是素數[-1],這樣的:

def nthprime(n): 
    primes = [] 
    x = 2 
    while len(primes) < n: 
     if primetest(x) == True: 
      primes.append(x) 
      x = x + 1 
    return primes[-1] // this is now correct 

你」還需要指定整數範圍,而不是浮點數。所以這個:

for i in range(3,(x**0.5)+1): 

變爲這樣:

for i in range(3,int((x**0.5)+1)): // note the "int"