我是从麻省理工学院开放课件网站自学Python.我只使用讲座中学到的信息完成这项任务时遇到了麻烦.我学到的最后一件事是使用"While"和"For"循环的迭代.我还没有学过功能.是否可以编写一个程序来计算和打印第1000个素数只用这个?
到目前为止,这是我的代码:
count = 0
prime = []
candidate = []
x = 2
y = 1
while count < 1000:
x = x+1
if x > 1:
if x%2 != 0:
if x%3 != 0:
if x%5 != 0:
if x%7 != 0:
if x%11 != 0:
if x%13 != 0:
candidate.append(x)
Run Code Online (Sandbox Code Playgroud)
你的代码有一些问题我会试着指出:
count = 0
prime = [] # this is obviously meant to collect all primes
candidate = [] # what is this supposed to do then though?
x = 2
y = 1 # never used
while count < 1000: # you start at `count = 0` but never increase the count
# later on, so would loop forever
x = x+1
if x > 1: # x is always bigger than 1 because you started at 2
# and only increase it; also, you skipped 2 itself
if x%2 != 0: # here, all you do is check if the
if x%3 != 0: # number is dividable by any prime you
if x%5 != 0: # know of
if x%7 != 0: # you can easily make this check work
if x%11 != 0: # for any set (or list) of primes
if x%13 != 0: #
candidate.append(x) # why a candidate? If it’s
# not dividable by all primes
# it’s a prime itself
Run Code Online (Sandbox Code Playgroud)
因此,在此基础上,您可以完成所有工作:
primes = [2] # we're going to start with 2 directly
count = 1 # and we have already one; `2`
x = 2
while count < 1000:
x += 1
isPrime = True # assume it’s a prime
for p in primes: # check for every prime
if x % p == 0: # if it’s a divisor of the number
isPrime = False # then x is definitely not a prime
break # so we can stop this loop directly
if isPrime: # if it’s still a prime after looping
primes.append(x) # then it’s a prime too, so store it
count += 1 # and don’t forget to increase the count
Run Code Online (Sandbox Code Playgroud)
for循环中的p来自何处?
for x in something是一个构造,它将遍历something每个迭代中的每个元素,并为每个迭代提供一个x包含当前值的变量.因此,例如下面将分别打印1,2,3.
for i in [1, 2, 3]:
print(i)
Run Code Online (Sandbox Code Playgroud)
或者对于素数列表,for p in primes将遍历所有存储的素数,并且在每次迭代p中将是列表中的一个素数.
因此,整个检查将基本上遍历每个已知的素数,并且对于每个素数,它将检查所述素数是否是数字的除数.如果我们找到一个这样的素数,我们可以中止循环,因为当前的数字肯定不是素数本身.