Minimum difference between any two primes from the given range | Python3 implementation of the approach ; Function for Sieve of Eratosthenes ; Function to return the minimum difference between any two prime numbers from the given range [ L , R ] ; Find the first prime from the range ; Find the second prime from the range ; If the number of primes in the given range is < 2 ; To store the minimum difference between two consecutive primes from the range ; Range left to check for primes ; For every integer in the range ; If the current integer is prime ; If the difference between i and snd is minimum so far ; Driver code ; Generate primes
from math import sqrt NEW_LINE sz = int ( 1e5 ) ; NEW_LINE isPrime = [ True ] * ( sz + 1 ) ; NEW_LINE def sieve ( ) : NEW_LINE INDENT isPrime [ 0 ] = isPrime [ 1 ] = False ; NEW_LINE for i in range ( 2 , int ( sqrt ( sz ) ) + 1 ) : NEW_LINE INDENT if ( isPrime [ i ] ) : NEW_LINE INDENT for j in range ( i * i , sz , i ) : NEW_LINE INDENT isPrime [ j ] = False ; NEW_LINE DEDENT DEDENT DEDENT DEDENT def minDifference ( L , R ) : NEW_LINE INDENT fst = 0 ; NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT if ( isPrime [ i ] ) : NEW_LINE INDENT fst = i ; NEW_LINE break ; NEW_LINE DEDENT DEDENT snd = 0 ; NEW_LINE for i in range ( fst + 1 , R + 1 ) : NEW_LINE INDENT if ( isPrime [ i ] ) : NEW_LINE INDENT snd = i ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( snd == 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT diff = snd - fst ; NEW_LINE left = snd + 1 ; NEW_LINE right = R ; NEW_LINE for i in range ( left , right + 1 ) : NEW_LINE INDENT if ( isPrime [ i ] ) : NEW_LINE INDENT if ( i - snd <= diff ) : NEW_LINE INDENT fst = snd ; NEW_LINE snd = i ; NEW_LINE diff = snd - fst ; NEW_LINE DEDENT DEDENT DEDENT return diff ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT sieve ( ) ; NEW_LINE L = 21 ; R = 50 ; NEW_LINE print ( minDifference ( L , R ) ) ; NEW_LINE DEDENT