Categories
Class 10 Class 11 Class 12

Prime Triplet in Java

A 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.io.*;
class PrimeTriplet{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("M = ");
        int m = Integer.parseInt(br.readLine());
        System.out.print("N = ");
        int n = Integer.parseInt(br.readLine());
        for(int i = m; i <= n; i++){
            int p1 = i;
            int p2 = i + 2;
            int p3 = i + 6;
            if(p2 > n || p3 > n)
                break;
            if(isPrime(p1) && isPrime(p2) && isPrime(p3))
                System.out.println(p1 + ", " + p2 + ", " + p3);
            p1 = i;
            p2 = i + 4;
            p3 = i + 6;
            if(p2 > n || p3 > n)
                break;
            if(isPrime(p1) && isPrime(p2) && isPrime(p3))
                System.out.println(p1 + ", " + p2 + ", " + p3);
        }
    }
    public static boolean isPrime(int n){
        int f = 0;
        for(int i = 1; i <= n; i++)
            if(n % i == 0)
                f++;
        return f == 2;
    }
}

By admin

I am a Computer Science teacher in one of the renowned schools in India. I teach Java programming language to my students, and I maintain a website happycompiler.com

7 replies on “Prime Triplet in Java”

Sir,a program is given which states that:
WAP in Java to display all Pythagorean triplets from m to n(both m and n are inclusive)(m<n)(m and n are to be accepted by the user)
Hint:6,8,10 are said to be pythagorean triplet
(6^2+8^2=10^2)
m and n are to be accepted as positive integers

Sir,a program is given which states that:
WAP in Java to display all Pythagorean triplets from m to n(both m and n are inclusive)(m<n)(m and n are to be accepted by the user)
Hint:6,8,10 are said to be pythagorean triplet
(6^2+8^2=10^2)
m and n are to be accepted as positive integer

Leave a Reply

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