874. 筛法求欧拉函数


题目链接

874. 筛法求欧拉函数

给定一个正整数 \(n\),求 \(1~n\) 中每个数的欧拉函数之和。

输入格式

共一行,包含一个整数 \(n\)

输出格式

共一行,包含一个整数,表示 \(1~n\) 中每个数的欧拉函数之和。

数据范围

\(1≤n≤10^6\)

输入样例:

6

输出样例:

12

解题思路

Eratosthenes筛法求欧拉函数

  • 时间复杂度:\(O(nloglogn)\)

代码

// Problem: 筛法求欧拉函数
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/description/876/
// Memory Limit: 64 MB
// Time Limit: 1000 ms

// %%%Skyqwq
#include 

#define pb push_back
#define fi first
#define se second
#define mp make_pair
using namespace std;

typedef long long LL;
typedef pair PII;

template  bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template  bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }

template  void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

int n,phi[1000005];
void euler(int n)
{
	for(int i=1;i<=n;i++)phi[i]=i;
	for(int i=2;i<=n;i++)
		if(phi[i]==i)
		{
			for(int j=i;j<=n;j+=i)
				phi[j]=phi[j]/i*(i-1);
		}
}
int main()
{
	scanf("%d",&n);
	euler(n);
	LL res=0;
	for(int i=1;i<=n;i++)res+=phi[i];
	printf("%lld",res);
	return 0;
}

线性筛法求欧拉函数

用到的性质:
1.若 \(p|n\)\(p^2|n\),则 \(?(n)=?(n/p)*p\)
2.若 \(p|n\)\(p^2\nmid n\),则 \(?(n)=?(n/p)*(p-1)\)

  • 时间复杂度:\(O(n)\)

代码

// Problem: 筛法求欧拉函数
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/description/876/
// Memory Limit: 64 MB
// Time Limit: 1000 ms

// %%%Skyqwq
#include 

#define pb push_back
#define fi first
#define se second
#define mp make_pair
using namespace std;

typedef long long LL;
typedef pair PII;

template  bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template  bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }

template  void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

const int N=1e6+5;
int n,prime[N],v[N],m,phi[N];
void euler(int n)
{
	memset(v,0,sizeof v);
	phi[1]=1;
	for(int i=2;i<=n;i++)
	{
		if(v[i]==0)
		{
			v[i]=i;
			prime[++m]=i;
			phi[i]=i-1;
		}
		for(int j=1;j<=m;j++)
		{
			if(i*prime[j]>n||v[i]