Skip to main content
Code Review

Return to Answer

deleted 1 character in body
Source Link
SylvainD
  • 29.7k
  • 1
  • 49
  • 93

**Tests **Tests

**Tests **

Tests

replaced http://stackoverflow.com/ with https://stackoverflow.com/
Source Link

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 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.

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.

added 754 characters in body
Source Link
SylvainD
  • 29.7k
  • 1
  • 49
  • 93

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)
added 1176 characters in body
Source Link
SylvainD
  • 29.7k
  • 1
  • 49
  • 93
Loading
added 942 characters in body
Source Link
SylvainD
  • 29.7k
  • 1
  • 49
  • 93
Loading
added 661 characters in body
Source Link
SylvainD
  • 29.7k
  • 1
  • 49
  • 93
Loading
Source Link
SylvainD
  • 29.7k
  • 1
  • 49
  • 93
Loading
lang-py

AltStyle によって変換されたページ (->オリジナル) /