题意:给出N,M
执行如下程序:
long long ans = 0,ansx = 0,ansy = 0;
for(int i = 1; i <= N; i ++)
for(int j = 1; j <= M; j ++)
if(gcd(i,j) == 1) ans ++,ansx += i,ansy += j;
cout << ans << " " << ansx << " " << ansy << endl;
思路: 首先要会莫比乌斯,然后对于ans,自然是非常好求的,现在就是怎么求ansx和ansy。 设
手误!上面的d%gcd(i, j)=0 实际应为 gcd(i, j)%d=0
反演后得到:
因为n/i,m/i的值是分段的,每段都是相同的,分别有sqrt级别的段数,所以(n/i, m/i)也是sqrt级别的段数。所以这个可以分段求了,然后预处理出i*mu(i)的前缀和即可!
code:
#include
#include
#include
using namespace std;
typedef long long ll;
const int N = 100000+5;
int pri[N], mu[N], pnum, presum[N];
ll presum2[N];
bool vis[N];
void mobius(int n) {
mu[1] = 1; pnum = 0;
for(int i = 2;i <= n; i++) {
if(!vis[i]) {
pri[pnum++] = i;
mu[i] = -1;
}
for(int j = 0;j < pnum; j++) {
if(i*pri[j] > n) break;
vis[i*pri[j]] = 1;
if(i%pri[j] == 0) {
mu[i*pri[j]] = 0;
break;
}
mu[i*pri[j]] = -mu[i];
}
}
for(int i = 1;i <= n; i++) {
presum2[i] = presum2[i-1] + i*mu[i];
}
for(int i = 1;i <= n; i++) presum[i] = presum[i-1]+mu[i];
}
int n, m;
bool input() {
return scanf("%d%d", &n, &m) == 2;
}
void solve() {
int top = min(n, m);
ll ans = 0, ansx = 0, ansy = 0;
for(int i = 1;i <= top; i++) {
int tmp1 = n/i, tmp2 = m/i;
int nxt = min(n/tmp1, m/tmp2);
//printf("i = %d tmp1 = %d tmp2 = %d nxt = %d\n", i, tmp1, tmp2, nxt);
ans += (ll)(n/i)*(m/i)*(presum[nxt]-presum[i-1]);
ansx += (ll)m/i*(n/i + (ll)n/i*(n/i))/2*(presum2[nxt] - presum2[i-1]);
ansy += (ll)n/i*(m/i + (ll)m/i*(m/i))/2*(presum2[nxt] - presum2[i-1]);
i = nxt;
}
printf("%lld %lld %lld\n", ans, ansx, ansy);
}
int main() {
mobius(100000);
while(input()) {
solve();
}
return 0;
}