求素数的第n个 [英] Finding the nth number of primes

查看:90
本文介绍了求素数的第n个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么这行不通.请帮助我

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

推荐答案

您需要更改

root=int(sqrt(x))

进入

root=int(sqrt(x))+1

(例如,以9为例,int(sqrt(9))3,而range(3, 3, 2)[],而您 do 确实想测试除以3!).

(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!).

从技术上讲,1也不是质数.添加

Technically, 1 is not a prime either. Add

if(x<=1):
   prime = False

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

这篇关于求素数的第n个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆