Quick actions

cmd+k|ctrl+k

Navigation

Languages

Sieve of Eratosthenes - Prime numbers algorithm

Snippet info

Language

Python

Visibility

public

Author

rajivm1991

Created

2021-08-10T04:42:35.809147Z

Updated

2021-08-10T04:42:35.809147Z

# prime numbers algorithm - Sieve of Eratosthenes

def primesBelowN(n):
  if n > 2:
    yield 2
  if n > 3:
    arr = [1] * (n-1)
    p = 2
    while p < n-1:
      start = inc = p
      while start + inc < n:
        start += inc
        arr[start-1] = 0
      # print(arr)
      found = False
      for i in range(p+1, n):
        if arr[i-1]:
          found = True
          p = i
          break
      if not found:
        break
      # print(p)
      yield p


# Memory Error for large values
print(list(primesBelowN(150)))
INFO