Twin Prime Number in JAVA

Twin Prime Number in JAVA

Twin Prime Number : A Twin Prime is a prime number that is either 2 less or 2 more than another prime number—

For example, (41, 43) are twin pairs. In other words, a twin prime is a prime that has a prime gap of two.

Algorithm to check whether two numbers are Twin prime or not :-
  • Input two numbers
  • Check both the numbers are prime or not
  • Check if the difference between the numbers is equal to 2 or not
  • If both the numbers are prime and difference is equal to 2
  • Print "Numbers are Twin Prime"
  • Else print "Numbers are not Twin Prime"


Program to check & Print whether two numbers are Twin prime or not :-


Program :-

import java.io.*;
import java.util.*;
class Twin_P
{
    public static void main(String args[])
    {
        Scanner in= new Scanner(System.in);
        int a,b,i,j,c=0,d=0,x=0;
        System.out.println("Enter two numbers");
        a= in.nextInt(); //input first number
        b= in.nextInt(); //input second number
        for(i=1;i<=a;i++) //check if the 1st number is prime or not
        {
            if(a%i==0)
            {
                c++;
            }
        }
        for(j=1;j<=b;j++) //check if the 2nd number is prime or not
        {
            if(b%j==0)
            {
                d++;
            }
        }
        x= Math.abs(a-b); //Storing the difference between the numbers
        if(c==2&&d==2&&x==2)
        {
            System.out.println("Numbers are Twin Prime");
        }
        else
        {
            System.out.println("Numbers are not Twin Prime");
        }
    } //end of main
} //end of class

For Proper Understanding Watch the Video :-


Watch this video : Twin Prime Number in JAVA

All the best :)
Keep Learning :)

Comments

Popular posts from this blog

Frequency of each digit of a number in Java

Trimorphic Number in JAVA

Tri-Automorphic Number in JAVA