Prime triplets consisting of values up to N having difference between two elements equal to the third | C ++ 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 ] ; Consider all numbers to prime initially ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool prime [ 100000 ] ; void SieveOfEratosthenes ( int n ) { memset ( prime , true , sizeof ( prime ) ) ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) { prime [ i ] = false ; } } } } void findTriplets ( int N ) { SieveOfEratosthenes ( N ) ; vector < vector < int > > V ; for ( int i = 3 ; i <= N ; i ++ ) { if ( 2 + i <= N && prime [ i ] && prime [ 2 + i ] ) { V . push_back ( { 2 , i , i + 2 } ) ; } } for ( int i = 0 ; i < V . size ( ) ; i ++ ) { cout << V [ i ] [ 0 ] << " ▁ " << V [ i ] [ 1 ] << " ▁ " << V [ i ] [ 2 ] << " STRNEWLINE " ; } } int main ( ) { int N = 8 ; findTriplets ( N ) ; return 0 ; }