Created
February 9, 2014 21:42
-
-
Save thoolihan/8906371 to your computer and use it in GitHub Desktop.
Python Primes
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
#!/usr/bin/env python | |
import sys | |
import locale | |
locale.setlocale(locale.LC_ALL, 'en_US') | |
def is_prime_brute(n): | |
for x in range(2, n / 2 + 1): | |
if n % x == 0: | |
return False | |
return True | |
def is_prime_sieve(n, primes): | |
for x in primes: | |
for y in range(2, n / 2 + 1): | |
z = x * y | |
if z > n: | |
break | |
if z in primes: | |
primes.remove(z) | |
return n in primes | |
def is_prime_sieve2(n, primes): | |
x = 2 | |
while x <= n / 2 + 1: | |
if x in primes: | |
for y in range(2 * x, n, x): | |
if y in primes: | |
primes.remove(y) | |
x += 1 | |
def pline(msg, n=30): | |
print "=" * n | |
print msg | |
print "=" * n | |
def test(limit, alg): | |
primes = range(2,limit) | |
pline("using " + alg) | |
if alg == 'brute': | |
primes = [i for i in primes if is_prime_brute(i)] | |
elif alg == 'sieve': | |
is_prime_sieve(limit, primes) | |
else: | |
is_prime_sieve2(limit, primes) | |
format = "%" + ("%d" % (len(locale.format("%d", limit, grouping=True)) + 1)) + "d" | |
count = 0 | |
for p in primes: | |
if count > 0 and count % 10 == 0: | |
print "" | |
sys.stdout.write(locale.format(format, p, grouping=True)) | |
count += 1 | |
print "" | |
pline("%d primes between 2 and %d" % (count, limit)) | |
test(int(sys.argv[1]), sys.argv[2]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment