Computer Science, asked by yuvanshashivernam, 1 month ago

Make a program in java to input two numbers and check whether they are twin prime numbers or not.
Hint: Twin prime numbers are the prime numbers whose difference is 2.
For example: (5,7), (11,13) and so on.

Answers

Answered by anindyaadhikari13
7

Solution.

The given problem is solved using language - Java.

import java.util.*;

public class TwinPrime{

   public static void main(String s[]){

       Scanner sc=new Scanner(System.in);

       int a,b;

       System.out.print("Enter first number: ");

       a=sc.nextInt();

       System.out.print("Enter second number: ");

       b=sc.nextInt();

       if(isPrime(a) && isPrime(b)&&Math.abs(a-b)==2)

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

       else

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

   }

   static boolean isPrime(int n){

       int c=0;

       for(int i=1;i<=n;i++){

           if(n%i==0)

               c++;

       }

       return c==2;

   }

}

Explanation.

  • Here, we have asked user to enter two numbers.
  • Then, we will check whether both the numbers are prime or not using the method isPrime(n).
  • Then, we will check whether the numbers differ by two or not.
  • If all the conditions are satisfied, numbers are twin prime else not.

See attachment for output.

Attachments:
Similar questions