简体   繁体   English

找到第1000个素数(python)

[英]finding the 1000th prime (python)

I've tried working on this question using this code: 我尝试使用以下代码解决这个问题:

def nthprime(n):

    cnt=1
    count=0
    while(cnt==n):
        for i in range(3, ):
            for j in range(2, i):
                if i % j != 0:
                    count = count + 1
            if count == (i - 2):
                    cnt = cnt + 1
            return I

print(nthprime(1000))

Can anyone please tell me what's wrong with my code? 谁能告诉我我的代码有什么问题吗? It only returns "None" all the time. 它只会一直返回“无”。

Your code would be easier to understand if you split it in two functions 如果将代码分为两个函数,则代码将更容易理解

def is_prime(i):   
  if i == 2: return True  # 2 is a prime number
  for j in range(2,i):  # you could stop sooner (optimize)
    if i % j == 0: return False
  return True

def nthprime(n):
  i = 1
  count = 0
  while count < n:
    i += 1
    if is_prime(i): count += 1
  return i

for n in (1,2,3,4,5,6,7,8,9,10,100,1000):
  print( n, nthprime(n) )

When I run it, I get (in python2, add from __future__ import print_function ) 当我运行它时,我得到了(在python2中, from __future__ import print_function添加)

1 2
2 3
3 5
4 7
5 11
6 13
7 17
8 19
9 23
10 29
100 541
1000 7919    

You code has a few issues, as arif pointed out I is not initialized, the while loop will never run as cnt == n is not going to be valid etc. Rather than perfect your code i've got a slightly modified example of how to do what you want: 您的代码有一些问题,正如arif指出的那样,我尚未初始化,而while循环将永远不会运行,因为cnt == n无效。等等。不是完善您的代码,我有一个关于如何修改代码的示例做你想做的:

def nth_prime_number(n):
    prime_list = [2]
    num = 3
    while len(prime_list) < n:
        for p in prime_list:
            if num % p == 0:
                break
        else:
            prime_list.append(num)
        num += 2
    return prime_list[-1]

print(nth_prime_number(1000))

You could look at the differences between this example and your own code to understand where you went wrong. 您可以查看此示例与您自己的代码之间的区别,以了解哪里出错了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM