Question
Check whether the given number is twisted prime using Recursion.
(A number is called a twisted prime number if it is a prime number and the reverse of this number is also a prime number.)
For example,let's say 13 is the given number then as 13 is prime number and reverse of 13 is 31 which is also prime number therefore,
13 is a Twisted Prime number
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
Java
Python
Java
import java.util.Scanner;
public class twistedPrimeUsingRecursion
{
public static boolean isPrime(int n,int i)
{
if(n<=1)
{
return false;
}
else if(n==i)
{
return true;
}
else if(n%i==0)
{
return false;
}
else
{
return isPrime(n,i+1);
}
}
public static int reverseOfNumber(int n,int reverse)
{
if(n==0)
{
return reverse;
}
else
{
reverse=reverse*10+(n%10);
return reverseOfNumber(n/10,reverse);
}
}
public static void main(String[] args)
{
int number=0,reversedNumber=0;
Scanner sc=new Scanner(System.in);
System.out.println("ENTER A NUMBER:");
number=sc.nextInt();
if(number<0)
{
System.out.println(number+" IS NOT A TWISTED PRIME NUMBER");
}
else
{
if(isPrime(number,2)==true)
{
reversedNumber=reverseOfNumber(number,0);
if(isPrime(reversedNumber,2)==true)
{
System.out.println(number+" IS A TWISTED PRIME NUMBER");
}
else
{
System.out.println(number+" IS NOT A TWISTED PRIME NUMBER");
}
}
else
{
System.out.println(number+" IS NOT A TWISTED PRIME NUMBER");
}
}
}
}
Python
def isPrime(n,i=2):
if(n<=1):
return False
elif(i==n):
return True
elif(n%i==0):
return False
else:
return isPrime(n,i+1)
def reverseOfNumber(n,reverse=0):
if(n==0):
return reverse
else:
rem=n%10
reverse=reverse*10+rem
return reverseOfNumber(n // 10,reverse)
if (__name__=='__main__'):
number=int(input("Enter a number:"))
if(number<0):
print(number,"is not a Twisted Prime number")
else:
reversedNumber= reverseOfNumber(number)
if(isPrime(number)==True and isPrime(reversedNumber)==True):
print(number,"is a Twisted Prime number")
else:
print(number,"is not a Twisted Prime number")