Problem Author: | Tamzid Alahi (tamzid01) |
textbfPrepared by: | Tamzid Alahi (tamzid01) |
textbfEdited by: | Hasan Saleh (MathModel) |
Solution
The fundamental observation is that an integer is a common divisor of a pair (a_i, a_j) if and only if both a_i and a_j are multiples of . If we let represent the count of elements in the array that are multiples of , then the total number of pairs for which divides \gcd(a_i, a_j) is given by:
However, this value counts every pair where is a divisor, not necessarily the greatest common divisor. For example, a pair with a GCD of or would be included in the count for . To isolate the pairs where the GCD is exactly , we must subtract the pairs belonging to its multiples.We implement this using a descending sieve. First, we precompute the divisors for all numbers up to 10^5 to quickly update our counts as we read the input. For each a_i, we increment the counter for every one of its divisors. We only care about values of where C(g) \ge 2, as a GCD requires at least two numbers.Next, we define as the number of pairs whose GCD is exactly . We initialize f[g] = \binom{C(g)}{2}. By iterating from 10^5 down to , we ensure that when we process , we have already finalized the counts for all of its multiples 2g, 3g, 4g, \dots. For every such multiple , we subtract from . This process effectively "cleans" so that it only contains the count of pairs whose greatest common divisor is no larger and no smaller than itself.
After this subtraction, if f[g] > 0, it means there exists at least one pair in the array with a GCD of , and we increment our total answer. The complexity is dominated by the divisor precomputation and the sieve, resulting in an efficient O(A \log A + \sum d(a_i)) per test case.
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int MAXA=100005;
vector<int> divs[MAXA];
int cnt[MAXA],f[MAXA];
void pre(){
for(int i=1;i<MAXA;i++){
for(int j=i;j<MAXA;j+=i){
divs[j].push_back(i);
}
}
}
void solve(){
int n;cin>>n;
vector<int>used;
for(int i=0;i<n;i++){
int x;cin>>x;
for(int d:divs[x]){
if(!cnt[d])used.push_back(d);
cnt[d]++;
}
}
vector<int>cand;
for(int d:used){
if(cnt[d]>=2)cand.push_back(d);
}
sort(cand.rbegin(),cand.rend());
int ans=0;
for(int d:cand)f[d]=(cnt[d]*(cnt[d]-1))/2;
for(int m:cand){
if(f[m]>0){
ans++;
for(int d:divs[m]){
if(d!=m&&cnt[d]>=2)f[d]-=f[m];
}
}
}
cout<<ans<<"\n";
for(int d:used){
cnt[d]=0;
f[d]=0;
}
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
pre();
int t;cin>>t;
while(t--)solve();
return 0;
}