Sha256: 3b0799fbbf247ca7f841ad150adecf5d1a418a896ef50c977b03a4b3246dab33

Contents?: true

Size: 664 Bytes

Versions: 258

Compression:

Stored size: 664 Bytes

Contents

from itertools import count
from math import sqrt


def nth_prime(n):
    if n < 1:
        raise ValueError('The parameter `n` has to be a positive number.')

    known = []
    candidates = prime_candidates()

    def is_prime(m):
        sqrt_m = sqrt(m)
        for k in known:
            if k > sqrt_m:
                return True
            elif m % k == 0:
                return False
        return True

    while len(known) < n:
        x = next(candidates)
        if is_prime(x):
            known.append(x)

    return known[n - 1]


def prime_candidates():
    yield 2
    yield 3
    for n in count(6, 6):
        yield n - 1
        yield n + 1

Version data entries

258 entries across 258 versions & 1 rubygems

Version Path
trackler-2.2.1.159 tracks/python/exercises/nth-prime/example.py
trackler-2.2.1.158 tracks/python/exercises/nth-prime/example.py
trackler-2.2.1.157 tracks/python/exercises/nth-prime/example.py
trackler-2.2.1.156 tracks/python/exercises/nth-prime/example.py
trackler-2.2.1.155 tracks/python/exercises/nth-prime/example.py
trackler-2.2.1.154 tracks/python/exercises/nth-prime/example.py
trackler-2.2.1.153 tracks/python/exercises/nth-prime/example.py
trackler-2.2.1.152 tracks/python/exercises/nth-prime/example.py
trackler-2.2.1.151 tracks/python/exercises/nth-prime/example.py
trackler-2.2.1.150 tracks/python/exercises/nth-prime/example.py
trackler-2.2.1.149 tracks/python/exercises/nth-prime/example.py
trackler-2.2.1.148 tracks/python/exercises/nth-prime/example.py
trackler-2.2.1.147 tracks/python/exercises/nth-prime/example.py
trackler-2.2.1.146 tracks/python/exercises/nth-prime/example.py
trackler-2.2.1.145 tracks/python/exercises/nth-prime/example.py
trackler-2.2.1.144 tracks/python/exercises/nth-prime/example.py
trackler-2.2.1.143 tracks/python/exercises/nth-prime/example.py
trackler-2.2.1.142 tracks/python/exercises/nth-prime/example.py
trackler-2.2.1.141 tracks/python/exercises/nth-prime/example.py
trackler-2.2.1.140 tracks/python/exercises/nth-prime/example.py