An Emirp (prime spelled backward) is a nonpalindromic prime number whose reversa
ID: 3544086 • Letter: A
Question
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 are 17 and 71 are emirps. Write a program that displays the first 100 emirps. Display 10 numbers per line and align the numbers properly, as follows:
13 17 31 37 71 73 79 97 107 113
149 157 167 179 199 311 337 347 359 389
This section presents a program that displays the first fifty prime numbers in five lines, each containing ten numbers. An integer greater than 1 is prime if its only positive divisor is 1 or itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not. The problem is to display the first 50 prime numbers in five lines, each of which contains ten numbers. The problem can be broken into the following tasks: Determine whether a given number is prime. For number = 2, 3, 4, 5, 6.......test whether it is prime. Count the prime numbers. Display each prime number, and display ten numbers per line. Obviously, you need to write a loop and repeatedly test whether a new number is prime. If the number is prime, increase the count by 1. The count is 0 initially. When it reaches 50, the loop terminates. Here is the algorithm for the problem: Set the number of prime numbers to be printed as constant NUMBER_OF_PRIMES; Use count to track the number of prime numbers and set an initial count to 0; Set an initial number to 2;
Explanation / Answer
public class emirp {
public static void main(String[] args) {
int count = 0;
int n = 13;
while (count < 100) {
if (Emirp(n)) {
System.out.print(n + " ");
count++;
if (count % 10 == 0) {
System.out.println();
}
}
n++;
}
}
public static boolean primeNumber(int n) {
for (int i = 2; i <= n / 2 ; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static boolean Emirp(int n) {
return primeNumber(n) && primeNumber(reversal(n));
}
public static int reversal(int n) {
if (n < 10) {
return n;
}
return recursive(n % 10, n/10);
}
public static int recursive(int a, int b) {
if (b < 1) {
return a;
}
return recursive(a * 10 + b % 10, b / 10);
}
}