Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New exercise: python nth-prime #15

Merged
merged 1 commit into from
Mar 22, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions EXERCISES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ gigasecond
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()