Pages

Saturday, 20 August 2016

Chapter 6 Exercise 27, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

**6.27 (Emirp) An emirp (prime spelled backward) is a nonpalindromic prime number whose reversal is also a prime. For example, 17 is a prime and 71 is a prime, so 17 and 71 are emirps. Write a program that displays the first 100 emirps. Display 10 numbers per line, separated by exactly one space, as follows:

13 17 31 37 71 73 79 97 107 113
149 157 167 179 199 311 337 347 359 389

public class ProgrammingExercise6_27 {
 
 public static void main(String[] args) {
  final int NUMBER_OF_EMIRPS = 100;
  int numberPrinted = 0, testedNumber = 2;
 
  while (numberPrinted < NUMBER_OF_EMIRPS) {
 
   if (isPrime(testedNumber) && isPrime(reverse(testedNumber))
     && !isPalindrome(testedNumber)) {
    numberPrinted++;
    System.out.print(testedNumber + " ");
 
    if (numberPrinted % 10 == 0) {
     System.out.println();
    }
   }
   testedNumber++;
  }
 
 }
 
 /** Check whether number is prime */
 public static boolean isPrime(int number) {
  for (int divisor = 2; divisor <= number / 2; divisor++) {
   if (number % divisor == 0) { // If true, number is not prime
    return false; // number is not a prime
   }
  }
 
  return true; // number is prime
 }
 
 public static boolean isPalindrome(int number) {
 
  return (number == reverse(number));
 
 }
 
 public static int reverse(int number) {
  int reverse = 0;
  int digit;
 
  do {
   digit = number % 10;
   reverse = reverse * 10 + digit;
   number /= 10;
  } while (number != 0);
 
  return reverse;
 }
}

No comments :

Post a Comment