Python Program to Check Twin Prime Numbers
def is_twin_prime(a, b): return is_prime(a) and is_prime(b) and abs(a - b) == 2.Examples
How to Think About It
Algorithm
Code
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")
Dry Run
Let's trace the example (11, 13) through the code
Check if 11 is prime
Test divisibility from 2 to 3 (sqrt of 11). No divisor found, so 11 is prime.
Check if 13 is prime
Test divisibility from 2 to 3 (sqrt of 13). No divisor found, so 13 is prime.
Check difference
Absolute difference between 11 and 13 is 2.
Result
Both numbers are prime and difference is 2, so they are twin primes.
| Number | Divisor Tested | Is Prime? |
|---|---|---|
| 11 | 2,3 | Yes |
| 13 | 2,3 | Yes |
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
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")
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")
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct prime check | O(√n) | O(1) | Single or few checks |
| Sieve of Eratosthenes | O(n log log n) precompute | O(n) | Many prime checks |
| Odd number optimization | About half of O(√n) | O(1) | Moderate size inputs |