Find number from its divisors | C ++ implementation of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findX ( int a [ ] , int n ) { sort ( a , a + n ) ; int x = a [ 0 ] * a [ n - 1 ] ; vector < int > vec ; for ( int i = 2 ; i * i <= x ; i ++ ) { if ( x % i == 0 ) { vec . push_back ( i ) ; if ( ( x / i ) != i ) vec . push_back ( x / i ) ; } } sort ( vec . begin ( ) , vec . end ( ) ) ; if ( vec . size ( ) != n ) return -1 ; else { int i = 0 ; for ( auto it : vec ) { if ( a [ i ++ ] != it ) return -1 ; } } return x ; } int main ( ) { int a [ ] = { 2 , 5 , 4 , 10 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << findX ( a , n ) ; return 0 ; }