找出第 n 个素数

发布于 2024-09-05 14:55:11 字数 651 浏览 13 评论 0原文

我不明白为什么这行不通。请帮我

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

何以笙箫默 2024-09-12 14:55:11

需要改为

root=int(sqrt(x))

root=int(sqrt(x))+1

以9为例,int(sqrt(9))3range(3, 3, 2)[],并且您确实确实想测试除以 3!)。

从技术上讲,1 也不是素数。添加

if(x<=1):
   prime = False

,您将得到与 http://www.rsok.com/~ 相同的结果jrm/first100primes.html

You need to change

root=int(sqrt(x))

into

root=int(sqrt(x))+1

(Take 9 for instance, int(sqrt(9)) is 3, and range(3, 3, 2) is [], and you do really want to test dividing by 3!).

Technically, 1 is not a prime either. Add

if(x<=1):
   prime = False

and you'll get the same result as http://www.rsok.com/~jrm/first100primes.html

好菇凉咱不稀罕他 2024-09-12 14:55:11

与@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;-).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文