如何在python中生成第1000个素数?

时间:2016-08-18 00:38:53

标签: python-2.7

candidate = 1
prime_counter = 1

while prime_counter < 1000:
    test = 2
    candidate = candidate + 2

    while candidate%test > 0:
        test = test + 1

    if candidate == test:
            prime_counter = prime_counter + 1

print "The 1000th prime is: " + str(candidate)

我试图通过MIT OCW在python中生成第1000个素数。我在互联网上找到了这个代码并且它有效,但我并不完全理解它。有人可以一步一步地向我解释这段代码的工作原理吗?

2 个答案:

答案 0 :(得分:0)

candidate = 1 #this is the number to test for prime-ness
prime_counter = 1 #this is the number of primes we have found

while prime_counter < 1000: #only look for prime numbers until we have found the 1000th one
    test = 2 #this is the number we will divide the candidate by - start with 2 and work our way up
    candidate = candidate + 2 #heurisitic - only test odd numbers for prime-ness

    while candidate%test > 0: #find the lowest number that the candidate is divisible by exactly - % finds the remainder
        test = test + 1 #this did not divide exactly, increment the test value by 1

    if candidate == test: #is the only number that is divisble by candidate the candidate itself (definition of prime)?
            prime_counter = prime_counter + 1 #increment the number of primes we have found

print "The 1000th prime is: " + str(candidate) #print the result

无论如何,这是效率极低的代码。你应该尝试类似于Erasthosthenes的筛子 - https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

答案 1 :(得分:0)

当你在test = 2循环之前直接移动while行两行时,程序可能会更加清晰。

然后,此块通过搜索均匀分割candidate的最小数字来确定candidate是否为素数。例如,当候选人是25时,test将是5.但是当候选人是29时,test也将是29,因为没有较小的数字均匀地划分它。 (除了1,这就是test从2开始的原因。)

在理解了这一部分后,您只需要了解对于找到的每个候选人,计数器都会递增。如果该计数器为1000,则表示candidate保持第1000个素数。

顺便说一句,这个程序通过将1视为素数而不是2来作弊。但对于所有大于2的数字,它都有效。