Question
Print twisted prime number in a given range 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 a number in given range then as 13 is prime number and reverse of 13 is 31 which is also prime number therefore,
13 is a Twisted Prime number
ENTER Lower Value:
-10
ENTER Upper Value:
500
Twisted Prime numbers between -10 and 500:
2 3 5 7 11 13 17 31 37 71 73 79 97 101 107 113 131 149 151 157 167 179 181 191 199 311 313 337 347 353 359 373 383 389
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 twistedPrimeInGivenRangeUsingRecursion
{
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 i=0,lowerRange=0,upperRange=0,reversedNumber=0;
Scanner sc=new Scanner(System.in);
System.out.println("ENTER Lower Value:");
lowerRange=sc.nextInt();
System.out.println("ENTER Upper Value:");
upperRange=sc.nextInt();
System.out.println("Twisted Prime numbers between "+ lowerRange+" and "+upperRange+":");
for(i=lowerRange;i<=upperRange;i++)
{
if(i>1)
{
if(isPrime(i,2)==true)
{
reversedNumber=reverseOfNumber(i,0);
if(isPrime(reversedNumber,2)==true)
{
System.out.print(i+" ");
}
}
}
}
}
}
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__'):
lowerRange=int(input("Enter lower value:"))
upperRange = int(input("Enter upper value:"))
print("Twisted Prime Number from",lowerRange,"to",upperRange,":")
for i in range(lowerRange,upperRange+1):
if(i>1):
reversedNumber= reverseOfNumber(i)
if(isPrime(i)==True and isPrime(reversedNumber)==True):
print(i,end=" ")