Ok, so first and foremost:
If some number X appears multiple times in A, we can calculate the answer for X once and just check the precalculated answer.
So basically, now we have 10^6 distinct numbers. AKA, 1,2,3...10^6.
Good! So we just have to calculate the answer for all numbers between 1 and 10^6.
The second observation it's trivial to see that if the divisors set contains repeated numbers we can just erase the repetitions.
So now the divisors set only has distinct elements. Cool! Now a kinda brute force algorithm will work.
For each divisor X we will mark their multiples as "divisible". Please notice the number X has 10^6/X divisors.
You can see the code below of how this works:
#include <iostream>
#define MAX 1000005
///If I already added X to the set
bool already_computed[MAX];
///If the number X is divisible by someone in the set
bool seen[MAX];
int main(){
///First and foremost, we are reading the set
int N;///Number of elements in the set
std::cin>>N;
for(int i=0;i!=N;++i){
int x;
std::cin>>x;
///If we didn't add x yet
if(!already_computed[x]){
///Mark that you checked x
already_computed[x]=true;
///Now I'm going to iterate EVERY single number upto 10^6
///I'm just checking the numbers that are divisible by X
///Please notice I'm checking 10^6/X numbers.
int b=x;
while(b<MAX){
seen[b]=1;
b+=x;
}
}
}
///Now I'm reading the array
int M;
std::cin>>M;
int answer=0;
for(int i=0;i!=M;++i){
int x;
std::cin>>x;
///Notice that we already calculated our answer above :)
answer+=seen[x];
}
std::cout<<answer<<"\n";
return 0;
}
Here's the example the author gave us in the code's input format:
3
3 5 7
6
3 5 7 15 21 143
Ok, cool. At first glance this may seem like an optimized O(N^2), but it's actually O(N log N).
Proof:
$\frac{1}{1}+\frac{1}{2}+\frac{1}{3}+...\frac{1}{N}\approx log(N)$
Now multiplying the above equation by N:
$\frac{N}{1}+\frac{N}{2}+\frac{N}{3}+...\frac{N}{N}\approx N\cdot log(N)$
And the below fraction is EXACTLY the complexity of what we are doing in the loop where we insert the numbers contained in the set.
If you are interested in this equation please check the Harmonic Series https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)
In my simulations the code above runs in around 30ms even in the worst-case scenarios, so I would say it's pretty efficient to solve the problem mentioned above.