K distant prime pairs in a given range | Python3 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
from math import sqrt NEW_LINE def findPrimeNos ( L , R , M ) : NEW_LINE INDENT for i in range ( L , R + 1 ) : NEW_LINE INDENT M [ i ] = M . get ( i , 0 ) + 1 NEW_LINE DEDENT if ( 1 in M ) : NEW_LINE INDENT M . pop ( 1 ) NEW_LINE DEDENT for i in range ( 2 , int ( sqrt ( R ) ) + 1 , 1 ) : NEW_LINE INDENT multiple = 2 NEW_LINE while ( ( i * multiple ) <= R ) : NEW_LINE INDENT if ( ( i * multiple ) in M ) : NEW_LINE INDENT M . pop ( i * multiple ) NEW_LINE DEDENT multiple += 1 NEW_LINE DEDENT DEDENT DEDENT def getPrimePairs ( L , R , K ) : NEW_LINE INDENT M = { } NEW_LINE findPrimeNos ( L , R , M ) NEW_LINE for key , values in M . items ( ) : NEW_LINE INDENT if ( ( key + K ) in M ) : NEW_LINE INDENT print ( " ( " , key , " , " , key + K , " ) " , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 1 NEW_LINE R = 19 NEW_LINE K = 6 NEW_LINE getPrimePairs ( L , R , K ) NEW_LINE DEDENT