Twin Prime Number Using Function in JAVA

Twin Prime Number using Function 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 Hello
{
    static boolean prime(int x) // method to check whether a number is prime or not
    {
        int k=0,i;
        for(i=2;i<=x;i++)
        {
            if(x%i==0)
            {
                k++;
            }
        }
        if(k==1)
        {
            return true;
        }
        else
        {
            return false;
        }
    } // end of prime method
    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        int a,b,max;
        System.out.println("Enter Two Numbers");
        a= in.nextInt();
        b= in.nextInt();
        if(prime(a) && prime(b))
        {
            max = Math.abs(a-b);
            if(max==2)
            {
                System.out.println("Numbers are Twin Prime : "+a+" & "+b);
            }
            else
            {
                System.out.println("Numbers are not Twin Prime : "+a+" & "+b);
            }
        }
        else
        {
            System.out.println("One or all of the numbers are not Prime : "+a+" & "+b);
        }
    } // end of main method
}// 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

Smith Number in JAVA

Trimorphic Number in JAVA