A prime number is said to be "Twisted Prime' if the new number obtained after
reversing the digits is also a prime number. Write a program to accept a number
check whether the number is 'Twisted Prime' or not.
Sample Input: 167
Sample Output: 761
167 is a 'Twisted Prime'.
Please help
Answers
Explanation:
Java
import java.util.Scanner;
class Twisted {
public static void main (String [ ] args) {
int n = new Scanner (System.in). nextInt();
boolean prime = true;
for(int i = 2;i<=n/2;i++){
if(n%i==0)prime=false;}
int rev=0;
while(n!=0){
rev=rev*10+n%10;
n/=10;
}
for(int i = 2;i<=rev/2;i++){
if(rev%i==0)prime=false;}
if(prime) System.out.println("Twisted Prime");
else System.out.println("not Twisted Prime");
}
}
Answer:
import java.lang.Math;
public class Main
{
static int rev(int x){
String s = Integer.toString(x) , y = "";
int len = s.length();
for(int i = len - 1; i >= 0; i--){
y = y + s.charAt(i);
}
return Integer.parseInt(y);
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
static boolean isTwistedPrime(int n){
int r = rev(n);
if(isPrime(n) && isPrime(r)){
return true;
}
return false;
}
public static void main(String[] args) {
System.out.println(isTwistedPrime(17));
}
}
Explanation: