找出第 n 个素数
我不明白为什么这行不通。请帮我
from math import sqrt
pN = 0
numPrimes = 0
num = 1
def checkPrime(x):
'''Check\'s whether a number is a prime or not'''
prime = True
if(x==2):
prime = True
elif(x%2==0):
prime=False
else:
root=int(sqrt(x))
for i in range(3,root,2):
if(x%i==0):
prime=False
break
return prime
n = int(input("Find n number of primes. N being:"))
while( numPrimes != n ):
if( checkPrime( num ) == True ):
numPrimes += 1
pN = num
print("{0}: {1}".format(numPrimes,pN))
num += 1
print("Prime {0} is: {1}".format(n,pN))
I can not figure out why this won't work. Please help me
from math import sqrt
pN = 0
numPrimes = 0
num = 1
def checkPrime(x):
'''Check\'s whether a number is a prime or not'''
prime = True
if(x==2):
prime = True
elif(x%2==0):
prime=False
else:
root=int(sqrt(x))
for i in range(3,root,2):
if(x%i==0):
prime=False
break
return prime
n = int(input("Find n number of primes. N being:"))
while( numPrimes != n ):
if( checkPrime( num ) == True ):
numPrimes += 1
pN = num
print("{0}: {1}".format(numPrimes,pN))
num += 1
print("Prime {0} is: {1}".format(n,pN))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
需要改为
(
以9为例,
int(sqrt(9))
为3
,range(3, 3, 2)
是[]
,并且您确实确实想测试除以3
!)。从技术上讲,1 也不是素数。添加
,您将得到与 http://www.rsok.com/~ 相同的结果jrm/first100primes.html
You need to change
into
(Take 9 for instance,
int(sqrt(9))
is3
, andrange(3, 3, 2)
is[]
, and you do really want to test dividing by3
!).Technically, 1 is not a prime either. Add
and you'll get the same result as http://www.rsok.com/~jrm/first100primes.html
与@Braxton在评论中所说的不同,埃拉托斯特尼筛法算法可以很容易地适应生成无界素数(例如作为潜在无限的生成器,然后可以根据需要进行缩减,例如通过itertools.slict)。
请参阅此食谱了解Python中的无界筛(并确保应用评论中显示的增强功能,包括我的;-) 或查看与最终编辑的印刷食谱相同的食谱 这里(不幸的是,讨论部分在这本谷歌图书中被缩减了,但是在至少解决方案的代码都在那里;-)。
Differently from what @Braxton says in a comment, the Sieve of Eratosthenes algorithm can easily be adapted to generate unbounded primes (e.g. as a potentially-infinite generator, which can then be curtailed as desired e.g. by
itertools.slict
).See this recipe for an unbounded Sieve in Python (and be sure to apply the enhancements shown in the comments, including mine;-) or see the same recipe as finally edited for the printed Cookbook here (unfortunately the discussion part is curtailed in this google books hit, but at least the Solution's code is all there;-).