We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Another approach to this problem is using C++ and vectors
Also, I think simply using factors instead of finding GCD and LCM can be a more simpler as well as transparent way:
using namespace std;
void factorsOf(int number, vector<int> &arr)
{
int temp, i=0;
for(temp=1;temp <= number;temp++)
{
if ((number % temp) == 0 )
{
arr.push_back(temp);
i++;
}
}
}
int getTotalX(vector<int> &a, vector<int> &b)
{
vector<int> allFactors; //THIS VECTOR COLLECTS ALL THE FACTORS OF THE ELEMENTS OF BOTH THE ARRAYS.
vector <int> temp;
int size_a = a.size();
int size_b = b.size();
int count=0,i=0,j=0,flag1,flag2;
//COLLECTING ALL THE FACTORS OF ALL THE ELEMENTS OF BOTH THE ARRAYS, SO AS TO LIMIT THE ITERATIONS NEEDED FOR SOLVING THE PROBLEM
while(size_a != 0) //RUNNING THROUGH THE ENTIRE ARRAY
{
factorsOf(a[size_a-1], temp);
//NOW, TEMP HAS STORED THE FACOTRS OF THE NUMBER SENT TO THE FUNCTION
allFactors.insert(allFactors.end(), temp.begin(), temp.end());
size_a--;
}
//REPEATING THE SAME PROCESS FOR ARRAY B
while(size_b != 0)
{
////cout<< endl<< size_b-1 << ", Value: "<< b[size_b-1];
factorsOf(b[size_b-1], temp);
//NOW, TEMP HAS STORED THE FACOTRS OF THE NUMBER SENT TO THE FUNCTION
allFactors.insert(allFactors.end(), temp.begin(), temp.end());
size_b--;
}
//NOW SORTING, REMOVING DUPLICATES AND FINALLY RESIZING THE VECTOR
sort(allFactors.begin(), allFactors.end());
allFactors.erase(unique(allFactors.begin(), allFactors.end()), allFactors.end() );
for(int j=0;j<allFactors.size();j++)
{
flag1 = 1;
for(i=0;i<a.size();i++)
{
if(allFactors[j] % a[i] != 0)
{
flag1 = 0;
break;
}
}
if(flag1 == 1)
{
flag2 = 1;
for(i=0;i<b.size();i++)
{
if(b[i] % allFactors[j] != 0)
{
flag2 = 0;
break;
}
}
if(flag2 == 1)
{
count++;
cout<< endl<<"RESULT: "<< allFactors[j];
}
}
}
return count;
}
int main()
{
vector <int> a = {2, 4};
vector <int> b = {16, 32, 96};
int total = getTotalX(a, b);
cout <<endl<<"THE TOTAL IS: " <<total << "\n";
}
Between Two Sets
You are viewing a single comment's thread. Return to all comments →
Another approach to this problem is using C++ and vectors Also, I think simply using factors instead of finding GCD and LCM can be a more simpler as well as transparent way:
}