Tags

JAVA CODING BOOTCAMP: LEARN LANGUAGE BASICS AND ALGORITHM

Java Coding Bootcamp for Beginners

It is one of the most common problem we face in any IT job interview related to software industry or any programming language. Can you write a program that will determine whether a number is twisted prime or not? Let us try it in Java. You can apply the same algorithm in other language like C, C++, PHP, C#, Python or Dart. First of all let us know what is twisted prime number. It is a prime number whose reverse is also a prime number, such as, 11, 71, 13, etc. Therefore, when the reversed prime number is also prime, we call it twisted prime. Example is 97. The reverse of 97 is 79, which is also prime.

```//code
package fun.sanjibsinha;

import java.util.Scanner;

class TwistedPrime{

static int temp, remain;

static int reverseNumber(int num){
while (num > 0){
remain = num % 10;
temp = temp * 10 + remain;
num /= 10;
}
return temp;
}
static boolean isPrime(int num){
if (num <= 1)
return false;
if (num <= 3)
return true;

if (num % 2 == 0 || num % 3 == 0)
return false;

for (int i = 5; i * i <= num; i = i + 6)
if (num % i == 0 || num % (i + 2) == 0)
return false;

return true;
}

static boolean isTwistedPrime(int num){
if (isPrime(num) == false)
return false;

return isPrime(reverseNumber(num));
}

}

public class ProblemEightySeven {

static int num = 0;

public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a number to check whether that is twisted prime number or not: ");
num = in.nextInt();
if(TwistedPrime.isTwistedPrime(num)){
System.out.println("The number " + num + " is a twisted prime number.");
}
else{
System.out.println("The number " + num + " is not a twisted prime number.");
}
}
}

We have taken more then one numbers to examine whether these numbers are twisted prime or not.```

Let us look at the output. We will run the code twice to test the number. User is asked to give the input.

```//output of code 87
Enter a number to check whether that is twisted prime number or not:
23
The number 23 is not a twisted prime number.
--------------------------------------
Enter a number to check whether that is twisted prime number or not:
101
The number 101 is a twisted prime number.```

https://leanpub.com/u/sanjibsinha