Nearest prime number in the array of every array element | Javascript program to find nearest prime number in the array for all array elements ; Create a boolean array and set all entries it as false . A value in prime [ i ] will be true if i is not a prime , else false ; Sieve of Eratosthenes function ; Update all multiples of i greater than or equal to the square of it numbers which are multiple of i and are less than i ^ 2 are already been marked . ; Function to find nearest prime number for all elements ; Compute and store all prime numbers up to maxm ; Store the indices of all primes ; If no primes are present in the array ; Store the current prime ; If the no further primes exist in the array ; For all indices less than that of the current prime ; If the current prime is nearer ; If the next prime is nearer ; Make the next prime as the current ; Driver code
let max = 10000000 ; let prime = new Array ( max ) ; function SieveOfEratosthenes ( maxm ) { prime [ 0 ] = prime [ 1 ] = true ; for ( let i = 2 ; i * i <= maxm ; i ++ ) { if ( ! prime [ i ] ) { for ( let j = i * i ; j <= maxm ; j += i ) { prime [ j ] = true ; } } } } function print_nearest_prime ( arr , N ) { let maxm = Math . max ( ... arr ) ; SieveOfEratosthenes ( maxm ) ; let primes = [ ] ; for ( let i = 0 ; i < N ; i ++ ) { if ( ! prime [ arr [ i ] ] ) primes . push ( i ) ; } if ( primes . length == 0 ) { for ( let i = 0 ; i < N ; i ++ ) { document . write ( - 1 + " " ) ; } return ; } let curr = 0 ; for ( let i = 0 ; i < N ; i ++ ) { if ( curr == primes . length - 1 || i <= primes [ curr ] ) { document . write ( arr [ primes [ curr ] ] + " " ) ; continue ; } if ( Math . abs ( primes [ curr ] - i ) < Math . abs ( primes [ curr + 1 ] - i ) ) { document . write ( arr [ primes [ curr ] ] + " " ) ; } else { curr ++ ; document . write ( arr [ primes [ curr ] ] + " " ) ; } } } let N = 6 ; let arr = [ 8 , 7 , 12 , 15 , 3 , 11 ] ; print_nearest_prime ( arr , N ) ;