hey guys , a while back I had come across this problem(sorry I don’t have the link to problem statement) , it was basically, given two arrays a and b of size n and m , find the gcd of all the elements of the resultant array c where c is the Cartesian product of a and b , I could not figure out a better approach than O(n*m) Does anyone have a better approach ?
Constraints : n,m<1e+5
How do you take the gcd of two pairs?
I’m sorry but I fail to see how that’s relevant to this question , I never get pairs anywhere here , we get two arrays a[] and b[] of size n and m respectively , we do a Cartesian product to obtain an array c[] of size n*m and get the GCd of all the elements of array c
Cartesian product of two arrays of sizes n,m results in a matrix of size nxm with each element in the matrix being a pair of two numbers
It Can Also Be An Array of pairs
I suppose you ignore the matrix part and put all its elements in an array, and just get the gcd of all elements existing (Ignoring the pairs), this would just be the gcd of all elements in array a and b, I think thats not what you meant, so please clarify what "Cartesian Product" means if you don't mean the method shown on wikipedia and the other article
Holy Shit it's Al_Khwarazmi himself! Big respect
First, let's take a look at the case where the size of array
a
is 1. We'll have the following answer:answer = GCD( a[0] * b[i], a[0] * b[i+1], ...)
This can be simplified to
answer = a[0] * GCD(b[i], b[i+1]...) = a[0] * GCD(b).
Now, what if we have a bigger array a, then we have the following derivation: