Count of elements not divisible by any other elements of Array | Function to count the number of elements of array which are not divisible by any other element of same array ; Length for boolean array ; Hash map for storing the element and it 's frequency ; Update the maximum element ; Boolean array of size of the max element + 1 ; Marking the multiples as false ; To store the final count ; Traverse boolean array ; Check if i is not divisible by any other array elements and appears in the array only once ; Return the final Count ; Given array ; Function Call
function countEle ( a , n ) { let len = 0 ; let hmap = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { len = Math . max ( len , a [ i ] ) ; if ( hmap . has ( a [ i ] ) ) { hmap . set ( a [ i ] , hmap . get ( a [ i ] ) + 1 ) ; } else { hmap . set ( a [ i ] , 1 ) ; } } let v = Array . from ( { length : len + 1 } , ( _ , i ) => 0 ) ; for ( let i = 0 ; i <= len ; i ++ ) { v [ i ] = true ; } for ( let i = 0 ; i < n ; i ++ ) { if ( v [ a [ i ] ] == false ) continue ; for ( let j = 2 * a [ i ] ; j <= len ; j += a [ i ] ) { v [ j ] = false ; } } let count = 0 ; for ( let i = 1 ; i <= len ; i ++ ) { if ( v [ i ] == true && hmap . has ( i ) && hmap . get ( i ) == 1 && hmap . get ( i ) == 1 ) { count += 1 ; } } return count ; } let arr = [ 86 , 45 , 18 , 4 , 8 , 28 , 19 , 33 , 2 ] ; let n = arr . length ; document . write ( countEle ( arr , n ) ) ;