In this tutorial of Emirp Number in Java, we will write a program to check for the Emirp number in Java. Let us start by understanding, what is Emirp number.
Emirp Number
A number is said to be an Emirp number if it is a prime number and when reversed, the result formed is also a Prime Number. Emirp is backward for Prime, which indicates that a number, when formed backward, is also a prime number. Hence also known as twisted prime numbers.
Example: 13, 79, 199, 107 etc.
Explanation: Consider a Prime Number, 13
The reverse of 13: 31, which is also a prime number. Therefore, 13 is an Emirp Number.
Java Program to check for Emirp Number Using Function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | import java.io.*; import java.util.*; public class EmirpNumber { //function to check for prime, returns boolean public static boolean isPrime(int n) { if (n <= 1) return false; for (int i = 2; i < n; i++) { if (n % i == 0) return false; } return true; } //function to check for emirp number, returns boolean public static boolean isEmirp(int n) { //calls isPrime function and checks for prime if (isPrime(n) == false) return false; int rev = 0; while (n != 0) { int digit = n % 10; rev = rev *10 + digit; n = n / 10; } //after reverse again checks for prime return isPrime(rev); } //main function public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int n = sc.nextInt(); //Display accordingly if (isEmirp(n) == true) System.out.println(n + " is an Emirp number."); else System.out.println(n + " is not an Emirp number."); } } |
Output:
//First Run
Enter a number: 13
13 is an Emirp number.
//Second Run
Enter a number: 107
107 is an Emirp number.
//Third Run
Enter a number: 23
23 is not an Emirp number.