In: Computer Science
A palindrome prime is a prime number that reads the same
forwards or backwards. An example of a
palindrome prime is 131. Write a method with the following
signature for determining if a given
number is a palindrome prime.
public static boolean isPallyPrime(int nVal)
Note: For this assignment you are not allowed to use the
built in Java class Array as part of your solution for any of these
questions. Your Method signatures must
be the same as given here.
I have uploaded the Images of the code, Typed code and Output of the Code. I have provided explanation using comments(read them for better understanding).
Images of the Code:
Note: If the below code is missing indentation please refer code Images
Typed Code:
//importing required package
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
//Scanner is used to take inputs from the user
Scanner scnr = new Scanner(System.in);
System.out.print("Enter a Number: ");
//Getting input from the user
int nVal = scnr.nextInt();
//calling function ==> if the
method returns true then
if(isPallyPrime(nVal))
{
//given number is palindrome
prime
System.out.print(nVal+" is a
palindrome prime");
}
//else
else
{
//given number is not a palindrome
prime
System.out.print(nVal+" is not a
palindrome prime");
}
}
//function called
public static boolean isPallyPrime(int nVal)
{
//initializing required variables
int val = nVal,count = 0,rev = 0, pal = 0;
//for loop will iterate val times
for(int i = 1; i <= val; i++)
{
//if val is divided by i and remainder is 0
if(val%i == 0)
{
//increasing count
count++;
}
}
//while loop will iterate until val is greater than
0
while(val > 0)
{
//rev is used to store last digit
rev = val % 10;
//adding rev value to it
pal = pal * 10 + rev;
//dividing val by 10
val = val/10;
}
//if nVal = pal and count = 2
if(nVal == pal && count == 2)
{
//return true
return true;
}
//else
else
{
//return false
return false;
}
}
}
//code ended here
Output:
If You Have Any Doubts. Please Ask Using Comments.
Have A Great Day!