Need a JAVA PROGRAM on- Write a program to input a number and check whether the number is twisted prime or not.
Answers
public class TwistedPrime
{
public static boolean prime(int n)//Checks if number is prime
{
int c=0;
for(int i=1;i<=n;i++)
{
if(n%i==0)
{
c++;
}
}
if(c==2)
return true;
else
return false;
}
public static int reverse(int n)//Reverses a number
{
int rev=0;
while(n!=0)
{
int a=n%10;
rev=rev*10+a;
n=n/10;
}
return rev;
}
public static void main(String args[])
{
Scanner ob=new Scanner(System.in);
System.out.println("Enter number to be checked.");
int num=ob.nextInt();
int rev=reverse(num);
if(prime(num)==true && prime(rev)==true)
{
System.out.println(num+" is a Twisted Prime Number.");
}
else
{
System.out.println(num+" is not a Twisted Prime Number.");
}
}
}
CODE :
import java.util.*;
class twisted_prime
{
public void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number to check whether it is twisted prime or not");
int n=sc.nextInt();
int f=0;
int c=0;
for(int i=1;i<=n;i++)
{
if(n%i==0)
{
c=c+1;
}
}
if(c==2)
{
f=1;
}
if(f==1)
{
int rev=0;
int cpy=n;
c=0;
int d=0;
while(n>0)
{
d=n%10;
rev=rev*10+d;
n=n/10;
}
for(int i=1;i<=rev;i++)
{
if(rev%i==0)
{
c=c+1;
}
}
if(c==2)
{
System.out.println("Twisted prime number");
}
else
{
System.out.println("Not a twisted prime number");
}
}
else
{
System.out.println("Not a twisted prime number");
}
}
}
Explanation:
The number is taken as input with the help of scanner class .
Then we check whether the number is prime or not by using for loop and counter variable .
Then we can reverse the number using digit extraction .
After that check whether the reverse of the number is prime or not .
Then if both conditions are true we will print that the numbers are twisted primes otherwise not .