Last active
April 30, 2017 07:37
-
-
Save nakagami/a732cefa43154c769be8c689b64149bd to your computer and use it in GitHub Desktop.
N 番目の素数を探す(Find Nth prime)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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