Find numbers which are multiples of first array and factors of second array | C ++ implementation of the approach ; Function to return the LCM of two numbers ; Function to print the required numbers ; To store the lcm of array a [ ] elements and the gcd of array b [ ] elements ; Finding LCM of first array ; Finding GCD of second array ; No such element exists ; All the multiples of lcmA which are less than or equal to gcdB and evenly divide gcdB will satisfy the conditions ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int lcm ( int x , int y ) { int temp = ( x * y ) / __gcd ( x , y ) ; return temp ; } void findNumbers ( int a [ ] , int n , int b [ ] , int m ) { int lcmA = 1 , gcdB = 0 ; for ( int i = 0 ; i < n ; i ++ ) lcmA = lcm ( lcmA , a [ i ] ) ; for ( int i = 0 ; i < m ; i ++ ) gcdB = __gcd ( gcdB , b [ i ] ) ; if ( gcdB % lcmA != 0 ) { cout << " - 1" ; return ; } int num = lcmA ; while ( num <= gcdB ) { if ( gcdB % num == 0 ) cout << num << " ▁ " ; num += lcmA ; } } int main ( ) { int a [ ] = { 1 , 2 , 2 , 4 } ; int b [ ] = { 16 , 32 , 64 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int m = sizeof ( b ) / sizeof ( b [ 0 ] ) ; findNumbers ( a , n , b , m ) ; return 0 ; }