Find original numbers from gcd ( ) every pair | Utility function to print the contents of an array ; Function to find the required numbers ; Sort array in decreasing order ; Count frequency of each element ; Size of the resultant array ; Store the highest element in the resultant array ; Decrement the frequency of that element ; Compute GCD ; Decrement GCD value by 2 ; Reverse array ; Driver code
function printArr ( arr , n ) { for ( let i = 0 ; i < n ; i ++ ) { document . write ( arr [ i ] + " " ) ; } } function findNumbers ( arr , n ) { arr . sort ( function ( a , b ) { return a - b } ) ; reverse ( arr ) ; let freq = new Array ( arr [ 0 ] + 1 ) ; freq . fill ( 0 ) ; for ( let i = 0 ; i < n ; i ++ ) { freq [ arr [ i ] ] ++ ; } let size = parseInt ( Math . sqrt ( n ) , 10 ) ; let brr = new Array ( size ) ; brr . fill ( 0 ) ; let x , l = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( freq [ arr [ i ] ] > 0 && l < size ) { brr [ l ] = arr [ i ] ; freq [ brr [ l ] ] -- ; l ++ ; for ( let j = 0 ; j < l ; j ++ ) { if ( i != j ) { x = __gcd ( arr [ i ] , brr [ j ] ) ; freq [ x ] -= 2 ; } } } } printArr ( brr , size ) ; } function reverse ( input ) { let last = input . length - 1 ; let middle = parseInt ( input . length / 2 , 10 ) ; for ( let i = 0 ; i <= middle ; i ++ ) { let temp = input [ i ] ; input [ i ] = input [ last - i ] ; input [ last - i ] = temp ; } } function __gcd ( a , b ) { if ( b == 0 ) { return a ; } return __gcd ( b , a % b ) ; } let arr = [ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 5 , 5 , 5 , 7 , 10 , 12 , 2 , 2 ] ; let n = arr . length ; findNumbers ( arr , n ) ;