简体   繁体   English

寻找第n个素数的程序

[英]Program to find the nth prime number

I wrote a code in python to find the nth prime number.我用python写了一段代码来找到第n个素数。

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.在我看来,它似乎试图说我指的是最后一行中的 ptrue,即使我不是。 What is the problem here... Can anyone help?这里有什么问题......任何人都可以帮忙吗?

how about using Boolean ?使用Boolean怎么样? and initalize ptrue out of while loop并在while loop初始化ptrue

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)

ptrue is local to your while loop which goes out of scope as soon as the while loop ends. ptrue 对您的 while 循环来说是本地的,一旦 while 循环结束,它就会超出范围。 so declare ptrue before the start of your inner while loop所以在你的内部 while 循环开始之前声明 ptrue

Get rid of ptrue entirely and use else with your inner loop.完全摆脱ptrue并在您的内部循环中使用else 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`

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

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 .例如, is_prime(10)将返回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] .例如, get_prime(5)将返回[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))

All answers depends on user input, but here is a simple code to give nth number, no matter how big the n is ....所有答案都取决于用户输入,但这里有一个简单的代码来给出第 n 个数字,无论 n 有多大......

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

Program to find nth Prime Number.寻找第 n 个素数的程序。

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

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.在这里,我使用all(num%i!=0 for i in range(2,num))检查每个素数all(num%i!=0 for i in range(2,num))检查其余数不等于零,因此该范围是否为真(从 2 开始并且小于自身) ) 它是一个素数,因为 all() 函数稍后会帮助我,如果它是一个素数,我会增加 'p' 计数并检查直到 'p' 小于 'n'(输入数),所以当它等于条件时我们正在寻找的第 n 个素数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM