Python 检查1到1000000之间的第n个素数,必须在3分钟内计算出第1000000个素数

Python 检查1到1000000之间的第n个素数,必须在3分钟内计算出第1000000个素数,python,math,Python,Math,我有这个,它很管用。对于数字100000+来说,它只需要花费大量的时间,我希望减少它,这样它就可以在不到3分钟的时间内计算出第1000000个素数。我已经设置好了,所以我们的数字(chk)只需要将数字(赔率)除以它,以检查整除性,直到chk的平方根。该程序设置为查找第n个素数,直到第1000000个素数。谢谢 goal=int(input("Enter a number n, 1-1,000,000 to find the nth prime number.")) #how many prim

我有这个,它很管用。对于数字100000+来说,它只需要花费大量的时间,我希望减少它,这样它就可以在不到3分钟的时间内计算出第1000000个素数。我已经设置好了,所以我们的数字(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
goal=int(输入(“输入一个数字n,1-1000000以查找第n个素数”)#需要查找多少个素数
如果目标>1000000:#如果数字不符合参数,则关闭程序
退出()
如果目标=1:#处理第一个素数,即2
打印(“2”)
如果目标=2:#然后是第二个目标,即3
打印(“3”)
chk=5#3之后的下一个奇数,上面已经考虑过了
素数=2#计数2和3后记录的素数数。
x=0#最后记录的素数
而primessqrtk:#如果chk不可被任何几率整除到chk的平方根
素数+=1#我们有一个素数
x=chk#记录该数字
chk+=2#检查下一个奇数是否为素数
赔率=3#并将赔率重置为3,以便下次使用
如果素数==目标:#一旦我们达到所需的素数数量
打印(“目标”,素数是:,x)#打印那个素数

更好的方法是在进行过程中生成素数列表,并检查该数字是否可以除以该列表中的数字

list = [ ]

while primes < goal: 
  found = false
  for n in list
    if chk % n = 0
      # is prime
      found = true
      break
  if not found
    list.append(chk)
list=[]
而primes<目标:
发现=错误
对于列表中的n
如果chk%n=0
#黄金
找到=真
打破
如果找不到
list.append(chk)
要在更短的时间内生成列表,请尝试使用其他编程语言。下面是C++程序,它可以在10秒内生成第一个1.0万个(取决于你使用的)。 为此,考虑了一些数学假设: 1) 只检查奇数 2) 仅检查低于当前数字平方根的数字

此外,还进行了一些C优化: 1) 首先定义数组大小。通过这样做,我们不必处理重新分配内存的昂贵操作 2) 使用“寄存器”加速时间关键型处理块 3) 预计算sqrt(chk)以加速

#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <time.h>
#include <iostream>
#include <math.h>


#define NUMBERS 1000000


using namespace std;


main(int argc, char **argv)
{
  unsigned *list = (unsigned*)malloc(NUMBERS * sizeof(unsigned) );
  if(!list)
    exit(1);

  list[0] = 2;

  register unsigned primes = 1;
  unsigned goal = NUMBERS;
  unsigned chk = 3;

  clock_t tStart = clock();

  bool found;

  while(primes < goal) {
    found = false;
    register unsigned sq = sqrt(chk);
    for(register unsigned i = 1 ; i < primes ; i++) {
      if(list[i] > sq)
        break;
      if(chk % list[i] == 0) {
        found = true;
        break;
      }
    }
    if(!found) {
      list[primes++] = chk;
   }

    chk += 2;
  }


  printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);

  for(int i = 0 ; i < primes ; i++)
    cout << list[i] << "  ;  ";
  cout << endl << endl;

  free(list);
}
#包括
#包括
#包括
#包括
#包括
#包括
#定义数字1000000
使用名称空间std;
主(内部argc,字符**argv)
{
无符号*列表=(无符号*)malloc(数字*sizeof(无符号));
如果(!列表)
出口(1);
列表[0]=2;
寄存器无符号素数=1;
无符号目标=数字;
无符号chk=3;
时钟启动=时钟();
布尔发现;
while(primessq)
打破
如果(chk%list[i]==0){
发现=真;
打破
}
}
如果(!找到){
列表[primes++]=chk;
}
chk+=2;
}
printf(“所用时间:%.2fs\n”,(双精度)(clock()-tStart)/CLOCKS\u/SEC);
for(int i=0;i
另外,我想写这篇文章,而不必导入任何库。当然,时间就是我要测试的时间

import time
goal = int(input("Enter a number n, 1-1,000,000 to find the nth prime number."))
start = time.time()
if goal > 1000000:
    exit()

if goal > 4:
    lst = [2, 3, 5, 7]
    chk = 11
    primes = 4
    while primes < goal:
        for n in lst:
            if n > chk**.5:
                lst.append(chk)
                primes += 1
                break
            if chk % n == 0:
                break
        chk += 2

    else:
        print("The", str(goal), "prime number is:", str(chk - 2))

else:
    if goal == 1:
        print("2")
    if goal == 2:
        print("3")
    if goal == 3:
        print("5")
    if goal == 4:
        print("7")
elapsed = (time.time() - start)
print(elapsed)
导入时间
目标=int(输入(“输入一个数字n,1-1000000以查找第n个素数”)
开始=时间。时间()
如果目标>1000000:
退出()
如果目标>4:
lst=[2,3,5,7]
chk=11
素数=4
而primes<目标:
对于lst中的n:
如果n>chk**.5:
第一次追加(chk)
素数+=1
打破
如果chk%n==0:
打破
chk+=2
其他:
打印(“The”,str(goal),“prime number is:”,str(chk-2))
其他:
如果目标==1:
打印(“2”)
如果目标==2:
打印(“3”)
如果目标==3:
打印(“5”)
如果目标==4:
打印(“7”)
已用=(time.time()-start)
打印(已用)

如果您只关心前一百万个素数,最简单的解决方案是使用Eratosthenes筛预先计算前一百万个素数的列表,然后索引到列表中以找到第n个素数。下面是一个简单的Eratosthenes筛:

def primes(n): # sieve of eratosthenes
    i, p, ps, m = 0, 3, [2], n // 2
    sieve = [True] * m
    while p <= n:
        if sieve[i]:
            ps.append(p)
            for j in range((p*p-3)/2, m, p):
                sieve[j] = False
        i, p = i+1, p+2
    return ps
然后您可以轻松查找第n个素数:

def nthPrime(n):
    return ps[n-1]
以下是一些例子:

>>> nthPrime(1)
2
>>> nthPrime(10000)
104729
>>> nthPrime(1000000)
15485863

预计算前一百万个素数只需几秒钟,查找第n个素数是即时的。

这是谢谢的。把它放在那里就行了。这是一个数学问题和一个编程问题,已经被问过一百万次了。请先对这个问题做些研究。这不是让它检查n是否平均分为chk,意思是chk不是素数,然后将那个非素数添加到列表中?啊,如果找不到的话。明白了。另外,你需要从2FWW开始检查,在2.00GHz奔腾4上,我可以在大约12秒内用十几行代码完成这项工作。(如果我没有听在线音乐,它可能运行得更快)。
def nthPrime(n):
    return ps[n-1]
>>> nthPrime(1)
2
>>> nthPrime(10000)
104729
>>> nthPrime(1000000)
15485863