Find a number that divides maximum array elements | JavaScript program to find a number that divides maximum array elements ; stores smallest prime factor for every number ; Calculating SPF ( Smallest Prime Factor ) for every number till MAXN . Time Complexity : O ( nloglogn ) ; marking smallest prime factor for every number to be itself . ; separately marking spf for every even number as 2 ; checking if i is prime ; marking SPF for all numbers divisible by i ; marking spf [ j ] if it is not previously marked ; A O ( log n ) function returning primefactorization by dividing by smallest prime factor at every step ; Function to find a number that divides maximum array elements ; precalculating Smallest Prime Factor ; Hash to store frequency of each divisors ; Traverse the array and get spf of each element ; calling getFactorization function ; Returns Set view ; Driver program
let MAXN = 100001 ; let spf = new Array ( MAXN ) ; for ( let i = 0 ; i < MAXN ; i ++ ) { spf [ i ] = 0 ; } function sieve ( ) { spf [ 1 ] = 1 ; for ( let i = 2 ; i < MAXN ; i ++ ) spf [ i ] = i ; for ( let i = 4 ; i < MAXN ; i += 2 ) spf [ i ] = 2 ; for ( let i = 3 ; i * i < MAXN ; i ++ ) { if ( spf [ i ] == i ) { for ( let j = i * i ; j < MAXN ; j += i ) if ( spf [ j ] == j ) spf [ j ] = i ; } } } function getFactorization ( x ) { let ret = [ ] ; while ( x != 1 ) { let temp = spf [ x ] ; ret . push ( temp ) ; while ( x % temp == 0 ) x = Math . floor ( x / temp ) ; } return ret ; } function maxElement ( A , n ) { sieve ( ) ; let m = new Map ( ) ; for ( let j = 0 ; j < n ; ++ j ) { let p = getFactorization ( A [ j ] ) ; for ( let i = 0 ; i < p . length ; i ++ ) m . set ( p [ i ] , m . get ( p [ i ] ) == null ? 0 : m . get ( p [ i ] ) + 1 ) ; } let cnt = 0 , ans = 10000000 ; for ( let [ key , value ] of m . entries ( ) ) { if ( value >= cnt ) { cnt = value ; if ( ans > key ) ans = key ; else ans = ans ; } } return ans ; } let A = [ 2 , 5 , 10 ] ; let n = A . length ; document . write ( maxElement ( A , n ) ) ;