Prime Triplet in Java

prime triplet is a collection of three prime numbers in the form (p, p + 2, p + 6) or (p, p + 4, p + 6).

Write a program in Java to display all the possible prime triplets in the range m and n, where the value of m and n are entered by the user.

Example:
INPUT:
M = 1
N = 20
OUTPUT:
5, 7, 11
7, 11, 13
11, 13, 17
13, 17, 19

import java.util.Scanner;
class PrimeTriplet
{
    static boolean isPrime(int n) //to check if a number is prime
    {
        int c=0;
        for(int i=1; i<=n; i++)
        {
            if(n%i == 0)
                c++;
        }
        if(c==2)
            return true;
        else
            return false;
    }
    
    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the range M and N");
        int m = in.nextInt();
        int n = in.nextInt();
        
        for(int i=m; i<=n-6; i++)
        {
            if(isPrime(i)&&isPrime(i+2)&&isPrime(i+6))
                System.out.println(i + " " + (i+2) + " " + (i+6));
                
            else if(isPrime(i)&&isPrime(i+4)&&isPrime(i+6))
                System.out.println(i + " " + (i+4) + " " + (i+6));
        }
    }
}

Video explanation

Leave a Comment

Your email address will not be published. Required fields are marked *