Python Forum
sieve of eratosthenes implementation
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
sieve of eratosthenes implementation
#2
You can read wikipedia: Sieve of Eratosthenes.

In simple terms it is eliminating numbers which are not primes. Remaining numbers are primes.

Some dummy quick-and-dirty example to give general idea (skipped part where you actually find whether number is prime, provided in tuple):

- get numbers which are not primes
- get gaps between non-prime numbers (primes)

import heapq

def not_prime(max_value, stream=heapq.merge):
    """Yield non-primes under 100."""
    primes = (2, 3, 5, 7)    
    last = object()
    
    non_primes = (range(prime*2, max_value + 1, prime) for prime in primes)
    
    for el in stream(*non_primes):    # to eliminate duplicates
        if el != last:
            last = el
            yield el


def retrive_gaps(non_primes):
    "Yield gaps in non-prime numbers."
    last = 2
    yield last
    for x in non_primes:
        if x != last + 1:
            yield x - 1
        last = x
Practical usage is combining these two functions:

list(gap for gap in retrive_gaps(not_prime(100)))
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
RE: sieve of eratosthenes implementation - by perfringo - May-24-2019, 12:38 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020