【问题标题】:Trouble finding the 1000th prime using python [duplicate]使用python查找第1000个素数时遇到问题[重复]
【发布时间】:2013-08-01 10:46:06
【问题描述】:

我正在从 MIT 开放课件网站自学 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)

【问题讨论】:

  • 如果这个数字能被 17 整除呢?还是 23 岁?
  • 不用说:你的方法在扩展方面存在一些问题。我建议你先用谷歌搜索一些不同的方法来计算素数。
  • 我还没有走到那一步,因为我想知道是否有更有效的方法来做到这一点。
  • 递归可能很容易。
  • 尝试用谷歌搜索关键字“埃拉托色尼筛”,然后尝试在代码中实现它,这将对 Euler 项目的其他问题很有用。

标签: python python-2.7


【解决方案1】:

您的代码存在一些问题,我将尝试指出:

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

因此,在此基础上,您可以使一切正常:

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

for循环中的p从何而来?

for x in something 是一个结构,它将遍历something 中的每个元素,并且对于每次迭代,它都会为您提供一个包含当前值的变量x。因此例如下面将分别打印123

for i in [1, 2, 3]:
    print(i)

或者对于素数列表,for p in primes 将遍历所有存储的素数,并且在每次迭代中,p 将是列表中的一个素数。

因此,整个检查基本上将遍历每个已知的素数,并且对于每个素数,它将检查所述素数是否是该数字的除数。如果我们找到一个素数,我们可以中止循环,因为当前数字本身肯定不是素数。

【讨论】:

  • 我仍然对 for 循环如何检查它是否是素数感到困惑。 for循环中的p从何而来,对x%p意味着什么?
  • 您的代码中有 x%2 等 - 模数运算符。 for p in primes 给出 p 中的每个素数
  • 我知道它是模运算符,但我很困惑“p”是什么。是随意分配的还是有功能的?
  • @StevenN 我在回答中对此作出了回应。
  • 感谢您修改您的答案,现在更清楚了:)。
【解决方案2】:

如前所述,您无需为您做所有事情,而是在prime 中建立一个素数列表,因此您可以使用它而不是硬编码来检查。

 prime = []
 x = 2
 while len(prime) < 1000:
     if *** check here ***
        prime.append(x)
     x = x + 1

【讨论】:

  • 我遇到的主要问题是试图找到一个适用于每个素数的检查......这似乎是不可能的。如果我正在为简单的编程而苦苦挣扎,我还想知道我是否应该主修计算机工程。
  • 不要惊慌——艰难的事情值得去做。我会使用 if all([x%p != 0 for p in prime]):prime.append(x) 但我想你还没有遇到“任何” - 所以使用史蒂夫巴恩斯的方式。
【解决方案3】:

当然有比链接所有ifs 更简洁的方法,你可以使用all

prime = []
x = 1
while len(prime) < 1000:
    x += 1
    if all(x%p for p in prime):
        prime.append(x) 

print prime

【讨论】:

    【解决方案4】:
    import time    
    start = time.time()
    
    primes = [2,]  # Initial list of primes
    l = 1  # No in the list
    n = 3  # First candidate
    while l < 10000:  # Target No
        Ok = True  # Assume it is
        for p in primes[1:1+l//2]:  # Check all in the first half of the list 
           if (n % p) == 0:  # Divides exactly
               Ok = False    # So not prime
               break         # Skip the rest
        if Ok:  # It was a prime
           primes.append(n)  # Add it
           l += 1            # and the count
           #print n
        n += 2  # Next non-even number
    end = time.time()
    print primes[-1]
    print 'took', end-start
    

    【讨论】:

    • 我们可以说 primes = [2] 吗?我确定 1 不是素数。然后你可以说 for p in primes
    • 是的,1 is not a prime
    • 抱歉 - 显示我现在的年龄 1 是几千年的素数,然后在 1950 年代后期被排除在外 - 当时我从中学到的很多书都被印刷了 - 正在修改。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    相关资源
    最近更新 更多