查找任何未按预期工作的质数的代码

Code to find any prime number not working as expected

我写了这段 python 代码来查找任何质数,第 1、2、1000 等。我 运行 代码并返回了这个,无论我输入什么整数:

2 is the 1 prime
3 is the 2 prime
5 is the 3 prime
7 is the 4 prime

这是代码(写在python 2.7.8):

 #code to find the nth prime
def isprime(n):
    '''check if integer n is a prime'''
    # make sure n is a positive integer
    n = abs(int(n))
    # 0 and 1 are not primes
    if n < 2:
        return False
        # 2 is the only even prime number
    if n == 2:
        return True
        # all other even numbers are not primes
    if not n:
        return False
        # range starts with 3 and only needs to go up the squareroot of n for all odd numbers
    for x in range(3, int(n**0.5)+1, 2):
        if n % x == 0:
            return False
    return True
num_ofprimes = 0
candidate_prime = 2
final_primes = raw_input("What prime would you like to find?")
while num_ofprimes <= final_primes:
    if isprime(candidate_prime) == True:
        if candidate_prime == 2:
            num_ofprimes = num_ofprimes + 1
            print (str(candidate_prime) + " is the " + str(num_ofprimes) + " prime")
            candidate_prime = candidate_prime + 1
            #2 is prime
        elif candidate_prime % 2 == 0:
            candidate_prime = candidate_prime + 1
            #if a number is even it is not prime
        else:
            num_ofprimes = num_ofprimes + 1
            print (str(candidate_prime) + " is the " + str(num_ofprimes) + " prime")
            candidate_prime = candidate_prime + 1
            # checks all odd numbers to see if prime then prints out if true
print ("All done!")

你的程序在找到前几个素数后并没有停止,而是进入了一个无限循环,不再产生输出。这样做的原因是,如果您的 isprime 检查失败,您永远不会增加 candidate_prime 变量!

此外,如评论中所述,您应该将 num_ofprimesint(final_primes) 进行比较;否则你就是在比较 intstr,这很像比较苹果和橙子。

最后,您应该将检查数字是否为偶数放在 isprime 函数中。这不仅会让你的 isprime 函数实际上 return 正确的偶数结果,而且还会使你的代码更紧凑,因为你不再需要所有那些 if/elif/else 块在你的 if isprime 支票下方。

除了托比亚斯的重要评论外,您似乎无缘无故地在脚本中做了很多额外的工作。 while 循环可以简化为:

while num_ofprimes < final_primes:
    if isprime(candidate_prime):
            num_ofprimes = num_ofprimes + 1
            print (str(candidate_prime) + " is the " + str(num_ofprimes) + " prime")
    candidate_prime = candidate_prime + 1
for num in range(3, 1000):
    if num > 1:
        for i in range(2, num):
            if (num % i) == 0:
                break
        else:
            print(num)