Check whether the given numbers are Cousin prime or not in Python

Two numbers are called cousin primes when both are prime numbers and their absolute difference is exactly 4. This is different from twin primes (difference of 2) and sexy primes (difference of 6).

For example, (7, 11) are cousin primes because both are prime and |11 - 7| = 4. Similarly, (19, 23) are cousin primes.

Algorithm

To check if two numbers are cousin primes ?

  • Check if the absolute difference between the numbers is exactly 4
  • Verify that both numbers are prime
  • Return True only if both conditions are satisfied

Implementation

First, we need a helper function to check if a number is prime ?

def isPrime(num):
    if num < 2:
        return False
    if num == 2:
        return True
    if num % 2 == 0:
        return False
    
    for i in range(3, int(num**0.5) + 1, 2):
        if num % i == 0:
            return False
    return True

def are_cousin_primes(pair):
    # Check if difference is exactly 4
    if abs(pair[0] - pair[1]) != 4:
        return False
    
    # Check if both numbers are prime
    return isPrime(pair[0]) and isPrime(pair[1])

# Test with example
pair = (19, 23)
result = are_cousin_primes(pair)
print(f"Are {pair} cousin primes? {result}")
Are (19, 23) cousin primes? True

Testing with Multiple Examples

Let's test with various pairs to verify our implementation ?

def isPrime(num):
    if num < 2:
        return False
    if num == 2:
        return True
    if num % 2 == 0:
        return False
    
    for i in range(3, int(num**0.5) + 1, 2):
        if num % i == 0:
            return False
    return True

def are_cousin_primes(pair):
    if abs(pair[0] - pair[1]) != 4:
        return False
    return isPrime(pair[0]) and isPrime(pair[1])

# Test cases
test_pairs = [(3, 7), (7, 11), (13, 17), (19, 23), (37, 41), (10, 14), (11, 15)]

for pair in test_pairs:
    result = are_cousin_primes(pair)
    print(f"{pair}: {result}")
(3, 7): True
(7, 11): True
(13, 17): True
(19, 23): True
(37, 41): True
(10, 14): False
(11, 15): False

Key Points

  • Difference check: The absolute difference must be exactly 4
  • Prime verification: Both numbers must be prime individually
  • Optimization: We only check divisors up to ?n for primality testing
  • Edge cases: Numbers less than 2 are not prime

Common Cousin Prime Pairs

Some well-known cousin prime pairs include ?

  • (3, 7), (7, 11), (13, 17), (19, 23)
  • (37, 41), (43, 47), (67, 71), (79, 83)

Conclusion

Cousin primes are prime number pairs with a difference of 4. The algorithm checks both the difference condition and primality of both numbers. This concept is useful in number theory and cryptographic applications.

Updated on: 2026-03-25T14:40:42+05:30

394 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements