user1744020
user1744020

Reputation:

Invalid Syntax; nth prime number

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)

Whenever I try to run this it says that "print nthprime(10001)" is invalid syntax.

-prime test is to test wether a number is prime and nthprime creates a list of prime numbers a certain lengths and then return the last element of the list.

Upvotes: 1

Views: 279

Answers (2)

Reut Sharabani
Reut Sharabani

Reputation: 31339

In your code:

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

I think you meant primes[-1], like this:

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

You're also going to need to specify a range in integers, not float. So this:

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

Becomes this:

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

Upvotes: 0

Andrea Spadaccini
Andrea Spadaccini

Reputation: 12651

print is a function in Python 3, not a statement. You should change your last line of code to:

print(nthprime(10001))

Upvotes: 1

Related Questions