【发布时间】:2014-12-07 16:44:49
【问题描述】:
我有这个,它有效。数字 100000+ 只需要大量时间,我希望将其减少,以便它可以在不到 3 分钟的时间内计算出第 1,000,000 个素数。我已经设置它,以便我们的数字(chk)只有数字(奇数)被分成它,以检查可分性,直到 chk 的平方根。该程序设置为查找第 n 个素数,直到第 1000000 个。谢谢。
goal=int(input("Enter a number n, 1-1,000,000 to find the nth prime number.")) #how many primes we need to find
if goal>1000000: #closes the program if the number doesn't fit the parameters
exit()
if goal==1: #takes care of the first prime, which is 2
print("2")
if goal==2: #and then the second, which is 3
print("3")
chk=5 #the next odd number after 3, which is already taken care of above
primes=2 #the number of primes recorded, after counting 2 and 3.
x=0 #the last recorded prime number
while primes<goal:
if chk<9: #if the number is odd and below 9....
primes+=1 #it's prime
x=chk #record that number
chk+=2 #and check the next odd number
else: #if it's =>9......
odds=3 #check to see if it's divisible by the smallest odd number
sqrtk=chk**.5 #all the way up to the square root of chk
while odds<sqrtk or odds==sqrtk: #if at any time...
if chk%odds==0: #...chk is divisible by this odd number....
chk+=2 #then raise the value of chk to the next odd number
break #and start the check from the beginning with next k
else: #if not...
odds+=2 #check to see if it's divisible by the next odd number.
if odds>sqrtk: #if chk isn't divisible by any odds up to the square root of chk
primes+=1 #we have a prime number
x=chk #record that number
chk+=2 #check the next odd number to see if it's prime
odds=3 #and reset odds back to 3 to use it next time
if primes==goal: #once we've reached the desired amount of prime numbers
print("The",goal,"prime number is:",x) #print that prime number
【问题讨论】:
-
这属于codereview
-
谢谢。把它放在那里。
-
这已被问过一百万次,无论是作为数学问题还是作为编程问题。请先对问题进行一些研究。