Queries for the smallest and the largest prime number of given digit | Javascript implementation of the approach ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; Function to return the smallest prime number with d digits ; check if prime ; Function to return the largest prime number with d digits ; check if prime ; Driver code ; Perform queries
const MAX = 100000 ; let prime = new Array ( MAX + 1 ) . fill ( true ) ; function SieveOfEratosthenes ( ) { for ( let p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( let i = p * p ; i <= MAX ; i += p ) prime [ i ] = false ; } } } function smallestPrime ( d ) { let l = Math . pow ( 10 , d - 1 ) ; let r = Math . pow ( 10 , d ) - 1 ; for ( let i = l ; i <= r ; i ++ ) { if ( prime [ i ] ) { return i ; } } return - 1 ; } function largestPrime ( d ) { let l = Math . pow ( 10 , d - 1 ) ; let r = Math . pow ( 10 , d ) - 1 ; for ( let i = r ; i >= l ; i -- ) { if ( prime [ i ] ) { return i ; } } return - 1 ; } SieveOfEratosthenes ( ) ; let queries = [ 2 , 5 ] ; let q = queries . length ; for ( let i = 0 ; i < q ; i ++ ) { document . write ( smallestPrime ( queries [ i ] ) + " " + largestPrime ( queries [ i ] ) + " " ) ; }