## Program to find the nth prime number

2020-08-01 05:51发布

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?

9条回答
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])

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])

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]))

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

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`

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