← All resources

Write a program to input two numbers x and y and print all prime triplets between these limits

Prime Triplets

A prime triplet is a set of three prime numbers of the form (p, p + 2, p + 6) or (p, p + 4, p + 6)
The first prime triplets are:
(5, 7, 11), (7, 11, 13), (11, 13, 17), (13, 17, 19), (17, 19, 23), (37, 41, 43), (41, 43, 47), (67, 71, 73), (97, 101, 103), (101, 103, 107), (103, 107, 109), (107, 109, 113), (191, 193, 197), (193, 197, 199), (223, 227, 229), (227, 229, 233), (277, 281, 283), (307, 311, 313), (311, 313, 317), (347, 349, 353), (457, 461, 463), (461, 463, 467), (613, 617, 619), (641, 643, 647), (821, 823, 827), (823, 827, 829), (853, 857, 859), (857, 859, 863), (877, 881, 883), (881, 883, 887)

import java.io.*;
public class prime_triplet
{
    public boolean isprime(int n)
    {
        int i;
        for(i=2;i<=n/2;i++)
        {
            if(n%i==0)
            return false;
        }
        return true;
    }
    public void print(int s, int l)
    {
        int i, tmp;
        if(s>=l)
        {
            tmp = s;
            s = l;
            l = tmp;
        }
        System.out.println("The prime triplets are:");
        for(i=s;i<=l;i++)
        {
            if(isprime(i)&&isprime(i+2)&&isprime(i+6))
            {
                System.out.println(i+", "+(i+2)+", "+(i+6));
            }
            if(isprime(i)&&isprime(i+4)&&isprime(i+6))
            {
                System.out.println(i+", "+(i+4)+", "+(i+6));
            }
        }
    }
    public static void main()throws IOException
    {
        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
        int x, y;
        System.out.println("Enter the lower limit:");
        x = Integer.parseInt(r.readLine());
        System.out.println("Enter the upper limit:");
        y = Integer.parseInt(r.readLine());
        prime_triplet obj = new prime_triplet();
        obj.print(x, y);
    }
}