Created
January 20, 2011 14:35
-
-
Save michaelcontento/787967 to your computer and use it in GitHub Desktop.
Detect prime twins in python
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 | |
from itertools import izip, tee | |
from sys import argv, exit | |
def pairwise(iter): | |
# See: http://docs.python.org/library/itertools.html#recipes | |
a, b = tee(iter) | |
next(b, None) | |
return izip(a, b) | |
def primes(stop): | |
# See: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes | |
sieve = [True for i in xrange(stop + 1)] | |
for i in xrange(2, stop + 1): | |
if sieve[i]: | |
for j in xrange(i + i, stop + 1, i): | |
sieve[j] = False | |
return [i for i in xrange(1, stop + 1) if sieve[i]] | |
if len(argv) is not 3: | |
print 'usage: %s start stop' % argv[0] | |
exit(1) | |
start = max(2, int(argv[1])) | |
stop = int(argv[2]) | |
for (a, b) in pairwise(primes(stop)): | |
if a < start: | |
continue | |
if b - a == 2: | |
print '%d\t%d' % (a, b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment