Skip to content

Instantly share code, notes, and snippets.

@pfreixes
Created April 4, 2015 17:36
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 pfreixes/ac9974bde0dcfe500f5a to your computer and use it in GitHub Desktop.
Save pfreixes/ac9974bde0dcfe500f5a to your computer and use it in GitHub Desktop.
Because the way matters #python and prime numbers
N = 100000
# First approximation, brute force
def is_prime(number):
if number == 2:
return True
for x in range(2, number/2+1):
if number % x == 0:
return False
return True
for i in range(2, N+1):
if is_prime(i):
print i
# A bit of python sauce to avoid the slow velocity of Python
def is_prime(x):
if x == 2:
return True
for d in xrange(2, x/2 + 1):
if x % d == 0:
return False
print x
map(is_prime, [x for x in xrange(1, N+1)])
# Memoization
primes = []
def is_prime(number, primes):
if number == 2:
return True
for prime in primes:
if number % prime == 0:
return False
return True
for i in range(2, N+1):
if is_prime(i, primes):
primes.append(i)
# it's the math stupid !!!
def primes_sieve(limit):
limitn = limit+1
not_prime = set()
primes = []
for i in range(2, limitn):
if i in not_prime:
continue
for f in range(i*2, limitn, i):
not_prime.add(f)
primes.append(i)
return primes
primes_sieve(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment