Python脚本查找第n个质数 [英] Python script to find nth prime number
问题描述
我是Python的新手,我想我会尝试通过编写一个函数来找到第n个素数来学习一些技巧,但是我无法使我的代码正常工作.毫无疑问,这是由于我遗漏了一些基本知识,但是我很感谢您在发现错误之处方面的帮助!
I'm new to Python and I thought I'd try to learn the ropes a bit by writing a function to find the nth prime number, however I can't get my code to work properly. No doubt this is due to me missing something fundamental, but I'd appreciate your help in finding where it went wrong!
c=2
n=input("Which prime would you like? ")
n=int(n)
a=[]
l=len(a)
while l<=n:
if c==2:
a.append(c)
elif (c % 2 ==0): #c is even
break
elif (c % 2 !=0): #c is odd
if c<7:
a.append(c)
elif c >=7:
for i in range(3,int((c+1)/2)):
if (c % i ==0):
break
else:
a.append(c)
else:
c+=1
a[n]
谢谢! 安德鲁
推荐答案
这可以是一个开始.这将检查数字N是否可被2
至int(sqrt(N)) + 1
的所有数字整除,其中int
函数将截断N的平方根.如果列表中的所有成员,python中的all()
函数将返回True
满足一些条件(此处不为零).您应该设置一个上限,因为对于很大的n
来说这不是很有效.我把它留给你.
This can be a start. This checks whether the number N is divisible by all numbers from 2
to int(sqrt(N)) + 1
, where the int
function truncates the square root of N. The all()
function in python returns True
if all members of a list satisfy some condition (here not zero). You should set an upper bound as this is not very efficient for really large n
. I'll leave that to you.
def nthprime(n):
import math
start = 2
count = 0
while True:
if all([start % i for i in range(2, int(math.sqrt(start)) + 1)]) != 0:
count += 1
if count == n:
return start
start += 1
In [91]: nthprime(50)
Out[91]: 229
In [92]: nthprime(100)
Out[92]: 541
使用此进行了测试.
这篇关于Python脚本查找第n个质数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!