可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
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)
回答2:
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
回答3:
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`
回答4:
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]))
回答5:
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))
回答6:
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])
回答7:
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])
回答8:
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])
回答9:
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