0
0
PythonProgramBeginner · 2 min read

Python Program to Check Twin Prime Numbers

To check twin prime numbers in Python, write a function to test if both numbers are prime and if their difference is 2, like def is_twin_prime(a, b): return is_prime(a) and is_prime(b) and abs(a - b) == 2.
📋

Examples

Input3, 5
Output3 and 5 are twin primes
Input11, 13
Output11 and 13 are twin primes
Input17, 20
Output17 and 20 are not twin primes
🧠

How to Think About It

First, check if each number is prime by testing divisibility from 2 up to its square root. Then check if the two numbers differ by exactly 2. If both conditions are true, they are twin primes.
📐

Algorithm

1
Get two numbers as input
2
Check if the first number is prime
3
Check if the second number is prime
4
Check if the absolute difference between the two numbers is 2
5
If all conditions are true, return that they are twin primes; otherwise, return they are not
💻

Code

python
def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

def is_twin_prime(a, b):
    return is_prime(a) and is_prime(b) and abs(a - b) == 2

x, y = 11, 13
if is_twin_prime(x, y):
    print(f"{x} and {y} are twin primes")
else:
    print(f"{x} and {y} are not twin primes")
Output
11 and 13 are twin primes
🔍

Dry Run

Let's trace the example (11, 13) through the code

1

Check if 11 is prime

Test divisibility from 2 to 3 (sqrt of 11). No divisor found, so 11 is prime.

2

Check if 13 is prime

Test divisibility from 2 to 3 (sqrt of 13). No divisor found, so 13 is prime.

3

Check difference

Absolute difference between 11 and 13 is 2.

4

Result

Both numbers are prime and difference is 2, so they are twin primes.

NumberDivisor TestedIs Prime?
112,3Yes
132,3Yes
💡

Why This Works

Step 1: Prime Check

The function is_prime checks if a number has any divisor other than 1 and itself by testing up to its square root.

Step 2: Difference Check

Twin primes differ by exactly 2, so the code checks if the absolute difference between the two numbers is 2.

Step 3: Combined Condition

Only if both numbers are prime and their difference is 2, the function returns True indicating twin primes.

🔄

Alternative Approaches

Using a sieve to precompute primes
python
def sieve(n):
    primes = [True] * (n+1)
    primes[0], primes[1] = False, False
    for i in range(2, int(n**0.5)+1):
        if primes[i]:
            for j in range(i*i, n+1, i):
                primes[j] = False
    return primes

primes = sieve(100)

def is_twin_prime(a, b):
    return primes[a] and primes[b] and abs(a - b) == 2

x, y = 17, 19
if is_twin_prime(x, y):
    print(f"{x} and {y} are twin primes")
else:
    print(f"{x} and {y} are not twin primes")
This method is faster for checking many numbers but uses extra memory for the sieve array.
Check only odd numbers and skip even
python
def is_prime(n):
    if n <= 1:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    for i in range(3, int(n**0.5)+1, 2):
        if n % i == 0:
            return False
    return True

def is_twin_prime(a, b):
    return is_prime(a) and is_prime(b) and abs(a - b) == 2

x, y = 29, 31
if is_twin_prime(x, y):
    print(f"{x} and {y} are twin primes")
else:
    print(f"{x} and {y} are not twin primes")
This reduces checks by skipping even numbers, improving efficiency for larger inputs.

Complexity: O(√n) time, O(1) space

Time Complexity

Checking if a number is prime takes O(√n) time because we test divisors up to its square root. The twin prime check calls this twice, so overall O(√n).

Space Complexity

The program uses constant extra space, only a few variables, so O(1) space.

Which Approach is Fastest?

Using a sieve is faster for many checks but uses O(n) space. The direct prime check is simpler and uses less memory but slower for large inputs.

ApproachTimeSpaceBest For
Direct prime checkO(√n)O(1)Single or few checks
Sieve of EratosthenesO(n log log n) precomputeO(n)Many prime checks
Odd number optimizationAbout half of O(√n)O(1)Moderate size inputs
💡
Check primality efficiently by testing divisors only up to the square root of the number.
⚠️
Beginners often forget to check if both numbers are prime before checking their difference.