简体   繁体   English

打印范围内的素数

[英]Printing prime numbers in range

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)

This code is for finding prime numbers in a given range of numbers.此代码用于在给定的数字范围内查找素数。 I tried to run the code but the list is having only number 2. Can anyone tell me what is happening?我试图运行代码,但列表只有第 2 个。谁能告诉我发生了什么? If I remove j%2==0 it's working.如果我删除j%2==0它正在工作。 I just want to know my mistake.我只想知道我的错误。

You should use your current result to accelerate your process.您应该使用当前的结果来加速您的过程。 You only need to test divisibility by primes.您只需要测试素数的整除性。 But you are building a list of primes.但是你正在建立一个质数列表。 So use it !所以使用它!

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

You can also improve by selecting only prime elements which are inferior to sqrt(i) like others suggested.您还可以通过仅选择不如其他人建议的 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)

in your inner loop j variable starts from value 2 and then you have an if statement that is always True because j%2==0 is always 2%2==0 which is always True , so you always break from the first step of inner for loop iteration在您的内部循环j变量从值 2 开始,然后您有一个 if 语句始终为True因为j%2==0始终为2%2==0始终为True ,因此您总是从第一步break内部for循环迭代

you can use:您可以使用:

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

output:输出:

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

for efficient prime generation, you can use the Sieve of Eratosthenes:为了有效地生成素数,您可以使用埃拉托色尼筛法:

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

Your code had one issue, in the inner loop the or condition is incorrect, as highlighted by @kederrac.您的代码有一个问题,在内部循环中 or 条件不正确,正如@kederrac 所强调的那样。 You don't need the j%2==0 as j always start from 2 and i%j==0 already covers the condition您不需要 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM