What is an Emirp Number?Solve dis java program?
Answers
Emirp Number
Emirp is the reverse of prime. An Emirp Number is a non-palindromic prime number which gives another prime number when its digits are reversed.
For example, 13 is a prime number. When its digits are reversed, 31 is also a Prime. So 13 is an Emirp Number.
However, 11 is not an Emirp number, since it is a Palindrome.
[Palindrome numbers are those which stay the same when their digits are reversed. E.g. 11, 101, 32523, etc]
Here is a Java Program which accomplishes the required task. Explanation is given in the form of comments. Screenshots are also attached.
import java.util.Scanner;
public class Emirp_Number
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); //Creating Scanner Object
System.out.println("An Emirp number is a non-palindromic prime number which results in another prime when its digits are reversed.");
System.out.print("Enter a prime number: "); //Taking User Input
int n = sc.nextInt();
//For checking a number to be Emirp, it should first be a Prime
if(isPrime(n)) //Calling a Function isPrime()
{
if(isPrime(reverse(n)) && isNotPalindrome(n)) //If number is not a Palindrome and reverse number is also a Prime, then it is Emirp
{
System.out.println(n+" is an Emirp Number.");
}
else
{
System.out.println(n+" is not an Emirp Number.");
}
}
else //Condition when input number is not itself a prime
{
System.out.println("Invalid Input. "+n+" is not a Prime.");
}
}
static boolean isPrime(int n) //Function to check if a number is Prime
{
for(int i=2;i<=(int)Math.sqrt(n);i++) //We check divisibility of n by every number from 2 to sqrt(n)
{
if(n%i==0)
{
return false; //If number is divisible anywhere, then we return False
}
}
return true; //If the number is not found to be divisible anywhere, then we return True
}
static int reverse(int n) //Function to reverse the digits of a number
{
String s=Integer.toString(n); //We first store the number n to a String
String ns=""; //ns will store our new reversed string
for(int i=s.length()-1;i>=0;i--) //Loop runs in reverse
{
ns += s . charAt(i); //We add characters from s to ns in reverse
}
return Integer.parseInt(ns); //ns is parsed to integer and returned
}
static boolean isNotPalindrome(int n) //This function returns true only if number is not a Palindrome
{
if(reverse(n)==n) //Checking number if it is a Palindrome
{
return false;
}
else
{
return true;
}
}
}
[Note: Remove the spaces in s . charAt(n)]