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

PythonServer Side ProgrammingProgramming

Suppose we have a pair of integers. We have to check whether they are cousin primes or not. Two numbers are said to be cousin primes when both are primes and differ by 4.

So, if the input is like pair = (19,23), then the output will be True as these are two primes and their difference is 4 so they are cousin primes.

To solve this, we will follow these steps −

  • if difference between two elements is not 4, then
    • return False
  • return true when both are prime, otherwise false

Let us see the following implementation to get better understanding −

Example Code

Live Demo

def isPrime(num):
   if num > 1:
      for i in range(2, num):
         if num % i == 0:
           return False
      return True
   return False

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

pair = (19,23)




Published on 16-Jan-2021 09:25:30