Generate elements of the array following given conditions | C ++ implementation of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void specialSieve ( int n ) { int cnt = 0 ; int prime [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) prime [ i ] = 0 ; for ( int i = 2 ; i <= n ; i ++ ) { if ( ! prime [ i ] ) { cnt ++ ; for ( int j = i ; j <= n ; j += i ) prime [ j ] = cnt ; } } for ( int i = 2 ; i <= n ; i ++ ) cout << prime [ i ] << " ▁ " ; } int main ( ) { int n = 6 ; specialSieve ( n ) ; return 0 ; }