UVA11426 GCD - Extreme (II) 莫比乌斯反演

UVA11426 GCD - Extreme (II)

标签

  • 莫比乌斯反演

前言

简明题意

\[\sum_{i=1}^{n-1}\sum_{j=i+1}^ngcd(i,j) \]

n <=4e6

思路

  • 首先求\(\sum_{i=1}^{n}\sum_{j=1}^ngcd(i,j)\),然后减去对角线,最后除以2就是答案。对角线上ij相等,所以对角线的gcd之和是n*(n+1)/2
  • 然后重点在于如何求\(\sum_{i=1}^{n}\sum_{j=1}^ngcd(i,j)\)
  • \(gcd(i,j)=\sum_{d|i且d|j}^n\phi(d)\)反演就可以了。这个式子的最后答案就是\(\sum_{d=1}^n\phi(d)*[\frac nd]^2\),整除分块写就行了。

注意事项

  • \(\phi\)的前缀和开long long

总结

AC代码

#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;

const int maxn = 4e6 + 10;

bool no_prime[maxn];
int prime[maxn];
long long phi[maxn];
int shai(int n)
{
	int cnt = 0;
	no_prime[1] = phi[1] = 1;

	for (int i = 2; i <= n; i++)
	{
		if (!no_prime[i])
			prime[++cnt] = i, phi[i] = i - 1;

		for (int j = 1; j <= cnt && prime[j] * i <= n; j++)
		{
			no_prime[prime[j] * i] = 1;
			phi[prime[j] * i] = (i % prime[j] == 0) ? phi[i] * prime[j] : phi[i] * (prime[j] - 1);
			if (i % prime[j] == 0) break;
		}
	}

	for (int i = 1; i <= n; i++)
		phi[i] += phi[i - 1];

	return cnt;
}

void solve()
{
	shai(maxn - 10);

	while (1)
	{
		int n;
		scanf("%d", &n);
		if (n == 0) return;

		long long ans = 0;
		int l = 1, r;
		while (l <= n)
		{
			r = n / (n / l);
			ans += 1ll * (phi[r] - phi[l - 1]) * (n / l) * (n / l);
			l = r + 1;
		}

		printf("%lld\n", (ans - 1ll*n*(n+1)/2) / 2);
	}

}

int main()
{
	freopen("Testin.txt", "r", stdin);
	solve();

	return 0;
}
posted @ 2019-08-29 16:41  danzh  阅读(152)  评论(0编辑  收藏  举报