Find number from its divisors | Function that returns X ; Sort the given array ; Get the possible X ; Container to store divisors ; Find the divisors of x ; Check if divisor ; sort the vec because a is sorted and we have to compare all the elements ; if size of both vectors is not same then we are sure that both vectors can 't be equal ; Check if a and vec have same elements in them ; Driver code ; Function call
function findX ( a , n ) { a . sort ( ( x , y ) => x - y ) ; let x = a [ 0 ] * a [ n - 1 ] ; let vec = [ ] ; for ( let i = 2 ; i * i <= x ; i ++ ) { if ( x % i == 0 ) { vec . push ( i ) ; if ( parseInt ( x / i ) != i ) vec . push ( parseInt ( x / i ) ) ; } } vec . sort ( ( x , y ) => x - y ) ; if ( vec . length != n ) return - 1 ; else { let i = 0 ; for ( let j = 0 ; j < vec . length ; j ++ ) { if ( a [ i ++ ] != vec [ j ] ) return - 1 ; } } return x ; } let a = [ 2 , 5 , 4 , 10 ] ; let n = a . length ; document . write ( findX ( a , n ) ) ;