Computer Science, asked by anu21305, 5 months ago

write a program to input two numbers n1 and n2 and print all twisted prime no. between them and define a function
boolean Prime(int x) which will return true if x is prime otherwise false
e.g n1 - 10 ,n2 - 20
output - 11,13,17
twisted prime because they are prime and there reverse is also prime.
e.g. 13 is prime and its reverse 31 is also prime.​


( in java , scanner class)

Answers

Answered by QGP
7

Twisted Primes - Java

We would use two functions. One to reverse a number and the other to check if the number is prime.

To reverse the number, we first extract each digit by modulo division with 10 in a loop. The number itself is divided by 10 in each iteration to remove the last digit after it is extracted in a separate variable. The reversed number is constructed from each digit.

After that, we check if the number is prime. We only check division from 2 to sqrt(number). If any factor is found, the number is not prime and we return false. Else, we return true. We do not need to check divisibility beyond the square root.

Finally, we simply take the user input for n1 and n2, loop through them and check if the number and its reverse are prime or not. If they both are, we print it.

 \rule{300}{1}

Code

import java.util.Scanner;

public class TwistedPrimes {

   // Reverse an integer

   static int Reverse(int number) {

       int reversedNumber = 0;

       while (number != 0) {

           // Extract the last digit

           int digit = number % 10;

           // Integer divide by 10 to kick out last digit

           number = number / 10;

           // Construct the reversed number with each digit

           reversedNumber = (reversedNumber * 10) + digit;

       }

       return reversedNumber;

   }

   static boolean Prime(int x) {

       // If number is less than 2, it is obviously not a prime

       if (x < 2) {

           return false;

       }

       // Check division by every number from 2 to sqrt(x)

       for (int i = 2; i <= Math.sqrt(x); i++) {

           if ((x % i) == 0) {

               return false;

           }

       }

       // If no factor is found, number is prime

       return true;

   }

   public static void main(String[] args) {

       // Create Scanner object

       Scanner in = new Scanner(System.in);

       // Take user input for n1 and n2

       System.out.print("n1: ");

       int n1 = in.nextInt();

       System.out.print("n2: ");

       int n2 = in.nextInt();

       // Close the Scanner object

       in.close();

       System.out.println("The Twisted Primes are: ");

       

       for (int n = n1; n <= n2; n++) {

           // If the number and its reverse both are prime, print it

           if (Prime(n) && Prime(Reverse(n))) {

               System.out.println(n);

           }

       }

   }

}

Attachments:
Similar questions