Generate elements of the array following given conditions | Function to generate the required array ; Initialize cnt variable for assigning unique value to prime and its multiples ; When we get a prime for the first time then assign a unique smallest value to it and all of its multiples ; Print the generated array ; Driver code
function specialSieve ( n ) { let cnt = 0 ; let prime = new Array ( n + 1 ) ; for ( let i = 0 ; i <= n ; i ++ ) prime [ i ] = 0 ; for ( let i = 2 ; i <= n ; i ++ ) { if ( ! prime [ i ] ) { cnt ++ ; for ( let j = i ; j <= n ; j += i ) prime [ j ] = cnt ; } } for ( let i = 2 ; i <= n ; i ++ ) document . write ( prime [ i ] + " " ) ; } let n = 6 ; specialSieve ( n ) ;