
// Emirps.java
// Andrew Davison, ad@coe.psu.ac.th, April 2023

/* Print out the first 20 eprimes.

   An emirp (prime spelled backwards) are primes that when
   reversed (in their decimal representation) become different
   primes. (This rules out palindromic primes.)

   https://rosettacode.org/wiki/Emirp_primes#Java

   Usage:
     > compile Emirps.java
     > run Emirps
   e.g.
     > run Emirps
*/


public class Emirps
{

  public static void main(String[] args)
  {
    int count = 0;
    long n = 1;
    System.out.println("First 20 emirps:");
    while(count < 20) {
      if (isEmirp(n)) {
        count++;
        System.out.print(" " + n);
      }
      n++;
    }
    System.out.println();
  } /* main */



  private static boolean isEmirp(long n)
  {
    String s = Long.toString(n);
    if (s.length() == 1) 
      return false;

    // eliminate some easy cases
    if (s.matches("[24568].*") || s.matches(".*[24568]")) 
      return false;  
            
    long nRev = Long.parseLong( new StringBuilder(s).
                                    reverse().toString());
    if (nRev == n) // reverse is the same
      return false;

    return (Nut.isPrime(n) && Nut.isPrime(nRev));
  } /* isEmirp */

 
}  // end of Emirps class
