洛谷 P2158 [SDOI2008]仪仗队

题意简述

给定一个n,求gcd(x, y) = 1(x, y <= n)的(x, y)个数

题解思路

欧拉函数,
则gcd(x, y) = 1(x <= y <= n)的个数 ans = φ(1) + φ(2) +...+ φ(n - 1)
最终答案为ans * 2 + 1;

代码

#include <cstdio>
using namespace std;
int n, ans;
int phi[41000];
int main()
{
	scanf("%d", &n);
	for (register int i = 1; i <= n; ++i) phi[i] = i;
	for (register int i = 2; i <= n; ++i)
		if (phi[i] == i)
			for (register int j = 1; i * j <= n; ++j)
				phi[i * j] = phi[i * j] / i * (i - 1);
	if (n == 1) printf("%d
", 0);
	else
	{
		for (register int i = 1; i < n; ++i) ans += phi[i];
		printf("%d
", ans * 2 + 1);
	}
}
原文地址:https://www.cnblogs.com/xuyixuan/p/9600248.html