Queries for maximum difference between prime numbers in given ranges | JavaScript program to find maximum differences between two prime numbers in given ranges ; Precompute Sieve , Prefix array , Suffix array ; Sieve of Eratosthenes ; Precomputing Prefix array . ; Precompute Suffix array . ; Function to solve each query ; Driver Code
let MAX = 100005 ; function precompute ( prefix , suffix ) { let prime = [ ] ; for ( let i = 0 ; i < MAX ; i ++ ) { prime [ i ] = true ; } for ( let i = 2 ; i * i < MAX ; i ++ ) { if ( prime [ i ] ) { for ( let j = i * i ; j < MAX ; j += i ) { prime [ j ] = false ; } } } prefix [ 1 ] = 1 ; suffix [ MAX - 1 ] = 1e9 + 7 ; for ( let i = 2 ; i < MAX ; i ++ ) { if ( prime [ i ] ) { prefix [ i ] = i ; } else { prefix [ i ] = prefix [ i - 1 ] ; } } for ( let i = MAX - 2 ; i > 1 ; i -- ) { if ( prime [ i ] ) { suffix [ i ] = i ; } else { suffix [ i ] = suffix [ i + 1 ] ; } } } function query ( prefix , suffix , L , R ) { if ( prefix [ R ] < L suffix [ L ] > R ) { return 0 ; } else { return prefix [ R ] - suffix [ L ] ; } } let q = 3 ; let L = [ 2 , 2 , 24 ] ; let R = [ 5 , 2 , 28 ] ; let prefix = [ ] , suffix = [ ] ; precompute ( prefix , suffix ) ; for ( let i = 0 ; i < q ; i ++ ) { document . write ( query ( prefix , suffix , L [ i ] , R [ i ] ) + " " ) ; }