luogu P1447_能量采集 (莫比乌斯反演)
题目:
求
\[ans = \sum_{k=1}^{k<=n} (2*k-1)*f(k)
\]
题解:
- f(k) 就是 x 在[1, n]范围内,y 在[1, m]范围内的满足 gcd(x, y) = k 的x,y对数。
- 2*k- 1是gcd(x,y)=k的贡献。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N = 2e5 + 5;
int pri[N], cnt;
int vis[N];
int mu[N];
int sum[N];
int read(){
int q=0;char ch=' ';
while(ch<'0'||ch>'9')ch=getchar();
while(ch>='0'&&ch<='9')q=q*10+ch-'0',ch=getchar();
return q;
}
void prime(){
mu[1] = 1;
for(int i = 2; i < N; ++ i){
if(!vis[i]){
pri[++ cnt] = i;
mu[i] = -1;
}
for(int j = 1; j <= cnt && pri[j] * i < N; ++ j){
vis[pri[j] * i] = 1;
if(i % pri[j] == 0){
mu[pri[j] * i] = 0;
break;
}
mu[pri[j] * i] = -mu[i];
}
}
for(int i = 1; i <= N; ++ i)
sum[i] = sum[i - 1] + mu[i];
}
ll sol(ll n, ll m, ll k){
n /= k, m /= k;
ll res = 0;
for(int i = 1, last = 1; i <= n; i = last + 1){
last = min(n / (n / i), m / (m / i));
res += (ll)(sum[last] - sum[i - 1]) * (n / i) * (m / i);
}
return res;
}
int n, m;
int main()
{
prime();
n = read(), m = read();
if(n > m) swap(n, m);
ll ans = 0;
for(int i = 1; i <= n; ++ i){
ans += (ll)(2* i - 1) * sol(n , m, i);
}
printf("%lld\n", ans);
return 0;
}