Question
print all the twisted prime numbers in a given range.
(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.)
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;
class TwistedPrimeInGivenRange
{
/* reverseOfNumber() reverses a number */
public static int reverseOfNumber(int num)
{
int temp=0,rem=0,reversedInteger=0,remainder=0;
temp=num;
while( temp > 0 )
{
remainder = temp % 10;
reversedInteger = reversedInteger * 10 + remainder;
temp /= 10;
}
return reversedInteger;
}
/* isPrime() checks whether a number is prime number or not */
public static boolean isPrime(int num)
{
boolean flag = true;
if(num>1)
{
for (int j = 2; j <= num / 2; j++)
{
if ((num % j) == 0)
{
flag = false;
break;
}
}
}
return flag;
}
public static void main(String[] args)
{
int lowerRange=0,upperRange=0,i=0,reversedNumber=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the lower range");
lowerRange=sc.nextInt();
System.out.println("Enter the Upper range");
upperRange=sc.nextInt();
System.out.print("Twisted Prime Numbers:");
for(i=lowerRange;i<=upperRange;i++)
{
if (isPrime(i)==true)
{
reversedNumber=reverseOfNumber(i);
if(isPrime(reversedNumber)==true)
{
System.out.println(i+" ");
}
}
}
}
}
Python
def reverseOfNumber(n):
reversedInteger= 0
temp= n
while(temp>0):
remainder=temp%10
reversedInteger=reversedInteger*10+remainder
temp=temp//10
return reversedInteger
def isPrimeNumber(n):
isPrime=True
if(n>1):
for i in range(2,n):
if(n%i==0):
isPrime=False
break
else:
isPrime = False
return isPrime
lowerRange=int(input("Enter a lower value:"))
upperRange=int(input("Enter a upper value:"))
print("Twisted prime number between",lowerRange,"and",upperRange,":")
for i in range(lowerRange,upperRange+1):
reversedNumber=reverseOfNumber(i)
if(isPrimeNumber(i)==True and isPrimeNumber(reversedNumber)==True):
print(i,end=" ")