Last active
August 29, 2015 14:11
-
-
Save ebartrum/a7e18fe9fa361872bd19 to your computer and use it in GitHub Desktop.
A solution to the 7th Project Euler problem
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 time | |
#Define a function which checks if any members of x divide y (If so return True, otherwise False) but only checks up to the squareroot of y (This greatly improves efficiency). | |
#In other words if the function finds a member of x that is >= the sqrt of y it stops looking and returns the current state (ans) | |
def divis(x,y): | |
ans=False | |
for z in x: | |
if y%z==0: | |
ans=True | |
break | |
if z>=y**0.5+1: | |
break | |
return ans | |
#Define a generator to generate primes: | |
def primeGenerator(): | |
yield 2 | |
primes=[2] | |
n=3 | |
while True: | |
if divis(primes,n): | |
n+=2 | |
else: | |
yield n | |
primes.append(n) | |
n+=2 | |
#Define a function to give the nth prime. | |
def nthPrime(n): | |
z=primeGenerator() | |
for i in range(n): | |
ans=next(z) | |
return ans | |
start = time.time() | |
prime = nthPrime(10001) | |
elapsed = (time.time() - start) | |
print("found " + str(prime) + " in " + str(elapsed) + " seconds") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment