text: K distant prime pairs in a given range | C ++ program for the above approach ; Function to generate prime numbers in the given range [ L , R ] ; Store all value in the range ; Erase 1 as its non - prime ; Perform Sieve of Eratosthenes ; Find current multiple ; Erase as it is a non - prime ; Increment multiple ; Function to print all the prime pairs in the given range that differs by K ; Generate all prime number ; Traverse the Map M ; If it . first & ( it . first + K ) is prime then print this pair ; Driver Code ; Given range ; Given K ; Function Call
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void findPrimeNos ( int L , int R , unordered_map < int , int > & M ) { for ( int i = L ; i <= R ; i ++ ) { M [ i ] ++ ; } if ( M . find ( 1 ) != M . end ( ) ) { M . erase ( 1 ) ; } for ( int i = 2 ; i <= sqrt ( R ) ; i ++ ) { int multiple = 2 ; while ( ( i * multiple ) <= R ) { if ( M . find ( i * multiple ) != M . end ( ) ) { M . erase ( i * multiple ) ; } multiple ++ ; } } } void getPrimePairs ( int L , int R , int K ) { unordered_map < int , int > M ; findPrimeNos ( L , R , M ) ; for ( auto & it : M ) { if ( M . find ( it . first + K ) != M . end ( ) ) { cout << " ( " << it . first << " , ▁ " << it . first + K << " ) ▁ " ; } } } int main ( ) { int L = 1 , R = 19 ; int K = 6 ; getPrimePairs ( L , R , K ) ; return 0 ; }