Write a program to accept two numbers from the user and print whether they are twin prime number or not. A twin prime is a pair of two numbers that are both prime and their difference is two.

Example: 11 and 13

import java.io.*;
class Twin_Prime{
    public static int prime(int k){
        int f=1;
        for(int i=2;i<k;i++){
            if(k%i==0){
                f=0;
            }
        }
        return f;
    }

    public static void main() throws IOException{
        int a1;
        int a2;
        int j;
        int n;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the limit");
        n=Integer.parseInt(br.readLine());
        System.out.println("Twin primes upto" +n+" are:");
        for(int i=2;i<(n-2);i++){
            j=i+2;
            a1=prime(i);
            a2=prime(j);
            if(a1==1 && a2==1){
                System.out.println(i+"\t"+j);
            }
        }
    }
}

Output:

Enter the limit
50
Twin primes upto50 are:
3 5
5 7
11 13
17 19
29 31
41 43

SHARE
Previous articleFrequency of letters
Next articleEncryption

LEAVE A REPLY

Please enter your comment!
Please enter your name here