Emirp numbers in C++


Emirp number is a special type of number that is a prime number whose digits when reversed create another prime number (this prime number is different from the original one).

Emirp is the reverse of prime. 

Some prime numbers that are not emirp are palindromic prime and single digit prime numbers. 

Some Emirp Numbers are 13, 17, 37, 733.

Program to print all emirp numbers less than n.

Here, we are given a number n, and we need to print all emirp numbers less than or equal to n.

Let’s take an example to understand the problem,

Input: n = 40

Output: 13, 17, 31, 37

Solution Approach

To find all emirp numbers less than the given number, we need to find all prime numbers less than n and then check if number formed by reversing its digits is a prime number than its a emirp number, print it.

For finding the prime number till n and then rechecking its reverse digits, the best method is using sieve of Eratosthenes.

Program to illustrate the working of our solution,

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;

int reverseDigits(int x) {

   int digitRev = 0;
   while (x > 0)
   {
      digitRev = (digitRev*10) + x%10;
      x = x/10;
   }
   return digitRev;
}

void findAllEmirpNumber(int n) {

   bool primeNo[10001];
   memset(primeNo, true, sizeof(primeNo));

   for (int p=2; p*p<=10001; p++)
   {
      if (primeNo[p] == true)
      {
         for (int i=p*2; i<=10001; i += p)
            primeNo[i] = false;
      }
   }
   for (int p=2; p<=n; p++)
   {
      if (primeNo[p])
      {
         int revNo = reverseDigits(p);
         if (p != revNo && primeNo[revNo]) {
         cout<<p<<"\t";
         if(revNo <= n)
          cout<<revNo<<"\t";
         primeNo[revNo] = false;
         }
      }
   }
}

int main()
{
   int n = 40;
   cout<<"All Emirp numbers less than or equal to "<<n<<" are\n";
   findAllEmirpNumber(n);
   return 0;
}

Output

All Emirp numbers less than or equal to 40 are 13 31 17 37

Updated on: 22-Jan-2021

355 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements