Count prime triplets upto N having sum of first two elements equal to the third number | Java program for the above approach ; Boolean array to mark prime numbers ; To count the prime triplets having the sum of the first two numbers equal to the third element ; Function to count prime triplets having sum of the first two elements equal to the third element ; Sieve of Eratosthenes ; Checks for the prime numbers having difference equal to2 ; Update count of triplets ; Print the answer ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static int MAX = 1000001 ; static boolean [ ] prime = new boolean [ MAX ] ; static int [ ] cntTriplet = new int [ MAX ] ; static void primeTriplet ( int N ) { Arrays . fill ( prime , true ) ; prime [ 0 ] = prime [ 1 ] = false ; for ( int i = 2 ; i * i <= N ; i ++ ) { if ( prime [ i ] ) { for ( int j = i * i ; j <= N ; j += i ) { prime [ j ] = false ; } } } for ( int i = 3 ; i <= N ; i ++ ) { if ( prime [ i ] && prime [ i - 2 ] ) { cntTriplet [ i ] = cntTriplet [ i - 1 ] + 1 ; } else { cntTriplet [ i ] = cntTriplet [ i - 1 ] ; } } System . out . println ( cntTriplet [ N ] ) ; } public static void main ( String [ ] args ) { int N = 7 ; primeTriplet ( N ) ; } }