In this tutorial, you will learn how to write a java program to check if a number is Emirp number.
What is an Emirp Number?
A prime number is called Emirp number if we get a different prime number when its digits are reversed. For example, 13 is an Emirp number because:
13 is a prime number Reverse of 13 = 31 31 is a different number and it is also a prime number. Hence 13 is an Emirp number.
As you can see I have highlighted the word different in the above definition, which means the palindrome prime numbers are not Emirp number as the number should return different number when reversed and not the same number.
Let’s take another example. Check for number 23.
23 is a prime number Reverse of 23 = 32 32 is not a prime number. Hence 23 is not an Emirp number.
Steps to check if a number is an Emirp number
- Read the number entered by user and assign it to an integer variable.
- Check if the entered number is a prime number.
- If entered number is prime proceed to next step.
- else break and display “not an Emirp number”.
- Find the reverse of the entered number.
- Check if reverse number is prime number.
- If prime, print the given number is an Emirp number.
- else display “not an Emirp number”.
Program to check Emirp number in Java
In this program we have two user-defined methods: checkPrime()
and checkEmirp()
. Method checkPrime()
checks if the number is prime number or not and the method checkEmirp()
checks if the number is Emirp number or not.
import java.util.*; public class JavaExample { public static boolean checkPrime(int num) { if (num <= 1) return false; for (int i = 2; i < num; i++) if (num % i == 0) return false; return true; } public static boolean checkEmirp(int num) { if (checkPrime(num) == false) return false; int reverseNum = 0; while (num != 0) { int lastDigit = num % 10; reverseNum = reverseNum * 10 + lastDigit; num = num/10; } return checkPrime(reverseNum); } public static void main(String args[]) { Scanner scanner=new Scanner(System.in); System.out.print("Enter any number: "); int num = scanner.nextInt(); if (checkEmirp(num) == true) System.out.println(num+ " is an Emirp number."); else System.out.println(num+ " is not an Emirp number."); } }
Output:
Enter any number: 37 37 is an Emirp number.
Output 2:
Enter any number: 23 23 is not an Emirp number.
Leave a Reply