简体   繁体   English

进一步优化素数生成器

[英]optimization of prime number generator further

Python program to print the list of Prime number to a given limit, but the catch is that it has to print them by skipping a step. Python 程序将素数列表打印到给定的限制,但问题是它必须通过跳过一个步骤来打印它们。 it means that prime number till 20 will be: 2,3,5,7,11,13,17,19这意味着直到 20 的素数将是:2,3,5,7,11,13,17,19

but I have to print them by skipping a number that means: 2 5 11 17但我必须通过跳过一个数字来打印它们,这意味着:2 5 11 17

but using python generator function: I have written the code down below but I want to ask that is there any other way or can I further optimize it.但是使用 python 生成器 function:我已经在下面写了代码,但我想问有没有其他方法或者我可以进一步优化它。

def prime(n):
  lst = []
  newlist = []
  if n == 1:
       pass
       for i in range(2,n):
           for j in range(2,i//2+1):
                if i%j==0:
                   break
       else:
           lst.append(i)

  length = len(last)
  newlist = lst[0:length:1]


  for m in newlist:
     yield m 


for i in prime(20):
   print(i)

Improvements改进

  • Only need to check for a divisor up to sqrt(n) (this changes algorithmn complexity to O(n*sqrt(n)) rather than O(n^2)只需要检查直到 sqrt(n) 的除数(这会将算法复杂度更改为 O(n*sqrt(n)) 而不是 O(n^2)
  • Only need to check if prime odd numbers after two只需要检查两个后的素数奇数
  • Use a flag to toggle on every prime detection as an efficient way to decide which primes to report (avoids having to save primes in a list reducing storage complexity from O(n/ln n) to O(1)).使用一个标志来切换每个素数检测,作为决定报告哪些素数的有效方法(避免必须将素数保存在列表中,从而将存储复杂度从 O(n/ln n) 降低到 O(1))。

Code代码

def prime(n):
  '''
      Report every other prime up to n
  '''
  if n < 2:
    return  # No primes

  yield 2   # First prime (only even prime, rest are odd)
  
  report = False     # Report flag (toggle on each prime)
  for candidate in range(3, n, 2):
    # Check only odd numbers
    for divisor in range(2, int((candidate**0.5) + 1)):
        if candidate % divisor == 0:
            break
    else:
        # No divisors found so prime (i.e. did not hit break)
        if report:    # Report this prime
            yield candidate
            
        report = not report   # Toggle report flag (don't report next prime)
                     
for i in prime(20):
   print(i, end = ' ')

# Out: 2 5 11 17

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

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