[英]MIT Open Course Code for finding 1000th Prime Number in Python Not working?
I am just starting out on programming and my first personal assignment is to find the 1000th prime number.我刚刚开始编程,我的第一个个人任务是找到第 1000 个质数。 I think this code is correct, but it lists the first 1000 odd numbers instead.
我认为这段代码是正确的,但它列出了前 1000 个奇数。 Any insight?
任何见解?
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])
I just wrote this one.我刚写了这个。 It will ask you how many prime number user wants to see, in this case it will be 1000. Feel free to use it :).
它会问你用户想要看到多少个素数,在这种情况下它将是 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'
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)`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.