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:
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
- SegWit ELI5
- Fresh meme from Slovenia
- Calculating the n-th prime number in Python
- Maximalism vs Agorism
- Fuzzy logic (what if you couldn't trust your bits?)
- Mnemonics and Offline Transactions in Bitcoin Cash
- If I ran an "ICO" on Yours.org
- The Elephant in the Room
- Using Metcalfe's law to analyze BTC and BCH price
- I don't always buy bitcoin...
- More than 2000 transactions in Bitcoin mempool have a fee of $1000+
- A programmer that had to find himself again
- Dragonslayer, Yours.org, Cryptokitties
- bitcoincash2018.com
- 10 BTC seized by the US government
- Banned from r/CryptoCurrency
- Operation Dragonslayer: info from a hongkong investment banker 2.0.2S