___  ___    _ _    _  _ _____   _____
 / __|/ _ \  | | |  | || |_ _\ \ / / __|
| (_ | (_) | |_  _| | __ || | \ V /| _|
 \___|\___/    |_|  |_||_|___| \_/ |___|

 --- A GOPHER-LIKE INTERFACE FOR HIVE BLOCKCHAIN ---

Calculating the n-th prime number in Python

BY: @codemojo | CREATED: Jan. 31, 2018, 3:24 p.m. | VOTES: 4 | PAYOUT: $0.15 | [ VOTE ]

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])))
TAGS: [ #math ] [ #prime ] [ #numbers ] [ #python ] [ #algorithms ]

Replies

@kryzsec | Feb. 1, 2018, 12:09 a.m. | Votes: 1 | [ VOTE ]

Except 1 is not a prime number.

@codemojo | Feb. 1, 2018, 5:14 a.m. | Votes: 0 | [ VOTE ]

PRIMES[170] = 1

We start counting with number 42.

@datatreemap | Feb. 1, 2018, 12:29 p.m. | Votes: 1 | [ VOTE ]

Python is a nice programming language for beginners!

[ BACK TO TRENDING ] [ BACK TO MENU ]
CMD>