我刚刚开始编程,我的第一个个人任务是找到第1000个素数。我认为这段代码是正确的,但它列出了前1000个奇数。有什么见解吗?
count = 1
num = 3
prime = [2]
while count <= 1000:
for x in range(2, num + 1):
if num % x == 0 and num == x:
prime.append(num)
num += 2
count += 1
print(prime[1000])
答案 0 :(得分:0)
我刚刚写了这篇文章。它会问你有多少素数用户想看,在这种情况下它会是1000.随意使用它:)。
# p is the sequence number of prime series
# n is the sequence of natural numbers to be tested if prime or not
# i is the sequence of natural numbers which will be used to devide n for testing
# L is the sequence limit of prime series user wants to see
p=2;n=3
L=int(input('Enter the how many prime numbers you want to see: '))
print ('# 1 prime is 2')
while(p<=L):
i=2
while i<n:
if n%i==0:break
i+=1
else:print('#',p,' prime is',n); p+=1
n+=1 #Line X
#when it breaks it doesn't execute the else and goes to the line 'X'
答案 1 :(得分:-1)
import math
def is_prime(a):
for i in xrange(2, int(math.sqrt(a)+1)):
if a%i == 0:
return False
return True
primes=[]
count = 2
while len(primes) < 1000:
if is_prime(count):
primes.append(count)
count += 1
print(primes)`