Check if given number is Emirp Number or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number n. We have to check whether n is an Emirp number or not. We all know Emirp number is (letters of prime in backward direction) is a prime number that results in a different prime when its digits are reversed.

So, if the input is like n = 97, then the output will be True as the reverse of 97 is 79 which is another prime.

To solve this, we will follow these steps −

  • if num is not prime, then
    • return False
  • reverse_num := reverse of num
  • return true when reverse_num is prime otherwise false


Let us see the following implementation to get better understanding −

 Live Demo

def is_prime(num):
   if num <= 1:
      return False
   for i in range(2, num):
      if num % i == 0:
         return False
   return True
def solve(num):
   if not is_prime(num):
      return False
   reverse_num = 0
   while num != 0:
      d = num % 10
      reverse_num = reverse_num * 10 + d
      num = int(num / 10)
   return is_prime(reverse_num)
n = 97
print (solve(n))




Published on 18-Jan-2021 17:20:28