Generate an N | JavaScript program for the above approach ; Function to generate all prime numbers upto 10 ^ 6 ; Initialize sieve [ ] as 1 ; Iterate over the range [ 2 , N ] ; If current element is non - prime ; Make all multiples of i as 0 ; Function to construct an array A [ ] satisfying the given conditions ; Stores the resultant array ; Stores all prime numbers ; Sieve of Erastosthenes ; Append the integer i if it is a prime ; Indicates current position in list of prime numbers ; Traverse the array arr [ ] ; If already filled with another prime number ; If A [ i ] is not filled but A [ ind ] is filled ; Store A [ i ] = A [ ind ] ; If none of them were filled ; To make sure A [ i ] does not affect other values , store next prime number ; Print the resultant array ; Driver Code ; Function Call
var sieve = Array ( 1000000 ) ; function sieveOfPrimes ( ) { sieve = Array ( 1000000 ) . fill ( 1 ) ; var N = 1000000 ; for ( var i = 2 ; i * i <= N ; i ++ ) { if ( sieve [ i ] == 0 ) continue ; for ( var j = i * i ; j <= N ; j += i ) sieve [ j ] = 0 ; } } function getArray ( arr , N ) { var A = Array ( N ) . fill ( 0 ) ; var v = [ ] ; sieveOfPrimes ( ) ; for ( var i = 2 ; i <= 1e5 ; i ++ ) if ( sieve [ i ] ) v . push ( i ) ; var j = 0 ; for ( var i = 0 ; i < N ; i ++ ) { var ind = arr [ i ] ; if ( A [ i ] != 0 ) continue ; else if ( A [ ind ] != 0 ) A [ i ] = A [ ind ] ; else { var prime = v [ j ++ ] ; A [ i ] = prime ; A [ ind ] = A [ i ] ; } } for ( var i = 0 ; i < N ; i ++ ) { document . write ( A [ i ] + " " ) ; } } var arr = [ 4 , 1 , 2 , 3 , 4 ] ; var N = arr . length ; getArray ( arr , N ) ;