K distant prime pairs in a given range | Java 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 ; Traverse the Map M ; If it . first & ( it . first + K ) is prime then print this pair ; Function to print all the prime pairs in the given range that differs by K ; Generate all prime number ; Driver Code ; Given range ; Given K ; Function Call
import java . util . * ; class solution { static void findPrimeNos ( int L , int R , Map < Integer , Integer > M , int K ) { for ( int i = L ; i <= R ; i ++ ) { if ( M . get ( i ) != null ) M . put ( i , M . get ( i ) + 1 ) ; else M . put ( i , 1 ) ; } if ( M . get ( 1 ) != null ) { M . remove ( 1 ) ; } for ( int i = 2 ; i <= Math . sqrt ( R ) ; i ++ ) { int multiple = 2 ; while ( ( i * multiple ) <= R ) { if ( M . get ( i * multiple ) != null ) { M . remove ( i * multiple ) ; } multiple ++ ; } } for ( Map . Entry < Integer , Integer > entry : M . entrySet ( ) ) { if ( M . get ( entry . getKey ( ) + K ) != null ) { System . out . print ( " ( " + entry . getKey ( ) + " , ▁ " + ( entry . getKey ( ) + K ) + " ) ▁ " ) ; } } } static void getPrimePairs ( int L , int R , int K ) { Map < Integer , Integer > M = new HashMap < Integer , Integer > ( ) ; findPrimeNos ( L , R , M , K ) ; } public static void main ( String args [ ] ) { int L = 1 , R = 19 ; int K = 6 ; getPrimePairs ( L , R , K ) ; } }