MIT开放课程代码在Python中寻找第1000个质数不工作?

-2 投票
2 回答
1438 浏览
提问于 2025-04-18 03:52

我刚开始学习编程,我的第一个个人作业是找出第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])

2 个回答

-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)`

当然可以!不过你没有提供具体的内容,我无法进行翻译。如果你能把需要翻译的内容发给我,我会很乐意帮你把它变得简单易懂。

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' 

撰写回答