Prime triplets consisting of values up to N having difference between two elements equal to the third | Java program for the above approach ; Stores 1 and 0 at indices which are prime and non - prime respectively ; Function to find all prime numbers from the range [ 0 , N ] ; Iterate over the range [ 2 , sqrt ( N ) ] ; If p is a prime ; Update all tultiples of p as false ; Function to find all prime triplets satisfying the given conditions ; Generate all primes up to N ; Stores the triplets ; Iterate over the range [ 3 , N ] ; Check for the condition ; Store the triplets ; Print all the stored triplets ; Driver Code
import java . util . * ; class GFG { static boolean [ ] prime = new boolean [ 100000 ] ; static void initialize ( ) { for ( int i = 0 ; i < 100000 ; i ++ ) prime [ i ] = true ; } static void SieveOfEratosthenes ( int n ) { for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) { prime [ i ] = false ; } } } } static void findTriplets ( int N ) { SieveOfEratosthenes ( N ) ; ArrayList < ArrayList < Integer > > V = new ArrayList < ArrayList < Integer > > ( ) ; for ( int i = 3 ; i <= N ; i ++ ) { if ( 2 + i <= N && prime [ i ] && prime [ 2 + i ] ) { ArrayList < Integer > a1 = new ArrayList < Integer > ( ) ; a1 . add ( 2 ) ; a1 . add ( i ) ; a1 . add ( i + 2 ) ; V . add ( a1 ) ; } } for ( int i = 0 ; i < V . size ( ) ; i ++ ) { System . out . println ( V . get ( i ) . get ( 0 ) + " ▁ " + V . get ( i ) . get ( 1 ) + " ▁ " + V . get ( i ) . get ( 2 ) ) ; } } public static void main ( String args [ ] ) { initialize ( ) ; int N = 8 ; findTriplets ( N ) ; } }