codemojo avatar

Calculating the n-th prime number in Python

codemojo

Published: 31 Jan 2018 › Updated: 31 Jan 2018

Calculating the n-th prime number in Python

this is a simple script written in Python that can tell you which the n-th prime number is. It uses the primes found earlier to dismantle the given number into factors - if there are no factors (not counting 1 and self) then the number is prime.

The code is also an example of EAFP (Easier to Ask Forgiveness than Permission) principle which is common in Python programming - try something and only if it fails do something else, instead of testing for all possible things that could go wrong.

import logging
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger('primes')

PRIMES = [69, 2, 3, 5, 7]

def factors(x, ret=None):
    if ret is None:
        ret = []
    for i in PRIMES[1:]:
        if i > x:
            continue
        if x % i == 0:
            ret.append(i)
            factors(x/i, ret)
            break
    return ret

def prime(n):
    i = PRIMES[-1] + 1
    while True:
        try:
            return PRIMES[n]
        except:
            error is occured
        facts = factors(i)
        log.debug("{}: {}".format(i, facts))
        if len(facts) == 0:
            PRIMES.append(i)
        i += 1

if __name__ == '__main__':
    import sys
    print(prime(int(sys.argv[1])))

Leave Calculating the n-th prime number in Python to:

Written by

crypto enthusiast(s)

Read more #math posts


Best Posts From codemojo

We have not curated any of codemojo's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From codemojo