Twin prime number program in java

A Twin prime are those numbers which are prime and having a difference of two ( 2 ) between the two prime numbers.

In other words, a twin prime is a prime that has a prime gap of two. Sometimes the term twin prime is used for a pair of twin primes; an alternative name for this is prime twin or prime pair.

3, 5), (5, 7), (11, 13), (17, 19), (29, 31), 
import java.io.*;
class TwinPrime
{        
     boolean isPrime(int n) //funton for checking prime
        {
            int count=0;
            for(int i=1; i<=n; i++)
                {
                    if(n%i == 0)
                        count++;
                }
            if(count == 2)
                return true;
             else
                return false;
        }
  
    public static void main(String args[]) throws IOException
        {
            TwinPrime tw= new TwinPrime();
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 
            System.out.print("Enter the lower range : ");
            int p = Integer.parseInt(br.readLine());
            System.out.print("Enter the upper range : ");
            int q = Integer.parseInt(br.readLine());
             
            if(p>q)
                System.out.println("Invalid Range !");
            else
            {
                System.out.println("nThe Twin Prime Numbers within the given range are : ");
                for(int i=p; i<=(q-2); i++)
                {
                    if(tw.isPrime(i) == true && tw.isPrime(i+2) == true)
                    {
                        System.out.print("("+i+","+(i+2)+") ");
                    }
                }
            }                 
        }
    }

Output:

Enter the lower range : 12
Enter the upper range : 24
The Twin Prime Numbers within the given range are :
(17,19)

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.