Skip to content

Instantly share code, notes, and snippets.

@nakagami
Last active April 30, 2017 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nakagami/a732cefa43154c769be8c689b64149bd to your computer and use it in GitHub Desktop.
Save nakagami/a732cefa43154c769be8c689b64149bd to your computer and use it in GitHub Desktop.
N 番目の素数を探す(Find Nth prime)
import math
def _is_prime_slow(prime_candidate):
for i in range(2, prime_candidate - 1):
if prime_candidate % i == 0:
return False
return True
def nthprime_slow(nth):
primes = [2]
next_prime_candidate = 3
while len(primes) < nth:
if _is_prime_slow(next_prime_candidate):
primes.append(next_prime_candidate)
next_prime_candidate += 1
return primes[-1]
def _is_prime(prime_candidate, primes):
sqrt = int(math.sqrt(prime_candidate))
for i in primes:
if sqrt < i:
break
if prime_candidate % i == 0:
return False
return True
def nthprime(nth):
primes = [2]
next_prime = 3
while len(primes) < nth:
if _is_prime(next_prime, primes):
primes.append(next_prime)
next_prime += 2
return primes[-1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment