Count distinct prime factors for each element of an array | JavaScript program for the above approach ; Stores smallest prime factor for every number ; Stores distinct prime factors ; Function to find the smallest prime factor of every number ; Mark the smallest prime factor of every number to itself ; Separately mark all the smallest prime factor of every even number to be 2 ; If i is prime ; Mark spf for all numbers divisible by i ; Mark spf [ j ] if it is not previously marked ; Function to find the distinct prime factors ; Push all distinct of x prime factor in v [ x ] ; Pushback into v [ i ] ; Increment the idx ; Update x = ( x / spf [ x ] ) ; Function to get the distinct factor count of arr [ ] ; initialization ; Precompute the smallest Prime Factors ; For distinct prime factors Fill the v [ ] vector ; Count of Distinct Prime Factors of each array element ; Driver code
let MAX = 100001 ; let spf ; let v ; function sieve ( ) { for ( let i = 1 ; i < MAX ; i ++ ) spf [ i ] = i ; for ( let i = 4 ; i < MAX ; i = i + 2 ) spf [ i ] = 2 ; for ( let i = 3 ; i * i < MAX ; i ++ ) if ( spf [ i ] == i ) { for ( let j = i * i ; j < MAX ; j = j + i ) { if ( spf [ j ] == j ) spf [ j ] = i ; } } } function DistPrime ( ) { for ( let i = 1 ; i < MAX ; i ++ ) { let idx = 1 ; let x = i ; if ( x != 1 ) v [ i ] . push ( spf [ x ] ) ; x = parseInt ( x / spf [ x ] , 10 ) ; while ( x != 1 ) { if ( v [ i ] [ idx - 1 ] != spf [ x ] ) { v [ i ] . push ( spf [ x ] ) ; idx += 1 ; } x = parseInt ( x / spf [ x ] , 10 ) ; } } } function getFactorCount ( arr , N ) { spf = new Array ( MAX ) ; v = new Array ( MAX ) ; for ( let i = 0 ; i < MAX ; i ++ ) v [ i ] = [ ] ; sieve ( ) ; DistPrime ( ) ; for ( let i = 0 ; i < N ; i ++ ) { document . write ( v [ arr [ i ] ] . length + " " ) ; } } let arr = [ 6 , 9 , 12 ] ; let N = arr . length ; getFactorCount ( arr , N ) ;