**Tests **Tests
**Tests **
Tests
At the moment, when one imports your code, he gets the prompt and everything. The usual way to do is to put the code "actually doing something" behind an if-main guard.
At the moment, when one imports your code, he gets the prompt and everything. The usual way to do is to put the code "actually doing something" behind an if-main guard.
Some math to make the code faster
At the moment, we check the primality of each and every odd numbers. We can do better by considering division by 6 : all numbers can be written :
6k + 0 -> divisible by 2 & 3
6k + 1 -> potential prime
6k + 2 -> divisible by 2
6k + 3 -> divisible by 3
6k + 4 -> divisible by 2
6k + 5 -> potential prime
Thus, except for the obvious pair (3, 5), the only way two prime numbers can be separated by two are if they can be written (6k + 5, 6k + 7).
Once you have this, the code pretty much writes itself :
def yield_twin_pairs():
yield (3, 5)
for i in itertools.count(5, 6):
if isprime(i) and isprime(i+2):
yield (i, i+2)
Some math to make the code faster
At the moment, we check the primality of each and every odd numbers. We can do better by considering division by 6 : all numbers can be written :
6k + 0 -> divisible by 2 & 3
6k + 1 -> potential prime
6k + 2 -> divisible by 2
6k + 3 -> divisible by 3
6k + 4 -> divisible by 2
6k + 5 -> potential prime
Thus, except for the obvious pair (3, 5), the only way two prime numbers can be separated by two are if they can be written (6k + 5, 6k + 7).
Once you have this, the code pretty much writes itself :
def yield_twin_pairs():
yield (3, 5)
for i in itertools.count(5, 6):
if isprime(i) and isprime(i+2):
yield (i, i+2)