KnowledgeBoat Logo

Java Number Programs (ISC Classes 11 / 12)

A prime number is said to be 'Twisted Prime', if the new number obtained after reversing the digits is also a prime number. Write a program to accept a number and check whether the number is 'Twisted Prime' or not.
Sample Input: 167
Sample Output: 761
167 is a 'Twisted Prime'.

Java

Java Iterative Stmts

139 Likes

Answer

import java.util.Scanner;

public class KboatTwistedPrime
{
    public void twistedPrimeCheck() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number: ");
        int num = in.nextInt();

        if (num == 1) {
            System.out.println(num + " is not a twisted prime number");
        }
        else {
            boolean isPrime = true;
            for (int i = 2; i <= num / 2; i++) {
                if (num % i == 0) {
                    isPrime = false;
                    break;
                }
            }
            
            if (isPrime) {
                
                int t = num;
                int revNum = 0;
                
                while (t != 0) {
                    int digit = t % 10;
                    t /= 10;
                    revNum = revNum * 10 + digit;
                }
                
                for (int i = 2; i <= revNum / 2; i++) {
                    if (revNum % i == 0) {
                        isPrime = false;
                        break;
                    }
                }
            }
            
            if (isPrime)
                    System.out.println(num + " is a twisted prime number");
                else
                    System.out.println(num + " is not a twisted prime number");
            }

    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of A prime number is said to be 'Twisted Prime', if the new number obtained after reversing the digits is also a prime number. Write a program to accept a number and check whether the number is 'Twisted Prime' or not. Sample Input: 167 Sample Output: 761 167 is a 'Twisted Prime'.

Answered By

41 Likes