Emirp numbers - GeeksforGeeks
Emirp is the word "prime" spelled backwards, and it refers to a prime number that becomes a new prime number when you reverse its digits. Emirps do not include palindromic primes (like 151 or 787) nor 1-digit primes like 7. 107, 113, 149, and 157 – reverse them and you've got a new prime number on your hands.
Read full article from Emirp numbers - GeeksforGeeks
Emirp is the word "prime" spelled backwards, and it refers to a prime number that becomes a new prime number when you reverse its digits. Emirps do not include palindromic primes (like 151 or 787) nor 1-digit primes like 7. 107, 113, 149, and 157 – reverse them and you've got a new prime number on your hands.
1) Use Sieve of Eratosthenes to generate all primes smaller than or equal to n. We can also use sieve of sundaram.
2) Traverse all generated prime numbers. For every traversed prime number print this number and its reverse if following conditions are satisfied.
………….a) If reverse is also prime.
………….b) Reverse is not same as prime (palindromes are not allowed)
………….c) Reverse is smaller than or equal to n.
………….a) If reverse is also prime.
………….b) Reverse is not same as prime (palindromes are not allowed)
………….c) Reverse is smaller than or equal to n.
// Function to find reverse of any number
int
reverse(
int
x)
{
int
rev = 0;
while
(x > 0)
{
rev = (rev*10) + x%10;
x = x/10;
}
return
rev;
}
// Sieve method used for generating emirp number
// (use of sieve of Eratosthenes)
void
printEmirp(
int
n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
bool
prime[n+1];
memset
(prime,
true
,
sizeof
(prime));
for
(
int
p=2; p*p<=n; p++)
{
// If prime[p] is not changed, then it is a prime
if
(prime[p] ==
true
)
{
// Update all multiples of p
for
(
int
i=p*2; i<=n; i += p)
prime[i] =
false
;
}
}
// Traverse all prime numbers
for
(
int
p=2; p<=n; p++)
{
if
(prime[p])
{
// Find reverse a number
int
rev = reverse(p);
// A number is emrip if it is not a palindrome
// number and its reverse is also prime.
if
(p != rev && rev <= n && prime[rev])
{
cout << p <<
" "
<< rev <<
" "
;
// Mark reverse prime as false so that it's
// not printed again
prime[rev] =
false
;
}
}
}
}