Subscribe Us

Twin Prime Number In Java

Twin Prime Number in Java


Java Program To Check Twin Prime Numbers Or Not

A twin prime is a prime number that is Either 2 less or 2 more than another prime number
A twin prime is a prime that has a prime gap of Two

Example:
Given Numbers : 11 and 13
11 and 13 are Twin Prime Number Because
11 and 13 Both are Prime Numbers and Gap Between Them are 2 .
Example:
Given Numbers : 11 and 19
11 and 19 are Not Twin Prime Number Because
11 and 19 Both are Prime Numbers But Gap Between Them are Not 2 .

Source Code

//Java Program To Check Twin Prime Numbers Or Not
import java.util.*;
public class TwinPrimeNumber
 {
  public static void main(String args[])
   {
     Scanner in=new Scanner(System.in);
     int num1,num2,i,count1=0,count2=0;
     System.out.print("Enter The First Number: ");
     num1=in.nextInt();
     System.out.print("Enter The Second Number : ");
     num2 = in.nextInt();
     // To Count The Factors of num1 
     for(i=1;i<=num1;i++)
      {
       if(num1%i==0)
        count1++;
      }
     // To Cound The Factors of num2 
     for(i=1;i<=num2;i++)
      {
       if(num2%i==0)
        count2++;
      }     
     if(count1==2 && count2==2 && ((num1-num2)==2 || (num1-num2)==-2)) 
       System.out.println(num1+" and "+num2+" are Twin Prime Numbers ");
     else
       System.out.println(num1+" and "+num2+" are Not Twin Prime Numbers ");      
   }
 }

Output

Sample Input :
Enter First Number : 11
Enter Second Number : 13
Sample Output:
11 and 13 are Twin Prime Numbers

Sample Input :
Enter First Number : 17
Enter Second Number : 23
Sample Output:
17 and 23 are Not Twin Prime Numbers

Looping Related Programs