Skip to content

Commit

Permalink
Merge pull request #15 from sjakobi/nth-prime
Browse files Browse the repository at this point in the history
New exercise: python nth-prime
  • Loading branch information
kytrinyx committed Mar 22, 2014
2 parents 752de4d + b3a1417 commit 8c3bc11
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions EXERCISES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ palindrome-products
triangle
scrabble-score
sieve
nth-prime
luhn
roman-numerals
binary
Expand Down
31 changes: 31 additions & 0 deletions nth-prime/example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from itertools import count
from math import sqrt


def nth_prime(n):
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
25 changes: 25 additions & 0 deletions nth-prime/nth_prime_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
try:
from prime import nth_prime
except ImportError:
raise SystemExit('Could not find prime.py. Does it exist?')

import unittest


class NthPrimeTests(unittest.TestCase):
def test_first_prime(self):
self.assertEqual(2, nth_prime(1))

def test_sixth_prime(self):
self.assertEqual(13, nth_prime(6))

def test_first_twenty_primes(self):
self.assertEqual([2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71],
[nth_prime(n) for n in range(1, 21)])

def test_prime_no_10000(self):
self.assertEqual(104729, nth_prime(10000))


if __name__ == '__main__':
unittest.main()

0 comments on commit 8c3bc11

Please sign in to comment.