Count of multiples in an Array before every element | Function to find all factors of N and keep their count in map ; Traverse from 1 to sqrt ( N ) if i divides N , increment i and N / i in map ; Function to count of multiples in an Array before every element ; To store factors all of all numbers ; Traverse for all possible i 's ; Printing value of a [ i ] in map ; Now updating the factors of a [ i ] in the map ; Driver code ; Function call
function add_factors ( n , mp ) { for ( var i = 1 ; i <= parseInt ( Math . sqrt ( n ) ) ; i ++ ) { if ( n % i == 0 ) { if ( parseInt ( n / i ) == i ) { if ( mp . has ( i ) ) mp . set ( i , mp . get ( i ) + 1 ) else mp . set ( i , 1 ) } else { if ( mp . has ( i ) ) mp . set ( i , mp . get ( i ) + 1 ) else mp . set ( i , 1 ) if ( mp . has ( parseInt ( n / i ) ) ) mp . set ( parseInt ( n / i ) , mp . get ( parseInt ( n / i ) ) + 1 ) else mp . set ( parseInt ( n / i ) , 1 ) } } } return mp ; } function count_divisors ( a , n ) { var mp = new Map ( ) ; for ( var i = 0 ; i < n ; i ++ ) { document . write ( ( mp . has ( a [ i ] ) ? mp . get ( a [ i ] ) : 0 ) + " " ) ; mp = add_factors ( a [ i ] , mp ) ; } } var arr = [ 8 , 1 , 28 , 4 , 2 , 6 , 7 ] ; var n = arr . length ; count_divisors ( arr , n ) ;