loading...

re: 10001st prime - Project Euler Soution VIEW POST

FULL DISCUSSION
 

Using the Python extensible prime generator: "Iterative sieve on unbounded count from 2" function prime_sieve as posted on Rosetta Code.

from itertools import count, islice
 
def prime_sieve():
    sieved = count(2)
    prime = next(sieved)
    yield prime
    primes = [prime]
    for x in sieved:
        if any(x % prime == 0 for prime in primes):
            continue
        yield x
        primes.append(x)
 
if __name__ == '__main__':
    print("Show the 10,001st prime.\n   =",
        next(islice(prime_sieve(), 10_000, 10_001)))
 

Modified to test less primes:

from itertools import count, islice, takewhile
 
def prime_sieve2():
    sieved = count(2)
    prime = next(sieved)
    yield prime
    primes = [prime]
    for x in sieved:
        possible_prime_divs = takewhile(lambda p: p <= x**0.5, primes)
        if any(x % prime == 0 for prime in possible_prime_divs):
            continue
        yield x
        primes.append(x)

if __name__ == '__main__':
    print("Show the 10,001st prime.\n   =",
        next(islice(prime_sieve2(), 10_000, 10_001)))
Code of Conduct Report abuse