我编写了这个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!")
答案 0 :(得分:1)
你的程序在找到前几个素数之后不会停止,但它会进入一个无限循环,不再产生输出。这样做的原因是,如果您的isprime
检查失败,则永远不会增加candidate_prime
变量!
此外,正如评论中所述,您应该将num_ofprimes
与int(final_primes)
进行比较;否则,您要将int
与str
进行比较,这非常类似于将苹果与橙子进行比较。
最后,您应该检查数字是否在isprime
函数内。这不仅可以使您的isprime
函数实际返回偶数数字的正确结果,而且还可以使您的代码更加紧凑,因为您不再需要if/elif/else
块以下的所有if isprime
块1}}检查。
答案 1 :(得分:0)
除了tobias的重要评论之外,您似乎无缘无故地在脚本中做了很多额外的工作。 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
答案 2 :(得分:0)
for num in range(3, 1000):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)