AvZ
AvZ

Reputation: 1035

Program to find the nth prime number

I wrote a code in python to find the nth prime number.

print("Finds the nth prime number")
def prime(n):
    primes = 1
    num = 2
    while primes <= n:
            mod = 1
            while mod < (num - 1):
                    ptrue = 'true'
                    if num%(num-mod) == 0:
                            ptrue = 'false'
                            break
                    mod += 1
            if ptrue == 'true':
                    primes += 1
    return(num)
nth = int(input("Enter the value of n: "))
print(prime(nth)

The code looked fine to me, but it returns an error when I run it:

  Traceback (most recent call last):            
  File "C:/Users/AV/Documents/Python/nth Prime.py", line 17, in <module>           
  print(prime(nth))           
  File "C:/Users/AV/Documents/Python/nth Prime.py", line 13, in prime          
  if ptrue == 'true':
  UnboundLocalError: local variable 'ptrue' referenced before assignment  

It appears to me as if it is trying to say that I am referring to ptrue in the last line even though I am not. What is the problem here... Can anyone help?

Upvotes: 2

Views: 26310

Answers (10)

SATYAM TRIPATHI
SATYAM TRIPATHI

Reputation: 67

Program to find nth Prime Number.

def nth_Prime(num):
    Semi = num*num
    Res_1 = [True for i in range(Semi+1)]
    prime = 2
    while prime*prime <= Semi:
        if Res_1[prime] == True:
            for i in range(prime*prime, Semi+1, prime):
                Res_1[i] = False
        prime += 1
    Res_2 = []
    for i in range(2, Semi+1):
        if Res_1[i]:
            Res_2.append(i)
    return Res_2[num-1]


if __name__ == "__main__":
    num = int(input("Enter nth Number: "))
    print(nth_Prime(num))

Upvotes: 0

Cyril Tom Mathew
Cyril Tom Mathew

Reputation: 1

Try this.

n = int(input())
count=1
u=2
prime=[]

while(count<=n):
    temp=0
    for i in range(2,u):
        if(u%i==0):
            temp=1
    if(temp==0):
        count+=1
        prime.append(u)
    u+=1

print(prime[-1])

Upvotes: 0

ashishkiirtwed
ashishkiirtwed

Reputation: 11

n=int(input('enter n'))
    a=[2,3,5,7]
    i=3
    j=9
while i<n:
        flag=0
        j=j+2
        for k in range(len(a)):
            if (a[k]<=int(j**0.5) and j%a[k]==0):
                flag=1
                break
        if flag==0:
            a=a+[j]
            i=i+1
print(a[n-1])

Upvotes: 0

shahri23
shahri23

Reputation: 1

All answers depends on user input, but here is a simple code to give nth number, no matter how big the n is ....

def isprime(n):  # First the primality test
    if n<2:
        return False
    for i in range(2,n):
        if n%i==0:
            return False
            break
    else:
        return True

def nthprime(n):   # then generic code for nth prime number
    x=[]
    j=2
    while len(x)<n:
        if (isprime(j)) == True:
            x.append(j)
        j =j+1
    print(x[n-1])

Upvotes: 0

shiva2492
shiva2492

Reputation: 429

Try this out ,I just made few changes in yours.

Here I am checking for each prime number using all(num%i!=0 for i in range(2,num)) checking its remainder not equal to zero so if it is true for that range (starting from 2 and less than itself) it is a prime and for that all() function helps me later if its a prime I increment the 'p' count and check till 'p' is less than the 'n'(Input Number) so when it equates the condition its the nth prime we are looking for.

n=raw_input("enter the nth prime ")
num=4
p=2

while p <int(n):
    if all(num%i!=0 for i in range(2,num)):
        p=p+1   
    num=num+1

print "nTH prime number: ",num-1

Upvotes: -1

Tianqi Yang
Tianqi Yang

Reputation: 1

The first part is define a function that calculates the next prime number given any number.

import math

def is_prime(x): # function
    for i in range(2,int(math.sqrt(x))+1):
        if x%i == 0:
            return is_prime(x+1)
    return x

For example, is_prime(10) will return 11.

The next step is to write a generator that returns a list of prime numbers.

def get_prime(k): # generator
    cnt = 1
    n = 2
    while cnt <= k:
        yield(is_prime(n))
        n = is_prime(n) + 1
        cnt += 1

For example, get_prime(5) will return [2,3,5,7,11].

The code below can help you test the results.

a = get_prime(50)
lists = list(a)[:]
for idx, value in enumerate(lists):
    print("The {idx}th value of prime is {value}.".format(idx = idx+1, value = value))

Upvotes: 0

Nimish Agrawal
Nimish Agrawal

Reputation: 159

You can try this:

#This program finds nth prime number

import math

def is_prime(number):
      if number < 2:
            return False
      if number % 2 == 0:
            return False
      else:
            for i in range(3, number):
                  if not number % i:
                        return False
            return True 


n = input('Enter n: ')

#This array stores all the prime numbers found till n
primes = []

for i in range(100000):
      if is_prime(i):
            primes.append(i)
      if len(primes) == n:
            break

print("nth prime number is: " + str(primes[n-1]))

Upvotes: 0

kindall
kindall

Reputation: 184200

Get rid of ptrue entirely and use else with your inner loop. For example:

while mod < (num - 1):
    if num % (num - mod) == 0:
       break
    mod += 1
else:
    primes += 1   # only executes if loop terminates normally, without `break`

Upvotes: 1

praveen
praveen

Reputation: 3263

ptrue is local to your while loop which goes out of scope as soon as the while loop ends. so declare ptrue before the start of your inner while loop

Upvotes: 1

akhter wahab
akhter wahab

Reputation: 4085

how about using Boolean ? and initalize ptrue out of while loop

print("Finds the nth prime number")
def prime(n):
    primes = 1
    num = 2
    while primes <= n:
            mod = 1
            ptrue = True
            while mod < (num - 1):
                    if num%(num-mod) == 0:
                            ptrue = False
                            break
                    mod += 1
            if ptrue == True:
                    primes += 1
    return(num)
nth = int(input("Enter the value of n: "))

print prime(nth)

Upvotes: 1

Related Questions