Created
April 4, 2015 17:36
-
-
Save pfreixes/ac9974bde0dcfe500f5a to your computer and use it in GitHub Desktop.
Because the way matters #python and prime numbers
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
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