Sum of elements in an array having composite frequency | JavaScript program to find sum of elements in an array having composite frequency ; Function to create Sieve to check primes ; If composite [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to composite ; Function to return the sum of elements in an array having composite frequency ; Map is used to store element frequencies ; To store sum ; Traverse the map using iterators ; Count the number of elements having composite frequencies ; Driver code ; Function call
let N = 100005 function SieveOfEratosthenes ( composite ) { for ( let i = 0 ; i < N ; i ++ ) composite [ i ] = false ; for ( let p = 2 ; p * p < N ; p ++ ) { if ( ! composite [ p ] ) { for ( let i = p * 2 ; i < N ; i += p ) composite [ i ] = true ; } } } function sumOfElements ( arr , n ) { let composite = new Array ( N ) ; SieveOfEratosthenes ( composite ) ; let m = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) if ( m . has ( arr [ i ] ) ) { m [ arr [ i ] ] = m [ arr [ i ] ] + 1 ; } else { m . set ( arr [ i ] , 1 ) ; } let sum = 0 ; m . forEach ( ( value , key ) => { if ( composite [ key ] ) { sum += value ; } } ) return sum ; } let arr = [ 1 , 2 , 1 , 1 , 1 , 3 , 3 , 2 , 4 ] ; let n = arr . length ; document . write ( sumOfElements ( arr , n ) ) ;