Computer Science, asked by Anonymous, 1 year ago

Write a JAVA program to input 2 numbers and check if they are twin primes or not WITHOUT USING SCANNER CLASS.

Answers

Answered by gurukulamdivya
1

Answer:

// JAVA Code for Twin Prime Numbers  

import java.util.*;  

 

class GFG {  

 

   // Please refer below post for  

   // details of this function  

   // https://goo.gl/Wv3fGv  

   static boolean isPrime(int n)  

   {  

       // Corner cases  

       if (n <= 1) return false;  

       if (n <= 3) return true;  

 

       // This is checked so that we can skip  

       // middle five numbers in below loop  

       if (n % 2 == 0 || n % 3 == 0)  

           return false;  

 

       for (int i = 5; i * i <= n; i = i + 6)  

           if (n % i == 0 || n % (i + 2) == 0)  

               return false;  

 

       return true;  

   }  

 

   // Returns true if n1 and n2 are twin primes  

   static boolean twinPrime(int n1, int n2)  

   {  

       return (isPrime(n1) && isPrime(n2) &&  

                    Math.abs(n1 - n2) == 2);  

   }  

 

   /* Driver program to test above function */

   public static void main(String[] args)  

   {  

       int n1 = 11, n2 = 13;  

 

       if (twinPrime(n1, n2))  

           System.out.println("Twin Prime");  

       else

           System.out.println("Not Twin Prime");  

   }  

}  

 

Similar questions