简体   繁体   中英

avoid for/else in this prime numbers generator function, use pure for loop

I am doing an exercise about generator to generate prime numbers.

Even though I've got a solution about this problem. I wonder if I don't know or want to use for/else loop. How can I make it with only for loop.

def genPrimes(): 
    primes = [] # primes generated so far 
    last = 1 # last number tried 
    while True: 
        last += 1 
        for p in primes: 
            if last % p == 0: 
                break 
        else: 
            primes.append(last) 
            yield last

You can use recursive functions if you want to:

def prime_number(n, d):
    if n//2 < d:
      return True
    if n%d == 0:
      return False
    return prime_number(n, d+1)

def find_primes(n,i, result):
  if i == n + 1:
    return result
  if prime_number(i, 2):
    result.append(i)
  return find_primes(n, i+1, result)

print(find_primes(100,2, []))

Using loops is better here because its simpler and avoids stack overflow;)

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