Write a Python program to print all twin primes less than N

Hi!, In this article, we are going to write a Python program to find and print all the Twin Primes less than the user input N.

What are Twin Primes?

We know that Prime Numbers are the numbers that have exactly 2 Factors. The two Factors are 1 and Number itself.

The Pairs of Primes that differ by two are known as Twin Primes.
Examples are (3, 5), (5, 7), (11, 13) and so on.

There are infinitely many Twin Primes in the Number System.

Print all the Twin Primes under N in Python

Let us define a function isPrime which takes a number as input and returns True when its is prime and returns None when it is not a prime.

Declare and initialize the variable count to Zero. Here, we use the count variable to count the number of Factors of a Number. We are going to increase the value of count whenever we find a factor for the given number.

If the count equals 2 then we can say that the number is prime and the function is defined to return True.

Now, take the input N from the user.

Initialize a variable n to 2. As the least prime number is 2.

Write a while loop with the condition n < N. As we want the twin primes below N.

If isPrime(n) and isPrime(n+2) both equals True, print the numbers n and n+2.
Else Increase the value of n by 1.

The while loop iteration occurs as long the value of n is less than prints the values of Twin Primes less than N.

def isPrime(a) :
    count = 0
    for i in range(1, a+1) :
        if a % i == 0 :
            count = count + 1
        if count == 2:
            return True
n = 2
N = int(input("Enter the value of N : "))
while n < N :
    if isPrime(n) == True and isPrime(n+2) == True:
        print("({0},{1})".format(n, n+2), end = "    ")
    n = n + 1

Input :

Enter the value of N : 1000

Output :

(3,5) (5,7) (11,13) (17,19) (29,31) (41,43) (59,61) (71,73) (101,103) (107,109) (137,139) (149,151) (179,181) (191,193) (197,199) (227,229) (239,241) (269,271) (281,283) (311,313) (347,349) (419,421) (431,433) (461,463) (521,523) (569,571) (599,601) (617,619) (641,643) (659,661) (809,811) 
(821,823) (827,829) (857,859) (881,883)


Hurrah! We just learnt how to wrote a program to print all the Twin Primes below a number N. Thank you for reading the article. I hope you found this article useful. Also, do check out other related articles below :

Python Program to find the smallest missing prime number in an array

Check if a number is Euler Pseudoprime in Python




Leave a Reply

Your email address will not be published. Required fields are marked *