简体   繁体   中英

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. it means that prime number till 20 will be: 2,3,5,7,11,13,17,19

but I have to print them by skipping a number that means: 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.

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)
  • 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)).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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