思路
首先推式子:
i=1∑nj=1∑n[popcount(i+j)⋅gcd(i,j)=max(i,j)]
设 d=gcd(i,j),那么枚举互质的 i,j:
d=1∑ni=1∑n/dj=1∑n/d[popcount((i+j)×d)=max(i,j)]
注意,此时是将 popcount(i+j)⋅gcd(i,j)=max(i,j) 的左右两边都乘以了 d。
设 i>j:
d=1∑ni=1∑n/dj=1∑n/d[popcount((i+j)×d)=i]
此时我们可以枚举 d,i,j 便可以得到结果。
一些优化
关于时间复杂度
可以发现 log(10000000)≈25,那么 popcount((i+j)×d) 最大为 25,所以 i≤popcount((i+j)×d),i,j≤25,i,j 只要枚举到 25 就可以啦。
更多优化
因为 popcount 的时间复杂度为 log(n),for循环时会炸掉,所以我们要预处理出 1 到 20000000 的 popcount。
代码
C++#include<bits/stdc++.h>
#define rep(i,s,t) for(int i=s;i<=t;i++)
using namespace std;
const int N=1e7+114;
int n,f[N];
bool st[30][30];
int pop[10000000<<1];
int lowbit(int x){return (x&-x);}
void init()
{
for(int i=1;i<=2*(10000000-10);i++)pop[i]=pop[i-lowbit(i)]+1;
rep(i,1,25)
rep(j,1,i)
if(__gcd(i,j)==1)st[i][j]=1;
}
int main()
{
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
cin>>n;
init();int res=0;
rep(d,1,n)
rep(i,1,min(25,n/d))
rep(j,1,i)
if(pop[i*d+j*d]==i && st[i][j])
{
if(i>j)f[i*d]+=2;
else f[i*d]++;
}
rep(i,1,n)f[i]+=f[i-1],res^=f[i];
cout<<res;
return 0;
}
//__builtin_popcount(5)