【问题标题】:Printing prime numbers in range打印范围内的素数
【发布时间】:2020-06-20 12:51:15
【问题描述】:
k=int(input())
res=[2]
for i in range(2,k+1):
    if i%2==0:
       continue 
    else:
      for j in range(2,i):
          if i%j==0 or j%2==0 :
              break
      else:
             res.append(i)
print(res)

此代码用于查找给定数字范围内的素数。 我试图运行代码,但列表中只有 2 号。谁能告诉我发生了什么? 如果我删除 j%2==0 它正在工作。我只是想知道我的错误。

【问题讨论】:

  • 那么 j 将始终以 2 开头。你说如果 j % 2 == 0 然后中断。因为 j 将始终以 2 开始,所以此条件将始终为真,因为 2 % 2 将始终为 0。因此您将始终调用 break j 将永远不会增加超过 2

标签: python-3.x list for-loop if-statement primes


【解决方案1】:

在您的内部循环中j 变量从值 2 开始,然后您有一个始终为 True 的 if 语句,因为 j%2==0 始终为 2%2==0 始终为 True,因此您始终为 break从内部for循环迭代的第一步开始

你可以使用:

import math 

k=int(input())
res=[]
for i in range(2, k+1):
    for x in range(2, int(math.sqrt(i) + 1)):
        if i % x == 0 :
            break
    else:
        res.append(i)
# k = 20

输出:

[2, 3, 5, 7, 11, 13, 17, 19]

为了高效生成素数,您可以使用埃拉托色尼筛:

# Sieve of Eratosthenes
# Code by David Eppstein, UC Irvine, 28 Feb 2002
# http://code.activestate.com/recipes/117119/

def _gen_primes():
    """ Generate an infinite sequence of prime numbers.
    """
    # Maps composites to primes witnessing their compositeness.
    # This is memory efficient, as the sieve is not "run forward"
    # indefinitely, but only as long as required by the current
    # number being tested.
    #
    D = {}

    # The running integer that's checked for primeness
    q = 2

    while True:
        if q not in D:
            # q is a new prime.
            # Yield it and mark its first multiple that isn't
            # already marked in previous iterations
            # 
            yield q
            D[q * q] = [q]
        else:
            # q is composite. D[q] is the list of primes that
            # divide it. Since we've reached q, we no longer
            # need it in the map, but we'll mark the next 
            # multiples of its witnesses to prepare for larger
            # numbers
            # 
            for p in D[q]:
                D.setdefault(p + q, []).append(p)
            del D[q]

        q += 1

k=int(input())

def gen_primes(k):
    gp = _gen_primes()

    p = next(gp)
    while p < k:
        yield p
        p = next(gp)

res = list(gen_primes(k))

【讨论】:

    【解决方案2】:

    您应该使用您当前的结果来加速您的流程。您只需要测试素数的可分性。但是你正在建立一个素数列表。所以使用它!

    k=int(input())
    primes=[]
    for i in range(2,k+1):
        if all(i%p!=0 for p in primes):
            primes.append(i)
    

    您也可以像其他人建议的那样,只选择不如 sqrt(i) 的素数元素来改进。

    import math
    k=int(input())
    primes=[]
    for i in range(2,k+1):
        j=math.sqrt(i)
        if all(i%p!=0 for p in primes if p<=j):
            primes.append(i)
    

    【讨论】:

      【解决方案3】:

      您的代码有一个问题,在内部循环中,or 条件不正确,正如@kederrac 所强调的那样。你不需要 j%2==0 因为 j 总是从 2 开始,i%j==0 已经涵盖了条件

      k=int(input())
      res=[2]
      for i in range(2,k+1):
          if i%2==0:
             continue 
          else:
            for j in range(2,i):
                if i%j==0 :
                    break
            else:
                   res.append(i)
      print(res)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-20
        • 1970-01-01
        • 2021-12-28
        • 2011-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多