其他分享
首页 > 其他分享> > 月月给华华出题(欧拉函数)

月月给华华出题(欧拉函数)

作者:互联网

题目链接:点击这里

题目大意:
给定一个正整数 N N N ,对于所有的 n ∈ [ 1 , N ] n\in[1,N] n∈[1,N] 输出 ∑ i = 1 n i gcd ⁡ ( i , n ) \sum_{i=1}^n\frac{i}{\gcd(i,n)} ∑i=1n​gcd(i,n)i​

题目分析:
∑ i = 1 n i gcd ⁡ ( i , n ) \sum_{i=1}^n\frac{i}{\gcd(i,n)} i=1∑n​gcd(i,n)i​
= ∑ d = 1 n 1 d ∑ i = 1 n i [ gcd ⁡ ( i , n ) = d ] =\sum_{d=1}^n\frac{1}{d}\sum_{i=1}^n i[\gcd(i,n)=d] =d=1∑n​d1​i=1∑n​i[gcd(i,n)=d]
= ∑ d = 1 n 1 d ∑ i = 1 ⌊ n d ⌋ i d [ gcd ⁡ ( i , n / d ) = 1 ] =\sum_{d=1}^n\frac{1}{d}\sum_{i=1}^{\lfloor \frac{n}{d} \rfloor} id[\gcd(i,n/d)=1] =d=1∑n​d1​i=1∑⌊dn​⌋​id[gcd(i,n/d)=1]
= ∑ d = 1 n n / d ⋅ φ ( n / d ) + [ n / d = 1 ] 2 =\sum_{d=1}^n\frac{n/d·\varphi(n/d)+[n/d=1]}{2} =d=1∑n​2n/d⋅φ(n/d)+[n/d=1]​
∑ d ∣ n d ⋅ φ ( d ) + [ d = 1 ] 2 \sum_{d|n}\frac{d·\varphi(d)+[d=1]}{2} d∣n∑​2d⋅φ(d)+[d=1]​
提前筛一下欧拉函数,然后根据上述公式调和级数枚举枚举因子计算贡献即可

具体细节见代码:

//#pragma GCC optimize(2)
//#pragma GCC optimize("Ofast","inline","-ffast-math")
//#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include<iostream>
#include<cstdio>
#include<iomanip>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#define ll long long
#define inf 0x3f3f3f3f
#define Inf 0x3f3f3f3f3f3f3f3f
#define int  ll
#define endl '\n'
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
using namespace std;
int read()
{
	int res = 0,flag = 1;
	char ch = getchar();
	while(ch<'0' || ch>'9')
	{
		if(ch == '-') flag = -1;
		ch = getchar();
	}
	while(ch>='0' && ch<='9')
	{
		res = (res<<3)+(res<<1)+(ch^48);//res*10+ch-'0';
		ch = getchar();
	}
	return res*flag;
}
const int maxn = 1e6+5;
const int mod = 1e9+7;
const double pi = acos(-1);
const double eps = 1e-8;
int n,cnt,pri[maxn],phi[maxn],ans[maxn];
bool vis[maxn];
void init(int n)
{
	vis[1] = phi[1] = 1;
	for(int i = 2;i <= n;i++)
	{
		if(!vis[i]) 
		{
			pri[++cnt] = i;
			phi[i] = i-1;
		}
		for(int j = 1;j<=cnt && i*pri[j]<=n;j++)
		{
			vis[i*pri[j]] = true;
			if(i%pri[j] == 0)
			{
				phi[i*pri[j]] = phi[i]*pri[j];
				break;
			}
			phi[i*pri[j]] = phi[i]*(pri[j]-1);
		}
	}
}
signed main() 
{
	n = read();
	init(n);
	for(int i = 1;i <= n;i++)
		for(int j = 1;j*i <= n;j++) ans[i*j] += phi[j]*j/2;
	for(int i = 1;i <= n;i++) cout<<ans[i]+1<<endl;
	return 0;
}

标签:ch,frac,gcd,华华,sum,pri,出题,include,欧拉
来源: https://blog.csdn.net/qq_39641976/article/details/120189513