How to generate prime twins using Python?


Twin primes are pairs of primes which differ by two. The first twin primes are {3,5}, {5,7}, {11,13} and {17,19}. You can generate prime twins in python by running a for loop and checking for primality of the numbers as you do so. 

example

def is_prime(n):
   for i in range(2, n):
      if n % i == 0:
         return False
   return True

def generate_twins(start, end):
   for i in range(start, end):
      j = i + 2
      if(is_prime(i) and is_prime(j)):
         print("{:d} and {:d}".format(i, j))

generate_twins(2, 100)

Output

This will give the output −

3 and 5
5 and 7
11 and 13
17 and 19
29 and 31
41 and 43
59 and 61
71 and 73

Updated on: 05-Mar-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements