Minimum difference between any two primes from the given range | Javascript 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 ; Generate primes
const sz = 1e5 ; let isPrime = new Array ( sz + 1 ) ; function sieve ( ) { isPrime . fill ( true ) ; isPrime [ 0 ] = isPrime [ 1 ] = false ; for ( let i = 2 ; i * i <= sz ; i ++ ) { if ( isPrime [ i ] ) { for ( let j = i * i ; j < sz ; j += i ) { isPrime [ j ] = false ; } } } } function minDifference ( L , R ) { let fst = 0 ; for ( let i = L ; i <= R ; i ++ ) { if ( isPrime [ i ] ) { fst = i ; break ; } } let snd = 0 ; for ( let i = fst + 1 ; i <= R ; i ++ ) { if ( isPrime [ i ] ) { snd = i ; break ; } } if ( snd == 0 ) return - 1 ; let diff = snd - fst ; let left = snd + 1 ; let right = R ; for ( let i = left ; i <= right ; i ++ ) { if ( isPrime [ i ] ) { if ( i - snd <= diff ) { fst = snd ; snd = i ; diff = snd - fst ; } } } return diff ; } sieve ( ) ; let L = 21 , R = 50 ; document . write ( minDifference ( L , R ) ) ;